output_i2s.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /*
  2. * Squeezelite for esp32
  3. *
  4. * (c) Sebastien 2019
  5. * Philippe G. 2019, philippe_44@outlook.com
  6. *
  7. * This software is released under the MIT License.
  8. * https://opensource.org/licenses/MIT
  9. *
  10. */
  11. /*
  12. Synchronisation is a bit of a hack with i2s. The esp32 driver is always
  13. full when it starts, so there is a delay of the total length of buffers.
  14. In other words, i2s_write blocks at first call, until at least one buffer
  15. has been written (it uses a queue with produce / consume).
  16. The first hack is to consume that length at the beginning of tracks when
  17. synchronization is active. It's about ~180ms @ 44.1kHz
  18. The second hack is that we never know exactly the number of frames in the
  19. DMA buffers when we update the output.frames_played_dmp. We assume that
  20. after i2s_write, these buffers are always full so by measuring the gap
  21. between time after i2s_write and update of frames_played_dmp, we have a
  22. good idea of the error.
  23. The third hack is when sample rate changes, buffers are reset and we also
  24. do the change too early, but can't do that exaclty at the right time. So
  25. there might be a pop and a de-sync when sampling rate change happens. Not
  26. sure that using rate_delay would fix that
  27. */
  28. #include "squeezelite.h"
  29. #include "esp_pthread.h"
  30. #include "driver/i2s.h"
  31. #include "driver/i2c.h"
  32. #include "driver/gpio.h"
  33. #include "perf_trace.h"
  34. #include <signal.h>
  35. #include "adac.h"
  36. #include "time.h"
  37. #include "led.h"
  38. #include "monitor.h"
  39. #include "platform_config.h"
  40. #include "accessors.h"
  41. #include "equalizer.h"
  42. #include "globdefs.h"
  43. #define LOCK mutex_lock(outputbuf->mutex)
  44. #define UNLOCK mutex_unlock(outputbuf->mutex)
  45. #define FRAME_BLOCK MAX_SILENCE_FRAMES
  46. // must have an integer ratio with FRAME_BLOCK (see spdif comment)
  47. #define DMA_BUF_LEN 512
  48. #define DMA_BUF_COUNT 12
  49. #define DECLARE_ALL_MIN_MAX \
  50. DECLARE_MIN_MAX(o); \
  51. DECLARE_MIN_MAX(s); \
  52. DECLARE_MIN_MAX(rec); \
  53. DECLARE_MIN_MAX(i2s_time); \
  54. DECLARE_MIN_MAX(buffering);
  55. #define RESET_ALL_MIN_MAX \
  56. RESET_MIN_MAX(o); \
  57. RESET_MIN_MAX(s); \
  58. RESET_MIN_MAX(rec); \
  59. RESET_MIN_MAX(i2s_time); \
  60. RESET_MIN_MAX(buffering);
  61. #define STATS_PERIOD_MS 5000
  62. #define STAT_STACK_SIZE (3*1024)
  63. extern struct outputstate output;
  64. extern struct buffer *streambuf;
  65. extern struct buffer *outputbuf;
  66. extern u8_t *silencebuf;
  67. const struct adac_s *dac_set[] = { &dac_tas57xx, &dac_tas5713, &dac_ac101, NULL };
  68. const struct adac_s *adac = &dac_external;
  69. static log_level loglevel;
  70. static bool jack_mutes_amp;
  71. static bool running, isI2SStarted;
  72. static i2s_config_t i2s_config;
  73. static u8_t *obuf;
  74. static frames_t oframes;
  75. static bool spdif;
  76. static size_t dma_buf_frames;
  77. static pthread_t thread;
  78. static TaskHandle_t stats_task;
  79. static bool stats;
  80. static struct {
  81. int gpio, active;
  82. } amp_control = { -1, 1 },
  83. mute_control = { CONFIG_MUTE_GPIO, CONFIG_MUTE_GPIO_LEVEL };
  84. DECLARE_ALL_MIN_MAX;
  85. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  86. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr);
  87. static void *output_thread_i2s(void *arg);
  88. static void *output_thread_i2s_stats(void *arg);
  89. static void spdif_convert(ISAMPLE_T *src, size_t frames, u32_t *dst, size_t *count);
  90. static void (*jack_handler_chain)(bool inserted);
  91. #define I2C_PORT 0
  92. /****************************************************************************************
  93. * jack insertion handler
  94. */
  95. static void jack_handler(bool inserted) {
  96. // jack detection bounces a bit but that seems fine
  97. if (jack_mutes_amp) {
  98. LOG_INFO("switching amplifier %s", inserted ? "OFF" : "ON");
  99. if (inserted) adac->speaker(false);
  100. else adac->speaker(true);
  101. }
  102. // activate headset
  103. if (inserted) adac->headset(true);
  104. else adac->headset(false);
  105. // and chain if any
  106. if (jack_handler_chain) (jack_handler_chain)(inserted);
  107. }
  108. /****************************************************************************************
  109. * amp GPIO
  110. */
  111. static void set_amp_gpio(int gpio, char *value) {
  112. char *p;
  113. if (!strcasecmp(value, "amp")) {
  114. amp_control.gpio = gpio;
  115. if ((p = strchr(value, ':')) != NULL) amp_control.active = atoi(p + 1);
  116. gpio_pad_select_gpio(amp_control.gpio);
  117. gpio_set_direction(amp_control.gpio, GPIO_MODE_OUTPUT);
  118. gpio_set_level(amp_control.gpio, !amp_control.active);
  119. LOG_INFO("setting amplifier GPIO %d (active:%d)", amp_control.gpio, amp_control.active);
  120. }
  121. }
  122. /****************************************************************************************
  123. * Initialize the DAC output
  124. */
  125. void output_init_i2s(log_level level, char *device, unsigned output_buf_size, char *params, unsigned rates[], unsigned rate_delay, unsigned idle) {
  126. loglevel = level;
  127. char *p;
  128. esp_err_t res;
  129. p = config_alloc_get_default(NVS_TYPE_STR, "jack_mutes_amp", "n", 0);
  130. jack_mutes_amp = (strcmp(p,"1") == 0 ||strcasecmp(p,"y") == 0);
  131. free(p);
  132. #if BYTES_PER_FRAME == 8
  133. output.format = S32_LE;
  134. #else
  135. output.format = S16_LE;
  136. #endif
  137. output.write_cb = &_i2s_write_frames;
  138. obuf = malloc(FRAME_BLOCK * BYTES_PER_FRAME);
  139. if (!obuf) {
  140. LOG_ERROR("Cannot allocate i2s buffer");
  141. return;
  142. }
  143. running = true;
  144. i2s_pin_config_t i2s_pin_config = { .bck_io_num = -1, .ws_io_num = -1, .data_out_num = -1, .data_in_num = -1 };
  145. // get SPDIF configuration from NVS or compile
  146. char *spdif_config = config_alloc_get_str("spdif_config", CONFIG_SPDIF_CONFIG, "bck=" STR(CONFIG_SPDIF_BCK_IO)
  147. ",ws=" STR(CONFIG_SPDIF_WS_IO) ",do=" STR(CONFIG_SPDIF_DO_IO));
  148. if ((p = strcasestr(spdif_config, "do")) != NULL) i2s_pin_config.data_out_num = atoi(strchr(p, '=') + 1);
  149. // common I2S initialization
  150. i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_TX;
  151. i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
  152. i2s_config.communication_format = I2S_COMM_FORMAT_I2S| I2S_COMM_FORMAT_I2S_MSB;
  153. // in case of overflow, do not replay old buffer
  154. i2s_config.tx_desc_auto_clear = true;
  155. i2s_config.use_apll = true;
  156. i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; //Interrupt level 1
  157. if (strcasestr(device, "spdif")) {
  158. spdif = true;
  159. if ((p = strcasestr(spdif_config, "bck")) != NULL) i2s_pin_config.bck_io_num = atoi(strchr(p, '=') + 1);
  160. if ((p = strcasestr(spdif_config, "ws")) != NULL) i2s_pin_config.ws_io_num = atoi(strchr(p, '=') + 1);
  161. if (i2s_pin_config.bck_io_num == -1 || i2s_pin_config.ws_io_num == -1 || i2s_pin_config.data_out_num == -1) {
  162. LOG_WARN("Cannot initialize I2S for SPDIF bck:%d ws:%d do:%d", i2s_pin_config.bck_io_num,
  163. i2s_pin_config.ws_io_num,
  164. i2s_pin_config.data_out_num);
  165. }
  166. i2s_config.sample_rate = output.current_sample_rate * 2;
  167. i2s_config.bits_per_sample = 32;
  168. // Normally counted in frames, but 16 sample are transformed into 32 bits in spdif
  169. i2s_config.dma_buf_len = DMA_BUF_LEN / 2;
  170. i2s_config.dma_buf_count = DMA_BUF_COUNT * 2;
  171. /*
  172. In DMA, we have room for (LEN * COUNT) frames of 32 bits samples that
  173. we push at sample_rate * 2. Each of these peuso-frames is a single true
  174. audio frame. So the real depth is true frames is (LEN * COUNT / 2)
  175. */
  176. dma_buf_frames = DMA_BUF_COUNT * DMA_BUF_LEN / 2;
  177. res = i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  178. res |= i2s_set_pin(CONFIG_I2S_NUM, &i2s_pin_config);
  179. LOG_INFO("SPDIF using I2S bck:%u, ws:%u, do:%u", i2s_pin_config.bck_io_num, i2s_pin_config.ws_io_num, i2s_pin_config.data_out_num);
  180. } else {
  181. // turn off SPDIF if configured
  182. if (i2s_pin_config.data_out_num >= 0) {
  183. gpio_pad_select_gpio(i2s_pin_config.data_out_num);
  184. gpio_set_direction(i2s_pin_config.data_out_num, GPIO_MODE_OUTPUT);
  185. gpio_set_level(i2s_pin_config.data_out_num, 0);
  186. }
  187. i2s_config.sample_rate = output.current_sample_rate;
  188. i2s_config.bits_per_sample = BYTES_PER_FRAME * 8 / 2;
  189. // Counted in frames (but i2s allocates a buffer <= 4092 bytes)
  190. i2s_config.dma_buf_len = DMA_BUF_LEN;
  191. i2s_config.dma_buf_count = DMA_BUF_COUNT;
  192. dma_buf_frames = DMA_BUF_COUNT * DMA_BUF_LEN;
  193. char *dac_config = config_alloc_get_str("dac_config", CONFIG_DAC_CONFIG, "model=i2s,bck=" STR(CONFIG_I2S_BCK_IO)
  194. ",ws=" STR(CONFIG_I2S_WS_IO) ",do=" STR(CONFIG_I2S_DO_IO)
  195. ",sda=" STR(CONFIG_I2C_SDA) ",scl=" STR(CONFIG_I2C_SCL)
  196. ",mute" STR(CONFIG_MUTE_GPIO));
  197. char model[32] = "i2s";
  198. if ((p = strcasestr(dac_config, "model")) != NULL) sscanf(p, "%*[^=]=%31[^,]", model);
  199. for (int i = 0; adac == &dac_external && dac_set[i]; i++) if (strcasestr(dac_set[i]->model, model)) adac = dac_set[i];
  200. res = adac->init(dac_config, I2C_PORT, &i2s_config) ? ESP_OK : ESP_FAIL;
  201. if ((p = strcasestr(dac_config, "bck")) != NULL) i2s_pin_config.bck_io_num = atoi(strchr(p, '=') + 1);
  202. if ((p = strcasestr(dac_config, "ws")) != NULL) i2s_pin_config.ws_io_num = atoi(strchr(p, '=') + 1);
  203. if ((p = strcasestr(dac_config, "do")) != NULL) i2s_pin_config.data_out_num = atoi(strchr(p, '=') + 1);
  204. if ((p = strcasestr(dac_config, "mute")) != NULL) {
  205. char mute[8];
  206. sscanf(p, "%*[^=]=%7[^,]", mute);
  207. mute_control.gpio = atoi(mute);
  208. if ((p = strchr(mute, ':')) != NULL) mute_control.active = atoi(p + 1);
  209. }
  210. free(dac_config);
  211. res |= i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  212. res |= i2s_set_pin(CONFIG_I2S_NUM, &i2s_pin_config);
  213. if (res == ESP_OK && mute_control.gpio >= 0) {
  214. gpio_pad_select_gpio(mute_control.gpio);
  215. gpio_set_direction(mute_control.gpio, GPIO_MODE_OUTPUT);
  216. gpio_set_level(mute_control.gpio, mute_control.active);
  217. }
  218. LOG_INFO("%s DAC using I2S bck:%d, ws:%d, do:%d, mute:%d:%d (res:%d)", model, i2s_pin_config.bck_io_num, i2s_pin_config.ws_io_num,
  219. i2s_pin_config.data_out_num, mute_control.gpio, mute_control.active, res);
  220. }
  221. free(spdif_config);
  222. if (res != ESP_OK) {
  223. LOG_WARN("no DAC configured");
  224. return;
  225. }
  226. LOG_INFO("Initializing I2S mode %s with rate: %d, bits per sample: %d, buffer frames: %d, number of buffers: %d ",
  227. spdif ? "S/PDIF" : "normal",
  228. i2s_config.sample_rate, i2s_config.bits_per_sample, i2s_config.dma_buf_len, i2s_config.dma_buf_count);
  229. i2s_stop(CONFIG_I2S_NUM);
  230. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  231. isI2SStarted=false;
  232. adac->power(ADAC_STANDBY);
  233. jack_handler_chain = jack_handler_svc;
  234. jack_handler_svc = jack_handler;
  235. if (jack_mutes_amp && jack_inserted_svc()) adac->speaker(false);
  236. else adac->speaker(true);
  237. adac->headset(jack_inserted_svc());
  238. parse_set_GPIO(set_amp_gpio);
  239. esp_pthread_cfg_t cfg = esp_pthread_get_default_config();
  240. cfg.thread_name= "output_i2s";
  241. cfg.inherit_cfg = false;
  242. cfg.prio = CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT + 1;
  243. cfg.stack_size = PTHREAD_STACK_MIN + OUTPUT_THREAD_STACK_SIZE;
  244. esp_pthread_set_cfg(&cfg);
  245. pthread_create(&thread, NULL, output_thread_i2s, NULL);
  246. // do we want stats
  247. p = config_alloc_get_default(NVS_TYPE_STR, "stats", "n", 0);
  248. stats = p && (*p == '1' || *p == 'Y' || *p == 'y');
  249. free(p);
  250. // memory still used but at least task is not created
  251. if (stats) {
  252. static DRAM_ATTR StaticTask_t xTaskBuffer __attribute__ ((aligned (4)));
  253. static EXT_RAM_ATTR StackType_t xStack[STAT_STACK_SIZE] __attribute__ ((aligned (4)));
  254. stats_task = xTaskCreateStatic( (TaskFunction_t) output_thread_i2s_stats, "output_i2s_sts", STAT_STACK_SIZE, NULL, ESP_TASK_PRIO_MIN + 1, xStack, &xTaskBuffer);
  255. }
  256. }
  257. /****************************************************************************************
  258. * Terminate DAC output
  259. */
  260. void output_close_i2s(void) {
  261. LOCK;
  262. running = false;
  263. UNLOCK;
  264. pthread_join(thread, NULL);
  265. if (stats) vTaskDelete(stats_task);
  266. i2s_driver_uninstall(CONFIG_I2S_NUM);
  267. free(obuf);
  268. equalizer_close();
  269. adac->deinit();
  270. }
  271. /****************************************************************************************
  272. * change volume
  273. */
  274. bool output_volume_i2s(unsigned left, unsigned right) {
  275. if (mute_control.gpio >= 0) gpio_set_level(mute_control.gpio, (left | right) ? !mute_control.active : mute_control.active);
  276. return adac->volume(left, right);
  277. }
  278. /****************************************************************************************
  279. * Write frames to the output buffer
  280. */
  281. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  282. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr) {
  283. #if BYTES_PER_FRAME == 8
  284. s32_t *optr;
  285. #endif
  286. if (!silence) {
  287. if (output.fade == FADE_ACTIVE && output.fade_dir == FADE_CROSS && *cross_ptr) {
  288. _apply_cross(outputbuf, out_frames, cross_gain_in, cross_gain_out, cross_ptr);
  289. }
  290. #if BYTES_PER_FRAME == 4
  291. if (gainL != FIXED_ONE || gainR!= FIXED_ONE) {
  292. _apply_gain(outputbuf, out_frames, gainL, gainR);
  293. }
  294. memcpy(obuf + oframes * BYTES_PER_FRAME, outputbuf->readp, out_frames * BYTES_PER_FRAME);
  295. #else
  296. optr = (s32_t*) outputbuf->readp;
  297. #endif
  298. } else {
  299. #if BYTES_PER_FRAME == 4
  300. memcpy(obuf + oframes * BYTES_PER_FRAME, silencebuf, out_frames * BYTES_PER_FRAME);
  301. #else
  302. optr = (s32_t*) silencebuf;
  303. #endif
  304. }
  305. #if BYTES_PER_FRAME == 8
  306. IF_DSD(
  307. if (output.outfmt == DOP) {
  308. update_dop((u32_t *) optr, out_frames, output.invert);
  309. } else if (output.outfmt != PCM && output.invert)
  310. dsd_invert((u32_t *) optr, out_frames);
  311. )
  312. _scale_and_pack_frames(obuf + oframes * BYTES_PER_FRAME, optr, out_frames, gainL, gainR, output.format);
  313. #endif
  314. output_visu_export((s16_t*) (obuf + oframes * BYTES_PER_FRAME), out_frames, output.current_sample_rate, silence, (gainL + gainR) / 2);
  315. oframes += out_frames;
  316. return out_frames;
  317. }
  318. /****************************************************************************************
  319. * Main output thread
  320. */
  321. static void *output_thread_i2s(void *arg) {
  322. size_t count = 0, bytes;
  323. frames_t iframes = FRAME_BLOCK;
  324. uint32_t timer_start = 0;
  325. int discard = 0;
  326. uint32_t fullness = gettime_ms();
  327. bool synced;
  328. output_state state = OUTPUT_OFF - 1;
  329. char *sbuf = NULL;
  330. // spdif needs 16 bytes per frame : 32 bits/sample, 2 channels, BMC encoded
  331. if (spdif && (sbuf = malloc(FRAME_BLOCK * 16)) == NULL) {
  332. LOG_ERROR("Cannot allocate SPDIF buffer");
  333. }
  334. while (running) {
  335. TIME_MEASUREMENT_START(timer_start);
  336. LOCK;
  337. // manage led display & analogue
  338. if (state != output.state) {
  339. LOG_INFO("Output state is %d", output.state);
  340. if (output.state == OUTPUT_OFF) {
  341. led_blink(LED_GREEN, 100, 2500);
  342. if (amp_control.gpio != -1) gpio_set_level(amp_control.gpio, !amp_control.active);
  343. LOG_INFO("switching off amp GPIO %d", amp_control.gpio);
  344. } else if (output.state == OUTPUT_STOPPED) {
  345. adac->speaker(false);
  346. led_blink(LED_GREEN, 200, 1000);
  347. } else if (output.state == OUTPUT_RUNNING) {
  348. if (!jack_mutes_amp || !jack_inserted_svc()) adac->speaker(true);
  349. led_on(LED_GREEN);
  350. }
  351. }
  352. state = output.state;
  353. if (output.state == OUTPUT_OFF) {
  354. UNLOCK;
  355. if (isI2SStarted) {
  356. isI2SStarted = false;
  357. i2s_stop(CONFIG_I2S_NUM);
  358. adac->power(ADAC_STANDBY);
  359. count = 0;
  360. }
  361. usleep(100000);
  362. continue;
  363. } else if (output.state == OUTPUT_STOPPED) {
  364. synced = false;
  365. }
  366. oframes = 0;
  367. output.updated = gettime_ms();
  368. output.frames_played_dmp = output.frames_played;
  369. // try to estimate how much we have consumed from the DMA buffer (calculation is incorrect at the very beginning ...)
  370. output.device_frames = dma_buf_frames - ((output.updated - fullness) * output.current_sample_rate) / 1000;
  371. _output_frames( iframes );
  372. // oframes must be a global updated by the write callback
  373. output.frames_in_process = oframes;
  374. SET_MIN_MAX_SIZED(oframes,rec,iframes);
  375. SET_MIN_MAX_SIZED(_buf_used(outputbuf),o,outputbuf->size);
  376. SET_MIN_MAX_SIZED(_buf_used(streambuf),s,streambuf->size);
  377. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),buffering);
  378. /* must skip first whatever is in the pipe (but not when resuming).
  379. This test is incorrect when we pause a track that has just started,
  380. but this is higly unlikely and I don't have a better one for now */
  381. if (output.state == OUTPUT_START_AT) {
  382. discard = output.frames_played_dmp ? 0 : output.device_frames;
  383. synced = true;
  384. } else if (discard) {
  385. discard -= oframes;
  386. iframes = discard ? min(FRAME_BLOCK, discard) : FRAME_BLOCK;
  387. UNLOCK;
  388. continue;
  389. }
  390. UNLOCK;
  391. // now send all the data
  392. TIME_MEASUREMENT_START(timer_start);
  393. if (!isI2SStarted ) {
  394. isI2SStarted = true;
  395. LOG_INFO("Restarting I2S.");
  396. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  397. i2s_start(CONFIG_I2S_NUM);
  398. adac->power(ADAC_ON);
  399. if (amp_control.gpio != -1) gpio_set_level(amp_control.gpio, amp_control.active);
  400. }
  401. // this does not work well as set_sample_rates resets the fifos (and it's too early)
  402. if (i2s_config.sample_rate != output.current_sample_rate) {
  403. LOG_INFO("changing sampling rate %u to %u", i2s_config.sample_rate, output.current_sample_rate);
  404. /*
  405. if (synced)
  406. // can sleep for a buffer_queue - 1 and then eat a buffer (discard) if we are synced
  407. usleep(((DMA_BUF_COUNT - 1) * DMA_BUF_LEN * BYTES_PER_FRAME * 1000) / 44100 * 1000);
  408. discard = DMA_BUF_COUNT * DMA_BUF_LEN * BYTES_PER_FRAME;
  409. }
  410. */
  411. i2s_config.sample_rate = output.current_sample_rate;
  412. i2s_set_sample_rates(CONFIG_I2S_NUM, spdif ? i2s_config.sample_rate * 2 : i2s_config.sample_rate);
  413. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  414. equalizer_close();
  415. equalizer_open(output.current_sample_rate);
  416. //return;
  417. }
  418. // run equalizer
  419. equalizer_process(obuf, oframes * BYTES_PER_FRAME, output.current_sample_rate);
  420. // we assume that here we have been able to entirely fill the DMA buffers
  421. if (spdif) {
  422. spdif_convert((ISAMPLE_T*) obuf, oframes, (u32_t*) sbuf, &count);
  423. i2s_write(CONFIG_I2S_NUM, sbuf, oframes * 16, &bytes, portMAX_DELAY);
  424. bytes /= 4;
  425. #if BYTES_PER_FRAME == 4
  426. } else if (i2s_config.bits_per_sample == 32) {
  427. i2s_write_expand(CONFIG_I2S_NUM, obuf, oframes * BYTES_PER_FRAME, 16, 32, &bytes, portMAX_DELAY);
  428. #endif
  429. } else {
  430. i2s_write(CONFIG_I2S_NUM, obuf, oframes * BYTES_PER_FRAME, &bytes, portMAX_DELAY);
  431. }
  432. fullness = gettime_ms();
  433. if (bytes != oframes * BYTES_PER_FRAME) {
  434. LOG_WARN("I2S DMA Overflow! available bytes: %d, I2S wrote %d bytes", oframes * BYTES_PER_FRAME, bytes);
  435. }
  436. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),i2s_time);
  437. }
  438. if (spdif) free(sbuf);
  439. return 0;
  440. }
  441. /****************************************************************************************
  442. * Stats output thread
  443. */
  444. static void *output_thread_i2s_stats(void *arg) {
  445. while (1) {
  446. // no need to lock
  447. output_state state = output.state;
  448. if(stats && state>OUTPUT_STOPPED){
  449. LOG_INFO( "Output State: %d, current sample rate: %d, bytes per frame: %d",state,output.current_sample_rate, BYTES_PER_FRAME);
  450. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD1);
  451. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD2);
  452. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD3);
  453. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD4);
  454. LOG_INFO(LINE_MIN_MAX_FORMAT_STREAM, LINE_MIN_MAX_STREAM("stream",s));
  455. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("output",o));
  456. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  457. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("received",rec));
  458. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  459. LOG_INFO("");
  460. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  461. LOG_INFO(" max (us) | min (us) | avg(us) | count | ");
  462. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  463. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("Buffering(us)",buffering));
  464. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("i2s tfr(us)",i2s_time));
  465. LOG_INFO(" ----------+----------+-----------+-----------+");
  466. RESET_ALL_MIN_MAX;
  467. }
  468. vTaskDelay( pdMS_TO_TICKS( STATS_PERIOD_MS ) );
  469. }
  470. return NULL;
  471. }
  472. /****************************************************************************************
  473. * SPDIF support
  474. */
  475. #define PREAMBLE_B (0xE8) //11101000
  476. #define PREAMBLE_M (0xE2) //11100010
  477. #define PREAMBLE_W (0xE4) //11100100
  478. #define VUCP ((0xCC) << 24)
  479. #define VUCP_MUTE ((0xD4) << 24) // To mute PCM, set VUCP = invalid.
  480. extern const u16_t spdif_bmclookup[256];
  481. /*
  482. SPDIF is supposed to be (before BMC encoding, from LSB to MSB)
  483. PPPP AAAA SSSS SSSS SSSS SSSS SSSS VUCP
  484. after BMC encoding, each bits becomes 2 hence this becomes a 64 bits word. The
  485. the trick is to start not with a PPPP sequence but with an VUCP sequence to that
  486. the 16 bits samples are aligned with a BMC word boundary. Note that the LSB of the
  487. audio is transmitted first (not the MSB) and that ESP32 libray sends R then L,
  488. contrary to what seems to be usually done, so (dst) order had to be changed
  489. */
  490. void spdif_convert(ISAMPLE_T *src, size_t frames, u32_t *dst, size_t *count) {
  491. u16_t hi, lo, aux;
  492. // frames are 2 channels of 16 bits
  493. frames *= 2;
  494. while (frames--) {
  495. #if BYTES_PER_FRAME == 4
  496. hi = spdif_bmclookup[(u8_t)(*src >> 8)];
  497. lo = spdif_bmclookup[(u8_t) *src];
  498. #else
  499. hi = spdif_bmclookup[(u8_t)(*src >> 24)];
  500. lo = spdif_bmclookup[(u8_t) *src >> 16];
  501. #endif
  502. lo ^= ~((s16_t)hi) >> 16;
  503. // 16 bits sample:
  504. *(dst+0) = ((u32_t)lo << 16) | hi;
  505. // 4 bits auxillary-audio-databits, the first used as parity
  506. aux = 0xb333 ^ (((u32_t)((s16_t)lo)) >> 17);
  507. // VUCP-Bits: Valid, Subcode, Channelstatus, Parity = 0
  508. // As parity is always 0, we can use fixed preambles
  509. if (++(*count) > 383) {
  510. *(dst+1) = VUCP | (PREAMBLE_B << 16 ) | aux; //special preamble for one of 192 frames
  511. *count = 0;
  512. } else {
  513. *(dst+1) = VUCP | ((((*count) & 0x01) ? PREAMBLE_W : PREAMBLE_M) << 16) | aux;
  514. }
  515. src++;
  516. dst += 2;
  517. }
  518. }
  519. const u16_t spdif_bmclookup[256] = { //biphase mark encoded values (least significant bit first)
  520. 0xcccc, 0x4ccc, 0x2ccc, 0xaccc, 0x34cc, 0xb4cc, 0xd4cc, 0x54cc,
  521. 0x32cc, 0xb2cc, 0xd2cc, 0x52cc, 0xcacc, 0x4acc, 0x2acc, 0xaacc,
  522. 0x334c, 0xb34c, 0xd34c, 0x534c, 0xcb4c, 0x4b4c, 0x2b4c, 0xab4c,
  523. 0xcd4c, 0x4d4c, 0x2d4c, 0xad4c, 0x354c, 0xb54c, 0xd54c, 0x554c,
  524. 0x332c, 0xb32c, 0xd32c, 0x532c, 0xcb2c, 0x4b2c, 0x2b2c, 0xab2c,
  525. 0xcd2c, 0x4d2c, 0x2d2c, 0xad2c, 0x352c, 0xb52c, 0xd52c, 0x552c,
  526. 0xccac, 0x4cac, 0x2cac, 0xacac, 0x34ac, 0xb4ac, 0xd4ac, 0x54ac,
  527. 0x32ac, 0xb2ac, 0xd2ac, 0x52ac, 0xcaac, 0x4aac, 0x2aac, 0xaaac,
  528. 0x3334, 0xb334, 0xd334, 0x5334, 0xcb34, 0x4b34, 0x2b34, 0xab34,
  529. 0xcd34, 0x4d34, 0x2d34, 0xad34, 0x3534, 0xb534, 0xd534, 0x5534,
  530. 0xccb4, 0x4cb4, 0x2cb4, 0xacb4, 0x34b4, 0xb4b4, 0xd4b4, 0x54b4,
  531. 0x32b4, 0xb2b4, 0xd2b4, 0x52b4, 0xcab4, 0x4ab4, 0x2ab4, 0xaab4,
  532. 0xccd4, 0x4cd4, 0x2cd4, 0xacd4, 0x34d4, 0xb4d4, 0xd4d4, 0x54d4,
  533. 0x32d4, 0xb2d4, 0xd2d4, 0x52d4, 0xcad4, 0x4ad4, 0x2ad4, 0xaad4,
  534. 0x3354, 0xb354, 0xd354, 0x5354, 0xcb54, 0x4b54, 0x2b54, 0xab54,
  535. 0xcd54, 0x4d54, 0x2d54, 0xad54, 0x3554, 0xb554, 0xd554, 0x5554,
  536. 0x3332, 0xb332, 0xd332, 0x5332, 0xcb32, 0x4b32, 0x2b32, 0xab32,
  537. 0xcd32, 0x4d32, 0x2d32, 0xad32, 0x3532, 0xb532, 0xd532, 0x5532,
  538. 0xccb2, 0x4cb2, 0x2cb2, 0xacb2, 0x34b2, 0xb4b2, 0xd4b2, 0x54b2,
  539. 0x32b2, 0xb2b2, 0xd2b2, 0x52b2, 0xcab2, 0x4ab2, 0x2ab2, 0xaab2,
  540. 0xccd2, 0x4cd2, 0x2cd2, 0xacd2, 0x34d2, 0xb4d2, 0xd4d2, 0x54d2,
  541. 0x32d2, 0xb2d2, 0xd2d2, 0x52d2, 0xcad2, 0x4ad2, 0x2ad2, 0xaad2,
  542. 0x3352, 0xb352, 0xd352, 0x5352, 0xcb52, 0x4b52, 0x2b52, 0xab52,
  543. 0xcd52, 0x4d52, 0x2d52, 0xad52, 0x3552, 0xb552, 0xd552, 0x5552,
  544. 0xccca, 0x4cca, 0x2cca, 0xacca, 0x34ca, 0xb4ca, 0xd4ca, 0x54ca,
  545. 0x32ca, 0xb2ca, 0xd2ca, 0x52ca, 0xcaca, 0x4aca, 0x2aca, 0xaaca,
  546. 0x334a, 0xb34a, 0xd34a, 0x534a, 0xcb4a, 0x4b4a, 0x2b4a, 0xab4a,
  547. 0xcd4a, 0x4d4a, 0x2d4a, 0xad4a, 0x354a, 0xb54a, 0xd54a, 0x554a,
  548. 0x332a, 0xb32a, 0xd32a, 0x532a, 0xcb2a, 0x4b2a, 0x2b2a, 0xab2a,
  549. 0xcd2a, 0x4d2a, 0x2d2a, 0xad2a, 0x352a, 0xb52a, 0xd52a, 0x552a,
  550. 0xccaa, 0x4caa, 0x2caa, 0xacaa, 0x34aa, 0xb4aa, 0xd4aa, 0x54aa,
  551. 0x32aa, 0xb2aa, 0xd2aa, 0x52aa, 0xcaaa, 0x4aaa, 0x2aaa, 0xaaaa
  552. };