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