output_i2s.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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 "services.h"
  40. #include "monitor.h"
  41. #include "platform_config.h"
  42. #include "gpio_exp.h"
  43. #include "accessors.h"
  44. #include "equalizer.h"
  45. #include "globdefs.h"
  46. #define LOCK mutex_lock(outputbuf->mutex)
  47. #define UNLOCK mutex_unlock(outputbuf->mutex)
  48. #define FRAME_BLOCK MAX_SILENCE_FRAMES
  49. #define SPDIF_BLOCK 256
  50. /* we produce FRAME_BLOCK (2048) per loop of the i2s thread so it's better if they fit
  51. * inside a set of DMA buffer nicely, i.e. DMA_BUF_FRAMES * DMA_BUF_COUNT is a multiple
  52. * of FRAME_BLOCK so that each DMA buffer is filled and we fully empty a FRAME_BLOCK at
  53. * each loop. Because one DMA buffer in esp32 is 4092 or below, when using 16 bits
  54. * samples and 2 channels, the best multiple is 512 (512*2*2=2048) and we use 6 of these.
  55. * In SPDIF, as we virtually use 32 bits per sample, the next proper multiple would
  56. * be 256 but such DMA buffers are too small and this causes stuttering. So we will use
  57. * non-multiples which means that at every loop one DMA buffer will be not fully filled.
  58. * At least, let's make sure it's not a too small amount of samples so 450*4*2=3600 fits
  59. * nicely in one DMA buffer and 2048/450 = 4 buffers + ~1/2 buffer which is acceptable.
  60. */
  61. #define DMA_BUF_FRAMES 512
  62. #define DMA_BUF_COUNT 12
  63. #define DMA_BUF_FRAMES_SPDIF 450
  64. #define DMA_BUF_COUNT_SPDIF 7
  65. #define DECLARE_ALL_MIN_MAX \
  66. DECLARE_MIN_MAX(o); \
  67. DECLARE_MIN_MAX(s); \
  68. DECLARE_MIN_MAX(rec); \
  69. DECLARE_MIN_MAX(i2s_time); \
  70. DECLARE_MIN_MAX(buffering);
  71. #define RESET_ALL_MIN_MAX \
  72. RESET_MIN_MAX(o); \
  73. RESET_MIN_MAX(s); \
  74. RESET_MIN_MAX(rec); \
  75. RESET_MIN_MAX(i2s_time); \
  76. RESET_MIN_MAX(buffering);
  77. #define STATS_PERIOD_MS 5000
  78. static void (*pseudo_idle_chain)(uint32_t now);
  79. #ifndef CONFIG_AMP_GPIO_LEVEL
  80. #define CONFIG_AMP_GPIO_LEVEL 1
  81. #endif
  82. extern struct outputstate output;
  83. extern struct buffer *streambuf;
  84. extern struct buffer *outputbuf;
  85. extern u8_t *silencebuf;
  86. const struct adac_s *dac_set[] = { &dac_tas57xx, &dac_tas5713, &dac_ac101, &dac_wm8978, NULL };
  87. const struct adac_s *adac = &dac_external;
  88. static log_level loglevel;
  89. static uint32_t i2s_idle_since;
  90. static void (*pseudo_idle_chain)(uint32_t);
  91. static bool (*slimp_handler_chain)(u8_t *data, int len);
  92. static bool jack_mutes_amp;
  93. static bool running, isI2SStarted, ended;
  94. static i2s_config_t i2s_config;
  95. static u8_t *obuf;
  96. static frames_t oframes;
  97. static struct {
  98. bool enabled;
  99. u8_t *buf;
  100. } spdif;
  101. static size_t dma_buf_frames;
  102. static TaskHandle_t output_i2s_task;
  103. static struct {
  104. int gpio, active;
  105. } amp_control = { CONFIG_AMP_GPIO, CONFIG_AMP_GPIO_LEVEL },
  106. mute_control = { CONFIG_MUTE_GPIO, CONFIG_MUTE_GPIO_LEVEL };
  107. DECLARE_ALL_MIN_MAX;
  108. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR, u8_t flags,
  109. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr);
  110. static void output_thread_i2s(void *arg);
  111. static void i2s_stats(uint32_t now);
  112. static void spdif_convert(ISAMPLE_T *src, size_t frames, u32_t *dst);
  113. static void (*jack_handler_chain)(bool inserted);
  114. #define I2C_PORT 0
  115. /****************************************************************************************
  116. * AUDO packet handler
  117. */
  118. static bool handler(u8_t *data, int len){
  119. bool res = true;
  120. if (!strncmp((char*) data, "audo", 4)) {
  121. struct audo_packet *pkt = (struct audo_packet*) data;
  122. // 0 = headphone (internal speakers off), 1 = sub out,
  123. // 2 = always on (internal speakers on), 3 = always off
  124. if (jack_mutes_amp != (pkt->config == 0)) {
  125. jack_mutes_amp = pkt->config == 0;
  126. config_set_value(NVS_TYPE_STR, "jack_mutes_amp", jack_mutes_amp ? "y" : "n");
  127. if (jack_mutes_amp && jack_inserted_svc()) {
  128. adac->speaker(false);
  129. if (amp_control.gpio != -1) gpio_set_level_x(amp_control.gpio, !amp_control.active);
  130. } else {
  131. adac->speaker(true);
  132. if (amp_control.gpio != -1) gpio_set_level_x(amp_control.gpio, amp_control.active);
  133. }
  134. }
  135. LOG_INFO("got AUDO %02x", pkt->config);
  136. } else {
  137. res = false;
  138. }
  139. // chain protocol handlers (bitwise or is fine)
  140. if (*slimp_handler_chain) res |= (*slimp_handler_chain)(data, len);
  141. return res;
  142. }
  143. /****************************************************************************************
  144. * jack insertion handler
  145. */
  146. static void jack_handler(bool inserted) {
  147. // jack detection bounces a bit but that seems fine
  148. if (jack_mutes_amp) {
  149. LOG_INFO("switching amplifier %s", inserted ? "OFF" : "ON");
  150. adac->speaker(!inserted);
  151. if (amp_control.gpio != -1) gpio_set_level_x(amp_control.gpio, inserted ? !amp_control.active : amp_control.active);
  152. }
  153. // activate headset
  154. adac->headset(inserted);
  155. // and chain if any
  156. if (jack_handler_chain) (jack_handler_chain)(inserted);
  157. }
  158. /****************************************************************************************
  159. * amp GPIO
  160. */
  161. #ifndef AMP_LOCKED
  162. static void set_amp_gpio(int gpio, char *value) {
  163. char *p;
  164. if (strcasestr(value, "amp")) {
  165. amp_control.gpio = gpio;
  166. if ((p = strchr(value, ':')) != NULL) amp_control.active = atoi(p + 1);
  167. }
  168. }
  169. #endif
  170. /****************************************************************************************
  171. * Get inactivity callback
  172. */
  173. static uint32_t i2s_idle_callback(void) {
  174. return output.state <= OUTPUT_STOPPED ? pdTICKS_TO_MS(xTaskGetTickCount()) - i2s_idle_since : 0;
  175. }
  176. /****************************************************************************************
  177. * Set pin from config string
  178. */
  179. static void set_i2s_pin(char *config, i2s_pin_config_t *pin_config) {
  180. pin_config->bck_io_num = pin_config->ws_io_num = pin_config->data_out_num = pin_config->data_in_num = -1;
  181. PARSE_PARAM(config, "bck", '=', pin_config->bck_io_num);
  182. PARSE_PARAM(config, "ws", '=', pin_config->ws_io_num);
  183. PARSE_PARAM(config, "do", '=', pin_config->data_out_num);
  184. #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)
  185. pin_config->mck_io_num = strcasestr(config, "mck") ? 0 : -1;
  186. PARSE_PARAM(config, "mck", '=', pin_config->mck_io_num);
  187. #endif
  188. }
  189. /* When a panic occurs during playback, the I2S interface can produce a loud noise burst.
  190. * This code runs just before the system panic handler to "emergency stop" the I2S iterface
  191. * to prevent the noise burst from happening. Note that when this code is called the system
  192. * has already crashed, so no need to disable interrupts, acquire locks, or otherwise be nice.
  193. *
  194. * This code makes use of the linker --wrap feature to intercept the call to esp_panic_handler.
  195. */
  196. void __real_esp_panic_handler(void*);
  197. void __wrap_esp_panic_handler (void* info) {
  198. esp_rom_printf("I2S abort!\r\n");
  199. i2s_stop(CONFIG_I2S_NUM);
  200. /* Call the original panic handler function to finish processing this error */
  201. __real_esp_panic_handler(info);
  202. }
  203. /****************************************************************************************
  204. * Initialize the DAC output
  205. */
  206. void output_init_i2s(log_level level, char *device, unsigned output_buf_size, char *params, unsigned rates[], unsigned rate_delay, unsigned idle) {
  207. loglevel = level;
  208. int silent_do = -1;
  209. char *p;
  210. esp_err_t res;
  211. // chain SLIMP handlers
  212. slimp_handler_chain = slimp_handler;
  213. slimp_handler = handler;
  214. p = config_alloc_get_default(NVS_TYPE_STR, "jack_mutes_amp", "n", 0);
  215. jack_mutes_amp = (strcmp(p,"1") == 0 ||strcasecmp(p,"y") == 0);
  216. free(p);
  217. #if BYTES_PER_FRAME == 8
  218. output.format = S32_LE;
  219. #else
  220. output.format = S16_LE;
  221. #endif
  222. output.write_cb = &_i2s_write_frames;
  223. obuf = malloc(FRAME_BLOCK * BYTES_PER_FRAME);
  224. if (!obuf) {
  225. LOG_ERROR("Cannot allocate i2s buffer");
  226. return;
  227. }
  228. running = true;
  229. // get SPDIF configuration from NVS or compile
  230. char *spdif_config = config_alloc_get_str("spdif_config", CONFIG_SPDIF_CONFIG, "bck=" STR(CONFIG_SPDIF_BCK_IO)
  231. ",ws=" STR(CONFIG_SPDIF_WS_IO) ",do=" STR(CONFIG_SPDIF_DO_IO));
  232. char *dac_config = config_alloc_get_str("dac_config", CONFIG_DAC_CONFIG, "model=i2s,bck=" STR(CONFIG_I2S_BCK_IO)
  233. ",ws=" STR(CONFIG_I2S_WS_IO) ",do=" STR(CONFIG_I2S_DO_IO) ",mck=" STR(CONFIG_I2S_MCK_IO)
  234. ",sda=" STR(CONFIG_I2C_SDA) ",scl=" STR(CONFIG_I2C_SCL)
  235. ",mute=" STR(CONFIG_MUTE_GPIO));
  236. i2s_pin_config_t i2s_dac_pin, i2s_spdif_pin;
  237. set_i2s_pin(spdif_config, &i2s_spdif_pin);
  238. set_i2s_pin(dac_config, &i2s_dac_pin);
  239. if (i2s_dac_pin.data_out_num == -1 && i2s_spdif_pin.data_out_num == -1) {
  240. LOG_WARN("DAC and SPDIF not configured, NOT launching i2s thread");
  241. return;
  242. }
  243. // common I2S initialization
  244. i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_TX;
  245. i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
  246. i2s_config.communication_format = I2S_COMM_FORMAT_STAND_I2S;
  247. // in case of overflow, do not replay old buffer
  248. i2s_config.tx_desc_auto_clear = true;
  249. #ifndef CONFIG_IDF_TARGET_ESP32S3
  250. i2s_config.use_apll = true;
  251. #endif
  252. i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; //Interrupt level 1
  253. i2s_config.dma_buf_len = DMA_BUF_FRAMES;
  254. i2s_config.dma_buf_count = DMA_BUF_COUNT;
  255. if (strcasestr(device, "spdif")) {
  256. spdif.enabled = true;
  257. if ((spdif.buf = heap_caps_malloc(SPDIF_BLOCK * 16, MALLOC_CAP_INTERNAL)) == NULL) {
  258. LOG_ERROR("Cannot allocate SPDIF buffer");
  259. }
  260. if (i2s_spdif_pin.bck_io_num == -1 || i2s_spdif_pin.ws_io_num == -1 || i2s_spdif_pin.data_out_num == -1) {
  261. LOG_WARN("Cannot initialize I2S for SPDIF bck:%d ws:%d do:%d", i2s_spdif_pin.bck_io_num,
  262. i2s_spdif_pin.ws_io_num,
  263. i2s_spdif_pin.data_out_num);
  264. }
  265. i2s_config.sample_rate = output.current_sample_rate * 2;
  266. i2s_config.bits_per_sample = 32;
  267. // Normally counted in frames, but 16 sample are transformed into 32 bits in spdif
  268. i2s_config.dma_buf_len = DMA_BUF_FRAMES_SPDIF;
  269. i2s_config.dma_buf_count = DMA_BUF_COUNT_SPDIF;
  270. /*
  271. In DMA, we have room for (LEN * COUNT) frames of 32 bits samples that
  272. we push at sample_rate * 2. Each of these pseudo-frames is a single true
  273. audio frame. So the real depth in true frames is (LEN * COUNT / 2)
  274. */
  275. dma_buf_frames = i2s_config.dma_buf_len * i2s_config.dma_buf_count / 2;
  276. // silence DAC output if sharing the same ws/bck
  277. 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;
  278. res = i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  279. res |= i2s_set_pin(CONFIG_I2S_NUM, &i2s_spdif_pin);
  280. 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);
  281. } else {
  282. i2s_config.sample_rate = output.current_sample_rate;
  283. i2s_config.bits_per_sample = BYTES_PER_FRAME * 8 / 2;
  284. // Counted in frames (but i2s allocates a buffer <= 4092 bytes)
  285. i2s_config.dma_buf_len = DMA_BUF_FRAMES;
  286. i2s_config.dma_buf_count = DMA_BUF_COUNT;
  287. dma_buf_frames = i2s_config.dma_buf_len * i2s_config.dma_buf_count;
  288. // silence SPDIF output
  289. silent_do = i2s_spdif_pin.data_out_num;
  290. char model[32] = "i2s";
  291. if ((p = strcasestr(dac_config, "model")) != NULL) sscanf(p, "%*[^=]=%31[^,]", model);
  292. if ((p = strcasestr(dac_config, "mute")) != NULL) {
  293. char mute[8] = "";
  294. sscanf(p, "%*[^=]=%7[^,]", mute);
  295. mute_control.gpio = atoi(mute);
  296. if ((p = strchr(mute, ':')) != NULL) mute_control.active = atoi(p + 1);
  297. }
  298. bool mck_required = false;
  299. for (int i = 0; adac == &dac_external && dac_set[i]; i++) if (strcasestr(dac_set[i]->model, model)) adac = dac_set[i];
  300. res = adac->init(dac_config, I2C_PORT, &i2s_config, &mck_required) ? ESP_OK : ESP_FAIL;
  301. #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 4, 0)
  302. int mck_io_num = strcasestr(dac_config, "mck") || mck_required ? 0 : -1;
  303. PARSE_PARAM(dac_config, "mck", '=', mck_io_num);
  304. LOG_INFO("configuring MCLK on GPIO %d", mck_io_num);
  305. if (mck_io_num == GPIO_NUM_0) {
  306. PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0_CLK_OUT1);
  307. WRITE_PERI_REG(PIN_CTRL, CONFIG_I2S_NUM == I2S_NUM_0 ? 0xFFF0 : 0xFFFF);
  308. } else if (mck_io_num == GPIO_NUM_1) {
  309. PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD_CLK_OUT3);
  310. WRITE_PERI_REG(PIN_CTRL, CONFIG_I2S_NUM == I2S_NUM_0 ? 0xF0F0 : 0xF0FF);
  311. } else if (mck_io_num == GPIO_NUM_2) {
  312. PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0RXD_U, FUNC_U0RXD_CLK_OUT2);
  313. WRITE_PERI_REG(PIN_CTRL, CONFIG_I2S_NUM == I2S_NUM_0 ? 0xFF00 : 0xFF0F);
  314. } else {
  315. LOG_WARN("invalid MCK gpio %d", mck_io_num);
  316. }
  317. #else
  318. if (mck_required && i2s_dac_pin.mck_io_num == -1) i2s_dac_pin.mck_io_num = 0;
  319. LOG_INFO("configuring MCLK on GPIO %d", i2s_dac_pin.mck_io_num);
  320. #endif
  321. res |= i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  322. res |= i2s_set_pin(CONFIG_I2S_NUM, &i2s_dac_pin);
  323. if (res == ESP_OK && mute_control.gpio >= 0) {
  324. gpio_pad_select_gpio(mute_control.gpio);
  325. gpio_set_direction(mute_control.gpio, GPIO_MODE_OUTPUT);
  326. gpio_set_level(mute_control.gpio, mute_control.active);
  327. }
  328. 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,
  329. i2s_dac_pin.data_out_num, mute_control.gpio, mute_control.active, res);
  330. }
  331. free(dac_config);
  332. free(spdif_config);
  333. if (res != ESP_OK) {
  334. LOG_WARN("no DAC configured");
  335. return;
  336. }
  337. // turn off GPIO than is not used (SPDIF of DAC DO when shared)
  338. if (silent_do >= 0) {
  339. gpio_pad_select_gpio(silent_do);
  340. gpio_set_direction(silent_do, GPIO_MODE_OUTPUT);
  341. gpio_set_level(silent_do, 0);
  342. }
  343. LOG_INFO("Initializing I2S mode %s with rate: %d, bits per sample: %d, buffer frames: %d, number of buffers: %d ",
  344. spdif.enabled ? "S/PDIF" : "normal",
  345. i2s_config.sample_rate, i2s_config.bits_per_sample, i2s_config.dma_buf_len, i2s_config.dma_buf_count);
  346. i2s_stop(CONFIG_I2S_NUM);
  347. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  348. isI2SStarted=false;
  349. equalizer_set_samplerate(output.current_sample_rate);
  350. adac->power(ADAC_STANDBY);
  351. jack_handler_chain = jack_handler_svc;
  352. jack_handler_svc = jack_handler;
  353. #ifndef AMP_LOCKED
  354. parse_set_GPIO(set_amp_gpio);
  355. #endif
  356. if (amp_control.gpio != -1) {
  357. gpio_pad_select_gpio_x(amp_control.gpio);
  358. gpio_set_direction_x(amp_control.gpio, GPIO_MODE_OUTPUT);
  359. gpio_set_level_x(amp_control.gpio, !amp_control.active);
  360. LOG_INFO("setting amplifier GPIO %d (active:%d)", amp_control.gpio, amp_control.active);
  361. }
  362. if (jack_mutes_amp && jack_inserted_svc()) adac->speaker(false);
  363. else adac->speaker(true);
  364. adac->headset(jack_inserted_svc());
  365. // do we want stats
  366. p = config_alloc_get_default(NVS_TYPE_STR, "stats", "n", 0);
  367. if (p && (*p == '1' || *p == 'Y' || *p == 'y')) {
  368. pseudo_idle_chain = pseudo_idle_svc;
  369. pseudo_idle_svc = i2s_stats;
  370. }
  371. free(p);
  372. // register a callback for inactivity
  373. i2s_idle_since = pdTICKS_TO_MS(xTaskGetTickCount());
  374. services_sleep_setsleeper(i2s_idle_callback);
  375. // create task as a FreeRTOS task but uses stack in internal RAM
  376. {
  377. static DRAM_ATTR StaticTask_t xTaskBuffer __attribute__ ((aligned (4)));
  378. static EXT_RAM_ATTR StackType_t xStack[OUTPUT_THREAD_STACK_SIZE] __attribute__ ((aligned (4)));
  379. output_i2s_task = xTaskCreateStaticPinnedToCore( (TaskFunction_t) output_thread_i2s, "output_i2s", OUTPUT_THREAD_STACK_SIZE,
  380. NULL, CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT + 10, xStack, &xTaskBuffer, 0 );
  381. }
  382. }
  383. /****************************************************************************************
  384. * Terminate DAC output
  385. */
  386. void output_close_i2s(void) {
  387. LOCK;
  388. running = false;
  389. UNLOCK;
  390. while (!ended) vTaskDelay(20 / portTICK_PERIOD_MS);
  391. i2s_driver_uninstall(CONFIG_I2S_NUM);
  392. free(obuf);
  393. equalizer_close();
  394. adac->deinit();
  395. }
  396. /****************************************************************************************
  397. * change volume
  398. */
  399. bool output_volume_i2s(unsigned left, unsigned right) {
  400. if (mute_control.gpio >= 0) gpio_set_level(mute_control.gpio, (left | right) ? !mute_control.active : mute_control.active);
  401. return adac->volume(left, right);
  402. }
  403. /****************************************************************************************
  404. * Write frames to the output buffer
  405. */
  406. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR, u8_t flags,
  407. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr) {
  408. if (!silence) {
  409. if (output.fade == FADE_ACTIVE && output.fade_dir == FADE_CROSS && *cross_ptr) {
  410. _apply_cross(outputbuf, out_frames, cross_gain_in, cross_gain_out, cross_ptr);
  411. }
  412. _apply_gain(outputbuf, out_frames, gainL, gainR, flags);
  413. memcpy(obuf + oframes * BYTES_PER_FRAME, outputbuf->readp, out_frames * BYTES_PER_FRAME);
  414. } else {
  415. memcpy(obuf + oframes * BYTES_PER_FRAME, silencebuf, out_frames * BYTES_PER_FRAME);
  416. }
  417. // don't update visu if we don't have enough data in buffer (500 ms)
  418. if (silence || _buf_used(outputbuf) > BYTES_PER_FRAME * output.current_sample_rate / 2) {
  419. output_visu_export(obuf + oframes * BYTES_PER_FRAME, out_frames, output.current_sample_rate, silence, (gainL + gainR) / 2);
  420. }
  421. oframes += out_frames;
  422. return out_frames;
  423. }
  424. /****************************************************************************************
  425. * Main output thread
  426. */
  427. static void output_thread_i2s(void *arg) {
  428. size_t bytes;
  429. frames_t iframes = FRAME_BLOCK;
  430. uint32_t timer_start = 0;
  431. int discard = 0;
  432. uint32_t fullness = gettime_ms();
  433. bool synced;
  434. output_state state = OUTPUT_OFF - 1;
  435. while (running) {
  436. TIME_MEASUREMENT_START(timer_start);
  437. LOCK;
  438. // manage led display & analogue
  439. if (state != output.state) {
  440. LOG_INFO("Output state is %d", output.state);
  441. if (output.state == OUTPUT_OFF) {
  442. led_blink(LED_GREEN, 100, 2500);
  443. if (amp_control.gpio != -1) gpio_set_level_x(amp_control.gpio, !amp_control.active);
  444. LOG_INFO("switching off amp GPIO %d", amp_control.gpio);
  445. } else if (output.state == OUTPUT_STOPPED) {
  446. i2s_idle_since = pdTICKS_TO_MS(xTaskGetTickCount());
  447. adac->speaker(false);
  448. led_blink(LED_GREEN, 200, 1000);
  449. } else if (output.state == OUTPUT_RUNNING) {
  450. if (!jack_mutes_amp || !jack_inserted_svc()) {
  451. if (amp_control.gpio != -1) gpio_set_level_x(amp_control.gpio, amp_control.active);
  452. adac->speaker(true);
  453. }
  454. led_on(LED_GREEN);
  455. }
  456. }
  457. state = output.state;
  458. if (output.state == OUTPUT_OFF) {
  459. UNLOCK;
  460. if (isI2SStarted) {
  461. isI2SStarted = false;
  462. i2s_stop(CONFIG_I2S_NUM);
  463. adac->power(ADAC_STANDBY);
  464. }
  465. usleep(100000);
  466. continue;
  467. } else if (output.state == OUTPUT_STOPPED) {
  468. synced = false;
  469. }
  470. oframes = 0;
  471. output.updated = gettime_ms();
  472. output.frames_played_dmp = output.frames_played;
  473. // try to estimate how much we have consumed from the DMA buffer (calculation is incorrect at the very beginning ...)
  474. output.device_frames = dma_buf_frames - ((output.updated - fullness) * output.current_sample_rate) / 1000;
  475. // we'll try to produce iframes if we have any, but we might return less if outpuf does not have enough
  476. _output_frames( iframes );
  477. // oframes must be a global updated by the write callback
  478. output.frames_in_process = oframes;
  479. SET_MIN_MAX_SIZED(oframes,rec,iframes);
  480. SET_MIN_MAX_SIZED(_buf_used(outputbuf),o,outputbuf->size);
  481. SET_MIN_MAX_SIZED(_buf_used(streambuf),s,streambuf->size);
  482. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),buffering);
  483. /* must skip first whatever is in the pipe (but not when resuming).
  484. This test is incorrect when we pause a track that has just started,
  485. but this is higly unlikely and I don't have a better one for now */
  486. if (output.state == OUTPUT_START_AT) {
  487. discard = output.frames_played_dmp ? 0 : output.device_frames;
  488. synced = true;
  489. } else if (discard) {
  490. discard -= min(oframes, discard);
  491. iframes = discard ? min(FRAME_BLOCK, discard) : FRAME_BLOCK;
  492. UNLOCK;
  493. continue;
  494. }
  495. UNLOCK;
  496. // now send all the data
  497. TIME_MEASUREMENT_START(timer_start);
  498. if (!isI2SStarted ) {
  499. isI2SStarted = true;
  500. LOG_INFO("Restarting I2S.");
  501. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  502. i2s_start(CONFIG_I2S_NUM);
  503. adac->power(ADAC_ON);
  504. if (spdif.enabled) spdif_convert(NULL, 0, NULL);
  505. }
  506. // this does not work well as set_sample_rates resets the fifos (and it's too early)
  507. if (i2s_config.sample_rate != output.current_sample_rate) {
  508. LOG_INFO("changing sampling rate %u to %u", i2s_config.sample_rate, output.current_sample_rate);
  509. if (synced) {
  510. /*
  511. // can sleep for a buffer_queue - 1 and then eat a buffer (discard) if we are synced
  512. usleep(((DMA_BUF_COUNT - 1) * DMA_BUF_LEN * BYTES_PER_FRAME * 1000) / 44100 * 1000);
  513. discard = DMA_BUF_COUNT * DMA_BUF_LEN * BYTES_PER_FRAME;
  514. */
  515. }
  516. i2s_config.sample_rate = output.current_sample_rate;
  517. i2s_set_sample_rates(CONFIG_I2S_NUM, spdif.enabled ? i2s_config.sample_rate * 2 : i2s_config.sample_rate);
  518. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  519. equalizer_set_samplerate(output.current_sample_rate);
  520. }
  521. // run equalizer
  522. equalizer_process(obuf, oframes * BYTES_PER_FRAME);
  523. // we assume that here we have been able to entirely fill the DMA buffers
  524. if (spdif.enabled) {
  525. size_t obytes, count = 0;
  526. bytes = 0;
  527. // need IRAM for speed but can't allocate a FRAME_BLOCK * 16, so process by smaller chunks
  528. while (count < oframes) {
  529. size_t chunk = min(SPDIF_BLOCK, oframes - count);
  530. spdif_convert((ISAMPLE_T*) obuf + count * 2, chunk, (u32_t*) spdif.buf);
  531. i2s_write(CONFIG_I2S_NUM, spdif.buf, chunk * 16, &obytes, portMAX_DELAY);
  532. bytes += obytes / (16 / BYTES_PER_FRAME);
  533. count += chunk;
  534. }
  535. #if BYTES_PER_FRAME == 4
  536. } else if (i2s_config.bits_per_sample == 32) {
  537. i2s_write_expand(CONFIG_I2S_NUM, obuf, oframes * BYTES_PER_FRAME, 16, 32, &bytes, portMAX_DELAY);
  538. #endif
  539. } else {
  540. i2s_write(CONFIG_I2S_NUM, obuf, oframes * BYTES_PER_FRAME, &bytes, portMAX_DELAY);
  541. }
  542. fullness = gettime_ms();
  543. if (bytes != oframes * BYTES_PER_FRAME) {
  544. LOG_WARN("I2S DMA Overflow! available bytes: %d, I2S wrote %d bytes", oframes * BYTES_PER_FRAME, bytes);
  545. }
  546. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),i2s_time);
  547. }
  548. if (spdif.enabled) free(spdif.buf);
  549. ended = true;
  550. vTaskDelete(NULL);
  551. }
  552. /****************************************************************************************
  553. * stats output callback
  554. */
  555. static void i2s_stats(uint32_t now) {
  556. static uint32_t last;
  557. // first chain to next handler
  558. if (pseudo_idle_chain) pseudo_idle_chain(now);
  559. // then see if we need to act
  560. if (output.state <= OUTPUT_STOPPED || now < last + STATS_PERIOD_MS) return;
  561. last = now;
  562. LOG_INFO( "Output State: %d, current sample rate: %d, bytes per frame: %d", output.state, output.current_sample_rate, BYTES_PER_FRAME);
  563. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD1);
  564. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD2);
  565. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD3);
  566. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD4);
  567. LOG_INFO(LINE_MIN_MAX_FORMAT_STREAM, LINE_MIN_MAX_STREAM("stream",s));
  568. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("output",o));
  569. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  570. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("received",rec));
  571. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  572. LOG_INFO("");
  573. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  574. LOG_INFO(" max (us) | min (us) | avg(us) | count | ");
  575. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  576. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("Buffering(us)",buffering));
  577. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("i2s tfr(us)",i2s_time));
  578. LOG_INFO(" ----------+----------+-----------+-----------+");
  579. RESET_ALL_MIN_MAX;
  580. }
  581. /****************************************************************************************
  582. * SPDIF support
  583. */
  584. #define PREAMBLE_B (0xE8) //11101000
  585. #define PREAMBLE_M (0xE2) //11100010
  586. #define PREAMBLE_W (0xE4) //11100100
  587. static const u8_t VUCP24[2] = { 0xCC, 0x32 };
  588. static const u16_t spdif_bmclookup[256] = {
  589. 0xcccc, 0xb333, 0xd333, 0xaccc, 0xcb33, 0xb4cc, 0xd4cc, 0xab33,
  590. 0xcd33, 0xb2cc, 0xd2cc, 0xad33, 0xcacc, 0xb533, 0xd533, 0xaacc,
  591. 0xccb3, 0xb34c, 0xd34c, 0xacb3, 0xcb4c, 0xb4b3, 0xd4b3, 0xab4c,
  592. 0xcd4c, 0xb2b3, 0xd2b3, 0xad4c, 0xcab3, 0xb54c, 0xd54c, 0xaab3,
  593. 0xccd3, 0xb32c, 0xd32c, 0xacd3, 0xcb2c, 0xb4d3, 0xd4d3, 0xab2c,
  594. 0xcd2c, 0xb2d3, 0xd2d3, 0xad2c, 0xcad3, 0xb52c, 0xd52c, 0xaad3,
  595. 0xccac, 0xb353, 0xd353, 0xacac, 0xcb53, 0xb4ac, 0xd4ac, 0xab53,
  596. 0xcd53, 0xb2ac, 0xd2ac, 0xad53, 0xcaac, 0xb553, 0xd553, 0xaaac,
  597. 0xcccb, 0xb334, 0xd334, 0xaccb, 0xcb34, 0xb4cb, 0xd4cb, 0xab34,
  598. 0xcd34, 0xb2cb, 0xd2cb, 0xad34, 0xcacb, 0xb534, 0xd534, 0xaacb,
  599. 0xccb4, 0xb34b, 0xd34b, 0xacb4, 0xcb4b, 0xb4b4, 0xd4b4, 0xab4b,
  600. 0xcd4b, 0xb2b4, 0xd2b4, 0xad4b, 0xcab4, 0xb54b, 0xd54b, 0xaab4,
  601. 0xccd4, 0xb32b, 0xd32b, 0xacd4, 0xcb2b, 0xb4d4, 0xd4d4, 0xab2b,
  602. 0xcd2b, 0xb2d4, 0xd2d4, 0xad2b, 0xcad4, 0xb52b, 0xd52b, 0xaad4,
  603. 0xccab, 0xb354, 0xd354, 0xacab, 0xcb54, 0xb4ab, 0xd4ab, 0xab54,
  604. 0xcd54, 0xb2ab, 0xd2ab, 0xad54, 0xcaab, 0xb554, 0xd554, 0xaaab,
  605. 0xcccd, 0xb332, 0xd332, 0xaccd, 0xcb32, 0xb4cd, 0xd4cd, 0xab32,
  606. 0xcd32, 0xb2cd, 0xd2cd, 0xad32, 0xcacd, 0xb532, 0xd532, 0xaacd,
  607. 0xccb2, 0xb34d, 0xd34d, 0xacb2, 0xcb4d, 0xb4b2, 0xd4b2, 0xab4d,
  608. 0xcd4d, 0xb2b2, 0xd2b2, 0xad4d, 0xcab2, 0xb54d, 0xd54d, 0xaab2,
  609. 0xccd2, 0xb32d, 0xd32d, 0xacd2, 0xcb2d, 0xb4d2, 0xd4d2, 0xab2d,
  610. 0xcd2d, 0xb2d2, 0xd2d2, 0xad2d, 0xcad2, 0xb52d, 0xd52d, 0xaad2,
  611. 0xccad, 0xb352, 0xd352, 0xacad, 0xcb52, 0xb4ad, 0xd4ad, 0xab52,
  612. 0xcd52, 0xb2ad, 0xd2ad, 0xad52, 0xcaad, 0xb552, 0xd552, 0xaaad,
  613. 0xccca, 0xb335, 0xd335, 0xacca, 0xcb35, 0xb4ca, 0xd4ca, 0xab35,
  614. 0xcd35, 0xb2ca, 0xd2ca, 0xad35, 0xcaca, 0xb535, 0xd535, 0xaaca,
  615. 0xccb5, 0xb34a, 0xd34a, 0xacb5, 0xcb4a, 0xb4b5, 0xd4b5, 0xab4a,
  616. 0xcd4a, 0xb2b5, 0xd2b5, 0xad4a, 0xcab5, 0xb54a, 0xd54a, 0xaab5,
  617. 0xccd5, 0xb32a, 0xd32a, 0xacd5, 0xcb2a, 0xb4d5, 0xd4d5, 0xab2a,
  618. 0xcd2a, 0xb2d5, 0xd2d5, 0xad2a, 0xcad5, 0xb52a, 0xd52a, 0xaad5,
  619. 0xccaa, 0xb355, 0xd355, 0xacaa, 0xcb55, 0xb4aa, 0xd4aa, 0xab55,
  620. 0xcd55, 0xb2aa, 0xd2aa, 0xad55, 0xcaaa, 0xb555, 0xd555, 0xaaaa
  621. };
  622. /*
  623. SPDIF is supposed to be (before BMC encoding, from LSB to MSB)
  624. 0.... 1... 191.. 0
  625. BLFMRF MLFWRF MLFWRF BLFMRF (B,M,W=preamble-4, L/R=left/Right-24, F=Flags-4)
  626. each xLF pattern is 32 bits
  627. PPPP AAAA SSSS SSSS SSSS SSSS SSSS VUCP (P=preamble, A=auxiliary, S=sample-20bits, V=valid, U=user data, C=channel status, P=parity)
  628. After BMC encoding, each bit becomes 2 hence this becomes a 64 bits word. The parity
  629. is fixed by changing AAAA bits so that VUPC does not change. Then then trick is to
  630. start not with a PPPP sequence but with an VUCP sequence to that the 16 bits samples
  631. are aligned with a BMC word boundary. Input buffer is left first => LRLR...
  632. The I2S interface must output first the B/M/W preamble which means that second
  633. 32 bits words must be first and so must be marked right channel.
  634. */
  635. static void IRAM_ATTR spdif_convert(ISAMPLE_T *src, size_t frames, u32_t *dst) {
  636. static u8_t vu, count;
  637. register u16_t hi, lo;
  638. #if BYTES_PER_FRAME == 8
  639. register u16_t aux;
  640. #endif
  641. // we assume frame == 0 as well...
  642. if (!src) {
  643. count = 0;
  644. vu = VUCP24[0];
  645. }
  646. while (frames--) {
  647. // start with left channel
  648. #if BYTES_PER_FRAME == 4
  649. hi = spdif_bmclookup[(u8_t)(*src >> 8)];
  650. lo = spdif_bmclookup[(u8_t)*src++];
  651. if (lo & 1) hi = ~hi;
  652. if (!count--) {
  653. *dst++ = (vu << 24) | (PREAMBLE_B << 16) | 0xCCCC;
  654. count = 191;
  655. } else {
  656. *dst++ = (vu << 24) | (PREAMBLE_M << 16) | 0xCCCC;
  657. }
  658. #else
  659. hi = spdif_bmclookup[(u8_t)(*src >> 24)];
  660. lo = spdif_bmclookup[(u8_t)(*src >> 16)];
  661. aux = spdif_bmclookup[(u8_t)(*src++ >> 8)];
  662. if (aux & 1) lo = ~lo;
  663. if (lo & 1) hi = ~hi;
  664. if (!count--) {
  665. *dst++ = (vu << 24) | (PREAMBLE_B << 16) | aux;
  666. count = 191;
  667. } else {
  668. *dst++ = (vu << 24) | (PREAMBLE_M << 16) | aux;
  669. }
  670. #endif
  671. vu = VUCP24[hi & 1];
  672. *dst++ = ((u32_t)lo << 16) | hi;
  673. // then do right channel, no need to check PREAMBLE_B
  674. #if BYTES_PER_FRAME == 4
  675. hi = spdif_bmclookup[(u8_t)(*src >> 8)];
  676. lo = spdif_bmclookup[(u8_t)*src++];
  677. if (lo & 1) hi = ~hi;
  678. *dst++ = (vu << 24) | (PREAMBLE_W << 16) | 0xCCCC;
  679. #else
  680. hi = spdif_bmclookup[(u8_t)(*src >> 24)];
  681. lo = spdif_bmclookup[(u8_t)(*src >> 16)];
  682. aux = spdif_bmclookup[(u8_t)(*src++ >> 8)];
  683. if (aux & 1) lo = ~lo;
  684. if (lo & 1) hi = ~hi;
  685. *dst++ = (vu << 24) | (PREAMBLE_W << 16) | aux;
  686. #endif
  687. vu = VUCP24[hi & 1];
  688. *dst++ = ((u32_t)lo << 16) | hi;
  689. }
  690. }