2
0

output_dac.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. #include "squeezelite.h"
  2. #include "driver/i2s.h"
  3. #include <signal.h>
  4. #define I2S_NUM (0)
  5. #define I2S_BCK_IO (GPIO_NUM_26)
  6. #define I2S_WS_IO (GPIO_NUM_25)
  7. #define I2S_DO_IO (GPIO_NUM_22)
  8. #define I2S_DI_IO (-1)
  9. #define TIMED_SECTION_START_MS_FORCE(x,force) { static time_t __aa_time_start = 0; if(hasTimeElapsed(&__aa_time_start,x,force)) {
  10. #define TIMED_SECTION_START_MS(x) { static time_t __aa_time_start = 0; if(hasTimeElapsed(&__aa_time_start,x,false)){
  11. #define TIMED_SECTION_START_FORCE(x,force) TIMED_SECTION_START_MS(x * 1000UL,force)
  12. #define TIMED_SECTION_START(x) TIMED_SECTION_START_MS(x * 1000UL)
  13. #define TIMED_SECTION_END }}
  14. static log_level loglevel;
  15. static bool running = true;
  16. static bool isI2SStarted=false;
  17. extern struct outputstate output;
  18. extern struct buffer *streambuf;
  19. extern struct buffer *outputbuf;
  20. static i2s_config_t i2s_config;
  21. #if REPACK && BYTES_PER_FRAMES == 4
  22. #error "REPACK is not compatible with BYTES_PER_FRAME=4"
  23. #endif
  24. #define LOCK mutex_lock(outputbuf->mutex)
  25. #define UNLOCK mutex_unlock(outputbuf->mutex)
  26. #define FRAME_BLOCK MAX_SILENCE_FRAMES
  27. #define DAC_OUTPUT_BUFFER_FRAMES FRAME_BLOCK
  28. #define DAC_OUTPUT_BUFFER_RESERVE FRAME_BLOCK/2
  29. #define I2S_FRAME_SIZE 256
  30. #define FRAME_TO_BYTES(f) f*BYTES_PER_FRAME
  31. #define BYTES_TO_FRAME(b) b/BYTES_PER_FRAME
  32. #define FRAMES_TO_MS(f) 1000*f/output.current_sample_rate
  33. #define BYTES_TO_MS(b) FRAMES_TO_MS(BYTES_TO_FRAME(b))
  34. #define SET_MIN_MAX(val,var) var=val; if(var<min_##var) min_##var=var; if(var>max_##var) max_##var=var
  35. #define RESET_MIN_MAX(var,mv) min_##var=mv##_MAX; max_##var=mv##_MIN
  36. #define DECLARE_MIN_MAX(var,t,mv) static t min_##var = mv##_MAX, max_##var = mv##_MIN; t var=0
  37. #define DECLARE_ALL_MIN_MAX DECLARE_MIN_MAX(req, long,LONG); DECLARE_MIN_MAX(o, long,LONG); DECLARE_MIN_MAX(s, long,LONG); DECLARE_MIN_MAX(d, long,LONG); DECLARE_MIN_MAX(duration, long,LONG);DECLARE_MIN_MAX(buffering, long,LONG);DECLARE_MIN_MAX(totalprocess, long,LONG);
  38. #define RESET_ALL_MIN_MAX RESET_MIN_MAX(d,LONG); RESET_MIN_MAX(o,LONG); RESET_MIN_MAX(s,LONG); RESET_MIN_MAX(req,LONG); RESET_MIN_MAX(duration,LONG);RESET_MIN_MAX(buffering,LONG);RESET_MIN_MAX(totalprocess,LONG);
  39. extern u8_t *silencebuf;
  40. static u8_t *optr;
  41. static int bytes_per_frame;
  42. static thread_type thread;
  43. static int _dac_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  44. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr);
  45. static void *output_thread();
  46. bool hasTimeElapsed(time_t * lastTime, time_t delayMS, bool bforce)
  47. {
  48. if (*lastTime <= gettime_ms() ||bforce)
  49. {
  50. *lastTime = gettime_ms() + delayMS;
  51. return true;
  52. }
  53. else
  54. return false;
  55. }
  56. void set_volume(unsigned left, unsigned right) {
  57. LOG_DEBUG("setting internal gain left: %u right: %u", left, right);
  58. LOCK;
  59. output.gainL = left;
  60. output.gainR = right;
  61. UNLOCK;
  62. }
  63. void output_init_dac(log_level level, char *device, unsigned output_buf_size, char *params, unsigned rates[], unsigned rate_delay, unsigned idle) {
  64. loglevel = level;
  65. optr = malloc(FRAME_TO_BYTES(DAC_OUTPUT_BUFFER_FRAMES));
  66. if (!optr) {
  67. LOG_ERROR("unable to malloc buf");
  68. return;
  69. }
  70. LOG_INFO("init output DAC");
  71. memset(&output, 0, sizeof(output));
  72. #if BYTES_PER_FRAME == 4
  73. output.format = S16_LE;
  74. #else
  75. output.format = S32_LE;
  76. #endif
  77. output.start_frames = DAC_OUTPUT_BUFFER_FRAMES*2;
  78. output.write_cb = &_dac_write_frames;
  79. output.rate_delay = rate_delay;
  80. if (params) {
  81. if (!strcmp(params, "32")) output.format = S32_LE;
  82. if (!strcmp(params, "24")) output.format = S24_3LE;
  83. if (!strcmp(params, "16")) output.format = S16_LE;
  84. }
  85. // ensure output rate is specified to avoid test open
  86. if (!rates[0]) {
  87. rates[0] = 44100;
  88. }
  89. output_init_common(level, device, output_buf_size, rates, idle);
  90. i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_TX; // Only TX
  91. i2s_config.sample_rate = output.current_sample_rate;
  92. i2s_config.bits_per_sample = BYTES_PER_FRAME * 8/2;
  93. i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT; //2-channels
  94. i2s_config.communication_format = I2S_COMM_FORMAT_I2S
  95. | (output.format==S16_LE||output.format==S32_LE||output.format==S24_3LE)?I2S_COMM_FORMAT_I2S_LSB:I2S_COMM_FORMAT_I2S_MSB;
  96. i2s_config.dma_buf_count = 6; //todo: tune this parameter. Expressed in numbrer of buffers.
  97. i2s_config.dma_buf_len = I2S_FRAME_SIZE; // todo: tune this parameter. Expressed in number of samples. Byte size depends on bit depth
  98. i2s_config.use_apll = false;
  99. i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; //Interrupt level 1
  100. i2s_pin_config_t pin_config = { .bck_io_num = I2S_BCK_IO, .ws_io_num =
  101. I2S_WS_IO, .data_out_num = I2S_DO_IO, .data_in_num = I2S_DI_IO //Not used
  102. };
  103. LOG_INFO("Initializing I2S with rate: %d, bits per sample: %d, buffer len: %d, number of buffers: %d ",
  104. i2s_config.sample_rate, i2s_config.bits_per_sample, i2s_config.dma_buf_len, i2s_config.dma_buf_count);
  105. i2s_driver_install(I2S_NUM, &i2s_config, 0, NULL);
  106. i2s_set_pin(I2S_NUM, &pin_config);
  107. i2s_set_clk(I2S_NUM, output.current_sample_rate, i2s_config.bits_per_sample, 2);
  108. isI2SStarted=false;
  109. i2s_stop(I2S_NUM);
  110. #if LINUX || OSX || FREEBSD || POSIX
  111. pthread_attr_t attr;
  112. pthread_attr_init(&attr);
  113. #ifdef PTHREAD_STACK_MIN
  114. pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + OUTPUT_THREAD_STACK_SIZE);
  115. #endif
  116. pthread_create(&thread, &attr, output_thread, NULL);
  117. pthread_attr_destroy(&attr);
  118. #endif
  119. #if WIN
  120. thread = CreateThread(NULL, OUTPUT_THREAD_STACK_SIZE, (LPTHREAD_START_ROUTINE)&output_thread, NULL, 0, NULL);
  121. #endif
  122. }
  123. void output_close_dac(void) {
  124. LOG_INFO("close output");
  125. LOCK;
  126. running = false;
  127. UNLOCK;
  128. free(optr);
  129. output_close_common();
  130. }
  131. static int _dac_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  132. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr) {
  133. u8_t *obuf;
  134. if (!silence) {
  135. if (output.fade == FADE_ACTIVE && output.fade_dir == FADE_CROSS && *cross_ptr) {
  136. _apply_cross(outputbuf, out_frames, cross_gain_in, cross_gain_out, cross_ptr);
  137. }
  138. #if !REPACK
  139. if (gainL != FIXED_ONE || gainR!= FIXED_ONE) {
  140. _apply_gain(outputbuf, out_frames, gainL, gainR);
  141. }
  142. IF_DSD(
  143. if (output.outfmt == DOP) {
  144. update_dop((u32_t *) outputbuf->readp, out_frames, output.invert);
  145. } else if (output.outfmt != PCM && output.invert)
  146. dsd_invert((u32_t *) outputbuf->readp, out_frames);
  147. )
  148. memcpy(optr, outputbuf->readp, out_frames * BYTES_PER_FRAME);
  149. #else
  150. obuf = outputbuf->readp;
  151. #endif
  152. } else {
  153. obuf = silencebuf;
  154. #if !REPACK
  155. IF_DSD(
  156. if (output.outfmt != PCM) {
  157. obuf = silencebuf_dsd;
  158. update_dop((u32_t *) obuf, out_frames, false); // don't invert silence
  159. }
  160. )
  161. memcpy(optr, obuf, out_frames * BYTES_PER_FRAME);
  162. #endif
  163. }
  164. #if REPACK
  165. _scale_and_pack_frames(optr, (s32_t *)(void *)obuf, out_frames, gainL, gainR, output.format);
  166. #endif
  167. // TIMED_SECTION_START_MS(500);
  168. // LOG_INFO("Done moving data to out buffer");
  169. // TIMED_SECTION_END;
  170. return (int)out_frames;
  171. }
  172. void wait_for_frames(size_t frames)
  173. {
  174. usleep((1000* frames/output.current_sample_rate) );
  175. }
  176. static void *output_thread() {
  177. // // buffer to hold output data so we can block on writing outside of output lock, allocated on init
  178. // u8_t *obuf = malloc(FRAME_BLOCK * BYTES_PER_FRAME);
  179. u8_t *opos=optr;
  180. frames_t frames=0, requested_frames = 0;
  181. size_t used_buffer=0;
  182. static int count = 0, count2=0;
  183. uint32_t start_writing=0, start_i2s=0;
  184. DECLARE_ALL_MIN_MAX;
  185. size_t i2s_bytes_write, i2s_bytes_to_write = 0;
  186. #if REPACK
  187. LOCK;
  188. switch (output.format) {
  189. case S32_BE:
  190. case S32_LE:
  191. bytes_per_frame = 4 * 2; break;
  192. case S24_3LE:
  193. case S24_3BE:
  194. bytes_per_frame = 3 * 2; break;
  195. case S16_LE:
  196. case S16_BE:
  197. bytes_per_frame = 2 * 2; break;
  198. default:
  199. bytes_per_frame = 4 * 2; break;
  200. break;
  201. }
  202. UNLOCK;
  203. #else
  204. bytes_per_frame = BYTES_PER_FRAME;
  205. #endif
  206. while (running) {
  207. start_writing=esp_timer_get_time();
  208. LOCK;
  209. if (output.state == OUTPUT_OFF) {
  210. UNLOCK;
  211. LOG_INFO("Output state is off.");
  212. isI2SStarted=false;
  213. i2s_stop(I2S_NUM);
  214. usleep(500000);
  215. continue;
  216. }
  217. requested_frames = 0;
  218. frames=0;
  219. if(used_buffer==0)
  220. {
  221. // replenish buffer when it's empty
  222. opos=optr;
  223. requested_frames =DAC_OUTPUT_BUFFER_FRAMES;
  224. frames = _output_frames( requested_frames ); // Keep the dma buffer full
  225. used_buffer+=FRAME_TO_BYTES(frames);
  226. }
  227. UNLOCK;
  228. if(frames>0) SET_MIN_MAX((esp_timer_get_time()-start_writing)/1000,buffering);
  229. // todo: call i2s_set_clock here if rate is changed
  230. if (used_buffer )
  231. {
  232. start_i2s=esp_timer_get_time();
  233. if(!isI2SStarted)
  234. {
  235. isI2SStarted=true;
  236. i2s_start(I2S_NUM);
  237. }
  238. i2s_write(I2S_NUM, opos,used_buffer, &i2s_bytes_write, portMAX_DELAY);
  239. if(i2s_bytes_write!=used_buffer)
  240. {
  241. LOG_WARN("I2S DMA Overflow! available bytes: %d, I2S wrote %d bytes", used_buffer,i2s_bytes_write);
  242. }
  243. used_buffer -= i2s_bytes_write;
  244. opos+=i2s_bytes_write;
  245. output.device_frames =BYTES_TO_FRAME(used_buffer);
  246. output.updated = gettime_ms();
  247. output.frames_played_dmp = output.frames_played-output.device_frames;
  248. SET_MIN_MAX((esp_timer_get_time()-start_i2s)/1000,duration);
  249. }
  250. SET_MIN_MAX(duration+frames>0?buffering:0,totalprocess);
  251. SET_MIN_MAX(_buf_used(outputbuf),o);
  252. SET_MIN_MAX(_buf_used(streambuf),s);
  253. SET_MIN_MAX(used_buffer,d);
  254. SET_MIN_MAX(requested_frames,req);
  255. if (!(count++ & 0x1ff)) {
  256. LOG_INFO( "count:%d"
  257. "\n ----------+----------+-----------+ +----------+----------+----------------+"
  258. "\n max | min | current| | max | min | current |"
  259. "\n (ms) | (ms) | (ms)| | (frames) | (frames) | (frames)|"
  260. "\n ----------+----------+-----------+ +----------+----------+----------------+"
  261. "\nout %10d|%10d|%11d|" " |%10d|%10d|%16d|"
  262. "\nstream %10d|%10d|%11d|" " |%10d|%10d|%16d|"
  263. "\nDMA overflow %10d|%10d|%11d|" " |%10d|%10d|%16d|"
  264. "\nrequested %10d|%10d|%11d|" " |%10d|%10d|%16d|"
  265. "\n ----------+----------+-----------+ +----------+----------+----------------+"
  266. "\n"
  267. "\n max (us) | min (us) | total(us) | "
  268. "\n ----------+----------+-----------+ "
  269. "\ni2s time (us):%10d|%10d|%11d|"
  270. "\nbuffering(us):%10d|%10d|%11d|"
  271. "\ntotal(us) :%10d|%10d|%11d|"
  272. "\n ----------+----------+-----------+ ",
  273. count,
  274. BYTES_TO_MS(max_o), BYTES_TO_MS(min_o),BYTES_TO_MS(o),max_o,min_o,o,
  275. BYTES_TO_MS(max_s), BYTES_TO_MS(min_s),BYTES_TO_MS(s),max_s,min_s,s,
  276. BYTES_TO_MS(max_d),BYTES_TO_MS(min_d),BYTES_TO_MS(d),max_d,min_d,d,
  277. FRAMES_TO_MS(max_req),FRAMES_TO_MS(min_req),FRAMES_TO_MS(req), max_req, min_req,req,
  278. max_duration, min_duration, duration,
  279. max_buffering, min_buffering, buffering,
  280. max_totalprocess,min_totalprocess,totalprocess
  281. );
  282. RESET_ALL_MIN_MAX;
  283. }
  284. }
  285. return 0;
  286. }
  287. bool test_open(const char *device, unsigned rates[], bool userdef_rates) {
  288. unsigned _rates[] = { 96000, 88200, 48000, 44100, 32000, 0 };
  289. memcpy(rates, _rates, sizeof(_rates));
  290. return true;
  291. }