output_i2s.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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, i2w_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 "driver/i2s.h"
  40. #include "driver/i2c.h"
  41. #include "driver/gpio.h"
  42. #include "perf_trace.h"
  43. #include <signal.h>
  44. #include "time.h"
  45. #include "led.h"
  46. #define LOCK mutex_lock(outputbuf->mutex)
  47. #define UNLOCK mutex_unlock(outputbuf->mutex)
  48. #define FRAME_BLOCK MAX_SILENCE_FRAMES
  49. // Prevent compile errors if dac output is
  50. // included in the build and not actually activated in menuconfig
  51. #ifndef CONFIG_I2S_BCK_IO
  52. #define CONFIG_I2S_BCK_IO -1
  53. #endif
  54. #ifndef CONFIG_I2S_WS_IO
  55. #define CONFIG_I2S_WS_IO -1
  56. #endif
  57. #ifndef CONFIG_I2S_DO_IO
  58. #define CONFIG_I2S_DO_IO -1
  59. #endif
  60. #ifndef CONFIG_I2S_NUM
  61. #define CONFIG_I2S_NUM -1
  62. #endif
  63. typedef enum { DAC_ON = 0, DAC_OFF, DAC_POWERDOWN, DAC_VOLUME } dac_cmd_e;
  64. // must have an integer ratio with FRAME_BLOCK
  65. #define DMA_BUF_LEN 512
  66. #define DMA_BUF_COUNT 16
  67. #define DECLARE_ALL_MIN_MAX \
  68. DECLARE_MIN_MAX(o); \
  69. DECLARE_MIN_MAX(s); \
  70. DECLARE_MIN_MAX(rec); \
  71. DECLARE_MIN_MAX(i2s_time); \
  72. DECLARE_MIN_MAX(buffering);
  73. #define RESET_ALL_MIN_MAX \
  74. RESET_MIN_MAX(o); \
  75. RESET_MIN_MAX(s); \
  76. RESET_MIN_MAX(rec); \
  77. RESET_MIN_MAX(i2s_time); \
  78. RESET_MIN_MAX(buffering);
  79. #define STATS_PERIOD_MS 5000
  80. extern struct outputstate output;
  81. extern struct buffer *streambuf;
  82. extern struct buffer *outputbuf;
  83. extern u8_t *silencebuf;
  84. static log_level loglevel;
  85. static bool running, isI2SStarted;
  86. static i2s_config_t i2s_config;
  87. static int bytes_per_frame;
  88. static thread_type thread, stats_thread;
  89. static u8_t *obuf;
  90. DECLARE_ALL_MIN_MAX;
  91. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  92. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr);
  93. static void *output_thread_i2s();
  94. static void *output_thread_i2s_stats();
  95. static void dac_cmd(dac_cmd_e cmd, ...);
  96. #ifdef CONFIG_SQUEEZEAMP
  97. #define TAS575x
  98. #undef CONFIG_I2S_BCK_IO
  99. #define CONFIG_I2S_BCK_IO 33
  100. #undef CONFIG_I2S_WS_IO
  101. #define CONFIG_I2S_WS_IO 25
  102. #undef CONFIG_I2S_DO_IO
  103. #define CONFIG_I2S_DO_IO 32
  104. #undef CONFIG_I2S_NUM
  105. #define CONFIG_I2S_NUM 0
  106. #define I2C_PORT 0
  107. #define I2C_ADDR 0x4c
  108. #define VOLUME_GPIO 33
  109. struct tas575x_cmd_s {
  110. u8_t reg;
  111. u8_t value;
  112. };
  113. static const struct tas575x_cmd_s tas575x_init_sequence[] = {
  114. { 0x00, 0x00 }, // select page 0
  115. { 0x02, 0x10 }, // standby
  116. { 0x0d, 0x10 }, // use SCK for PLL
  117. { 0x25, 0x08 }, // ignore SCK halt
  118. { 0x02, 0x00 }, // restart
  119. { 0xff, 0xff } // end of table
  120. };
  121. static const i2c_config_t i2c_config = {
  122. .mode = I2C_MODE_MASTER,
  123. .sda_io_num = 27,
  124. .sda_pullup_en = GPIO_PULLUP_ENABLE,
  125. .scl_io_num = 26,
  126. .scl_pullup_en = GPIO_PULLUP_ENABLE,
  127. .master.clk_speed = 100000,
  128. };
  129. static const struct tas575x_cmd_s tas575x_cmd[] = {
  130. { 0x02, 0x00 }, // DAC_ON
  131. { 0x02, 0x10 }, // DAC_OFF
  132. { 0x02, 0x01 }, // DAC_POWERDOWN
  133. };
  134. #endif
  135. /****************************************************************************************
  136. * Initialize the DAC output
  137. */
  138. void output_init_i2s(log_level level, char *device, unsigned output_buf_size, char *params, unsigned rates[], unsigned rate_delay, unsigned idle) {
  139. loglevel = level;
  140. #ifdef TAS575x
  141. gpio_pad_select_gpio(39);
  142. gpio_set_direction(39, GPIO_MODE_INPUT);
  143. adc1_config_width(ADC_WIDTH_BIT_12);
  144. adc1_config_channel_atten(ADC1_CHANNEL_0,ADC_ATTEN_DB_0);
  145. // init volume & mute
  146. gpio_pad_select_gpio(VOLUME_GPIO);
  147. gpio_set_direction(VOLUME_GPIO, GPIO_MODE_OUTPUT);
  148. gpio_set_level(VOLUME_GPIO, 0);
  149. // configure i2c
  150. i2c_param_config(I2C_PORT, &i2c_config);
  151. i2c_driver_install(I2C_PORT, I2C_MODE_MASTER, false, false, false);
  152. i2c_cmd_handle_t i2c_cmd = i2c_cmd_link_create();
  153. for (int i = 0; tas575x_init_sequence[i].reg != 0xff; i++) {
  154. i2c_master_start(i2c_cmd);
  155. i2c_master_write_byte(i2c_cmd, I2C_ADDR << 1 | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  156. i2c_master_write_byte(i2c_cmd, tas575x_init_sequence[i].reg, I2C_MASTER_NACK);
  157. i2c_master_write_byte(i2c_cmd, tas575x_init_sequence[i].value, I2C_MASTER_NACK);
  158. LOG_DEBUG("i2c write %x at %u", tas575x_init_sequence[i].reg, tas575x_init_sequence[i].value);
  159. }
  160. i2c_master_stop(i2c_cmd);
  161. esp_err_t ret = i2c_master_cmd_begin(I2C_PORT, i2c_cmd, 500 / portTICK_RATE_MS);
  162. i2c_cmd_link_delete(i2c_cmd);
  163. if (ret != ESP_OK) {
  164. LOG_ERROR("could not intialize TAS575x %d", ret);
  165. }
  166. #endif
  167. #ifdef CONFIG_I2S_BITS_PER_CHANNEL
  168. switch (CONFIG_I2S_BITS_PER_CHANNEL) {
  169. case 24:
  170. output.format = S24_BE;
  171. bytes_per_frame = 2*3;
  172. break;
  173. case 16:
  174. output.format = S16_BE;
  175. bytes_per_frame = 2*2;
  176. break;
  177. case 8:
  178. output.format = S8_BE;
  179. bytes_per_frame = 2*4;
  180. break;
  181. default:
  182. LOG_ERROR("Unsupported bit depth %d",CONFIG_I2S_BITS_PER_CHANNEL);
  183. break;
  184. }
  185. #else
  186. output.format = S16_LE;
  187. bytes_per_frame = 2*2;
  188. #endif
  189. output.write_cb = &_i2s_write_frames;
  190. obuf = malloc(FRAME_BLOCK * bytes_per_frame);
  191. if (!obuf) {
  192. LOG_ERROR("Cannot allocate i2s buffer");
  193. return;
  194. }
  195. running=true;
  196. i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_TX;
  197. i2s_config.sample_rate = output.current_sample_rate;
  198. i2s_config.bits_per_sample = bytes_per_frame * 8 / 2;
  199. i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
  200. i2s_config.communication_format = I2S_COMM_FORMAT_I2S| I2S_COMM_FORMAT_I2S_MSB;
  201. // in case of overflow, do not replay old buffer
  202. i2s_config.tx_desc_auto_clear = true;
  203. i2s_config.dma_buf_count = DMA_BUF_COUNT;
  204. // Counted in frames (but i2s allocates a buffer <= 4092 bytes)
  205. i2s_config.dma_buf_len = DMA_BUF_LEN;
  206. i2s_config.use_apll = true;
  207. i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; //Interrupt level 1
  208. i2s_pin_config_t pin_config = { .bck_io_num = CONFIG_I2S_BCK_IO, .ws_io_num =
  209. CONFIG_I2S_WS_IO, .data_out_num = CONFIG_I2S_DO_IO, .data_in_num = -1 //Not used
  210. };
  211. LOG_INFO("Initializing I2S with rate: %d, bits per sample: %d, buffer frames: %d, number of buffers: %d ",
  212. i2s_config.sample_rate, i2s_config.bits_per_sample, i2s_config.dma_buf_len, i2s_config.dma_buf_count);
  213. i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  214. i2s_set_pin(CONFIG_I2S_NUM, &pin_config);
  215. i2s_stop(CONFIG_I2S_NUM);
  216. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  217. isI2SStarted=false;
  218. pthread_attr_t attr;
  219. pthread_attr_init(&attr);
  220. pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + OUTPUT_THREAD_STACK_SIZE);
  221. pthread_create_name(&thread, &attr, output_thread_i2s, NULL, "output_i2s");
  222. pthread_attr_destroy(&attr);
  223. // leave stack size to default
  224. pthread_create_name(&stats_thread, NULL, output_thread_i2s_stats, NULL, "output_i2s_sts");
  225. }
  226. /****************************************************************************************
  227. * Terminate DAC output
  228. */
  229. void output_close_i2s(void) {
  230. LOCK;
  231. running = false;
  232. UNLOCK;
  233. pthread_join(thread, NULL);
  234. pthread_join(stats_thread, NULL);
  235. i2s_driver_uninstall(CONFIG_I2S_NUM);
  236. free(obuf);
  237. #ifdef TAS575x
  238. i2c_driver_delete(I2C_PORT);
  239. #endif
  240. }
  241. /****************************************************************************************
  242. * change volume
  243. */
  244. bool output_volume_i2s(unsigned left, unsigned right) {
  245. #ifdef TAS575x
  246. gpio_set_level(VOLUME_GPIO, left || right);
  247. #endif
  248. return false;
  249. }
  250. /****************************************************************************************
  251. * Write frames to the output buffer
  252. */
  253. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  254. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr) {
  255. #if BYTES_PER_FRAME == 8
  256. s32_t *optr;
  257. #endif
  258. if (!silence) {
  259. if (output.fade == FADE_ACTIVE && output.fade_dir == FADE_CROSS && *cross_ptr) {
  260. _apply_cross(outputbuf, out_frames, cross_gain_in, cross_gain_out, cross_ptr);
  261. }
  262. #if BYTES_PER_FRAME == 4
  263. if (gainL != FIXED_ONE || gainR!= FIXED_ONE) {
  264. _apply_gain(outputbuf, out_frames, gainL, gainR);
  265. }
  266. memcpy(obuf, outputbuf->readp, out_frames * bytes_per_frame);
  267. #else
  268. optr = (s32_t*) outputbuf->readp;
  269. #endif
  270. } else {
  271. #if BYTES_PER_FRAME == 4
  272. memcpy(obuf, silencebuf, out_frames * bytes_per_frame);
  273. #else
  274. optr = (s32_t*) silencebuf;
  275. #endif
  276. }
  277. #if BYTES_PER_FRAME == 8
  278. IF_DSD(
  279. if (output.outfmt == DOP) {
  280. update_dop((u32_t *) optr, out_frames, output.invert);
  281. } else if (output.outfmt != PCM && output.invert)
  282. dsd_invert((u32_t *) optr, out_frames);
  283. )
  284. _scale_and_pack_frames(obuf, optr, out_frames, gainL, gainR, output.format);
  285. #endif
  286. return out_frames;
  287. }
  288. /****************************************************************************************
  289. * Main output thread
  290. */
  291. static void *output_thread_i2s() {
  292. frames_t iframes = FRAME_BLOCK, oframes;
  293. size_t bytes;
  294. uint32_t timer_start = 0;
  295. int discard = 0;
  296. uint32_t fullness = gettime_ms();
  297. bool synced;
  298. #ifdef TAS575x
  299. output_state state = OUTPUT_OFF;
  300. #endif
  301. while (running) {
  302. TIME_MEASUREMENT_START(timer_start);
  303. LOCK;
  304. #ifdef TAS575x
  305. // manage led display
  306. if (state != output.state) {
  307. if (output.state == OUTPUT_OFF) led_blink(LED_GREEN, 100, 2500);
  308. else if (output.state == OUTPUT_STOPPED) led_blink_wait(LED_GREEN, 200, 1000);
  309. else if (output.state == OUTPUT_RUNNING) led_on(LED_GREEN);
  310. }
  311. state = output.state;
  312. #endif
  313. if (output.state == OUTPUT_OFF) {
  314. UNLOCK;
  315. LOG_INFO("Output state is off.");
  316. if (isI2SStarted) {
  317. isI2SStarted = false;
  318. i2s_stop(CONFIG_I2S_NUM);
  319. dac_cmd(DAC_OFF);
  320. }
  321. LOG_ERROR("Jack %d Voltage %.2fV", !gpio_get_level(39), adc1_get_raw(ADC1_CHANNEL_0) / 4095. * (10+169)/10. * 1.1);
  322. usleep(200000);
  323. continue;
  324. } else if (output.state == OUTPUT_STOPPED) {
  325. synced = false;
  326. }
  327. output.updated = gettime_ms();
  328. output.frames_played_dmp = output.frames_played;
  329. // try to estimate how much we have consumed from the DMA buffer
  330. output.device_frames = DMA_BUF_COUNT * DMA_BUF_LEN - ((output.updated - fullness) * output.current_sample_rate) / 1000;
  331. oframes = _output_frames( iframes );
  332. SET_MIN_MAX_SIZED(oframes,rec,iframes);
  333. SET_MIN_MAX_SIZED(_buf_used(outputbuf),o,outputbuf->size);
  334. SET_MIN_MAX_SIZED(_buf_used(streambuf),s,streambuf->size);
  335. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),buffering);
  336. /* must skip first whatever is in the pipe (but not when resuming).
  337. This test is incorrect when we pause a track that has just started,
  338. but this is higly unlikely and I don't have a better one for now */
  339. if (output.state == OUTPUT_START_AT) {
  340. discard = output.frames_played_dmp ? 0 : output.device_frames;
  341. synced = true;
  342. } else if (discard) {
  343. discard -= oframes;
  344. iframes = discard ? min(FRAME_BLOCK, discard) : FRAME_BLOCK;
  345. UNLOCK;
  346. continue;
  347. }
  348. UNLOCK;
  349. // now send all the data
  350. TIME_MEASUREMENT_START(timer_start);
  351. if (!isI2SStarted ) {
  352. isI2SStarted = true;
  353. LOG_INFO("Restarting I2S.");
  354. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  355. i2s_start(CONFIG_I2S_NUM);
  356. dac_cmd(DAC_ON);
  357. }
  358. // this does not work well as set_sample_rates resets the fifos (and it's too early)
  359. if (i2s_config.sample_rate != output.current_sample_rate) {
  360. LOG_INFO("changing sampling rate %u to %u", i2s_config.sample_rate, output.current_sample_rate);
  361. /*
  362. if (synced)
  363. // can sleep for a buffer_queue - 1 and then eat a buffer (discard) if we are synced
  364. usleep(((DMA_BUF_COUNT - 1) * DMA_BUF_LEN * bytes_per_frame * 1000) / 44100 * 1000);
  365. discard = DMA_BUF_COUNT * DMA_BUF_LEN * bytes_per_frame;
  366. }
  367. */
  368. i2s_config.sample_rate = output.current_sample_rate;
  369. i2s_set_sample_rates(CONFIG_I2S_NUM, i2s_config.sample_rate);
  370. i2s_zero_dma_buffer(CONFIG_I2S_NUM);
  371. //return;
  372. }
  373. // we assume that here we have been able to entirely fill the DMA buffers
  374. i2s_write(CONFIG_I2S_NUM, obuf, oframes * bytes_per_frame, &bytes, portMAX_DELAY);
  375. fullness = gettime_ms();
  376. if (bytes != oframes * bytes_per_frame) {
  377. LOG_WARN("I2S DMA Overflow! available bytes: %d, I2S wrote %d bytes", oframes * bytes_per_frame, bytes);
  378. }
  379. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),i2s_time);
  380. }
  381. return 0;
  382. }
  383. /****************************************************************************************
  384. * Stats output thread
  385. */
  386. static void *output_thread_i2s_stats() {
  387. while (running) {
  388. LOCK;
  389. output_state state = output.state;
  390. UNLOCK;
  391. if(state>OUTPUT_STOPPED){
  392. LOG_INFO( "Output State: %d, current sample rate: %d, bytes per frame: %d",state,output.current_sample_rate, bytes_per_frame);
  393. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD1);
  394. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD2);
  395. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD3);
  396. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD4);
  397. LOG_INFO(LINE_MIN_MAX_FORMAT_STREAM, LINE_MIN_MAX_STREAM("stream",s));
  398. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("output",o));
  399. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  400. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("received",rec));
  401. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  402. LOG_INFO("");
  403. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  404. LOG_INFO(" max (us) | min (us) | avg(us) | count | ");
  405. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  406. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("Buffering(us)",buffering));
  407. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("i2s tfr(us)",i2s_time));
  408. LOG_INFO(" ----------+----------+-----------+-----------+");
  409. RESET_ALL_MIN_MAX;
  410. }
  411. usleep(STATS_PERIOD_MS *1000);
  412. }
  413. return NULL;
  414. }
  415. /****************************************************************************************
  416. * DAC specific commands
  417. */
  418. void dac_cmd(dac_cmd_e cmd, ...) {
  419. va_list args;
  420. esp_err_t ret = ESP_OK;
  421. va_start(args, cmd);
  422. #ifdef TAS575x
  423. i2c_cmd_handle_t i2c_cmd = i2c_cmd_link_create();
  424. switch(cmd) {
  425. case DAC_VOLUME:
  426. LOG_ERROR("volume not handled yet");
  427. break;
  428. default:
  429. i2c_master_start(i2c_cmd);
  430. i2c_master_write_byte(i2c_cmd, I2C_ADDR << 1 | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  431. i2c_master_write_byte(i2c_cmd, tas575x_cmd[cmd].reg, I2C_MASTER_NACK);
  432. i2c_master_write_byte(i2c_cmd, tas575x_cmd[cmd].value, I2C_MASTER_NACK);
  433. i2c_master_stop(i2c_cmd);
  434. ret = i2c_master_cmd_begin(I2C_PORT, i2c_cmd, 50 / portTICK_RATE_MS);
  435. }
  436. i2c_cmd_link_delete(i2c_cmd);
  437. if (ret != ESP_OK) {
  438. LOG_ERROR("could not intialize TAS575x %d", ret);
  439. }
  440. #endif
  441. va_end(args);
  442. }