output_dac.c 13 KB

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