output_i2s.c 26 KB

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