output_dac.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. #include "squeezelite.h"
  2. #include "driver/i2s.h"
  3. #include "perf_trace.h"
  4. #include <signal.h>
  5. #define DECLARE_ALL_MIN_MAX \
  6. DECLARE_MIN_MAX(o); \
  7. DECLARE_MIN_MAX(s); \
  8. DECLARE_MIN_MAX(loci2sbuf); \
  9. DECLARE_MIN_MAX(req); \
  10. DECLARE_MIN_MAX(rec); \
  11. DECLARE_MIN_MAX(over); \
  12. DECLARE_MIN_MAX(i2savailable);\
  13. DECLARE_MIN_MAX(i2s_time); \
  14. DECLARE_MIN_MAX(buffering);
  15. #define RESET_ALL_MIN_MAX \
  16. RESET_MIN_MAX(o); \
  17. RESET_MIN_MAX(s); \
  18. RESET_MIN_MAX(loci2sbuf); \
  19. RESET_MIN_MAX(req); \
  20. RESET_MIN_MAX(rec); \
  21. RESET_MIN_MAX(over); \
  22. RESET_MIN_MAX(i2savailable);\
  23. RESET_MIN_MAX(i2s_time);\
  24. RESET_MIN_MAX(buffering);
  25. #define STATS_PERIOD_MS 5000
  26. // Prevent compile errors if dac output is
  27. // included in the build and not actually activated in menuconfig
  28. #ifndef CONFIG_I2S_BCK_IO
  29. #define CONFIG_I2S_BCK_IO -1
  30. #endif
  31. #ifndef CONFIG_I2S_WS_IO
  32. #define CONFIG_I2S_WS_IO -1
  33. #endif
  34. #ifndef CONFIG_I2S_DO_IO
  35. #define CONFIG_I2S_DO_IO -1
  36. #endif
  37. #ifndef CONFIG_I2S_NUM
  38. #define CONFIG_I2S_NUM -1
  39. #endif
  40. static log_level loglevel;
  41. size_t dac_buffer_size =0;
  42. static bool running = true;
  43. static bool isI2SStarted=false;
  44. extern struct outputstate output;
  45. extern struct buffer *streambuf;
  46. extern struct buffer *outputbuf;
  47. extern u8_t *silencebuf;
  48. static struct buffer _dac_buffer_structure;
  49. struct buffer *dacbuffer=&_dac_buffer_structure;
  50. u8_t *tfr_buffer;
  51. static i2s_config_t i2s_config;
  52. #if REPACK && BYTES_PER_FRAMES == 4
  53. #error "REPACK is not compatible with BYTES_PER_FRAME=4"
  54. #endif
  55. #define LOCK mutex_lock(outputbuf->mutex)
  56. #define UNLOCK mutex_unlock(outputbuf->mutex)
  57. #define FRAME_BLOCK MAX_SILENCE_FRAMES
  58. #define FRAME_TO_BYTES(f) f*out_bytes_per_frame
  59. #define BYTES_TO_FRAME(b) b/out_bytes_per_frame
  60. static int out_bytes_per_frame;
  61. static thread_type thread;
  62. static int _dac_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  63. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr);
  64. static void *output_thread_dac();
  65. extern void wait_for_frames(size_t frames, uint8_t pct);
  66. /****************************************************************************************
  67. * set output volume
  68. */
  69. void set_volume_dac(unsigned left, unsigned right) {
  70. LOG_DEBUG("setting internal gain left: %u right: %u", left, right);
  71. LOCK;
  72. output.gainL = left;
  73. output.gainR = right;
  74. UNLOCK;
  75. }
  76. /****************************************************************************************
  77. * Initialize the DAC output
  78. */
  79. void output_init_dac(log_level level, char *device, unsigned output_buf_size, char *params, unsigned rates[], unsigned rate_delay, unsigned idle) {
  80. loglevel = level;
  81. LOG_INFO("Init output DAC.");
  82. LOG_DEBUG("Setting output parameters.");
  83. memset(&output, 0, sizeof(output));
  84. #ifdef CONFIG_I2S_BITS_PER_CHANNEL
  85. switch (CONFIG_I2S_BITS_PER_CHANNEL) {
  86. case 24:
  87. output.format = S24_BE;
  88. break;
  89. case 16:
  90. output.format = S16_BE;
  91. break;
  92. case 8:
  93. output.format = S8_BE;
  94. break;
  95. default:
  96. LOG_ERROR("Unsupported bit depth %d",CONFIG_I2S_BITS_PER_CHANNEL);
  97. break;
  98. }
  99. #else
  100. output.format = S16_LE;
  101. #endif
  102. // ensure output rate is specified to avoid test open
  103. if (!rates[0]) {
  104. rates[0] = 44100;
  105. }
  106. running=true;
  107. // todo: move this to a hardware abstraction layer
  108. //hal_dac_init(device);
  109. // get common output configuration details
  110. output_init_common(level, device, output_buf_size, rates, idle);
  111. out_bytes_per_frame = get_bytes_per_frame(output.format);
  112. output.start_frames = FRAME_BLOCK;
  113. output.write_cb = &_dac_write_frames;
  114. output.rate_delay = rate_delay;
  115. i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_TX; // Only TX
  116. i2s_config.sample_rate = output.current_sample_rate;
  117. i2s_config.bits_per_sample = get_bytes_per_frame(output.format) * 8/2;
  118. i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT; //2-channels
  119. i2s_config.communication_format = I2S_COMM_FORMAT_I2S| I2S_COMM_FORMAT_I2S_MSB;
  120. // todo: tune this parameter. Expressed in number of samples. Byte size depends on bit depth.
  121. i2s_config.dma_buf_count = 10;
  122. // From the I2S driver source, the DMA buffer size is 4092 bytes.
  123. // so buf_len * 2 channels * 2 bytes/sample should be < 4092 or else it will be resized.
  124. i2s_config.dma_buf_len = FRAME_BLOCK/2;
  125. i2s_config.use_apll = false;
  126. i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; //Interrupt level 1
  127. i2s_pin_config_t pin_config = { .bck_io_num = CONFIG_I2S_BCK_IO, .ws_io_num =
  128. CONFIG_I2S_WS_IO, .data_out_num = CONFIG_I2S_DO_IO, .data_in_num = -1 //Not used
  129. };
  130. LOG_INFO("Initializing I2S with rate: %d, bits per sample: %d, buffer len: %d, number of buffers: %d ",
  131. i2s_config.sample_rate, i2s_config.bits_per_sample, i2s_config.dma_buf_len, i2s_config.dma_buf_count);
  132. i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  133. i2s_set_pin(CONFIG_I2S_NUM, &pin_config);
  134. i2s_set_clk(CONFIG_I2S_NUM, output.current_sample_rate, i2s_config.bits_per_sample, 2);
  135. isI2SStarted=false;
  136. i2s_stop(CONFIG_I2S_NUM);
  137. dac_buffer_size = 5*FRAME_BLOCK*get_bytes_per_frame(output.format);
  138. LOG_DEBUG("Allocating local DAC transfer buffer of %u bytes.",dac_buffer_size);
  139. buf_init(dacbuffer,dac_buffer_size );
  140. if (!dacbuffer->buf) {
  141. LOG_ERROR("unable to malloc i2s buffer");
  142. local_exit(0);
  143. }
  144. PTHREAD_SET_NAME("output_dac");
  145. #if LINUX || OSX || FREEBSD || POSIX
  146. pthread_attr_t attr;
  147. pthread_attr_init(&attr);
  148. #ifdef PTHREAD_STACK_MIN
  149. pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + OUTPUT_THREAD_STACK_SIZE);
  150. #endif
  151. pthread_create(&thread, &attr, output_thread_dac, NULL);
  152. pthread_attr_destroy(&attr);
  153. #endif
  154. #if WIN
  155. thread = CreateThread(NULL, OUTPUT_THREAD_STACK_SIZE, (LPTHREAD_START_ROUTINE)&output_thread, NULL, 0, NULL);
  156. #endif
  157. LOG_INFO("Init completed.");
  158. }
  159. /****************************************************************************************
  160. * Terminate DAC output
  161. */
  162. void output_close_dac(void) {
  163. LOG_INFO("close output");
  164. LOCK;
  165. running = false;
  166. UNLOCK;
  167. i2s_driver_uninstall(CONFIG_I2S_NUM);
  168. output_close_common();
  169. buf_destroy(dacbuffer);
  170. }
  171. /****************************************************************************************
  172. * Write frames to the output buffer
  173. */
  174. static int _dac_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  175. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr) {
  176. size_t actual_out_bytes=FRAME_TO_BYTES(out_frames);
  177. assert(out_bytes_per_frame>0);
  178. if (!silence) {
  179. if (output.fade == FADE_ACTIVE && output.fade_dir == FADE_CROSS && *cross_ptr) {
  180. _apply_cross(outputbuf, out_frames, cross_gain_in, cross_gain_out, cross_ptr);
  181. }
  182. #if !REPACK
  183. if (gainL != FIXED_ONE || gainR!= FIXED_ONE) {
  184. _apply_gain(outputbuf, out_frames, gainL, gainR);
  185. }
  186. IF_DSD(
  187. if (output.outfmt == DOP) {
  188. update_dop((u32_t *) outputbuf->readp, out_frames, output.invert);
  189. } else if (output.outfmt != PCM && output.invert)
  190. dsd_invert((u32_t *) outputbuf->readp, out_frames);
  191. )
  192. memcpy(dacbuffer->writep, outputbuf->readp, actual_out_bytes);
  193. #else
  194. obuf = outputbuf->readp;
  195. #endif
  196. } else {
  197. #if !REPACK
  198. IF_DSD(
  199. if (output.outfmt != PCM) {
  200. obuf = silencebuf_dsd;
  201. update_dop((u32_t *) obuf, out_frames, false); // don't invert silence
  202. }
  203. )
  204. memcpy(dacbuffer->writep, silencebuf, actual_out_bytes);
  205. #endif
  206. }
  207. #if REPACK
  208. _scale_and_pack_frames(optr, (s32_t *)(void *)obuf, out_frames, gainL, gainR, output.format);
  209. #endif
  210. _buf_inc_writep(dacbuffer,actual_out_bytes);
  211. return (int)BYTES_TO_FRAME(actual_out_bytes);
  212. }
  213. /****************************************************************************************
  214. * Main output thread
  215. */
  216. static void *output_thread_dac() {
  217. frames_t frames=0;
  218. frames_t available_frames_space=0;
  219. size_t bytes_to_send_i2s=0, // Contiguous buffer which can be addressed
  220. i2s_bytes_written = 0,
  221. i2s_total_bytes_written=0; //actual size that the i2s port was able to write
  222. uint32_t timer_start=0;
  223. static int count = 0;
  224. output_state state;
  225. DECLARE_ALL_MIN_MAX;
  226. while (running) {
  227. i2s_bytes_written=0;
  228. frames=0;
  229. available_frames_space=0;
  230. bytes_to_send_i2s=0, // Contiguous buffer which can be addressed
  231. i2s_bytes_written = 0; //actual size that the i2s port was able to write
  232. TIME_MEASUREMENT_START(timer_start);
  233. LOCK;
  234. state =output.state;
  235. if (output.state == OUTPUT_OFF) {
  236. UNLOCK;
  237. LOG_INFO("Output state is off.");
  238. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(dacbuffer),_buf_cont_read(dacbuffer));
  239. if(isI2SStarted) {
  240. isI2SStarted=false;
  241. i2s_stop(CONFIG_I2S_NUM);
  242. }
  243. usleep(200000);
  244. continue;
  245. }
  246. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(dacbuffer),_buf_cont_read(dacbuffer));
  247. output.device_frames =0;
  248. output.updated = gettime_ms();
  249. output.frames_played_dmp = output.frames_played;
  250. do{
  251. // fill our buffer
  252. available_frames_space = BYTES_TO_FRAME(min(_buf_space(dacbuffer), _buf_cont_write(dacbuffer)));
  253. if(available_frames_space)
  254. {
  255. frames = _output_frames( available_frames_space ); // Keep the transfer buffer full
  256. SET_MIN_MAX( available_frames_space,req);
  257. SET_MIN_MAX(frames,rec);
  258. }
  259. }while(available_frames_space>0 && frames>0);
  260. SET_MIN_MAX_SIZED(_buf_used(outputbuf),o,outputbuf->size);
  261. SET_MIN_MAX_SIZED(_buf_used(streambuf),s,streambuf->size);
  262. UNLOCK;
  263. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(dacbuffer),_buf_cont_read(dacbuffer));
  264. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),buffering);
  265. SET_MIN_MAX_SIZED(_buf_used(dacbuffer),loci2sbuf,dacbuffer->size);
  266. bytes_to_send_i2s = _buf_cont_read(dacbuffer);
  267. SET_MIN_MAX(bytes_to_send_i2s,i2savailable);
  268. i2s_total_bytes_written=0;
  269. while (bytes_to_send_i2s>0 )
  270. {
  271. // now send all the data
  272. TIME_MEASUREMENT_START(timer_start);
  273. if(!isI2SStarted)
  274. {
  275. isI2SStarted=true;
  276. LOG_INFO("Restarting I2S.");
  277. i2s_start(CONFIG_I2S_NUM);
  278. if( i2s_config.sample_rate != output.current_sample_rate)
  279. {
  280. i2s_config.sample_rate = output.current_sample_rate;
  281. i2s_set_sample_rates(CONFIG_I2S_NUM, i2s_config.sample_rate);
  282. }
  283. }
  284. count++;
  285. LOG_SDEBUG("Outputting to I2S");
  286. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(dacbuffer),_buf_cont_read(dacbuffer));
  287. i2s_write(CONFIG_I2S_NUM, dacbuffer->readp,bytes_to_send_i2s, &i2s_bytes_written, portMAX_DELAY);
  288. _buf_inc_readp(dacbuffer,i2s_bytes_written);
  289. if(i2s_bytes_written!=bytes_to_send_i2s)
  290. {
  291. LOG_WARN("I2S DMA Overflow! available bytes: %d, I2S wrote %d bytes", bytes_to_send_i2s,i2s_bytes_written);
  292. }
  293. LOG_SDEBUG("DONE Outputting to I2S. Wrote: %d bytes out of %d", i2s_bytes_written,bytes_to_send_i2s);
  294. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(dacbuffer),_buf_cont_read(dacbuffer));
  295. i2s_total_bytes_written+=i2s_bytes_written;
  296. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),i2s_time);
  297. if(bytes_to_send_i2s>0) {
  298. SET_MIN_MAX(bytes_to_send_i2s-i2s_bytes_written,over);
  299. }
  300. bytes_to_send_i2s = _buf_cont_read(dacbuffer);
  301. SET_MIN_MAX(bytes_to_send_i2s,i2savailable);
  302. }
  303. /*
  304. * Statistics reporting
  305. */
  306. count++;
  307. TIMED_SECTION_START_MS(STATS_PERIOD_MS);
  308. if(state>OUTPUT_STOPPED){
  309. LOG_INFO( "count:%d, Output State: %d, current sample rate: %d, bytes per frame: %d, avg cycle duration (ms): %d",count,state,output.current_sample_rate, out_bytes_per_frame,STATS_PERIOD_MS/count);
  310. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD1);
  311. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD2);
  312. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD3);
  313. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD4);
  314. LOG_INFO(LINE_MIN_MAX_FORMAT_STREAM, LINE_MIN_MAX_STREAM("stream",s));
  315. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("output",o));
  316. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("dac buf used",loci2sbuf));
  317. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  318. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("i2swrite",i2savailable));
  319. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("requested",req));
  320. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("received",rec));
  321. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("overflow",over));
  322. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  323. LOG_INFO("");
  324. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  325. LOG_INFO(" max (us) | min (us) | avg(us) | count | ");
  326. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  327. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("Buffering(us)",buffering));
  328. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("i2s tfr(us)",i2s_time));
  329. LOG_INFO(" ----------+----------+-----------+-----------+");
  330. RESET_ALL_MIN_MAX;
  331. }
  332. else {
  333. LOG_INFO( "count:%d, Output State: %d",count,state);
  334. }
  335. count=0;
  336. TIMED_SECTION_END;
  337. /*
  338. * End Statistics reporting
  339. */
  340. }
  341. return 0;
  342. }
  343. bool test_open(const char *device, unsigned rates[], bool userdef_rates) {
  344. unsigned _rates[] = { 96000, 88200, 48000, 44100, 32000, 0 };
  345. memcpy(rates, _rates, sizeof(_rates));
  346. return true;
  347. }