output_i2s.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. /*
  2. * Squeezelite for esp32
  3. *
  4. * (c) Sebastien 2019
  5. * Philippe G. 2019, philippe_44@outlook.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. /*
  22. Synchronisation is a bit of a hack with i2s. The esp32 driver is always
  23. full when it starts, so there is a delay of the total length of buffers.
  24. In other words, i2s_write blocks at first call, until at least one buffer
  25. has been written (it uses a queue with produce / consume).
  26. The first hack is to consume that length at the beginning of tracks when
  27. synchronization is active. It's about ~180ms @ 44.1kHz
  28. The second hack is that we never know exactly the number of frames in the
  29. DMA buffers when we update the output.frames_played_dmp. We assume that
  30. after i2s_write, these buffers are always full so by measuring the gap
  31. between time after i2s_write and update of frames_played_dmp, we have a
  32. good idea of the error.
  33. The third hack is when sample rate changes, buffers are reset and we also
  34. do the change too early, but can't do that exaclty at the right time. So
  35. there might be a pop and a de-sync when sampling rate change happens. Not
  36. sure that using rate_delay would fix that
  37. */
  38. #include "squeezelite.h"
  39. #include "esp_pthread.h"
  40. #include "driver/i2s.h"
  41. #include "driver/i2c.h"
  42. #include "driver/gpio.h"
  43. #include "perf_trace.h"
  44. #include <signal.h>
  45. #include "time.h"
  46. #include "led.h"
  47. #define LOCK mutex_lock(outputbuf->mutex)
  48. #define UNLOCK mutex_unlock(outputbuf->mutex)
  49. #define FRAME_BLOCK MAX_SILENCE_FRAMES
  50. // Prevent compile errors if dac output is
  51. // included in the build and not actually activated in menuconfig
  52. #ifndef CONFIG_I2S_BCK_IO
  53. #define CONFIG_I2S_BCK_IO -1
  54. #endif
  55. #ifndef CONFIG_I2S_WS_IO
  56. #define CONFIG_I2S_WS_IO -1
  57. #endif
  58. #ifndef CONFIG_I2S_DO_IO
  59. #define CONFIG_I2S_DO_IO -1
  60. #endif
  61. #ifndef CONFIG_I2S_NUM
  62. #define CONFIG_I2S_NUM -1
  63. #endif
  64. #ifndef CONFIG_SPDIF_BCK_IO
  65. #define CONFIG_SPDIF_BCK_IO -1
  66. #endif
  67. #ifndef CONFIG_SPDIF_WS_IO
  68. #define CONFIG_SPDIF_WS_IO -1
  69. #endif
  70. #ifndef CONFIG_SPDIF_DO_IO
  71. #define CONFIG_SPDIF_DO_IO -1
  72. #endif
  73. #ifndef CONFIG_SPDIF_NUM
  74. #define CONFIG_SPDIF_NUM -1
  75. #endif
  76. typedef enum { DAC_ACTIVE = 0, DAC_STANDBY, DAC_DOWN, DAC_ANALOGUE_OFF, DAC_ANALOGUE_ON, DAC_VOLUME } dac_cmd_e;
  77. // must have an integer ratio with FRAME_BLOCK (see spdif comment)
  78. #define DMA_BUF_LEN 512
  79. #define DMA_BUF_COUNT 12
  80. #define DECLARE_ALL_MIN_MAX \
  81. DECLARE_MIN_MAX(o); \
  82. DECLARE_MIN_MAX(s); \
  83. DECLARE_MIN_MAX(rec); \
  84. DECLARE_MIN_MAX(i2s_time); \
  85. DECLARE_MIN_MAX(buffering);
  86. #define RESET_ALL_MIN_MAX \
  87. RESET_MIN_MAX(o); \
  88. RESET_MIN_MAX(s); \
  89. RESET_MIN_MAX(rec); \
  90. RESET_MIN_MAX(i2s_time); \
  91. RESET_MIN_MAX(buffering);
  92. #define STATS_PERIOD_MS 5000
  93. extern struct outputstate output;
  94. extern struct buffer *streambuf;
  95. extern struct buffer *outputbuf;
  96. extern u8_t *silencebuf;
  97. bool jack_mutes_amp = false;
  98. static log_level loglevel;
  99. static bool running, isI2SStarted;
  100. static i2s_config_t i2s_config;
  101. static int bytes_per_frame;
  102. static thread_type thread, stats_thread;
  103. static u8_t *obuf;
  104. static frames_t oframes;
  105. static bool spdif;
  106. static size_t dma_buf_frames;
  107. static int jack_status = -1; // 0 = inserted
  108. DECLARE_ALL_MIN_MAX;
  109. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  110. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr);
  111. static void *output_thread_i2s();
  112. static void *output_thread_i2s_stats();
  113. static void dac_cmd(dac_cmd_e cmd, ...);
  114. static int tas57_detect(void);
  115. static void spdif_convert(ISAMPLE_T *src, size_t frames, u32_t *dst, size_t *count);
  116. #ifdef CONFIG_SQUEEZEAMP
  117. #define TAS57xx
  118. #undef CONFIG_I2S_BCK_IO
  119. #define CONFIG_I2S_BCK_IO 33
  120. #undef CONFIG_I2S_WS_IO
  121. #define CONFIG_I2S_WS_IO 25
  122. #undef CONFIG_I2S_DO_IO
  123. #define CONFIG_I2S_DO_IO 32
  124. #undef CONFIG_I2S_NUM
  125. #define CONFIG_I2S_NUM 0
  126. #undef CONFIG_SPDIF_BCK_IO
  127. #define CONFIG_SPDIF_BCK_IO 33
  128. #undef CONFIG_SPDIF_WS_IO
  129. #define CONFIG_SPDIF_WS_IO 25
  130. #undef CONFIG_SPDIF_DO_IO
  131. #define CONFIG_SPDIF_DO_IO 15
  132. #undef CONFIG_SPDIF_NUM
  133. #define CONFIG_SPDIF_NUM 0
  134. #define I2C_PORT 0
  135. #define VOLUME_GPIO 14
  136. #define JACK_GPIO 34
  137. #define TAS575x 0x98
  138. #define TAS578x 0x90
  139. static struct {
  140. float sum, avg;
  141. u16_t count;
  142. } battery;
  143. struct tas57xx_cmd_s {
  144. u8_t reg;
  145. u8_t value;
  146. };
  147. u8_t config_spdif_gpio = CONFIG_SPDIF_DO_IO;
  148. static const struct tas57xx_cmd_s tas57xx_init_sequence[] = {
  149. { 0x00, 0x00 }, // select page 0
  150. { 0x02, 0x10 }, // standby
  151. { 0x0d, 0x10 }, // use SCK for PLL
  152. { 0x25, 0x08 }, // ignore SCK halt
  153. { 0x08, 0x10 }, // Mute control enable (from TAS5780)
  154. { 0x54, 0x02 }, // Mute output control (from TAS5780)
  155. { 0x02, 0x00 }, // restart
  156. { 0xff, 0xff } // end of table
  157. };
  158. static const i2c_config_t i2c_config = {
  159. .mode = I2C_MODE_MASTER,
  160. .sda_io_num = 27,
  161. .sda_pullup_en = GPIO_PULLUP_ENABLE,
  162. .scl_io_num = 26,
  163. .scl_pullup_en = GPIO_PULLUP_ENABLE,
  164. .master.clk_speed = 100000,
  165. };
  166. static const struct tas57xx_cmd_s tas57xx_cmd[] = {
  167. { 0x02, 0x00 }, // DAC_ACTIVE
  168. { 0x02, 0x10 }, // DAC_STANDBY
  169. { 0x02, 0x01 }, // DAC_DOWN
  170. { 0x56, 0x10 }, // DAC_ANALOGUE_OFF
  171. { 0x56, 0x00 }, // DAC_ANALOGUE_ON
  172. };
  173. static u8_t tas57_addr;
  174. #endif
  175. /****************************************************************************************
  176. * Initialize the DAC output
  177. */
  178. void output_init_i2s(log_level level, char *device, unsigned output_buf_size, char *params, unsigned rates[], unsigned rate_delay, unsigned idle) {
  179. loglevel = level;
  180. #ifdef TAS57xx
  181. LOG_INFO("Initializing TAS57xx ");
  182. gpio_pad_select_gpio(JACK_GPIO);
  183. gpio_set_direction(JACK_GPIO, GPIO_MODE_INPUT);
  184. adc1_config_width(ADC_WIDTH_BIT_12);
  185. adc1_config_channel_atten(ADC1_CHANNEL_7, ADC_ATTEN_DB_0);
  186. // init volume & mute
  187. gpio_pad_select_gpio(VOLUME_GPIO);
  188. gpio_set_direction(VOLUME_GPIO, GPIO_MODE_OUTPUT);
  189. gpio_set_level(VOLUME_GPIO, 0);
  190. // configure i2c
  191. i2c_param_config(I2C_PORT, &i2c_config);
  192. i2c_driver_install(I2C_PORT, I2C_MODE_MASTER, false, false, false);
  193. // find which TAS we are using
  194. tas57_addr = tas57_detect();
  195. i2c_cmd_handle_t i2c_cmd = i2c_cmd_link_create();
  196. for (int i = 0; tas57xx_init_sequence[i].reg != 0xff; i++) {
  197. i2c_master_start(i2c_cmd);
  198. i2c_master_write_byte(i2c_cmd, tas57_addr | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  199. i2c_master_write_byte(i2c_cmd, tas57xx_init_sequence[i].reg, I2C_MASTER_NACK);
  200. i2c_master_write_byte(i2c_cmd, tas57xx_init_sequence[i].value, I2C_MASTER_NACK);
  201. LOG_DEBUG("i2c write %x at %u", tas57xx_init_sequence[i].reg, tas57xx_init_sequence[i].value);
  202. }
  203. i2c_master_stop(i2c_cmd);
  204. esp_err_t ret = i2c_master_cmd_begin(I2C_PORT, i2c_cmd, 500 / portTICK_RATE_MS);
  205. i2c_cmd_link_delete(i2c_cmd);
  206. if (ret != ESP_OK) {
  207. LOG_ERROR("could not intialize TAS57xx %d", ret);
  208. }
  209. #endif
  210. #ifdef CONFIG_I2S_BITS_PER_CHANNEL
  211. switch (CONFIG_I2S_BITS_PER_CHANNEL) {
  212. case 24:
  213. output.format = S24_BE;
  214. bytes_per_frame = 2*3;
  215. break;
  216. case 16:
  217. output.format = S16_BE;
  218. bytes_per_frame = 2*2;
  219. break;
  220. case 8:
  221. output.format = S8_BE;
  222. bytes_per_frame = 2*4;
  223. break;
  224. default:
  225. LOG_ERROR("Unsupported bit depth %d",CONFIG_I2S_BITS_PER_CHANNEL);
  226. break;
  227. }
  228. #else
  229. output.format = S16_LE;
  230. bytes_per_frame = 2*2;
  231. #endif
  232. if (strcasestr(device, "spdif")) spdif = true;
  233. output.write_cb = &_i2s_write_frames;
  234. obuf = malloc(FRAME_BLOCK * bytes_per_frame);
  235. if (!obuf) {
  236. LOG_ERROR("Cannot allocate i2s buffer");
  237. return;
  238. }
  239. running=true;
  240. i2s_pin_config_t pin_config;
  241. if (spdif) {
  242. pin_config = (i2s_pin_config_t) { .bck_io_num = CONFIG_SPDIF_BCK_IO, .ws_io_num = CONFIG_SPDIF_WS_IO,
  243. .data_out_num = CONFIG_SPDIF_DO_IO, .data_in_num = -1 //Not used
  244. };
  245. i2s_config.sample_rate = output.current_sample_rate * 2;
  246. i2s_config.bits_per_sample = 32;
  247. // Normally counted in frames, but 16 sample are transformed into 32 bits in spdif
  248. i2s_config.dma_buf_len = DMA_BUF_LEN / 2;
  249. i2s_config.dma_buf_count = DMA_BUF_COUNT * 2;
  250. /*
  251. In DMA, we have room for (LEN * COUNT) frames of 32 bits samples that
  252. we push at sample_rate * 2. Each of these peuso-frames is a single true
  253. audio frame. So the real depth is true frames is (LEN * COUNT / 2)
  254. */
  255. dma_buf_frames = DMA_BUF_COUNT * DMA_BUF_LEN / 2;
  256. } else {
  257. pin_config = (i2s_pin_config_t) { .bck_io_num = CONFIG_I2S_BCK_IO, .ws_io_num = CONFIG_I2S_WS_IO,
  258. .data_out_num = CONFIG_I2S_DO_IO, .data_in_num = -1 //Not used
  259. };
  260. i2s_config.sample_rate = output.current_sample_rate;
  261. i2s_config.bits_per_sample = bytes_per_frame * 8 / 2;
  262. // Counted in frames (but i2s allocates a buffer <= 4092 bytes)
  263. i2s_config.dma_buf_len = DMA_BUF_LEN;
  264. i2s_config.dma_buf_count = DMA_BUF_COUNT;
  265. dma_buf_frames = DMA_BUF_COUNT * DMA_BUF_LEN;
  266. #ifdef TAS57xx
  267. gpio_pad_select_gpio(CONFIG_SPDIF_DO_IO);
  268. gpio_set_direction(CONFIG_SPDIF_DO_IO, GPIO_MODE_OUTPUT);
  269. gpio_set_level(CONFIG_SPDIF_DO_IO, 0);
  270. #endif
  271. }
  272. i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_TX;
  273. i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
  274. i2s_config.communication_format = I2S_COMM_FORMAT_I2S| I2S_COMM_FORMAT_I2S_MSB;
  275. // in case of overflow, do not replay old buffer
  276. i2s_config.tx_desc_auto_clear = true;
  277. i2s_config.use_apll = true;
  278. i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; //Interrupt level 1
  279. LOG_INFO("Initializing I2S mode %s with rate: %d, bits per sample: %d, buffer frames: %d, number of buffers: %d ",
  280. spdif ? "S/PDIF" : "normal",
  281. i2s_config.sample_rate, i2s_config.bits_per_sample, i2s_config.dma_buf_len, i2s_config.dma_buf_count);
  282. i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  283. i2s_set_pin(CONFIG_I2S_NUM, &pin_config);
  284. i2s_stop(CONFIG_I2S_NUM);
  285. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  286. isI2SStarted=false;
  287. dac_cmd(DAC_STANDBY);
  288. esp_pthread_cfg_t cfg = esp_pthread_get_default_config();
  289. cfg.thread_name= "output_i2s";
  290. cfg.inherit_cfg = false;
  291. cfg.prio = CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT + 1;
  292. cfg.stack_size = PTHREAD_STACK_MIN + OUTPUT_THREAD_STACK_SIZE;
  293. esp_pthread_set_cfg(&cfg);
  294. pthread_create(&thread, NULL, output_thread_i2s, NULL);
  295. cfg.thread_name= "output_i2s_sts";
  296. cfg.prio = CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT - 1;
  297. cfg.stack_size = 2048;
  298. esp_pthread_set_cfg(&cfg);
  299. pthread_create(&stats_thread, NULL, output_thread_i2s_stats, NULL);
  300. }
  301. /****************************************************************************************
  302. * Terminate DAC output
  303. */
  304. void output_close_i2s(void) {
  305. LOCK;
  306. running = false;
  307. UNLOCK;
  308. pthread_join(thread, NULL);
  309. pthread_join(stats_thread, NULL);
  310. i2s_driver_uninstall(CONFIG_I2S_NUM);
  311. free(obuf);
  312. #ifdef TAS57xx
  313. i2c_driver_delete(I2C_PORT);
  314. #endif
  315. }
  316. /****************************************************************************************
  317. * change volume
  318. */
  319. bool output_volume_i2s(unsigned left, unsigned right) {
  320. #ifdef TAS57xx
  321. if (!spdif) {
  322. LOG_INFO("TAS57xx volume (L:%u R:%u)", left, right);
  323. gpio_set_level(VOLUME_GPIO, left || right);
  324. }
  325. #endif
  326. return false;
  327. }
  328. /****************************************************************************************
  329. * Write frames to the output buffer
  330. */
  331. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  332. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr) {
  333. #if BYTES_PER_FRAME == 8
  334. s32_t *optr;
  335. #endif
  336. if (!silence) {
  337. if (output.fade == FADE_ACTIVE && output.fade_dir == FADE_CROSS && *cross_ptr) {
  338. _apply_cross(outputbuf, out_frames, cross_gain_in, cross_gain_out, cross_ptr);
  339. }
  340. #if BYTES_PER_FRAME == 4
  341. if (gainL != FIXED_ONE || gainR!= FIXED_ONE) {
  342. _apply_gain(outputbuf, out_frames, gainL, gainR);
  343. }
  344. memcpy(obuf + oframes * bytes_per_frame, outputbuf->readp, out_frames * bytes_per_frame);
  345. #else
  346. optr = (s32_t*) outputbuf->readp;
  347. #endif
  348. } else {
  349. #if BYTES_PER_FRAME == 4
  350. memcpy(obuf + oframes * bytes_per_frame, silencebuf, out_frames * bytes_per_frame);
  351. #else
  352. optr = (s32_t*) silencebuf;
  353. #endif
  354. }
  355. #if BYTES_PER_FRAME == 8
  356. IF_DSD(
  357. if (output.outfmt == DOP) {
  358. update_dop((u32_t *) optr, out_frames, output.invert);
  359. } else if (output.outfmt != PCM && output.invert)
  360. dsd_invert((u32_t *) optr, out_frames);
  361. )
  362. _scale_and_pack_frames(obuf + oframes * bytes_per_frame, optr, out_frames, gainL, gainR, output.format);
  363. #endif
  364. oframes += out_frames;
  365. return out_frames;
  366. }
  367. /****************************************************************************************
  368. * Main output thread
  369. */
  370. static void *output_thread_i2s() {
  371. size_t count = 0, bytes;
  372. frames_t iframes = FRAME_BLOCK;
  373. uint32_t timer_start = 0;
  374. int discard = 0;
  375. uint32_t fullness = gettime_ms();
  376. bool synced;
  377. output_state state = OUTPUT_OFF;
  378. char *sbuf = NULL;
  379. // spdif needs 16 bytes per frame : 32 bits/sample, 2 channels, BMC encoded
  380. if (spdif && (sbuf = malloc(FRAME_BLOCK * 16)) == NULL) {
  381. LOG_ERROR("Cannot allocate SPDIF buffer");
  382. }
  383. while (running) {
  384. TIME_MEASUREMENT_START(timer_start);
  385. #ifdef TAS57xx
  386. // handle jack insertion as a polling function (to avoid to have to do de-bouncing)
  387. if (gpio_get_level(JACK_GPIO) != jack_status) {
  388. jack_status = gpio_get_level(JACK_GPIO);
  389. if (jack_mutes_amp) {
  390. dac_cmd(jack_status ? DAC_ANALOGUE_ON : DAC_ANALOGUE_OFF);
  391. LOG_INFO("Changing jack status %d", jack_status);
  392. }
  393. }
  394. #endif
  395. LOCK;
  396. // manage led display
  397. if (state != output.state) {
  398. LOG_INFO("Output state is %d", output.state);
  399. if (output.state == OUTPUT_OFF) led_blink(LED_GREEN, 100, 2500);
  400. else if (output.state == OUTPUT_STOPPED) {
  401. #ifdef TAS57xx
  402. dac_cmd(DAC_ANALOGUE_OFF);
  403. #endif
  404. led_blink(LED_GREEN, 200, 1000);
  405. } else if (output.state == OUTPUT_RUNNING) {
  406. #ifdef TAS57xx
  407. if (!jack_mutes_amp || (jack_mutes_amp && jack_status)) dac_cmd(DAC_ANALOGUE_ON);
  408. #endif
  409. led_on(LED_GREEN);
  410. }
  411. }
  412. state = output.state;
  413. if (output.state == OUTPUT_OFF) {
  414. UNLOCK;
  415. if (isI2SStarted) {
  416. isI2SStarted = false;
  417. i2s_stop(CONFIG_I2S_NUM);
  418. if (!spdif) dac_cmd(DAC_STANDBY);
  419. count = 0;
  420. }
  421. usleep(200000);
  422. continue;
  423. } else if (output.state == OUTPUT_STOPPED) {
  424. synced = false;
  425. }
  426. oframes = 0;
  427. output.updated = gettime_ms();
  428. output.frames_played_dmp = output.frames_played;
  429. // try to estimate how much we have consumed from the DMA buffer (calculation is incorrect at the very beginning ...)
  430. output.device_frames = dma_buf_frames - ((output.updated - fullness) * output.current_sample_rate) / 1000;
  431. _output_frames( iframes );
  432. // oframes must be a global updated by the write callback
  433. output.frames_in_process = oframes;
  434. SET_MIN_MAX_SIZED(oframes,rec,iframes);
  435. SET_MIN_MAX_SIZED(_buf_used(outputbuf),o,outputbuf->size);
  436. SET_MIN_MAX_SIZED(_buf_used(streambuf),s,streambuf->size);
  437. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),buffering);
  438. /* must skip first whatever is in the pipe (but not when resuming).
  439. This test is incorrect when we pause a track that has just started,
  440. but this is higly unlikely and I don't have a better one for now */
  441. if (output.state == OUTPUT_START_AT) {
  442. discard = output.frames_played_dmp ? 0 : output.device_frames;
  443. synced = true;
  444. } else if (discard) {
  445. discard -= oframes;
  446. iframes = discard ? min(FRAME_BLOCK, discard) : FRAME_BLOCK;
  447. UNLOCK;
  448. continue;
  449. }
  450. UNLOCK;
  451. // now send all the data
  452. TIME_MEASUREMENT_START(timer_start);
  453. if (!isI2SStarted ) {
  454. isI2SStarted = true;
  455. LOG_INFO("Restarting I2S.");
  456. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  457. i2s_start(CONFIG_I2S_NUM);
  458. if (!spdif) dac_cmd(DAC_ACTIVE);
  459. }
  460. // this does not work well as set_sample_rates resets the fifos (and it's too early)
  461. if (i2s_config.sample_rate != output.current_sample_rate) {
  462. LOG_INFO("changing sampling rate %u to %u", i2s_config.sample_rate, output.current_sample_rate);
  463. /*
  464. if (synced)
  465. // can sleep for a buffer_queue - 1 and then eat a buffer (discard) if we are synced
  466. usleep(((DMA_BUF_COUNT - 1) * DMA_BUF_LEN * bytes_per_frame * 1000) / 44100 * 1000);
  467. discard = DMA_BUF_COUNT * DMA_BUF_LEN * bytes_per_frame;
  468. }
  469. */
  470. i2s_config.sample_rate = output.current_sample_rate;
  471. i2s_set_sample_rates(CONFIG_I2S_NUM, spdif ? i2s_config.sample_rate * 2 : i2s_config.sample_rate);
  472. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  473. //return;
  474. }
  475. // we assume that here we have been able to entirely fill the DMA buffers
  476. if (spdif) {
  477. spdif_convert((ISAMPLE_T*) obuf, oframes, (u32_t*) sbuf, &count);
  478. i2s_write(CONFIG_I2S_NUM, sbuf, oframes * 16, &bytes, portMAX_DELAY);
  479. bytes /= 4;
  480. } else {
  481. i2s_write(CONFIG_I2S_NUM, obuf, oframes * bytes_per_frame, &bytes, portMAX_DELAY);
  482. }
  483. fullness = gettime_ms();
  484. if (bytes != oframes * bytes_per_frame) {
  485. LOG_WARN("I2S DMA Overflow! available bytes: %d, I2S wrote %d bytes", oframes * bytes_per_frame, bytes);
  486. }
  487. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),i2s_time);
  488. }
  489. if (spdif) free(sbuf);
  490. return 0;
  491. }
  492. /****************************************************************************************
  493. * Stats output thread
  494. */
  495. static void *output_thread_i2s_stats() {
  496. int memory_count = 0;
  497. while (running) {
  498. #ifdef TAS57xx
  499. battery.sum += adc1_get_raw(ADC1_CHANNEL_7) / 4095. * (10+174)/10. * 1.1;
  500. if (++battery.count == (300 * 1000) / STATS_PERIOD_MS) {
  501. battery.avg = battery.sum / battery.count;
  502. battery.sum = battery.count = 0;
  503. LOG_INFO("Voltage %.2fV", battery.avg);
  504. }
  505. #endif
  506. LOCK;
  507. output_state state = output.state;
  508. UNLOCK;
  509. if(state>OUTPUT_STOPPED){
  510. LOG_INFO( "Output State: %d, current sample rate: %d, bytes per frame: %d",state,output.current_sample_rate, bytes_per_frame);
  511. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD1);
  512. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD2);
  513. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD3);
  514. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD4);
  515. LOG_INFO(LINE_MIN_MAX_FORMAT_STREAM, LINE_MIN_MAX_STREAM("stream",s));
  516. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("output",o));
  517. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  518. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("received",rec));
  519. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  520. LOG_INFO("");
  521. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  522. LOG_INFO(" max (us) | min (us) | avg(us) | count | ");
  523. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  524. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("Buffering(us)",buffering));
  525. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("i2s tfr(us)",i2s_time));
  526. LOG_INFO(" ----------+----------+-----------+-----------+");
  527. RESET_ALL_MIN_MAX;
  528. }
  529. if (loglevel == lDEBUG || !memory_count--) {
  530. LOG_INFO("Heap internal:%zu (min:%zu) external:%zu (min:%zu)",
  531. heap_caps_get_free_size(MALLOC_CAP_INTERNAL),
  532. heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL),
  533. heap_caps_get_free_size(MALLOC_CAP_SPIRAM),
  534. heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM));
  535. memory_count = (60*1000) / STATS_PERIOD_MS;
  536. }
  537. usleep(STATS_PERIOD_MS *1000);
  538. }
  539. return NULL;
  540. }
  541. /****************************************************************************************
  542. * DAC specific commands
  543. */
  544. void dac_cmd(dac_cmd_e cmd, ...) {
  545. va_list args;
  546. esp_err_t ret = ESP_OK;
  547. va_start(args, cmd);
  548. #ifdef TAS57xx
  549. i2c_cmd_handle_t i2c_cmd = i2c_cmd_link_create();
  550. switch(cmd) {
  551. case DAC_VOLUME:
  552. LOG_ERROR("volume not handled yet");
  553. break;
  554. default:
  555. i2c_master_start(i2c_cmd);
  556. i2c_master_write_byte(i2c_cmd, tas57_addr | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  557. i2c_master_write_byte(i2c_cmd, tas57xx_cmd[cmd].reg, I2C_MASTER_NACK);
  558. i2c_master_write_byte(i2c_cmd, tas57xx_cmd[cmd].value, I2C_MASTER_NACK);
  559. i2c_master_stop(i2c_cmd);
  560. ret = i2c_master_cmd_begin(I2C_PORT, i2c_cmd, 50 / portTICK_RATE_MS);
  561. }
  562. i2c_cmd_link_delete(i2c_cmd);
  563. if (ret != ESP_OK) {
  564. LOG_ERROR("could not intialize TAS57xx %d", ret);
  565. }
  566. #endif
  567. va_end(args);
  568. }
  569. /****************************************************************************************
  570. * TAS57 detection
  571. */
  572. #ifdef TAS57xx
  573. static int tas57_detect(void) {
  574. u8_t data, addr[] = {TAS578x, TAS575x};
  575. int ret;
  576. for (int i = 0; i < sizeof(addr); i++) {
  577. i2c_cmd_handle_t i2c_cmd = i2c_cmd_link_create();
  578. i2c_master_start(i2c_cmd);
  579. i2c_master_write_byte(i2c_cmd, addr[i] | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  580. i2c_master_write_byte(i2c_cmd, 00, I2C_MASTER_NACK);
  581. i2c_master_start(i2c_cmd);
  582. i2c_master_write_byte(i2c_cmd, addr[i] | I2C_MASTER_READ, I2C_MASTER_NACK);
  583. i2c_master_read_byte(i2c_cmd, &data, I2C_MASTER_NACK);
  584. i2c_master_stop(i2c_cmd);
  585. ret = i2c_master_cmd_begin(I2C_PORT, i2c_cmd, 50 / portTICK_RATE_MS);
  586. i2c_cmd_link_delete(i2c_cmd);
  587. if (ret == ESP_OK) {
  588. LOG_INFO("Detected TAS @0x%x", addr[i]);
  589. return addr[i];
  590. }
  591. }
  592. return 0;
  593. }
  594. #endif
  595. /****************************************************************************************
  596. * SPDIF support
  597. */
  598. #define PREAMBLE_B (0xE8) //11101000
  599. #define PREAMBLE_M (0xE2) //11100010
  600. #define PREAMBLE_W (0xE4) //11100100
  601. #define VUCP ((0xCC) << 24)
  602. #define VUCP_MUTE ((0xD4) << 24) // To mute PCM, set VUCP = invalid.
  603. extern const u16_t spdif_bmclookup[256];
  604. /*
  605. SPDIF is supposed to be (before BMC encoding, from LSB to MSB)
  606. PPPP AAAA SSSS SSSS SSSS SSSS SSSS VUCP
  607. after BMC encoding, each bits becomes 2 hence this becomes a 64 bits word. The
  608. the trick is to start not with a PPPP sequence but with an VUCP sequence to that
  609. the 16 bits samples are aligned with a BMC word boundary. Note that the LSB of the
  610. audio is transmitted first (not the MSB) and that ESP32 libray sends R then L,
  611. contrary to what seems to be usually done, so (dst) order had to be changed
  612. */
  613. void spdif_convert(ISAMPLE_T *src, size_t frames, u32_t *dst, size_t *count) {
  614. u16_t hi, lo, aux;
  615. // frames are 2 channels of 16 bits
  616. frames *= 2;
  617. while (frames--) {
  618. #if BYTES_PER_FRAME == 4
  619. hi = spdif_bmclookup[(u8_t)(*src >> 8)];
  620. lo = spdif_bmclookup[(u8_t) *src];
  621. #else
  622. hi = spdif_bmclookup[(u8_t)(*src >> 24)];
  623. lo = spdif_bmclookup[(u8_t) *src >> 16];
  624. #endif
  625. lo ^= ~((s16_t)hi) >> 16;
  626. // 16 bits sample:
  627. *(dst+0) = ((u32_t)lo << 16) | hi;
  628. // 4 bits auxillary-audio-databits, the first used as parity
  629. aux = 0xb333 ^ (((u32_t)((s16_t)lo)) >> 17);
  630. // VUCP-Bits: Valid, Subcode, Channelstatus, Parity = 0
  631. // As parity is always 0, we can use fixed preambles
  632. if (++(*count) > 383) {
  633. *(dst+1) = VUCP | (PREAMBLE_B << 16 ) | aux; //special preamble for one of 192 frames
  634. *count = 0;
  635. } else {
  636. *(dst+1) = VUCP | ((((*count) & 0x01) ? PREAMBLE_W : PREAMBLE_M) << 16) | aux;
  637. }
  638. src++;
  639. dst += 2;
  640. }
  641. }
  642. const u16_t spdif_bmclookup[256] = { //biphase mark encoded values (least significant bit first)
  643. 0xcccc, 0x4ccc, 0x2ccc, 0xaccc, 0x34cc, 0xb4cc, 0xd4cc, 0x54cc,
  644. 0x32cc, 0xb2cc, 0xd2cc, 0x52cc, 0xcacc, 0x4acc, 0x2acc, 0xaacc,
  645. 0x334c, 0xb34c, 0xd34c, 0x534c, 0xcb4c, 0x4b4c, 0x2b4c, 0xab4c,
  646. 0xcd4c, 0x4d4c, 0x2d4c, 0xad4c, 0x354c, 0xb54c, 0xd54c, 0x554c,
  647. 0x332c, 0xb32c, 0xd32c, 0x532c, 0xcb2c, 0x4b2c, 0x2b2c, 0xab2c,
  648. 0xcd2c, 0x4d2c, 0x2d2c, 0xad2c, 0x352c, 0xb52c, 0xd52c, 0x552c,
  649. 0xccac, 0x4cac, 0x2cac, 0xacac, 0x34ac, 0xb4ac, 0xd4ac, 0x54ac,
  650. 0x32ac, 0xb2ac, 0xd2ac, 0x52ac, 0xcaac, 0x4aac, 0x2aac, 0xaaac,
  651. 0x3334, 0xb334, 0xd334, 0x5334, 0xcb34, 0x4b34, 0x2b34, 0xab34,
  652. 0xcd34, 0x4d34, 0x2d34, 0xad34, 0x3534, 0xb534, 0xd534, 0x5534,
  653. 0xccb4, 0x4cb4, 0x2cb4, 0xacb4, 0x34b4, 0xb4b4, 0xd4b4, 0x54b4,
  654. 0x32b4, 0xb2b4, 0xd2b4, 0x52b4, 0xcab4, 0x4ab4, 0x2ab4, 0xaab4,
  655. 0xccd4, 0x4cd4, 0x2cd4, 0xacd4, 0x34d4, 0xb4d4, 0xd4d4, 0x54d4,
  656. 0x32d4, 0xb2d4, 0xd2d4, 0x52d4, 0xcad4, 0x4ad4, 0x2ad4, 0xaad4,
  657. 0x3354, 0xb354, 0xd354, 0x5354, 0xcb54, 0x4b54, 0x2b54, 0xab54,
  658. 0xcd54, 0x4d54, 0x2d54, 0xad54, 0x3554, 0xb554, 0xd554, 0x5554,
  659. 0x3332, 0xb332, 0xd332, 0x5332, 0xcb32, 0x4b32, 0x2b32, 0xab32,
  660. 0xcd32, 0x4d32, 0x2d32, 0xad32, 0x3532, 0xb532, 0xd532, 0x5532,
  661. 0xccb2, 0x4cb2, 0x2cb2, 0xacb2, 0x34b2, 0xb4b2, 0xd4b2, 0x54b2,
  662. 0x32b2, 0xb2b2, 0xd2b2, 0x52b2, 0xcab2, 0x4ab2, 0x2ab2, 0xaab2,
  663. 0xccd2, 0x4cd2, 0x2cd2, 0xacd2, 0x34d2, 0xb4d2, 0xd4d2, 0x54d2,
  664. 0x32d2, 0xb2d2, 0xd2d2, 0x52d2, 0xcad2, 0x4ad2, 0x2ad2, 0xaad2,
  665. 0x3352, 0xb352, 0xd352, 0x5352, 0xcb52, 0x4b52, 0x2b52, 0xab52,
  666. 0xcd52, 0x4d52, 0x2d52, 0xad52, 0x3552, 0xb552, 0xd552, 0x5552,
  667. 0xccca, 0x4cca, 0x2cca, 0xacca, 0x34ca, 0xb4ca, 0xd4ca, 0x54ca,
  668. 0x32ca, 0xb2ca, 0xd2ca, 0x52ca, 0xcaca, 0x4aca, 0x2aca, 0xaaca,
  669. 0x334a, 0xb34a, 0xd34a, 0x534a, 0xcb4a, 0x4b4a, 0x2b4a, 0xab4a,
  670. 0xcd4a, 0x4d4a, 0x2d4a, 0xad4a, 0x354a, 0xb54a, 0xd54a, 0x554a,
  671. 0x332a, 0xb32a, 0xd32a, 0x532a, 0xcb2a, 0x4b2a, 0x2b2a, 0xab2a,
  672. 0xcd2a, 0x4d2a, 0x2d2a, 0xad2a, 0x352a, 0xb52a, 0xd52a, 0x552a,
  673. 0xccaa, 0x4caa, 0x2caa, 0xacaa, 0x34aa, 0xb4aa, 0xd4aa, 0x54aa,
  674. 0x32aa, 0xb2aa, 0xd2aa, 0x52aa, 0xcaaa, 0x4aaa, 0x2aaa, 0xaaaa
  675. };