output_i2s.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. #include "squeezelite.h"
  22. #include "driver/i2s.h"
  23. #include "perf_trace.h"
  24. #include <signal.h>
  25. #include "time.h"
  26. #define DECLARE_ALL_MIN_MAX \
  27. DECLARE_MIN_MAX(o); \
  28. DECLARE_MIN_MAX(s); \
  29. DECLARE_MIN_MAX(loci2sbuf); \
  30. DECLARE_MIN_MAX(req); \
  31. DECLARE_MIN_MAX(rec); \
  32. DECLARE_MIN_MAX(over); \
  33. DECLARE_MIN_MAX(i2savailable);\
  34. DECLARE_MIN_MAX(i2s_time); \
  35. DECLARE_MIN_MAX(buffering);
  36. #define RESET_ALL_MIN_MAX \
  37. RESET_MIN_MAX(o); \
  38. RESET_MIN_MAX(s); \
  39. RESET_MIN_MAX(loci2sbuf); \
  40. RESET_MIN_MAX(req); \
  41. RESET_MIN_MAX(rec); \
  42. RESET_MIN_MAX(over); \
  43. RESET_MIN_MAX(i2savailable);\
  44. RESET_MIN_MAX(i2s_time);\
  45. RESET_MIN_MAX(buffering);
  46. #define STATS_PERIOD_MS 5000
  47. // Prevent compile errors if dac output is
  48. // included in the build and not actually activated in menuconfig
  49. #ifndef CONFIG_I2S_BCK_IO
  50. #define CONFIG_I2S_BCK_IO -1
  51. #endif
  52. #ifndef CONFIG_I2S_WS_IO
  53. #define CONFIG_I2S_WS_IO -1
  54. #endif
  55. #ifndef CONFIG_I2S_DO_IO
  56. #define CONFIG_I2S_DO_IO -1
  57. #endif
  58. #ifndef CONFIG_I2S_NUM
  59. #define CONFIG_I2S_NUM -1
  60. #endif
  61. #if REPACK && BYTES_PER_FRAMES == 4
  62. #error "REPACK is not compatible with BYTES_PER_FRAME=4"
  63. #endif
  64. #define LOCK mutex_lock(outputbuf->mutex)
  65. #define UNLOCK mutex_unlock(outputbuf->mutex)
  66. #define FRAME_BLOCK MAX_SILENCE_FRAMES
  67. extern struct outputstate output;
  68. extern struct buffer *streambuf;
  69. extern struct buffer *outputbuf;
  70. extern u8_t *silencebuf;
  71. static log_level loglevel;
  72. static size_t i2s_buffer_size = 0;
  73. static bool running = true;
  74. static bool isI2SStarted=false;
  75. static struct buffer _i2s_buffer_structure;
  76. static struct buffer *i2sbuffer=&_i2s_buffer_structure;
  77. static i2s_config_t i2s_config;
  78. static int bytes_per_frame;
  79. static thread_type thread;
  80. static pthread_t stats_thread;
  81. DECLARE_ALL_MIN_MAX;
  82. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  83. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr);
  84. static void *output_thread_i2s();
  85. static void *output_thread_i2s_stats();
  86. /****************************************************************************************
  87. * Initialize the DAC output
  88. */
  89. void output_init_i2s(log_level level, char *device, unsigned output_buf_size, char *params, unsigned rates[], unsigned rate_delay, unsigned idle) {
  90. loglevel = level;
  91. #ifdef CONFIG_I2S_BITS_PER_CHANNEL
  92. switch (CONFIG_I2S_BITS_PER_CHANNEL) {
  93. case 24:
  94. output.format = S24_BE;
  95. bytes_per_frame = 2*3;
  96. break;
  97. case 16:
  98. output.format = S16_BE;
  99. bytes_per_frame = 2*2;
  100. break;
  101. case 8:
  102. output.format = S8_BE;
  103. bytes_per_frame = 2*4;
  104. break;
  105. default:
  106. LOG_ERROR("Unsupported bit depth %d",CONFIG_I2S_BITS_PER_CHANNEL);
  107. break;
  108. }
  109. #else
  110. output.format = S16_LE;
  111. bytes_per_frame = 2*2;
  112. #endif
  113. output.write_cb = &_i2s_write_frames;
  114. running=true;
  115. // todo: move this to a hardware abstraction layer
  116. //hal_dac_init(device);
  117. i2s_config.mode = I2S_MODE_MASTER | I2S_MODE_TX; // Only TX
  118. i2s_config.sample_rate = output.current_sample_rate;
  119. i2s_config.bits_per_sample = bytes_per_frame * 8 / 2;
  120. i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT; //2-channels
  121. i2s_config.communication_format = I2S_COMM_FORMAT_I2S| I2S_COMM_FORMAT_I2S_MSB;
  122. // todo: tune this parameter. Expressed in number of samples. Byte size depends on bit depth.
  123. i2s_config.dma_buf_count = 10;
  124. // From the I2S driver source, the DMA buffer size is 4092 bytes.
  125. // so buf_len * 2 channels * 2 bytes/sample should be < 4092 or else it will be resized.
  126. i2s_config.dma_buf_len = FRAME_BLOCK/2;
  127. i2s_config.use_apll = false;
  128. i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; //Interrupt level 1
  129. i2s_pin_config_t pin_config = { .bck_io_num = CONFIG_I2S_BCK_IO, .ws_io_num =
  130. CONFIG_I2S_WS_IO, .data_out_num = CONFIG_I2S_DO_IO, .data_in_num = -1 //Not used
  131. };
  132. LOG_INFO("Initializing I2S with rate: %d, bits per sample: %d, buffer len: %d, number of buffers: %d ",
  133. i2s_config.sample_rate, i2s_config.bits_per_sample, i2s_config.dma_buf_len, i2s_config.dma_buf_count);
  134. i2s_driver_install(CONFIG_I2S_NUM, &i2s_config, 0, NULL);
  135. i2s_set_pin(CONFIG_I2S_NUM, &pin_config);
  136. i2s_set_clk(CONFIG_I2S_NUM, output.current_sample_rate, i2s_config.bits_per_sample, 2);
  137. isI2SStarted=false;
  138. i2s_stop(CONFIG_I2S_NUM);
  139. i2s_buffer_size = 5*FRAME_BLOCK*bytes_per_frame;
  140. LOG_INFO("Allocating local DAC transfer buffer of %u bytes.",i2s_buffer_size);
  141. buf_init(i2sbuffer,i2s_buffer_size);
  142. if (!i2sbuffer->buf) {
  143. LOG_ERROR("unable to malloc i2s buffer");
  144. exit(0);
  145. }
  146. pthread_attr_t attr;
  147. pthread_attr_init(&attr);
  148. pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + OUTPUT_THREAD_STACK_SIZE);
  149. pthread_create(&thread, &attr, output_thread_i2s, NULL);
  150. pthread_attr_destroy(&attr);
  151. #if HAS_PTHREAD_SETNAME_NP
  152. pthread_setname_np(thread, "output_i2s");
  153. #endif
  154. // leave stack size to default
  155. pthread_create(&stats_thread, NULL, output_thread_i2s_stats, NULL);
  156. #if HAS_PTHREAD_SETNAME_NP
  157. pthread_setname_np(stats_thread, "output_i2s_sts");
  158. #endif
  159. }
  160. /****************************************************************************************
  161. * Terminate DAC output
  162. */
  163. void output_close_i2s(void) {
  164. i2s_driver_uninstall(CONFIG_I2S_NUM);
  165. buf_destroy(i2sbuffer);
  166. }
  167. /****************************************************************************************
  168. * Write frames to the output buffer
  169. */
  170. static int _i2s_write_frames(frames_t out_frames, bool silence, s32_t gainL, s32_t gainR,
  171. s32_t cross_gain_in, s32_t cross_gain_out, ISAMPLE_T **cross_ptr) {
  172. size_t bytes = out_frames * bytes_per_frame;
  173. assert(bytes > 0);
  174. if (!silence) {
  175. if (output.fade == FADE_ACTIVE && output.fade_dir == FADE_CROSS && *cross_ptr) {
  176. _apply_cross(outputbuf, out_frames, cross_gain_in, cross_gain_out, cross_ptr);
  177. }
  178. #if !REPACK
  179. if (gainL != FIXED_ONE || gainR!= FIXED_ONE) {
  180. _apply_gain(outputbuf, out_frames, gainL, gainR);
  181. }
  182. memcpy(i2sbuffer->writep, outputbuf->readp, bytes);
  183. #else
  184. obuf = outputbuf->readp;
  185. #endif
  186. } else {
  187. #if !REPACK
  188. memcpy(i2sbuffer->writep, silencebuf, bytes);
  189. #endif
  190. }
  191. #if REPACK
  192. _scale_and_pack_frames(optr, (s32_t *)(void *)obuf, out_frames, gainL, gainR, output.format);
  193. #endif
  194. _buf_inc_writep(i2sbuffer, bytes);
  195. return bytes / bytes_per_frame;
  196. }
  197. /****************************************************************************************
  198. * Main output thread
  199. */
  200. static void *output_thread_i2s() {
  201. frames_t frames=0;
  202. frames_t available_frames_space=0;
  203. size_t bytes_to_send_i2s=0, // Contiguous buffer which can be addressed
  204. i2s_bytes_written = 0,
  205. i2s_total_bytes_written=0; //actual size that the i2s port was able to write
  206. uint32_t timer_start=0;
  207. static int count = 0;
  208. output_state state;
  209. while (running) {
  210. i2s_bytes_written=0;
  211. frames=0;
  212. available_frames_space=0;
  213. bytes_to_send_i2s=0, // Contiguous buffer which can be addressed
  214. i2s_bytes_written = 0; //actual size that the i2s port was able to write
  215. TIME_MEASUREMENT_START(timer_start);
  216. LOCK;
  217. state =output.state;
  218. if (output.state == OUTPUT_OFF) {
  219. UNLOCK;
  220. LOG_INFO("Output state is off.");
  221. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(i2sbuffer),_buf_cont_read(i2sbuffer));
  222. if(isI2SStarted) {
  223. isI2SStarted=false;
  224. i2s_stop(CONFIG_I2S_NUM);
  225. }
  226. usleep(200000);
  227. continue;
  228. }
  229. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(i2sbuffer),_buf_cont_read(i2sbuffer));
  230. output.device_frames =0;
  231. output.updated = gettime_ms();
  232. output.frames_played_dmp = output.frames_played;
  233. do{
  234. // fill our buffer
  235. available_frames_space = min(_buf_space(i2sbuffer), _buf_cont_write(i2sbuffer)) / bytes_per_frame;
  236. if(available_frames_space)
  237. {
  238. frames = _output_frames( available_frames_space ); // Keep the transfer buffer full
  239. SET_MIN_MAX( available_frames_space,req);
  240. SET_MIN_MAX(frames,rec);
  241. }
  242. }while(available_frames_space>0 && frames>0);
  243. SET_MIN_MAX_SIZED(_buf_used(outputbuf),o,outputbuf->size);
  244. SET_MIN_MAX_SIZED(_buf_used(streambuf),s,streambuf->size);
  245. UNLOCK;
  246. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(i2sbuffer),_buf_cont_read(i2sbuffer));
  247. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),buffering);
  248. SET_MIN_MAX_SIZED(_buf_used(i2sbuffer),loci2sbuf,i2sbuffer->size);
  249. bytes_to_send_i2s = _buf_cont_read(i2sbuffer);
  250. SET_MIN_MAX(bytes_to_send_i2s,i2savailable);
  251. i2s_total_bytes_written=0;
  252. while (bytes_to_send_i2s>0 )
  253. {
  254. // now send all the data
  255. TIME_MEASUREMENT_START(timer_start);
  256. if(!isI2SStarted)
  257. {
  258. isI2SStarted=true;
  259. LOG_INFO("Restarting I2S.");
  260. i2s_start(CONFIG_I2S_NUM);
  261. }
  262. if (i2s_config.sample_rate != output.current_sample_rate) {
  263. LOG_INFO("changing sampling rate %u to %u", i2s_config.sample_rate, output.current_sample_rate);
  264. i2s_config.sample_rate = output.current_sample_rate;
  265. i2s_set_sample_rates(CONFIG_I2S_NUM, i2s_config.sample_rate);
  266. }
  267. count++;
  268. LOG_SDEBUG("Outputting to I2S");
  269. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(i2sbuffer),_buf_cont_read(i2sbuffer));
  270. i2s_write(CONFIG_I2S_NUM, i2sbuffer->readp,bytes_to_send_i2s, &i2s_bytes_written, portMAX_DELAY);
  271. _buf_inc_readp(i2sbuffer,i2s_bytes_written);
  272. if(i2s_bytes_written!=bytes_to_send_i2s)
  273. {
  274. LOG_WARN("I2S DMA Overflow! available bytes: %d, I2S wrote %d bytes", bytes_to_send_i2s,i2s_bytes_written);
  275. }
  276. LOG_SDEBUG("DONE Outputting to I2S. Wrote: %d bytes out of %d", i2s_bytes_written,bytes_to_send_i2s);
  277. LOG_SDEBUG("Current buffer free: %10d, cont read: %10d",_buf_space(i2sbuffer),_buf_cont_read(i2sbuffer));
  278. i2s_total_bytes_written+=i2s_bytes_written;
  279. SET_MIN_MAX( TIME_MEASUREMENT_GET(timer_start),i2s_time);
  280. if(bytes_to_send_i2s>0) {
  281. SET_MIN_MAX(bytes_to_send_i2s-i2s_bytes_written,over);
  282. }
  283. bytes_to_send_i2s = _buf_cont_read(i2sbuffer);
  284. SET_MIN_MAX(bytes_to_send_i2s,i2savailable);
  285. }
  286. }
  287. return 0;
  288. }
  289. /****************************************************************************************
  290. * Stats output thread
  291. */
  292. static void *output_thread_i2s_stats() {
  293. while (running) {
  294. LOCK;
  295. output_state state = output.state;
  296. UNLOCK;
  297. if(state>OUTPUT_STOPPED){
  298. LOG_INFO( "Output State: %d, current sample rate: %d, bytes per frame: %d",state,output.current_sample_rate, bytes_per_frame);
  299. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD1);
  300. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD2);
  301. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD3);
  302. LOG_INFO( LINE_MIN_MAX_FORMAT_HEAD4);
  303. LOG_INFO(LINE_MIN_MAX_FORMAT_STREAM, LINE_MIN_MAX_STREAM("stream",s));
  304. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("output",o));
  305. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("dac buf used",loci2sbuf));
  306. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  307. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("i2swrite",i2savailable));
  308. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("requested",req));
  309. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("received",rec));
  310. LOG_INFO(LINE_MIN_MAX_FORMAT,LINE_MIN_MAX("overflow",over));
  311. LOG_INFO(LINE_MIN_MAX_FORMAT_FOOTER);
  312. LOG_INFO("");
  313. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  314. LOG_INFO(" max (us) | min (us) | avg(us) | count | ");
  315. LOG_INFO(" ----------+----------+-----------+-----------+ ");
  316. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("Buffering(us)",buffering));
  317. LOG_INFO(LINE_MIN_MAX_DURATION_FORMAT,LINE_MIN_MAX_DURATION("i2s tfr(us)",i2s_time));
  318. LOG_INFO(" ----------+----------+-----------+-----------+");
  319. RESET_ALL_MIN_MAX;
  320. }
  321. usleep(STATS_PERIOD_MS *1000);
  322. }
  323. return NULL;
  324. }