output_i2s.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /*
  2. * Squeezelite for esp32
  3. *
  4. * (c) Sebastien 2019
  5. * Philippe G. 2019, philippe_44@outlook.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. /*
  22. Synchronisation is a bit of a hack with i2s. The esp32 driver is always
  23. full when it starts, so there is a delay of the total length of buffers.
  24. In other words, i2w_write blocks at first call, until at least one buffer
  25. has been written (it uses a queue with produce / consume).
  26. The first hack is to consume that length at the beginning of tracks when
  27. synchronization is active. It's about ~180ms @ 44.1kHz
  28. The second hack is that we never know exactly the number of frames in the
  29. DMA buffers when we update the output.frames_played_dmp. We assume that
  30. after i2s_write, these buffers are always full so by measuring the gap
  31. between time after i2s_write and update of frames_played_dmp, we have a
  32. good idea of the error.
  33. The third hack is when sample rate changes, buffers are reset and we also
  34. do the change too early, but can't do that exaclty at the right time. So
  35. there might be a pop and a de-sync when sampling rate change happens. Not
  36. sure that using rate_delay would fix that
  37. */
  38. #include "squeezelite.h"
  39. #include "driver/i2s.h"
  40. #include "perf_trace.h"
  41. #include <signal.h>
  42. #include "time.h"
  43. #define LOCK mutex_lock(outputbuf->mutex)
  44. #define UNLOCK mutex_unlock(outputbuf->mutex)
  45. #define FRAME_BLOCK MAX_SILENCE_FRAMES
  46. // Prevent compile errors if dac output is
  47. // included in the build and not actually activated in menuconfig
  48. #ifndef CONFIG_I2S_BCK_IO
  49. #define CONFIG_I2S_BCK_IO -1
  50. #endif
  51. #ifndef CONFIG_I2S_WS_IO
  52. #define CONFIG_I2S_WS_IO -1
  53. #endif
  54. #ifndef CONFIG_I2S_DO_IO
  55. #define CONFIG_I2S_DO_IO -1
  56. #endif
  57. #ifndef CONFIG_I2S_NUM
  58. #define CONFIG_I2S_NUM -1
  59. #endif
  60. // must have an integer ratio with FRAME_BLOCK
  61. #define DMA_BUF_LEN 512
  62. #define DMA_BUF_COUNT 16
  63. #define DECLARE_ALL_MIN_MAX \
  64. DECLARE_MIN_MAX(o); \
  65. DECLARE_MIN_MAX(s); \
  66. DECLARE_MIN_MAX(rec); \
  67. DECLARE_MIN_MAX(i2s_time); \
  68. DECLARE_MIN_MAX(buffering);
  69. #define RESET_ALL_MIN_MAX \
  70. RESET_MIN_MAX(o); \
  71. RESET_MIN_MAX(s); \
  72. RESET_MIN_MAX(rec); \
  73. RESET_MIN_MAX(i2s_time); \
  74. RESET_MIN_MAX(buffering);
  75. #define STATS_PERIOD_MS 5000
  76. extern struct outputstate output;
  77. extern struct buffer *streambuf;
  78. extern struct buffer *outputbuf;
  79. extern u8_t *silencebuf;
  80. static log_level loglevel;
  81. static bool running, isI2SStarted;
  82. static i2s_config_t i2s_config;
  83. static int bytes_per_frame;
  84. static thread_type thread, stats_thread;
  85. static u8_t *obuf;
  86. DECLARE_ALL_MIN_MAX;
  87. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  88. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr);
  89. static void *output_thread_i2s();
  90. static void *output_thread_i2s_stats();
  91. /****************************************************************************************
  92. * Initialize the DAC output
  93. */
  94. void output_init_i2s(log_level level, char *device, unsigned output_buf_size, char *params, unsigned rates[], unsigned rate_delay, unsigned idle) {
  95. loglevel = level;
  96. #ifdef CONFIG_I2S_BITS_PER_CHANNEL
  97. switch (CONFIG_I2S_BITS_PER_CHANNEL) {
  98. case 24:
  99. output.format = S24_BE;
  100. bytes_per_frame = 2*3;
  101. break;
  102. case 16:
  103. output.format = S16_BE;
  104. bytes_per_frame = 2*2;
  105. break;
  106. case 8:
  107. output.format = S8_BE;
  108. bytes_per_frame = 2*4;
  109. break;
  110. default:
  111. LOG_ERROR("Unsupported bit depth %d",CONFIG_I2S_BITS_PER_CHANNEL);
  112. break;
  113. }
  114. #else
  115. output.format = S16_LE;
  116. bytes_per_frame = 2*2;
  117. #endif
  118. output.write_cb = &_i2s_write_frames;
  119. obuf = malloc(FRAME_BLOCK * bytes_per_frame);
  120. if (!obuf) {
  121. LOG_ERROR("Cannot allocate i2s buffer");
  122. return;
  123. }
  124. running=true;
  125. i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_TX;
  126. i2s_config.sample_rate = output.current_sample_rate;
  127. i2s_config.bits_per_sample = bytes_per_frame * 8 / 2;
  128. i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
  129. i2s_config.communication_format = I2S_COMM_FORMAT_I2S| I2S_COMM_FORMAT_I2S_MSB;
  130. // in case of overflow, do not replay old buffer
  131. i2s_config.tx_desc_auto_clear = true;
  132. i2s_config.dma_buf_count = DMA_BUF_COUNT;
  133. // Counted in frames (but i2s allocates a buffer <= 4092 bytes)
  134. i2s_config.dma_buf_len = DMA_BUF_LEN;
  135. i2s_config.use_apll = true;
  136. i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; //Interrupt level 1
  137. i2s_pin_config_t pin_config = { .bck_io_num = CONFIG_I2S_BCK_IO, .ws_io_num =
  138. CONFIG_I2S_WS_IO, .data_out_num = CONFIG_I2S_DO_IO, .data_in_num = -1 //Not used
  139. };
  140. LOG_INFO("Initializing I2S with rate: %d, bits per sample: %d, buffer frames: %d, number of buffers: %d ",
  141. i2s_config.sample_rate, i2s_config.bits_per_sample, i2s_config.dma_buf_len, i2s_config.dma_buf_count);
  142. i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  143. i2s_set_pin(CONFIG_I2S_NUM, &pin_config);
  144. i2s_stop(CONFIG_I2S_NUM);
  145. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  146. isI2SStarted=false;
  147. pthread_attr_t attr;
  148. pthread_attr_init(&attr);
  149. pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + OUTPUT_THREAD_STACK_SIZE);
  150. pthread_create_name(&thread, &attr, output_thread_i2s, NULL, "output_i2s");
  151. pthread_attr_destroy(&attr);
  152. // leave stack size to default
  153. pthread_create_name(&stats_thread, NULL, output_thread_i2s_stats, NULL, "output_i2s_sts");
  154. }
  155. /****************************************************************************************
  156. * Terminate DAC output
  157. */
  158. void output_close_i2s(void) {
  159. LOCK;
  160. running = false;
  161. UNLOCK;
  162. pthread_join(thread, NULL);
  163. pthread_join(stats_thread, NULL);
  164. i2s_driver_uninstall(CONFIG_I2S_NUM);
  165. free(obuf);
  166. }
  167. /****************************************************************************************
  168. * Write frames to the output buffer
  169. */
  170. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  171. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr) {
  172. #if BYTES_PER_FRAME == 8
  173. s32_t *optr;
  174. #endif
  175. if (!silence) {
  176. if (output.fade == FADE_ACTIVE && output.fade_dir == FADE_CROSS && *cross_ptr) {
  177. _apply_cross(outputbuf, out_frames, cross_gain_in, cross_gain_out, cross_ptr);
  178. }
  179. #if BYTES_PER_FRAME == 4
  180. if (gainL != FIXED_ONE || gainR!= FIXED_ONE) {
  181. _apply_gain(outputbuf, out_frames, gainL, gainR);
  182. }
  183. memcpy(obuf, outputbuf->readp, out_frames * bytes_per_frame);
  184. #else
  185. optr = (s32_t*) outputbuf->readp;
  186. #endif
  187. } else {
  188. #if BYTES_PER_FRAME == 4
  189. memcpy(obuf, silencebuf, out_frames * bytes_per_frame);
  190. #else
  191. optr = (s32_t*) silencebuf;
  192. #endif
  193. }
  194. #if BYTES_PER_FRAME == 8
  195. IF_DSD(
  196. if (output.outfmt == DOP) {
  197. update_dop((u32_t *) optr, out_frames, output.invert);
  198. } else if (output.outfmt != PCM && output.invert)
  199. dsd_invert((u32_t *) optr, out_frames);
  200. )
  201. _scale_and_pack_frames(obuf, optr, out_frames, gainL, gainR, output.format);
  202. #endif
  203. return out_frames;
  204. }
  205. /****************************************************************************************
  206. * Main output thread
  207. */
  208. static void *output_thread_i2s() {
  209. frames_t frames = 0;
  210. size_t bytes;
  211. uint32_t timer_start = 0;
  212. int discard = DMA_BUF_COUNT * DMA_BUF_LEN;
  213. uint32_t jitter = gettime_ms();
  214. while (running) {
  215. TIME_MEASUREMENT_START(timer_start);
  216. LOCK;
  217. if (output.state == OUTPUT_OFF) {
  218. UNLOCK;
  219. LOG_INFO("Output state is off.");
  220. if (isI2SStarted) {
  221. isI2SStarted=false;
  222. i2s_stop(CONFIG_I2S_NUM);
  223. }
  224. usleep(200000);
  225. continue;
  226. }
  227. output.updated = gettime_ms();
  228. // try to estimate how much we have consumed from the DMA buffer
  229. output.frames_played_dmp = output.frames_played - ((output.updated - jitter) * output.current_sample_rate) / 1000;
  230. output.device_frames = DMA_BUF_COUNT * DMA_BUF_LEN;
  231. frames = _output_frames( FRAME_BLOCK );
  232. SET_MIN_MAX_SIZED(frames,rec,FRAME_BLOCK);
  233. SET_MIN_MAX_SIZED(_buf_used(outputbuf),o,outputbuf->size);
  234. SET_MIN_MAX_SIZED(_buf_used(streambuf),s,streambuf->size);
  235. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),buffering);
  236. // must skip first frames as buffer already filled with silence
  237. // if (output.state < OUTPUT_RUNNING || output.state == OUTPUT_START_AT) {
  238. if (output.state == OUTPUT_START_AT) {
  239. discard = DMA_BUF_COUNT * DMA_BUF_LEN;
  240. } else if (discard) {
  241. discard -= output.frames_played + frames;
  242. if (discard < 0) {
  243. frames += discard;
  244. discard = 0;
  245. } else {
  246. UNLOCK;
  247. continue;
  248. }
  249. }
  250. UNLOCK;
  251. // now send all the data
  252. TIME_MEASUREMENT_START(timer_start);
  253. if (!isI2SStarted ) {
  254. isI2SStarted = true;
  255. LOG_INFO("Restarting I2S.");
  256. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  257. i2s_start(CONFIG_I2S_NUM);
  258. }
  259. // this does not work well as set_sample_rates resets the fifos (and it's too early)
  260. if (i2s_config.sample_rate != output.current_sample_rate) {
  261. LOG_INFO("changing sampling rate %u to %u", i2s_config.sample_rate, output.current_sample_rate);
  262. i2s_config.sample_rate = output.current_sample_rate;
  263. i2s_set_sample_rates(CONFIG_I2S_NUM, i2s_config.sample_rate);
  264. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  265. }
  266. // we assume that here we have been able to entirely fill the DMA buffers
  267. i2s_write(CONFIG_I2S_NUM, obuf, frames * bytes_per_frame, &bytes, portMAX_DELAY);
  268. jitter = gettime_ms();
  269. if (bytes != frames * bytes_per_frame) {
  270. LOG_WARN("I2S DMA Overflow! available bytes: %d, I2S wrote %d bytes", frames * bytes_per_frame, bytes);
  271. }
  272. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),i2s_time);
  273. frames = 0;
  274. }
  275. return 0;
  276. }
  277. /****************************************************************************************
  278. * Stats output thread
  279. */
  280. static void *output_thread_i2s_stats() {
  281. while (running) {
  282. LOCK;
  283. output_state state = output.state;
  284. UNLOCK;
  285. if(state>OUTPUT_STOPPED){
  286. LOG_INFO( "Output State: %d, current sample rate: %d, bytes per frame: %d",state,output.current_sample_rate, bytes_per_frame);
  287. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD1);
  288. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD2);
  289. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD3);
  290. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD4);
  291. LOG_INFO(LINE_MIN_MAX_FORMAT_STREAM, LINE_MIN_MAX_STREAM("stream",s));
  292. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("output",o));
  293. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  294. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("received",rec));
  295. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  296. LOG_INFO("");
  297. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  298. LOG_INFO(" max (us) | min (us) | avg(us) | count | ");
  299. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  300. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("Buffering(us)",buffering));
  301. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("i2s tfr(us)",i2s_time));
  302. LOG_INFO(" ----------+----------+-----------+-----------+");
  303. RESET_ALL_MIN_MAX;
  304. }
  305. usleep(STATS_PERIOD_MS *1000);
  306. }
  307. return NULL;
  308. }