output_i2s.c 28 KB

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