i2s.c 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <stdbool.h>
  8. #include <math.h>
  9. #include <esp_types.h>
  10. #include "freertos/FreeRTOS.h"
  11. #include "freertos/queue.h"
  12. #include "freertos/semphr.h"
  13. #include "soc/lldesc.h"
  14. #include "driver/gpio.h"
  15. #include "driver/i2s.h"
  16. #include "hal/gpio_hal.h"
  17. #include "hal/i2s_hal.h"
  18. #if SOC_I2S_SUPPORTS_DAC
  19. #include "driver/dac.h"
  20. #endif // SOC_I2S_SUPPORTS_DAC
  21. #if SOC_I2S_SUPPORTS_ADC
  22. #include "adc1_private.h"
  23. #endif // SOC_I2S_SUPPORTS_ADC
  24. #if SOC_GDMA_SUPPORTED
  25. #include "esp_private/gdma.h"
  26. #endif
  27. #include "soc/clk_ctrl_os.h"
  28. #include "esp_intr_alloc.h"
  29. #include "esp_err.h"
  30. #include "esp_check.h"
  31. #include "esp_attr.h"
  32. #include "esp_log.h"
  33. #include "esp_pm.h"
  34. #include "esp_efuse.h"
  35. #include "esp_rom_gpio.h"
  36. #include "esp_private/i2s_platform.h"
  37. #include "sdkconfig.h"
  38. static const char *TAG = "I2S";
  39. #define I2S_ENTER_CRITICAL_ISR(i2s_num) portENTER_CRITICAL_ISR(&i2s_spinlock[i2s_num])
  40. #define I2S_EXIT_CRITICAL_ISR(i2s_num) portEXIT_CRITICAL_ISR(&i2s_spinlock[i2s_num])
  41. #define I2S_ENTER_CRITICAL(i2s_num) portENTER_CRITICAL(&i2s_spinlock[i2s_num])
  42. #define I2S_EXIT_CRITICAL(i2s_num) portEXIT_CRITICAL(&i2s_spinlock[i2s_num])
  43. #define I2S_DMA_BUFFER_MAX_SIZE 4092
  44. #if !SOC_GDMA_SUPPORTED
  45. #define I2S_INTR_IN_SUC_EOF BIT(9)
  46. #define I2S_INTR_OUT_EOF BIT(12)
  47. #define I2S_INTR_IN_DSCR_ERR BIT(13)
  48. #define I2S_INTR_OUT_DSCR_ERR BIT(14)
  49. #define I2S_INTR_MAX (~0)
  50. #endif
  51. /**
  52. * @brief DMA buffer object
  53. *
  54. */
  55. typedef struct {
  56. char **buf;
  57. int buf_size;
  58. volatile int rw_pos;
  59. volatile void *curr_ptr;
  60. SemaphoreHandle_t mux;
  61. xQueueHandle queue;
  62. lldesc_t **desc;
  63. } i2s_dma_t;
  64. /**
  65. * @brief I2S object instance
  66. *
  67. */
  68. typedef struct {
  69. i2s_port_t i2s_num; /*!< I2S port number*/
  70. int queue_size; /*!< I2S event queue size*/
  71. QueueHandle_t i2s_queue; /*!< I2S queue handler*/
  72. int dma_buf_count; /*!< DMA buffer count, number of buffer*/
  73. int dma_buf_len; /*!< DMA buffer length, length of each buffer*/
  74. uint32_t last_buf_size; /*!< DMA last buffer size */
  75. i2s_dma_t *tx; /*!< DMA Tx buffer*/
  76. i2s_dma_t *rx; /*!< DMA Rx buffer*/
  77. #if SOC_GDMA_SUPPORTED
  78. gdma_channel_handle_t rx_dma_chan; /*!< I2S rx gDMA channel handle*/
  79. gdma_channel_handle_t tx_dma_chan; /*!< I2S tx gDMA channel handle*/
  80. #else
  81. i2s_isr_handle_t i2s_isr_handle; /*!< I2S Interrupt handle*/
  82. #endif
  83. bool tx_desc_auto_clear; /*!< I2S auto clear tx descriptor on underflow */
  84. bool use_apll; /*!< I2S use APLL clock */
  85. int fixed_mclk; /*!< I2S fixed MLCK clock */
  86. i2s_mclk_multiple_t mclk_multiple; /*!< The multiple of I2S master clock(MCLK) to sample rate */
  87. #ifdef CONFIG_PM_ENABLE
  88. esp_pm_lock_handle_t pm_lock;
  89. #endif
  90. i2s_hal_context_t hal; /*!< I2S hal context*/
  91. i2s_hal_config_t hal_cfg; /*!< I2S hal configurations*/
  92. } i2s_obj_t;
  93. static i2s_obj_t *p_i2s[SOC_I2S_NUM];
  94. static portMUX_TYPE i2s_platform_spinlock = (portMUX_TYPE)portMUX_INITIALIZER_UNLOCKED;
  95. static portMUX_TYPE i2s_spinlock[SOC_I2S_NUM] = {
  96. [0 ... SOC_I2S_NUM - 1] = (portMUX_TYPE)portMUX_INITIALIZER_UNLOCKED,
  97. };
  98. #if SOC_I2S_SUPPORTS_ADC
  99. static int _i2s_adc_unit = -1;
  100. static int _i2s_adc_channel = -1;
  101. #endif
  102. /*
  103. * This block is an overview of APIs in i2s.c
  104. * Functions with [main] tag are summary functions that provide main i2s service
  105. * Functions with [helper] tag are helper functions that served for summary functions
  106. * Functions with [intr] tag are interrupt handling functions or interrupt callback functions
  107. -------------------------------------------------------------
  108. I2S GPIO operation
  109. -------------------------------------------------------------
  110. - [helper] gpio_matrix_out_check_and_set
  111. - [helper] gpio_matrix_in_check_and_set
  112. - [helper] i2s_check_set_mclk
  113. - [main] i2s_set_pin
  114. -------------------------------------------------------------
  115. I2S DMA operation
  116. -------------------------------------------------------------
  117. - [intr] i2s_dma_rx_callback
  118. - [intr] i2s_dma_tx_callback
  119. - [intr] i2s_intr_handler_default
  120. - [helper] i2s_dma_intr_init
  121. - [helper] i2s_tx_reset
  122. - [helper] i2s_rx_reset
  123. - [helper] i2s_tx_start
  124. - [helper] i2s_rx_start
  125. - [helper] i2s_tx_stop
  126. - [helper] i2s_rx_stop
  127. -------------------------------------------------------------
  128. I2S buffer operation
  129. -------------------------------------------------------------
  130. - [helper] i2s_get_buf_size
  131. - [helper] i2s_delete_dma_buffer
  132. - [helper] i2s_alloc_dma_buffer
  133. - [main] i2s_realloc_dma_buffer
  134. - [main] i2s_destroy_dma_object
  135. - [main] i2s_create_dma_object
  136. - [main] i2s_zero_dma_buffer
  137. -------------------------------------------------------------
  138. I2S clock operation
  139. -------------------------------------------------------------
  140. - [helper] i2s_config_source_clock
  141. - [helper] i2s_calculate_adc_dac_clock
  142. - [helper] i2s_calculate_pdm_tx_clock
  143. - [helper] i2s_calculate_pdm_rx_clock
  144. - [helper] i2s_calculate_common_clock
  145. - [main] i2s_calculate_clock
  146. -------------------------------------------------------------
  147. I2S configuration
  148. -------------------------------------------------------------
  149. - [helper] i2s_get_max_channel_num
  150. - [helper] i2s_get_active_channel_num
  151. - [helper] i2s_set_dac_mode
  152. - [helper] _i2s_adc_mode_recover
  153. - [main] i2s_set_adc_mode
  154. - [main] i2s_adc_enable
  155. - [main] i2s_adc_disable
  156. - [helper] i2s_set_sample_rates
  157. - [main] i2s_pcm_config
  158. - [helper] i2s_set_pdm_rx_down_sample
  159. - [helper] i2s_set_pdm_tx_up_sample
  160. - [helper] i2s_check_cfg_validity
  161. - [helper] i2s_tx_set_clk_and_channel
  162. - [helper] i2s_rx_set_clk_and_channel
  163. - [main] i2s_get_clk
  164. - [main] i2s_set_clk
  165. -------------------------------------------------------------
  166. I2S driver operation
  167. -------------------------------------------------------------
  168. - [main] i2s_start
  169. - [main] i2s_stop
  170. - [helper] i2s_driver_init
  171. - [helper] i2s_dma_object_init
  172. - [main] i2s_driver_install
  173. - [main] i2s_driver_uninstall
  174. - [main] i2s_write
  175. - [main] i2s_write_expand
  176. - [main] i2s_read
  177. -------------------------------------------------------------*/
  178. /*-------------------------------------------------------------
  179. I2S GPIO operation
  180. -------------------------------------------------------------*/
  181. /**
  182. * @brief I2S GPIO matrix set ouput
  183. *
  184. * @param gpio GPIO number
  185. * @param singal_idx GPIO singnal ID, refer to 'gpio_sig_map.h'
  186. * @param out_inv Output invert enable
  187. * @param oen_inv Output eanble control invert enable
  188. */
  189. static void gpio_matrix_out_check_and_set(gpio_num_t gpio, uint32_t signal_idx, bool out_inv, bool oen_inv)
  190. {
  191. //if pin = -1, do not need to configure
  192. if (gpio != -1) {
  193. gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[gpio], PIN_FUNC_GPIO);
  194. gpio_set_direction(gpio, GPIO_MODE_OUTPUT);
  195. esp_rom_gpio_connect_out_signal(gpio, signal_idx, out_inv, oen_inv);
  196. }
  197. }
  198. /**
  199. * @brief I2S GPIO matrix set input
  200. *
  201. * @param gpio GPIO number
  202. * @param singal_idx GPIO singnal ID, refer to 'gpio_sig_map.h'
  203. * @param out_inv Output invert enable
  204. * @param oen_inv Output eanble control invert enable
  205. */
  206. static void gpio_matrix_in_check_and_set(gpio_num_t gpio, uint32_t signal_idx, bool inv)
  207. {
  208. if (gpio != -1) {
  209. gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[gpio], PIN_FUNC_GPIO);
  210. /* Set direction, for some GPIOs, the input function are not enabled as default */
  211. gpio_set_direction(gpio, GPIO_MODE_INPUT);
  212. esp_rom_gpio_connect_in_signal(gpio, signal_idx, inv);
  213. }
  214. }
  215. /**
  216. * @brief I2S set GPIO for mclk
  217. *
  218. * @param i2s_num I2S device number
  219. * @param gpio_num GPIO number for mclk
  220. * @return
  221. * - ESP_OK Check or set success
  222. * - ESP_ERR_INVALID_ARG GPIO is not available
  223. */
  224. static esp_err_t i2s_check_set_mclk(i2s_port_t i2s_num, gpio_num_t gpio_num)
  225. {
  226. if (gpio_num == -1) {
  227. return ESP_OK;
  228. }
  229. #if CONFIG_IDF_TARGET_ESP32
  230. ESP_RETURN_ON_FALSE((gpio_num == GPIO_NUM_0 || gpio_num == GPIO_NUM_1 || gpio_num == GPIO_NUM_3),
  231. ESP_ERR_INVALID_ARG, TAG,
  232. "ESP32 only support to set GPIO0/GPIO1/GPIO3 as mclk signal, error GPIO number:%d", gpio_num);
  233. bool is_i2s0 = i2s_num == I2S_NUM_0;
  234. if (gpio_num == GPIO_NUM_0) {
  235. PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0_CLK_OUT1);
  236. WRITE_PERI_REG(PIN_CTRL, is_i2s0 ? 0xFFF0 : 0xFFFF);
  237. } else if (gpio_num == GPIO_NUM_1) {
  238. PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD_CLK_OUT3);
  239. WRITE_PERI_REG(PIN_CTRL, is_i2s0 ? 0xF0F0 : 0xF0FF);
  240. } else {
  241. PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0RXD_U, FUNC_U0RXD_CLK_OUT2);
  242. WRITE_PERI_REG(PIN_CTRL, is_i2s0 ? 0xFF00 : 0xFF0F);
  243. }
  244. #else
  245. ESP_RETURN_ON_FALSE(GPIO_IS_VALID_GPIO(gpio_num), ESP_ERR_INVALID_ARG, TAG, "mck_io_num invalid");
  246. gpio_matrix_out_check_and_set(gpio_num, i2s_periph_signal[i2s_num].mck_out_sig, 0, 0);
  247. #endif
  248. ESP_LOGI(TAG, "I2S%d, MCLK output by GPIO%d", i2s_num, gpio_num);
  249. return ESP_OK;
  250. }
  251. /**
  252. * @brief Set gpio pins for I2S
  253. *
  254. * @param i2s_num I2S device number
  255. * @param pin Pin configuration
  256. * @return
  257. * - ESP_OK Set pin success
  258. * - ESP_ERR_INVALID_ARG GPIO is not available
  259. */
  260. esp_err_t i2s_set_pin(i2s_port_t i2s_num, const i2s_pin_config_t *pin)
  261. {
  262. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  263. if (pin == NULL) {
  264. #if SOC_I2S_SUPPORTS_DAC
  265. return i2s_set_dac_mode(I2S_DAC_CHANNEL_BOTH_EN);
  266. #else
  267. return ESP_ERR_INVALID_ARG;
  268. #endif
  269. }
  270. /* Check validity of selected pins */
  271. ESP_RETURN_ON_FALSE((pin->bck_io_num == -1 || GPIO_IS_VALID_GPIO(pin->bck_io_num)),
  272. ESP_ERR_INVALID_ARG, TAG, "bck_io_num invalid");
  273. ESP_RETURN_ON_FALSE((pin->ws_io_num == -1 || GPIO_IS_VALID_GPIO(pin->ws_io_num)),
  274. ESP_ERR_INVALID_ARG, TAG, "ws_io_num invalid");
  275. ESP_RETURN_ON_FALSE((pin->data_out_num == -1 || GPIO_IS_VALID_GPIO(pin->data_out_num)),
  276. ESP_ERR_INVALID_ARG, TAG, "data_out_num invalid");
  277. ESP_RETURN_ON_FALSE((pin->data_in_num == -1 || GPIO_IS_VALID_GPIO(pin->data_in_num)),
  278. ESP_ERR_INVALID_ARG, TAG, "data_in_num invalid");
  279. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_SLAVE) {
  280. /* For "tx + rx + slave" or "rx + slave" mode, we should select RX signal index for ws and bck */
  281. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  282. gpio_matrix_in_check_and_set(pin->ws_io_num, i2s_periph_signal[i2s_num].s_rx_ws_sig, 0);
  283. gpio_matrix_in_check_and_set(pin->bck_io_num, i2s_periph_signal[i2s_num].s_rx_bck_sig, 0);
  284. /* For "tx + slave" mode, we should select TX signal index for ws and bck */
  285. } else {
  286. gpio_matrix_in_check_and_set(pin->ws_io_num, i2s_periph_signal[i2s_num].s_tx_ws_sig, 0);
  287. gpio_matrix_in_check_and_set(pin->bck_io_num, i2s_periph_signal[i2s_num].s_tx_bck_sig, 0);
  288. }
  289. } else {
  290. /* mclk only available in master mode */
  291. ESP_RETURN_ON_ERROR(i2s_check_set_mclk(i2s_num, pin->mck_io_num), TAG, "mclk config failed");
  292. /* For "tx + rx + master" or "tx + master" mode, we should select TX signal index for ws and bck */
  293. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  294. gpio_matrix_out_check_and_set(pin->ws_io_num, i2s_periph_signal[i2s_num].m_tx_ws_sig, 0, 0);
  295. gpio_matrix_out_check_and_set(pin->bck_io_num, i2s_periph_signal[i2s_num].m_tx_bck_sig, 0, 0);
  296. /* For "rx + master" mode, we should select RX signal index for ws and bck */
  297. } else {
  298. gpio_matrix_out_check_and_set(pin->ws_io_num, i2s_periph_signal[i2s_num].m_rx_ws_sig, 0, 0);
  299. gpio_matrix_out_check_and_set(pin->bck_io_num, i2s_periph_signal[i2s_num].m_rx_bck_sig, 0, 0);
  300. }
  301. }
  302. /* Set data input/ouput GPIO */
  303. gpio_matrix_out_check_and_set(pin->data_out_num, i2s_periph_signal[i2s_num].data_out_sig, 0, 0);
  304. gpio_matrix_in_check_and_set(pin->data_in_num, i2s_periph_signal[i2s_num].data_in_sig, 0);
  305. return ESP_OK;
  306. }
  307. /*-------------------------------------------------------------
  308. I2S DMA operation
  309. -------------------------------------------------------------*/
  310. #if SOC_GDMA_SUPPORTED
  311. /**
  312. * @brief GDMA rx callback function
  313. * @note This function is called by GDMA default ISR handler
  314. *
  315. * @param dma_chan GDMA channel handler
  316. * @param event_data GDMA rx event data
  317. * @param user_data GDMA user data
  318. * @return
  319. * - true need yield
  320. * - false no need
  321. */
  322. static bool IRAM_ATTR i2s_dma_rx_callback(gdma_channel_handle_t dma_chan, gdma_event_data_t *event_data, void *user_data)
  323. {
  324. i2s_obj_t *p_i2s = (i2s_obj_t *) user_data;
  325. portBASE_TYPE high_priority_task_awoken = 0;
  326. BaseType_t ret = 0;
  327. int dummy;
  328. i2s_event_t i2s_event;
  329. uint32_t finish_desc;
  330. if (p_i2s->rx) {
  331. finish_desc = event_data->rx_eof_desc_addr;
  332. if (xQueueIsQueueFullFromISR(p_i2s->rx->queue)) {
  333. xQueueReceiveFromISR(p_i2s->rx->queue, &dummy, &high_priority_task_awoken);
  334. }
  335. ret = xQueueSendFromISR(p_i2s->rx->queue, &(((lldesc_t *)finish_desc)->buf), &high_priority_task_awoken);
  336. if (p_i2s->i2s_queue) {
  337. i2s_event.type = (ret == pdPASS) ? I2S_EVENT_RX_DONE : I2S_EVENT_RX_Q_OVF;
  338. if (p_i2s->i2s_queue && xQueueIsQueueFullFromISR(p_i2s->i2s_queue)) {
  339. xQueueReceiveFromISR(p_i2s->i2s_queue, &dummy, &high_priority_task_awoken);
  340. }
  341. xQueueSendFromISR(p_i2s->i2s_queue, (void * )&i2s_event, &high_priority_task_awoken);
  342. }
  343. }
  344. return high_priority_task_awoken;
  345. }
  346. /**
  347. * @brief GDMA tx callback function
  348. * @note This function is called by GDMA default ISR handler
  349. *
  350. * @param dma_chan GDMA channel handler
  351. * @param event_data GDMA tx event data
  352. * @param user_data GDMA user data
  353. * @return
  354. * - whether need yield
  355. */
  356. static bool IRAM_ATTR i2s_dma_tx_callback(gdma_channel_handle_t dma_chan, gdma_event_data_t *event_data, void *user_data)
  357. {
  358. i2s_obj_t *p_i2s = (i2s_obj_t *) user_data;
  359. portBASE_TYPE high_priority_task_awoken = 0;
  360. BaseType_t ret;
  361. int dummy;
  362. i2s_event_t i2s_event;
  363. uint32_t finish_desc;
  364. if (p_i2s->tx) {
  365. finish_desc = event_data->tx_eof_desc_addr;
  366. if (xQueueIsQueueFullFromISR(p_i2s->tx->queue)) {
  367. xQueueReceiveFromISR(p_i2s->tx->queue, &dummy, &high_priority_task_awoken);
  368. if (p_i2s->tx_desc_auto_clear) {
  369. memset((void *) dummy, 0, p_i2s->tx->buf_size);
  370. }
  371. }
  372. ret = xQueueSendFromISR(p_i2s->tx->queue, &(((lldesc_t *)finish_desc)->buf), &high_priority_task_awoken);
  373. if (p_i2s->i2s_queue) {
  374. i2s_event.type = (ret == pdPASS) ? I2S_EVENT_TX_DONE : I2S_EVENT_TX_Q_OVF;
  375. if (xQueueIsQueueFullFromISR(p_i2s->i2s_queue)) {
  376. xQueueReceiveFromISR(p_i2s->i2s_queue, &dummy, &high_priority_task_awoken);
  377. }
  378. xQueueSendFromISR(p_i2s->i2s_queue, (void * )&i2s_event, &high_priority_task_awoken);
  379. }
  380. }
  381. return high_priority_task_awoken;
  382. }
  383. #else
  384. /**
  385. * @brief I2S defalut interrupt handler
  386. * @note This function is triggered by I2S dedicated DMA interrupt
  387. *
  388. * @param arg Argument transport to ISR, here is the pointer to I2S object
  389. */
  390. static void IRAM_ATTR i2s_intr_handler_default(void *arg)
  391. {
  392. i2s_obj_t *p_i2s = (i2s_obj_t *) arg;
  393. uint32_t status = i2s_hal_get_intr_status(&(p_i2s->hal));
  394. if (status == 0) {
  395. //Avoid spurious interrupt
  396. return;
  397. }
  398. i2s_event_t i2s_event;
  399. int dummy;
  400. portBASE_TYPE high_priority_task_awoken = 0;
  401. uint32_t finish_desc = 0;
  402. if ((status & I2S_INTR_OUT_DSCR_ERR) || (status & I2S_INTR_IN_DSCR_ERR)) {
  403. ESP_EARLY_LOGE(TAG, "dma error, interrupt status: 0x%08x", status);
  404. if (p_i2s->i2s_queue) {
  405. i2s_event.type = I2S_EVENT_DMA_ERROR;
  406. if (xQueueIsQueueFullFromISR(p_i2s->i2s_queue)) {
  407. xQueueReceiveFromISR(p_i2s->i2s_queue, &dummy, &high_priority_task_awoken);
  408. }
  409. xQueueSendFromISR(p_i2s->i2s_queue, (void * )&i2s_event, &high_priority_task_awoken);
  410. }
  411. }
  412. if ((status & I2S_INTR_OUT_EOF) && p_i2s->tx) {
  413. i2s_hal_get_out_eof_des_addr(&(p_i2s->hal), &finish_desc);
  414. // All buffers are empty. This means we have an underflow on our hands.
  415. if (xQueueIsQueueFullFromISR(p_i2s->tx->queue)) {
  416. xQueueReceiveFromISR(p_i2s->tx->queue, &dummy, &high_priority_task_awoken);
  417. // See if tx descriptor needs to be auto cleared:
  418. // This will avoid any kind of noise that may get introduced due to transmission
  419. // of previous data from tx descriptor on I2S line.
  420. if (p_i2s->tx_desc_auto_clear == true) {
  421. memset((void *) dummy, 0, p_i2s->tx->buf_size);
  422. }
  423. }
  424. xQueueSendFromISR(p_i2s->tx->queue, &(((lldesc_t *)finish_desc)->buf), &high_priority_task_awoken);
  425. if (p_i2s->i2s_queue) {
  426. i2s_event.type = I2S_EVENT_TX_DONE;
  427. if (xQueueIsQueueFullFromISR(p_i2s->i2s_queue)) {
  428. xQueueReceiveFromISR(p_i2s->i2s_queue, &dummy, &high_priority_task_awoken);
  429. }
  430. xQueueSendFromISR(p_i2s->i2s_queue, (void * )&i2s_event, &high_priority_task_awoken);
  431. }
  432. }
  433. if ((status & I2S_INTR_IN_SUC_EOF) && p_i2s->rx) {
  434. // All buffers are full. This means we have an overflow.
  435. i2s_hal_get_in_eof_des_addr(&(p_i2s->hal), &finish_desc);
  436. if (xQueueIsQueueFullFromISR(p_i2s->rx->queue)) {
  437. xQueueReceiveFromISR(p_i2s->rx->queue, &dummy, &high_priority_task_awoken);
  438. }
  439. xQueueSendFromISR(p_i2s->rx->queue, &(((lldesc_t *)finish_desc)->buf), &high_priority_task_awoken);
  440. if (p_i2s->i2s_queue) {
  441. i2s_event.type = I2S_EVENT_RX_DONE;
  442. if (p_i2s->i2s_queue && xQueueIsQueueFullFromISR(p_i2s->i2s_queue)) {
  443. xQueueReceiveFromISR(p_i2s->i2s_queue, &dummy, &high_priority_task_awoken);
  444. }
  445. xQueueSendFromISR(p_i2s->i2s_queue, (void * )&i2s_event, &high_priority_task_awoken);
  446. }
  447. }
  448. i2s_hal_clear_intr_status(&(p_i2s->hal), status);
  449. if (high_priority_task_awoken == pdTRUE) {
  450. portYIELD_FROM_ISR();
  451. }
  452. }
  453. #endif
  454. /**
  455. * @brief I2S DMA interrupt initialization
  456. * @note I2S will use GDMA if chip supports, and the interrupt is triggered by GDMA.
  457. *
  458. * @param i2s_num I2S device number
  459. * @return
  460. * - ESP_OK I2S DMA interrupt initialize success
  461. * - ESP_ERR_NOT_FOUND GDMA channel not found
  462. * - ESP_ERR_INVALID_ARG Invalid arguments
  463. * - ESP_ERR_INVALID_STATE GDMA state error
  464. */
  465. static esp_err_t i2s_dma_intr_init(i2s_port_t i2s_num, int intr_flag)
  466. {
  467. #if SOC_GDMA_SUPPORTED
  468. /* Set GDMA trigger module */
  469. gdma_trigger_t trig = {.periph = GDMA_TRIG_PERIPH_I2S};
  470. switch (i2s_num) {
  471. #if SOC_I2S_NUM > 1
  472. case I2S_NUM_1:
  473. trig.instance_id = SOC_GDMA_TRIG_PERIPH_I2S1;
  474. break;
  475. #endif
  476. default:
  477. trig.instance_id = SOC_GDMA_TRIG_PERIPH_I2S0;
  478. break;
  479. }
  480. /* Set GDMA config */
  481. gdma_channel_alloc_config_t dma_cfg = {};
  482. if ( p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  483. dma_cfg.direction = GDMA_CHANNEL_DIRECTION_TX;
  484. /* Register a new GDMA tx channel */
  485. ESP_RETURN_ON_ERROR(gdma_new_channel(&dma_cfg, &p_i2s[i2s_num]->tx_dma_chan), TAG, "Register tx dma channel error");
  486. ESP_RETURN_ON_ERROR(gdma_connect(p_i2s[i2s_num]->tx_dma_chan, trig), TAG, "Connect tx dma channel error");
  487. gdma_tx_event_callbacks_t cb = {.on_trans_eof = i2s_dma_tx_callback};
  488. /* Set callback function for GDMA, the interrupt is triggered by GDMA, then the GDMA ISR will call the callback function */
  489. gdma_register_tx_event_callbacks(p_i2s[i2s_num]->tx_dma_chan, &cb, p_i2s[i2s_num]);
  490. }
  491. if ( p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  492. dma_cfg.direction = GDMA_CHANNEL_DIRECTION_RX;
  493. /* Register a new GDMA rx channel */
  494. ESP_RETURN_ON_ERROR(gdma_new_channel(&dma_cfg, &p_i2s[i2s_num]->rx_dma_chan), TAG, "Register rx dma channel error");
  495. ESP_RETURN_ON_ERROR(gdma_connect(p_i2s[i2s_num]->rx_dma_chan, trig), TAG, "Connect rx dma channel error");
  496. gdma_rx_event_callbacks_t cb = {.on_recv_eof = i2s_dma_rx_callback};
  497. /* Set callback function for GDMA, the interrupt is triggered by GDMA, then the GDMA ISR will call the callback function */
  498. gdma_register_rx_event_callbacks(p_i2s[i2s_num]->rx_dma_chan, &cb, p_i2s[i2s_num]);
  499. }
  500. #else
  501. /* Initial I2S module interrupt */
  502. ESP_RETURN_ON_ERROR(esp_intr_alloc(i2s_periph_signal[i2s_num].irq, intr_flag, i2s_intr_handler_default, p_i2s[i2s_num], &p_i2s[i2s_num]->i2s_isr_handle), TAG, "Register I2S Interrupt error");
  503. #endif // SOC_GDMA_SUPPORTED
  504. return ESP_OK;
  505. }
  506. /**
  507. * @brief I2S tx reset
  508. *
  509. * @param i2s_num I2S device number
  510. */
  511. static void i2s_tx_reset(i2s_port_t i2s_num)
  512. {
  513. p_i2s[i2s_num]->tx->curr_ptr = NULL;
  514. p_i2s[i2s_num]->tx->rw_pos = 0;
  515. i2s_hal_reset_tx(&(p_i2s[i2s_num]->hal));
  516. #if SOC_GDMA_SUPPORTED
  517. gdma_reset(p_i2s[i2s_num]->tx_dma_chan);
  518. #else
  519. i2s_hal_reset_txdma(&(p_i2s[i2s_num]->hal));
  520. #endif
  521. i2s_hal_reset_tx_fifo(&(p_i2s[i2s_num]->hal));
  522. }
  523. /**
  524. * @brief I2S rx reset
  525. *
  526. * @param i2s_num I2S device number
  527. */
  528. static void i2s_rx_reset(i2s_port_t i2s_num)
  529. {
  530. p_i2s[i2s_num]->rx->curr_ptr = NULL;
  531. p_i2s[i2s_num]->rx->rw_pos = 0;
  532. i2s_hal_reset_rx(&(p_i2s[i2s_num]->hal));
  533. #if SOC_GDMA_SUPPORTED
  534. gdma_reset(p_i2s[i2s_num]->rx_dma_chan);
  535. #else
  536. i2s_hal_reset_rxdma(&(p_i2s[i2s_num]->hal));
  537. #endif
  538. i2s_hal_reset_rx_fifo(&(p_i2s[i2s_num]->hal));
  539. }
  540. /**
  541. * @brief I2S tx start
  542. *
  543. * @param i2s_num I2S device number
  544. */
  545. static void i2s_tx_start(i2s_port_t i2s_num)
  546. {
  547. #if SOC_GDMA_SUPPORTED
  548. gdma_start(p_i2s[i2s_num]->tx_dma_chan, (uint32_t) p_i2s[i2s_num]->tx->desc[0]);
  549. #else
  550. i2s_hal_enable_tx_dma(&(p_i2s[i2s_num]->hal));
  551. i2s_hal_enable_tx_intr(&(p_i2s[i2s_num]->hal));
  552. i2s_hal_start_tx_link(&(p_i2s[i2s_num]->hal), (uint32_t) p_i2s[i2s_num]->tx->desc[0]);
  553. #endif
  554. i2s_hal_start_tx(&(p_i2s[i2s_num]->hal));
  555. }
  556. /**
  557. * @brief I2S rx start
  558. *
  559. * @param i2s_num I2S device number
  560. */
  561. static void i2s_rx_start(i2s_port_t i2s_num)
  562. {
  563. #if SOC_GDMA_SUPPORTED
  564. gdma_start(p_i2s[i2s_num]->rx_dma_chan, (uint32_t) p_i2s[i2s_num]->rx->desc[0]);
  565. #else
  566. i2s_hal_enable_rx_dma(&(p_i2s[i2s_num]->hal));
  567. i2s_hal_enable_rx_intr(&(p_i2s[i2s_num]->hal));
  568. i2s_hal_start_rx_link(&(p_i2s[i2s_num]->hal), (uint32_t) p_i2s[i2s_num]->rx->desc[0]);
  569. #endif
  570. i2s_hal_start_rx(&(p_i2s[i2s_num]->hal));
  571. }
  572. /**
  573. * @brief I2S tx stop
  574. *
  575. * @param i2s_num I2S device number
  576. */
  577. static void i2s_tx_stop(i2s_port_t i2s_num)
  578. {
  579. i2s_hal_stop_tx(&(p_i2s[i2s_num]->hal));
  580. #if SOC_GDMA_SUPPORTED
  581. gdma_stop(p_i2s[i2s_num]->tx_dma_chan);
  582. #else
  583. i2s_hal_stop_tx_link(&(p_i2s[i2s_num]->hal));
  584. i2s_hal_disable_tx_intr(&(p_i2s[i2s_num]->hal));
  585. i2s_hal_disable_tx_dma(&(p_i2s[i2s_num]->hal));
  586. #endif
  587. }
  588. /**
  589. * @brief I2S rx stop
  590. *
  591. * @param i2s_num I2S device number
  592. */
  593. static void i2s_rx_stop(i2s_port_t i2s_num)
  594. {
  595. i2s_hal_stop_rx(&(p_i2s[i2s_num]->hal));
  596. #if SOC_GDMA_SUPPORTED
  597. gdma_stop(p_i2s[i2s_num]->rx_dma_chan);
  598. #else
  599. i2s_hal_stop_rx_link(&(p_i2s[i2s_num]->hal));
  600. i2s_hal_disable_rx_intr(&(p_i2s[i2s_num]->hal));
  601. i2s_hal_disable_rx_dma(&(p_i2s[i2s_num]->hal));
  602. #endif
  603. }
  604. /*-------------------------------------------------------------
  605. I2S buffer operation
  606. -------------------------------------------------------------*/
  607. /**
  608. * @brief I2S get DMA buffer size
  609. *
  610. * @param i2s_num I2S device number
  611. * @return
  612. * - DMA buffer size
  613. */
  614. static inline uint32_t i2s_get_buf_size(i2s_port_t i2s_num)
  615. {
  616. /* Calculate bytes per sample, align to 16 bit */
  617. uint32_t bytes_per_sample = ((p_i2s[i2s_num]->hal_cfg.sample_bits + 15) / 16) * 2;
  618. /* The DMA buffer limitation is 4092 bytes */
  619. uint32_t bytes_per_frame = bytes_per_sample * p_i2s[i2s_num]->hal_cfg.active_chan;
  620. p_i2s[i2s_num]->dma_buf_len = (p_i2s[i2s_num]->dma_buf_len * bytes_per_frame > I2S_DMA_BUFFER_MAX_SIZE) ?
  621. I2S_DMA_BUFFER_MAX_SIZE / bytes_per_frame : p_i2s[i2s_num]->dma_buf_len;
  622. return p_i2s[i2s_num]->dma_buf_len * bytes_per_frame;
  623. }
  624. /**
  625. * @brief Delete DMA buffer and descriptor
  626. *
  627. * @param i2s_num I2S device number
  628. * @param dma_obj DMA object
  629. * @return
  630. * - ESP_OK DMA buffer delete success
  631. * - ESP_ERR_INVALID_ARG dma_obj is NULL
  632. */
  633. static esp_err_t i2s_delete_dma_buffer(i2s_port_t i2s_num, i2s_dma_t *dma_obj)
  634. {
  635. ESP_RETURN_ON_FALSE(dma_obj, ESP_ERR_INVALID_ARG, TAG, "I2S DMA object can't be NULL");
  636. /* Loop to destroy every descriptor and buffer */
  637. for (int cnt = 0; cnt < p_i2s[i2s_num]->dma_buf_count; cnt++) {
  638. if (dma_obj->desc && dma_obj->desc[cnt]) {
  639. free(dma_obj->desc[cnt]);
  640. dma_obj->desc[cnt] = NULL;
  641. }
  642. if (dma_obj->buf && dma_obj->buf[cnt]) {
  643. free(dma_obj->buf[cnt]);
  644. dma_obj->buf[cnt] = NULL;
  645. }
  646. }
  647. return ESP_OK;
  648. }
  649. /**
  650. * @brief Allocate memory for DMA buffer and descriptor
  651. *
  652. * @param i2s_num I2S device number
  653. * @param dma_obj DMA object
  654. * @return
  655. * - ESP_OK Allocate success
  656. * - ESP_ERR_NO_MEM No memory for DMA buffer
  657. */
  658. static esp_err_t i2s_alloc_dma_buffer(i2s_port_t i2s_num, i2s_dma_t *dma_obj)
  659. {
  660. esp_err_t ret = ESP_OK;
  661. ESP_GOTO_ON_FALSE(dma_obj, ESP_ERR_INVALID_ARG, err, TAG, "I2S DMA object can't be NULL");
  662. uint32_t buf_cnt = p_i2s[i2s_num]->dma_buf_count;
  663. for (int cnt = 0; cnt < buf_cnt; cnt++) {
  664. /* Allocate DMA buffer */
  665. dma_obj->buf[cnt] = (char *) heap_caps_calloc(dma_obj->buf_size, sizeof(char), MALLOC_CAP_DMA);
  666. ESP_GOTO_ON_FALSE(dma_obj->buf[cnt], ESP_ERR_NO_MEM, err, TAG, "Error malloc dma buffer");
  667. /* Initialize DMA buffer to 0 */
  668. memset(dma_obj->buf[cnt], 0, dma_obj->buf_size);
  669. ESP_LOGD(TAG, "Addr[%d] = %d", cnt, (int)dma_obj->buf[cnt]);
  670. /* Allocate DMA descpriptor */
  671. dma_obj->desc[cnt] = (lldesc_t *) heap_caps_calloc(1, sizeof(lldesc_t), MALLOC_CAP_DMA);
  672. ESP_GOTO_ON_FALSE(dma_obj->desc[cnt], ESP_ERR_NO_MEM, err, TAG, "Error malloc dma description entry");
  673. }
  674. /* DMA descriptor must be initialize after all descriptor has been created, otherwise they can't be linked together as a chain */
  675. for (int cnt = 0; cnt < buf_cnt; cnt++) {
  676. /* Initialize DMA descriptor */
  677. dma_obj->desc[cnt]->owner = 1;
  678. dma_obj->desc[cnt]->eof = 1;
  679. dma_obj->desc[cnt]->sosf = 0;
  680. dma_obj->desc[cnt]->length = dma_obj->buf_size;
  681. dma_obj->desc[cnt]->size = dma_obj->buf_size;
  682. dma_obj->desc[cnt]->buf = (uint8_t *) dma_obj->buf[cnt];
  683. dma_obj->desc[cnt]->offset = 0;
  684. /* Link to the next descriptor */
  685. dma_obj->desc[cnt]->empty = (uint32_t)((cnt < (buf_cnt - 1)) ? (dma_obj->desc[cnt + 1]) : dma_obj->desc[0]);
  686. }
  687. ESP_LOGI(TAG, "DMA Malloc info, datalen=blocksize=%d, dma_buf_count=%d", dma_obj->buf_size, buf_cnt);
  688. return ESP_OK;
  689. err:
  690. /* Delete DMA buffer if failed to allocate memory */
  691. i2s_delete_dma_buffer(i2s_num, dma_obj);
  692. return ret;
  693. }
  694. /**
  695. * @brief Realloc I2S dma buffer
  696. *
  697. * @param i2s_num I2S device number
  698. * @param dma_obj DMA object
  699. *
  700. * @return
  701. * - ESP_OK Success
  702. * - ESP_ERR_NO_MEM No memory for I2S tx dma buffer
  703. */
  704. static esp_err_t i2s_realloc_dma_buffer(i2s_port_t i2s_num, i2s_dma_t *dma_obj)
  705. {
  706. ESP_RETURN_ON_FALSE(dma_obj, ESP_ERR_INVALID_ARG, TAG, "I2S DMA object can't be NULL");
  707. /* Destroy old dma descriptor and buffer */
  708. i2s_delete_dma_buffer(i2s_num, dma_obj);
  709. /* Alloc new dma descriptor and buffer */
  710. ESP_RETURN_ON_ERROR(i2s_alloc_dma_buffer(i2s_num, dma_obj), TAG, "Failed to allocate dma buffer");
  711. return ESP_OK;
  712. }
  713. /**
  714. * @brief I2S destroy the whole DMA object
  715. *
  716. * @param i2s_num I2S device number
  717. * @param dma Secondary pointer to the DMA object
  718. * @return
  719. * - ESP_OK I2S DMA buffer has been destroyed successfully
  720. * - ESP_ERR_INVALID_ARG I2S driver has not installed yet
  721. */
  722. static esp_err_t i2s_destroy_dma_object(i2s_port_t i2s_num, i2s_dma_t **dma)
  723. {
  724. /* Check if DMA truely need destroy */
  725. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_ERR_INVALID_ARG, TAG, "I2S not initialized yet");
  726. if (!(*dma)) {
  727. return ESP_OK;
  728. }
  729. /* Destroy every descriptor and buffer */
  730. i2s_delete_dma_buffer(i2s_num, (*dma));
  731. /* Destroy descriptor pointer */
  732. if ((*dma)->desc) {
  733. free((*dma)->desc);
  734. (*dma)->desc = NULL;
  735. }
  736. /* Destroy buffer pointer */
  737. if ((*dma)->buf) {
  738. free((*dma)->buf);
  739. (*dma)->buf = NULL;
  740. }
  741. /* Delete DMA mux */
  742. vSemaphoreDelete((*dma)->mux);
  743. /* Delete DMA queue */
  744. vQueueDelete((*dma)->queue);
  745. /* Free DMA structure */
  746. free(*dma);
  747. *dma = NULL;
  748. ESP_LOGI(TAG, "DMA queue destroyed");
  749. return ESP_OK;
  750. }
  751. /**
  752. * @brief Create I2S DMA object
  753. * @note This function only create I2S DMA object but will not allocate memory
  754. * for DMA descriptor and buffer, call 'i2s_alloc_dma_buffer' additionally to
  755. * allocate DMA buffer
  756. *
  757. * @param i2s_num I2S device number
  758. * @param dma The secondary pointer of DMA object
  759. * @return
  760. * - ESP_OK The pointer of DMA object
  761. * - ESP_ERR_INVALID_ARG NULL pointer error or DMA object has been created
  762. * - ESP_ERR_NO_MEM No memory for new DMA object
  763. */
  764. static esp_err_t i2s_create_dma_object(i2s_port_t i2s_num, i2s_dma_t **dma)
  765. {
  766. ESP_RETURN_ON_FALSE(dma, ESP_ERR_INVALID_ARG, TAG, "DMA object secondary pointer is NULL");
  767. ESP_RETURN_ON_FALSE((*dma == NULL), ESP_ERR_INVALID_ARG, TAG, "DMA object has been created");
  768. uint32_t buf_cnt = p_i2s[i2s_num]->dma_buf_count;
  769. /* Allocate new DMA structure */
  770. *dma = (i2s_dma_t *) malloc(sizeof(i2s_dma_t));
  771. ESP_RETURN_ON_FALSE(*dma, ESP_ERR_NO_MEM, TAG, "DMA object allocate failed");
  772. /* Allocate DMA buffer poiter */
  773. (*dma)->buf = (char **)heap_caps_calloc(buf_cnt, sizeof(char *), MALLOC_CAP_DMA);
  774. if (!(*dma)->buf) {
  775. goto err;
  776. }
  777. /* Allocate secondary pointer of DMA descriptor chain */
  778. (*dma)->desc = (lldesc_t **)heap_caps_calloc(buf_cnt, sizeof(lldesc_t *), MALLOC_CAP_DMA);
  779. if (!(*dma)->desc) {
  780. goto err;
  781. }
  782. /* Create queue and mutex */
  783. (*dma)->queue = xQueueCreate(buf_cnt - 1, sizeof(char *));
  784. if (!(*dma)->queue) {
  785. goto err;
  786. }
  787. (*dma)->mux = xSemaphoreCreateMutex();
  788. if (!(*dma)->mux) {
  789. goto err;
  790. }
  791. return ESP_OK;
  792. err:
  793. ESP_LOGE(TAG, "I2S DMA object create failed, preparing to uninstall");
  794. /* Destroy DMA queue if failed to allocate memory */
  795. i2s_destroy_dma_object(i2s_num, dma);
  796. return ESP_ERR_NO_MEM;
  797. }
  798. /**
  799. * @brief Zero the contents of the TX DMA buffer.
  800. * @note Pushes zero-byte samples into the TX DMA buffer, until it is full.
  801. *
  802. * @param i2s_num I2S device number
  803. * @return
  804. * - ESP_OK Success
  805. * - ESP_ERR_INVALID_ARG Parameter error
  806. */
  807. esp_err_t i2s_zero_dma_buffer(i2s_port_t i2s_num)
  808. {
  809. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  810. /* Clear I2S RX DMA buffer */
  811. if (p_i2s[i2s_num]->rx && p_i2s[i2s_num]->rx->buf != NULL && p_i2s[i2s_num]->rx->buf_size != 0) {
  812. for (int i = 0; i < p_i2s[i2s_num]->dma_buf_count; i++) {
  813. memset(p_i2s[i2s_num]->rx->buf[i], 0, p_i2s[i2s_num]->rx->buf_size);
  814. }
  815. }
  816. /* Clear I2S TX DMA buffer */
  817. if (p_i2s[i2s_num]->tx && p_i2s[i2s_num]->tx->buf != NULL && p_i2s[i2s_num]->tx->buf_size != 0) {
  818. /* Finish to write all tx data */
  819. int bytes_left = (p_i2s[i2s_num]->tx->buf_size - p_i2s[i2s_num]->tx->rw_pos) % 4;
  820. if (bytes_left) {
  821. size_t zero_bytes = 0, bytes_written;
  822. i2s_write(i2s_num, (void *)&zero_bytes, bytes_left, &bytes_written, portMAX_DELAY);
  823. }
  824. for (int i = 0; i < p_i2s[i2s_num]->dma_buf_count; i++) {
  825. memset(p_i2s[i2s_num]->tx->buf[i], 0, p_i2s[i2s_num]->tx->buf_size);
  826. }
  827. }
  828. return ESP_OK;
  829. }
  830. /*-------------------------------------------------------------
  831. I2S clock operation
  832. -------------------------------------------------------------*/
  833. #if SOC_I2S_SUPPORTS_APLL
  834. static esp_err_t i2s_set_apll_freq(uint32_t expt_freq, uint32_t *real_freq)
  835. {
  836. uint32_t rtc_xtal_freq = (uint32_t)rtc_clk_xtal_freq_get();
  837. ESP_RETURN_ON_FALSE(rtc_xtal_freq, ESP_ERR_INVALID_STATE, TAG, "Get xtal clock frequency failed, it has not been set yet");
  838. /* Reference formula: apll_freq = xtal_freq * (4 + sdm2 + sdm1/256 + sdm0/65536) / ((o_div + 2) * 2)
  839. * ---------------------------------------------- -----------------
  840. * 350 MHz <= Numerator <= 500 MHz Denominator
  841. */
  842. int o_div = 0; // range: 0~31
  843. int sdm0 = 0; // range: 0~255
  844. int sdm1 = 0; // range: 0~255
  845. int sdm2 = 0; // range: 0~63
  846. /* Firstly try to satisfy the condition that the operation frequency of numerator should be greater than 350 MHz,
  847. * i.e. xtal_freq * (4 + sdm2 + sdm1/256 + sdm0/65536) >= 350 MHz, '+1' in the following code is to get the ceil value.
  848. * With this condition, as we know the 'o_div' can't be greater than 31, then we can calculate the APLL minimum support frequency is
  849. * 350 MHz / ((31 + 2) * 2) = 5303031 Hz (for ceil) */
  850. o_div = (int)(SOC_APLL_MULTIPLIER_OUT_MIN_HZ / (float)(expt_freq * 2) + 1) - 2;
  851. ESP_RETURN_ON_FALSE(o_div < 32, ESP_ERR_INVALID_ARG, TAG, "Expected frequency is too small");
  852. if (o_div < 0) {
  853. /* Try to satisfy the condition that the operation frequency of numerator should be smaller than 500 MHz,
  854. * i.e. xtal_freq * (4 + sdm2 + sdm1/256 + sdm0/65536) <= 500 MHz, we need to get the floor value in the following code.
  855. * With this condition, as we know the 'o_div' can't be smaller than 0, then we can calculate the APLL maximum support frequency is
  856. * 500 MHz / ((0 + 2) * 2) = 125000000 Hz */
  857. o_div = (int)(SOC_APLL_MULTIPLIER_OUT_MAX_HZ / (float)(expt_freq * 2)) - 2;
  858. ESP_RETURN_ON_FALSE(o_div >= 0, ESP_ERR_INVALID_ARG, TAG, "Expected frequency is too small");
  859. }
  860. // sdm2 = (int)(((o_div + 2) * 2) * apll_freq / xtal_freq) - 4
  861. sdm2 = (int)(((o_div + 2) * 2 * expt_freq) / (rtc_xtal_freq * 1000000)) - 4;
  862. // numrator = (((o_div + 2) * 2) * apll_freq / xtal_freq) - 4 - sdm2
  863. float numrator = (((o_div + 2) * 2 * expt_freq) / ((float)rtc_xtal_freq * 1000000)) - 4 - sdm2;
  864. // If numrator is bigger than 255/256 + 255/65536 + (1/65536)/2 = 1 - (1 / 65536)/2, carry bit to sdm2
  865. if (numrator > 1.0 - (1.0 / 65536.0) / 2.0) {
  866. sdm2++;
  867. }
  868. // If numrator is smaller than (1/65536)/2, keep sdm0 = sdm1 = 0, otherwise calculate sdm0 and sdm1
  869. else if (numrator > (1.0 / 65536.0) / 2.0) {
  870. // Get the closest sdm1
  871. sdm1 = (int)(numrator * 65536.0 + 0.5) / 256;
  872. // Get the closest sdm0
  873. sdm0 = (int)(numrator * 65536.0 + 0.5) % 256;
  874. }
  875. rtc_clk_apll_enable(true, sdm0, sdm1, sdm2, o_div);
  876. *real_freq = (uint32_t)(rtc_xtal_freq * 1000000 * (4 + sdm2 + (float)sdm1/256.0 + (float)sdm0/65536.0) / (((float)o_div + 2) * 2));
  877. return ESP_OK;
  878. }
  879. #endif
  880. /**
  881. * @brief Config I2S source clock and get its frequency
  882. *
  883. * @param i2s_num I2S device number
  884. * @param use_apll Whether use apll, only take effect when chip supports
  885. * @param mclk module clock
  886. *
  887. * @return
  888. * - 0 use I2S_CLK_APLL as clock source, no I2S system clock to set
  889. * - I2S_LL_BASE_CLK use I2S_CLK_D2CLK as clock source, return APB clock frequency
  890. */
  891. static uint32_t i2s_config_source_clock(i2s_port_t i2s_num, bool use_apll, uint32_t mclk)
  892. {
  893. #if SOC_I2S_SUPPORTS_APLL
  894. if (use_apll) {
  895. /* Calculate the expected APLL */
  896. int div = (int)((SOC_APLL_MIN_HZ / mclk) + 1);
  897. /* apll_freq = mclk * div
  898. * when div = 1, hardware will still divide 2
  899. * when div = 0, the final mclk will be unpredictable
  900. * So the div here should be at least 2 */
  901. div = div < 2 ? 2 : div;
  902. uint32_t expt_freq = mclk * div;
  903. /* Set APLL coefficients to the given frequency */
  904. uint32_t real_freq = 0;
  905. esp_err_t ret = i2s_set_apll_freq(expt_freq, &real_freq);
  906. if (ret != ESP_OK) {
  907. ESP_LOGE(TAG, "set APLL coefficients failed");
  908. return 0;
  909. }
  910. ESP_LOGI(TAG, "APLL expected frequency is %d Hz, real frequency is %d Hz", expt_freq, real_freq);
  911. /* Set I2S_APLL as I2S module clock source */
  912. i2s_hal_set_clock_src(&(p_i2s[i2s_num]->hal), I2S_CLK_APLL);
  913. /* In APLL mode, there is no sclk but only mclk, so return 0 here to indicate APLL mode */
  914. return real_freq;
  915. }
  916. /* Set I2S_D2CLK (160M) as default I2S module clock source */
  917. i2s_hal_set_clock_src(&(p_i2s[i2s_num]->hal), I2S_CLK_D2CLK);
  918. return I2S_LL_BASE_CLK;
  919. #else
  920. if (use_apll) {
  921. ESP_LOGW(TAG, "APLL not supported on current chip, use I2S_CLK_D2CLK as default clock source");
  922. }
  923. /* Set I2S_D2CLK (160M) as I2S module clock source */
  924. i2s_hal_set_clock_src(&(p_i2s[i2s_num]->hal), I2S_CLK_D2CLK);
  925. return I2S_LL_BASE_CLK;
  926. #endif
  927. }
  928. #if SOC_I2S_SUPPORTS_ADC || SOC_I2S_SUPPORTS_DAC
  929. /**
  930. * @brief I2S calculate clock for built-in ADC/DAC mode
  931. *
  932. * @param i2s_num I2S device number
  933. * @param clk_cfg Struct to restore clock confiuration
  934. * @return
  935. * - ESP_OK Get clock success
  936. * - ESP_ERR_INVALID_ARG Invalid args
  937. */
  938. static esp_err_t i2s_calculate_adc_dac_clock(int i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  939. {
  940. ESP_RETURN_ON_FALSE(clk_cfg, ESP_ERR_INVALID_ARG, TAG, "input clk_cfg is NULL");
  941. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->hal_cfg.mode & (I2S_MODE_DAC_BUILT_IN | I2S_MODE_ADC_BUILT_IN), ESP_ERR_INVALID_ARG, TAG, "current mode is not built-in ADC/DAC");
  942. /* Set I2S bit clock */
  943. clk_cfg->bclk = p_i2s[i2s_num]->hal_cfg.sample_rate * I2S_LL_AD_BCK_FACTOR * 2;
  944. /* Set I2S bit clock default division */
  945. clk_cfg->bclk_div = I2S_LL_AD_BCK_FACTOR;
  946. /* If fixed_mclk and use_apll are set, use fixed_mclk as mclk frequency, otherwise calculate by mclk = sample_rate * multiple */
  947. clk_cfg->mclk = (p_i2s[i2s_num]->use_apll && p_i2s[i2s_num]->fixed_mclk) ?
  948. p_i2s[i2s_num]->fixed_mclk : clk_cfg->bclk * clk_cfg->bclk_div;
  949. /* Calculate bclk_div = mclk / bclk */
  950. clk_cfg->bclk_div = clk_cfg->mclk / clk_cfg->bclk;
  951. /* Get I2S system clock by config source clock */
  952. clk_cfg->sclk = i2s_config_source_clock(i2s_num, p_i2s[i2s_num]->use_apll, clk_cfg->mclk);
  953. /* Get I2S master clock rough division, later will calculate the fine division parameters in HAL */
  954. clk_cfg->mclk_div = clk_cfg->sclk / clk_cfg->mclk;
  955. /* Check if the configuration is correct */
  956. ESP_RETURN_ON_FALSE(clk_cfg->mclk <= clk_cfg->sclk, ESP_ERR_INVALID_ARG, TAG, "sample rate is too large");
  957. return ESP_OK;
  958. }
  959. #endif // SOC_I2S_SUPPORTS_ADC || SOC_I2S_SUPPORTS_DAC
  960. #if SOC_I2S_SUPPORTS_PDM_TX
  961. /**
  962. * @brief I2S calculate clock for PDM tx mode
  963. *
  964. * @param i2s_num I2S device number
  965. * @param clk_cfg Struct to restore clock confiuration
  966. * @return
  967. * - ESP_OK Get clock success
  968. * - ESP_ERR_INVALID_ARG Invalid args
  969. */
  970. static esp_err_t i2s_calculate_pdm_tx_clock(int i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  971. {
  972. ESP_RETURN_ON_FALSE(clk_cfg, ESP_ERR_INVALID_ARG, TAG, "input clk_cfg is NULL");
  973. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_PDM, ESP_ERR_INVALID_ARG, TAG, "current mode is not PDM");
  974. int fp = i2s_hal_get_tx_pdm_fp(&(p_i2s[i2s_num]->hal));
  975. int fs = i2s_hal_get_tx_pdm_fs(&(p_i2s[i2s_num]->hal));
  976. /* Set I2S bit clock */
  977. clk_cfg->bclk = p_i2s[i2s_num]->hal_cfg.sample_rate * I2S_LL_PDM_BCK_FACTOR * fp / fs;
  978. /* Set I2S bit clock default division */
  979. clk_cfg->bclk_div = 8;
  980. /* If fixed_mclk and use_apll are set, use fixed_mclk as mclk frequency, otherwise calculate by mclk = sample_rate * multiple */
  981. clk_cfg->mclk = (p_i2s[i2s_num]->use_apll && p_i2s[i2s_num]->fixed_mclk) ?
  982. p_i2s[i2s_num]->fixed_mclk : clk_cfg->bclk * clk_cfg->bclk_div;
  983. /* Calculate bclk_div = mclk / bclk */
  984. clk_cfg->bclk_div = clk_cfg->mclk / clk_cfg->bclk;
  985. /* Get I2S system clock by config source clock */
  986. clk_cfg->sclk = i2s_config_source_clock(i2s_num, p_i2s[i2s_num]->use_apll, clk_cfg->mclk);
  987. /* Get I2S master clock rough division, later will calculate the fine division parameters in HAL */
  988. clk_cfg->mclk_div = clk_cfg->sclk / clk_cfg->mclk;
  989. /* Check if the configuration is correct */
  990. ESP_RETURN_ON_FALSE(clk_cfg->mclk <= clk_cfg->sclk, ESP_ERR_INVALID_ARG, TAG, "sample rate is too large");
  991. return ESP_OK;
  992. }
  993. #endif // SOC_I2S_SUPPORTS_PDM_TX
  994. #if SOC_I2S_SUPPORTS_PDM_RX
  995. /**
  996. * @brief I2S calculate clock for PDM rx mode
  997. *
  998. * @param i2s_num I2S device number
  999. * @param clk_cfg Struct to restore clock confiuration
  1000. * @return
  1001. * - ESP_OK Get clock success
  1002. * - ESP_ERR_INVALID_ARG Invalid args
  1003. */
  1004. static esp_err_t i2s_calculate_pdm_rx_clock(int i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1005. {
  1006. ESP_RETURN_ON_FALSE(clk_cfg, ESP_ERR_INVALID_ARG, TAG, "input clk_cfg is NULL");
  1007. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_PDM, ESP_ERR_INVALID_ARG, TAG, "current mode is not PDM");
  1008. i2s_pdm_dsr_t dsr;
  1009. i2s_hal_get_rx_pdm_dsr(&(p_i2s[i2s_num]->hal), &dsr);
  1010. /* Set I2S bit clock */
  1011. clk_cfg->bclk = p_i2s[i2s_num]->hal_cfg.sample_rate * I2S_LL_PDM_BCK_FACTOR * (dsr == I2S_PDM_DSR_16S ? 2 : 1);
  1012. /* Set I2S bit clock default division */
  1013. clk_cfg->bclk_div = 8;
  1014. /* If fixed_mclk and use_apll are set, use fixed_mclk as mclk frequency, otherwise calculate by mclk = sample_rate * multiple */
  1015. clk_cfg->mclk = (p_i2s[i2s_num]->use_apll && p_i2s[i2s_num]->fixed_mclk) ?
  1016. p_i2s[i2s_num]->fixed_mclk : clk_cfg->bclk * clk_cfg->bclk_div;
  1017. /* Calculate bclk_div = mclk / bclk */
  1018. clk_cfg->bclk_div = clk_cfg->mclk / clk_cfg->bclk;
  1019. /* Get I2S system clock by config source clock */
  1020. clk_cfg->sclk = i2s_config_source_clock(i2s_num, p_i2s[i2s_num]->use_apll, clk_cfg->mclk);
  1021. /* Get I2S master clock rough division, later will calculate the fine division parameters in HAL */
  1022. clk_cfg->mclk_div = clk_cfg->sclk / clk_cfg->mclk;
  1023. /* Check if the configuration is correct */
  1024. ESP_RETURN_ON_FALSE(clk_cfg->mclk <= clk_cfg->sclk, ESP_ERR_INVALID_ARG, TAG, "sample rate is too large");
  1025. return ESP_OK;
  1026. }
  1027. #endif // SOC_I2S_SUPPORTS_PDM_RX
  1028. /**
  1029. * @brief I2S calculate clock for common mode (philip, MSB, PCM)
  1030. *
  1031. * @param i2s_num I2S device number
  1032. * @param clk_cfg Struct to restore clock confiuration
  1033. * @return
  1034. * - ESP_OK Get clock success
  1035. * - ESP_ERR_INVALID_ARG Invalid args
  1036. */
  1037. static esp_err_t i2s_calculate_common_clock(int i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1038. {
  1039. ESP_RETURN_ON_FALSE(clk_cfg, ESP_ERR_INVALID_ARG, TAG, "input clk_cfg is NULL");
  1040. uint32_t rate = p_i2s[i2s_num]->hal_cfg.sample_rate;
  1041. uint32_t chan_num = p_i2s[i2s_num]->hal_cfg.total_chan < 2 ? 2 : p_i2s[i2s_num]->hal_cfg.total_chan;
  1042. uint32_t chan_bit = p_i2s[i2s_num]->hal_cfg.chan_bits;
  1043. uint32_t multi;
  1044. /* Calculate multiple */
  1045. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_MASTER || p_i2s[i2s_num]->use_apll) {
  1046. multi = p_i2s[i2s_num]->mclk_multiple ? p_i2s[i2s_num]->mclk_multiple : I2S_MCLK_MULTIPLE_256;
  1047. } else {
  1048. /* Only need to set the multiple of mclk to sample rate for MASTER mode,
  1049. * because BCK and WS clock are provided by the external codec in SLAVE mode.
  1050. * The multiple should be big enough to get a high module clock which could detect the edges of externel clock more accurately,
  1051. * otherwise the data we receive or send would get a large latency and go wrong due to the slow module clock.
  1052. * But on ESP32 and ESP32S2, due to the different clock work mode in hardware,
  1053. * their multiple should be set to an appropriate range according to the sample bits,
  1054. * and this particular multiple finally aims at guaranteeing the bclk_div not smaller than 8,
  1055. * if not, the I2S may can't send data or send wrong data.
  1056. * Here use 'SOC_I2S_SUPPORTS_TDM' to differentialize other chips with ESP32 and ESP32S2.
  1057. */
  1058. #if SOC_I2S_SUPPORTS_TDM
  1059. multi = I2S_LL_BASE_CLK / rate;
  1060. #else
  1061. multi = 64 * chan_bit;
  1062. #endif
  1063. }
  1064. /* Set I2S bit clock */
  1065. clk_cfg->bclk = rate * chan_num * chan_bit;
  1066. /* If fixed_mclk and use_apll are set, use fixed_mclk as mclk frequency, otherwise calculate by mclk = sample_rate * multiple */
  1067. clk_cfg->mclk = (p_i2s[i2s_num]->use_apll && p_i2s[i2s_num]->fixed_mclk) ?
  1068. p_i2s[i2s_num]->fixed_mclk : (rate * multi);
  1069. /* Calculate bclk_div = mclk / bclk */
  1070. clk_cfg->bclk_div = clk_cfg->mclk / clk_cfg->bclk;
  1071. /* Get I2S system clock by config source clock */
  1072. clk_cfg->sclk = i2s_config_source_clock(i2s_num, p_i2s[i2s_num]->use_apll, clk_cfg->mclk);
  1073. /* Get I2S master clock rough division, later will calculate the fine division parameters in HAL */
  1074. clk_cfg->mclk_div = clk_cfg->sclk / clk_cfg->mclk;
  1075. /* Check if the configuration is correct */
  1076. ESP_RETURN_ON_FALSE(clk_cfg->mclk <= clk_cfg->sclk, ESP_ERR_INVALID_ARG, TAG, "sample rate is too large");
  1077. return ESP_OK;
  1078. }
  1079. /**
  1080. * @brief I2S calculate clocks according to the selected I2S mode
  1081. *
  1082. * @param i2s_num I2S device number
  1083. * @param clk_cfg Struct to restore clock confiuration
  1084. * @return
  1085. * - ESP_OK Claculate clock success
  1086. * - ESP_ERR_INVALID_ARG Invalid args
  1087. */
  1088. static esp_err_t i2s_calculate_clock(i2s_port_t i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1089. {
  1090. /* Calculate clock for ADC mode */
  1091. #if SOC_I2S_SUPPORTS_ADC
  1092. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_ADC_BUILT_IN) {
  1093. ESP_RETURN_ON_ERROR(i2s_calculate_adc_dac_clock(i2s_num, clk_cfg), TAG, "ADC clock calculate failed");
  1094. return ESP_OK;
  1095. }
  1096. #endif // SOC_I2S_SUPPORTS_ADC
  1097. /* Calculate clock for DAC mode */
  1098. #if SOC_I2S_SUPPORTS_DAC
  1099. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_DAC_BUILT_IN) {
  1100. ESP_RETURN_ON_ERROR(i2s_calculate_adc_dac_clock(i2s_num, clk_cfg), TAG, "DAC clock calculate failed");
  1101. return ESP_OK;
  1102. }
  1103. #endif // SOC_I2S_SUPPORTS_DAC
  1104. /* Calculate clock for PDM mode */
  1105. #if SOC_I2S_SUPPORTS_PDM_TX || SOC_I2S_SUPPORTS_PDM_RX
  1106. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_PDM) {
  1107. #if SOC_I2S_SUPPORTS_PDM_TX
  1108. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1109. ESP_RETURN_ON_ERROR(i2s_calculate_pdm_tx_clock(i2s_num, clk_cfg), TAG, "PDM TX clock calculate failed");
  1110. }
  1111. #endif // SOC_I2S_SUPPORTS_PDM_TX
  1112. #if SOC_I2S_SUPPORTS_PDM_RX
  1113. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1114. ESP_RETURN_ON_ERROR(i2s_calculate_pdm_rx_clock(i2s_num, clk_cfg), TAG, "PDM RX clock calculate failed");
  1115. }
  1116. #endif // SOC_I2S_SUPPORTS_PDM_RX
  1117. return ESP_OK;
  1118. }
  1119. #endif // SOC_I2S_SUPPORTS_PDM_TX || SOC_I2S_SUPPORTS_PDM_RX
  1120. /* Calculate clock for common mode */
  1121. ESP_RETURN_ON_ERROR(i2s_calculate_common_clock(i2s_num, clk_cfg), TAG, "Common clock calculate failed");
  1122. return ESP_OK;
  1123. }
  1124. /*-------------------------------------------------------------
  1125. I2S configuration
  1126. -------------------------------------------------------------*/
  1127. #if SOC_I2S_SUPPORTS_TDM
  1128. /**
  1129. * @brief Get max actived channel number
  1130. *
  1131. * @param chan_mask I2S channel mask that indicates which channels are actived
  1132. * @return
  1133. * - Max actived channel number
  1134. */
  1135. static uint32_t i2s_get_max_channel_num(i2s_channel_t chan_mask)
  1136. {
  1137. uint32_t max_chan = 0;
  1138. uint32_t channel = chan_mask & 0xFFFF;
  1139. for (int i = 0; channel && i < 16; i++, channel >>= 1) {
  1140. if (channel & 0x01) {
  1141. max_chan = i + 1;
  1142. }
  1143. }
  1144. /* Can't be smaller than 2 */
  1145. return max_chan < 2 ? 2 : max_chan;
  1146. }
  1147. #endif
  1148. /**
  1149. * @brief Get active channel number according to channel format
  1150. * @note In 'I2S_CHANNEL_FMT_MULTIPLE' format, this function will check
  1151. * 'total_chan' and fix it if it is not correct.
  1152. *
  1153. * @param hal_cfg [input/output] I2S hal configuration structer
  1154. * @return
  1155. * - Active channel number
  1156. */
  1157. static uint32_t i2s_get_active_channel_num(const i2s_hal_config_t *hal_cfg)
  1158. {
  1159. switch (hal_cfg->chan_fmt) {
  1160. case I2S_CHANNEL_FMT_RIGHT_LEFT: //fall through
  1161. case I2S_CHANNEL_FMT_ALL_RIGHT: //fall through
  1162. case I2S_CHANNEL_FMT_ALL_LEFT:
  1163. return 2;
  1164. case I2S_CHANNEL_FMT_ONLY_RIGHT: //fall through
  1165. case I2S_CHANNEL_FMT_ONLY_LEFT:
  1166. return 1;
  1167. #if SOC_I2S_SUPPORTS_TDM
  1168. case I2S_CHANNEL_FMT_MULTIPLE: {
  1169. uint32_t num = 0;
  1170. uint32_t chan_mask = hal_cfg->chan_mask & 0xFFFF;
  1171. for (int i = 0; chan_mask && i < 16; i++, chan_mask >>= 1) {
  1172. if (chan_mask & 0x01) {
  1173. num++;
  1174. }
  1175. }
  1176. return num;
  1177. }
  1178. #endif
  1179. default:
  1180. return 0;
  1181. }
  1182. }
  1183. #if SOC_I2S_SUPPORTS_DAC
  1184. /**
  1185. * @brief I2S set built-in DAC mode
  1186. *
  1187. * @param dac_mode DAC mode
  1188. * @return
  1189. * - ESP_OK Set DAC success
  1190. * - ESP_ERR_INVALID_ARG Wrong DAC mode
  1191. */
  1192. esp_err_t i2s_set_dac_mode(i2s_dac_mode_t dac_mode)
  1193. {
  1194. ESP_RETURN_ON_FALSE((dac_mode < I2S_DAC_CHANNEL_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s dac mode error");
  1195. if (dac_mode == I2S_DAC_CHANNEL_DISABLE) {
  1196. dac_output_disable(DAC_CHANNEL_1);
  1197. dac_output_disable(DAC_CHANNEL_2);
  1198. dac_i2s_disable();
  1199. } else {
  1200. dac_i2s_enable();
  1201. }
  1202. if (dac_mode & I2S_DAC_CHANNEL_RIGHT_EN) {
  1203. //DAC1, right channel
  1204. dac_output_enable(DAC_CHANNEL_1);
  1205. }
  1206. if (dac_mode & I2S_DAC_CHANNEL_LEFT_EN) {
  1207. //DAC2, left channel
  1208. dac_output_enable(DAC_CHANNEL_2);
  1209. }
  1210. return ESP_OK;
  1211. }
  1212. #endif // SOC_I2S_SUPPORTS_DAC
  1213. #if SOC_I2S_SUPPORTS_ADC
  1214. /**
  1215. * @brief ADC mode recover
  1216. *
  1217. * @return
  1218. * - ESP_OK ADC Recover success
  1219. * - ESP_ERR_INVALID_ARG ADC not initialized yet
  1220. */
  1221. static esp_err_t _i2s_adc_mode_recover(void)
  1222. {
  1223. ESP_RETURN_ON_FALSE(((_i2s_adc_unit != -1) && (_i2s_adc_channel != -1)), ESP_ERR_INVALID_ARG, TAG, "i2s ADC recover error, not initialized...");
  1224. return adc_i2s_mode_init(_i2s_adc_unit, _i2s_adc_channel);
  1225. }
  1226. /**
  1227. * @brief I2S set adc mode
  1228. *
  1229. * @param adc_unit ADC unit number
  1230. * @param adc_channel ADC channel
  1231. * @return
  1232. * - ESP_OK ADC Recover success
  1233. * - ESP_ERR_INVALID_ARG ADC not initialized yet
  1234. */
  1235. esp_err_t i2s_set_adc_mode(adc_unit_t adc_unit, adc1_channel_t adc_channel)
  1236. {
  1237. ESP_RETURN_ON_FALSE((adc_unit < ADC_UNIT_2), ESP_ERR_INVALID_ARG, TAG, "i2s ADC unit error, only support ADC1 for now");
  1238. // For now, we only support SAR ADC1.
  1239. _i2s_adc_unit = adc_unit;
  1240. _i2s_adc_channel = adc_channel;
  1241. return adc_i2s_mode_init(adc_unit, adc_channel);
  1242. }
  1243. /**
  1244. * @brief I2S enable ADC mode
  1245. *
  1246. * @param i2s_num I2S device number
  1247. * @return
  1248. * - ESP_OK Enable ADC success
  1249. * - ESP_ERR_INVALID_ARG Invalid argument
  1250. * - ESP_ERR_INVALID_STATE Current I2S mode is not built-in ADC
  1251. */
  1252. esp_err_t i2s_adc_enable(i2s_port_t i2s_num)
  1253. {
  1254. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1255. ESP_RETURN_ON_FALSE((p_i2s[i2s_num] != NULL), ESP_ERR_INVALID_STATE, TAG, "Not initialized yet");
  1256. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_ADC_BUILT_IN), ESP_ERR_INVALID_STATE, TAG, "i2s built-in adc not enabled");
  1257. adc1_dma_mode_acquire();
  1258. _i2s_adc_mode_recover();
  1259. i2s_rx_reset(i2s_num);
  1260. return i2s_set_clk(i2s_num, p_i2s[i2s_num]->hal_cfg.sample_rate, p_i2s[i2s_num]->hal_cfg.sample_bits, p_i2s[i2s_num]->hal_cfg.active_chan);
  1261. }
  1262. /**
  1263. * @brief I2S disable ADC
  1264. *
  1265. * @param i2s_num I2S device number
  1266. * @return
  1267. * - ESP_OK I2S ADC mode successfully disabled
  1268. * - ESP_ERR_INVALID_ARG Invalid argument
  1269. * - ESP_ERR_INVALID_STATE Current I2S mode is not built-in ADC
  1270. */
  1271. esp_err_t i2s_adc_disable(i2s_port_t i2s_num)
  1272. {
  1273. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1274. ESP_RETURN_ON_FALSE((p_i2s[i2s_num] != NULL), ESP_ERR_INVALID_STATE, TAG, "Not initialized yet");
  1275. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_ADC_BUILT_IN), ESP_ERR_INVALID_STATE, TAG, "i2s built-in adc not enabled");
  1276. i2s_hal_stop_rx(&(p_i2s[i2s_num]->hal));
  1277. adc1_lock_release();
  1278. return ESP_OK;
  1279. }
  1280. #endif
  1281. /**
  1282. * @brief Set sample rate used for I2S RX and TX.
  1283. * @note The bit clock rate is determined by the sample rate and i2s_config_t configuration parameters (number of channels, bits_per_sample).
  1284. * `bit_clock = rate * (number of channels) * bits_per_sample`
  1285. *
  1286. * @param i2s_num I2S device number
  1287. * @param rate I2S sample rate (ex: 8000, 44100...)
  1288. * @return
  1289. * - ESP_OK Success
  1290. * - ESP_ERR_INVALID_ARG Parameter error
  1291. * - ESP_ERR_NO_MEM Out of memory
  1292. */
  1293. esp_err_t i2s_set_sample_rates(i2s_port_t i2s_num, uint32_t rate)
  1294. {
  1295. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1296. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->hal_cfg.sample_bits > 0), ESP_ERR_INVALID_ARG, TAG, "sample bits not set");
  1297. return i2s_set_clk(i2s_num, rate, p_i2s[i2s_num]->hal_cfg.sample_bits, p_i2s[i2s_num]->hal_cfg.active_chan);
  1298. }
  1299. #if SOC_I2S_SUPPORTS_PCM
  1300. /**
  1301. * @brief Configure I2S a/u-law decompress or compress
  1302. * @note This function should be called after i2s driver installed
  1303. * Only take effect when the i2s 'communication_format' is set to 'I2S_COMM_FORMAT_STAND_PCM_SHORT' or 'I2S_COMM_FORMAT_STAND_PCM_LONG'
  1304. *
  1305. * @param i2s_num I2S_NUM_0
  1306. * @param pcm_cfg Including mode selection and a/u-law decompress or compress configuration paramater
  1307. * @return
  1308. * - ESP_OK Success
  1309. * - ESP_ERR_INVALID_ARG Parameter error
  1310. */
  1311. esp_err_t i2s_pcm_config(i2s_port_t i2s_num, const i2s_pcm_cfg_t *pcm_cfg)
  1312. {
  1313. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_FAIL, TAG, "i2s has not installed yet");
  1314. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->hal_cfg.comm_fmt & I2S_COMM_FORMAT_STAND_PCM_SHORT),
  1315. ESP_ERR_INVALID_ARG, TAG, "i2s communication mode is not PCM mode");
  1316. i2s_stop(i2s_num);
  1317. I2S_ENTER_CRITICAL(i2s_num);
  1318. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1319. i2s_hal_tx_pcm_cfg(&(p_i2s[i2s_num]->hal), pcm_cfg->pcm_type);
  1320. } else if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1321. i2s_hal_rx_pcm_cfg(&(p_i2s[i2s_num]->hal), pcm_cfg->pcm_type);
  1322. }
  1323. I2S_EXIT_CRITICAL(i2s_num);
  1324. i2s_start(i2s_num);
  1325. return ESP_OK;
  1326. }
  1327. #endif
  1328. #if SOC_I2S_SUPPORTS_PDM_RX
  1329. /**
  1330. * @brief Set PDM mode down-sample rate
  1331. * In PDM RX mode, there would be 2 rounds of downsample process in hardware.
  1332. * In the first downsample process, the sampling number can be 16 or 8.
  1333. * In the second downsample process, the sampling number is fixed as 8.
  1334. * So the clock frequency in PDM RX mode would be (fpcm * 64) or (fpcm * 128) accordingly.
  1335. * @note After calling this function, it would call i2s_set_clk inside to update the clock frequency.
  1336. * Please call this function after I2S driver has been initialized.
  1337. *
  1338. * @param i2s_num I2S device number
  1339. * @param downsample i2s RX down sample rate for PDM mode.
  1340. * @return
  1341. * - ESP_OK Success
  1342. * - ESP_ERR_INVALID_ARG Parameter error
  1343. * - ESP_ERR_NO_MEM Out of memory
  1344. */
  1345. esp_err_t i2s_set_pdm_rx_down_sample(i2s_port_t i2s_num, i2s_pdm_dsr_t downsample)
  1346. {
  1347. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_FAIL, TAG, "i2s has not installed yet");
  1348. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_PDM), ESP_ERR_INVALID_ARG, TAG, "i2s mode is not PDM mode");
  1349. i2s_stop(i2s_num);
  1350. i2s_hal_set_rx_pdm_dsr(&(p_i2s[i2s_num]->hal), downsample);
  1351. // i2s will start in 'i2s_set_clk'
  1352. return i2s_set_clk(i2s_num, p_i2s[i2s_num]->hal_cfg.sample_rate, p_i2s[i2s_num]->hal_cfg.sample_bits, p_i2s[i2s_num]->hal_cfg.active_chan);
  1353. }
  1354. #endif
  1355. #if SOC_I2S_SUPPORTS_PDM_TX
  1356. /**
  1357. * @brief Set TX PDM mode up-sample rate
  1358. * @note If you have set PDM mode while calling 'i2s_driver_install',
  1359. * default PDM TX upsample parameters have already been set,
  1360. * no need to call this function again if you don't have to change the default configuration
  1361. *
  1362. * @param i2s_num I2S device number
  1363. * @param upsample_cfg Set I2S PDM up-sample rate configuration
  1364. * @return
  1365. * - ESP_OK Success
  1366. * - ESP_ERR_INVALID_ARG Parameter error
  1367. * - ESP_ERR_NO_MEM Out of memory
  1368. */
  1369. esp_err_t i2s_set_pdm_tx_up_sample(i2s_port_t i2s_num, const i2s_pdm_tx_upsample_cfg_t *upsample_cfg)
  1370. {
  1371. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_FAIL, TAG, "i2s has not installed yet");
  1372. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_PDM), ESP_ERR_INVALID_ARG, TAG, "i2s mode is not PDM mode");
  1373. i2s_stop(i2s_num);
  1374. i2s_hal_set_tx_pdm_fpfs(&(p_i2s[i2s_num]->hal), upsample_cfg->fp, upsample_cfg->fs);
  1375. // i2s will start in 'i2s_set_clk'
  1376. return i2s_set_clk(i2s_num, upsample_cfg->sample_rate, p_i2s[i2s_num]->hal_cfg.sample_bits, p_i2s[i2s_num]->hal_cfg.active_chan);
  1377. }
  1378. #endif
  1379. /**
  1380. * @brief I2S check the validity of configuration
  1381. *
  1382. * @param i2s_num I2S device number
  1383. * @param cfg I2S HAL configuration
  1384. * @return
  1385. * - ESP_OK I2S configuration is valid
  1386. * - ESP_ERR_INVALID_ARG I2S configuration is invalid
  1387. */
  1388. static esp_err_t i2s_check_cfg_validity(i2s_port_t i2s_num, i2s_hal_config_t *cfg)
  1389. {
  1390. #if SOC_I2S_SUPPORTS_PDM_TX || SOC_I2S_SUPPORTS_PDM_RX
  1391. /* Check PDM mode */
  1392. if (cfg->mode & I2S_MODE_PDM) {
  1393. ESP_RETURN_ON_FALSE(i2s_num == I2S_NUM_0, ESP_ERR_INVALID_ARG, TAG, "I2S PDM mode only support on I2S0");
  1394. #if !SOC_I2S_SUPPORTS_PDM_TX
  1395. ESP_RETURN_ON_FALSE(!(cfg->mode & I2S_MODE_TX), ESP_ERR_INVALID_ARG, TAG, "PDM does not support TX on this chip");
  1396. #endif // SOC_I2S_SUPPORTS_PDM_TX
  1397. #if !SOC_I2S_SUPPORTS_PDM_RX
  1398. ESP_RETURN_ON_FALSE(!(cfg->mode & I2S_MODE_RX), ESP_ERR_INVALID_ARG, TAG, "PDM does not support RX on this chip");
  1399. #endif // SOC_I2S_SUPPORTS_PDM_RX
  1400. }
  1401. #else
  1402. ESP_RETURN_ON_FALSE(!(cfg->mode & I2S_MODE_PDM), ESP_ERR_INVALID_ARG, TAG, "I2S PDM mode not supported on current chip");
  1403. #endif // SOC_I2S_SUPPORTS_PDM_TX || SOC_I2S_SUPPORTS_PDM_RX
  1404. #if SOC_I2S_SUPPORTS_ADC || SOC_I2S_SUPPORTS_DAC
  1405. /* Check built-in ADC/DAC mode */
  1406. if (cfg->mode & (I2S_MODE_ADC_BUILT_IN | I2S_MODE_DAC_BUILT_IN)) {
  1407. ESP_RETURN_ON_FALSE(i2s_num == I2S_NUM_0, ESP_ERR_INVALID_ARG, TAG, "I2S built-in ADC/DAC only support on I2S0");
  1408. }
  1409. #else
  1410. /* Check the transmit/receive mode */
  1411. ESP_RETURN_ON_FALSE((cfg->mode & I2S_MODE_TX) || (cfg->mode & I2S_MODE_RX), ESP_ERR_INVALID_ARG, TAG, "I2S no TX/RX mode selected");
  1412. /* Check communication format */
  1413. ESP_RETURN_ON_FALSE(cfg->comm_fmt && (cfg->comm_fmt < I2S_COMM_FORMAT_STAND_MAX), ESP_ERR_INVALID_ARG, TAG, "invalid communication formats");
  1414. #endif // SOC_I2S_SUPPORTS_ADC || SOC_I2S_SUPPORTS_DAC
  1415. return ESP_OK;
  1416. }
  1417. static void i2s_tx_set_clk_and_channel(i2s_port_t i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1418. {
  1419. i2s_hal_tx_clock_config(&(p_i2s[i2s_num]->hal), clk_cfg);
  1420. i2s_hal_set_tx_sample_bit(&(p_i2s[i2s_num]->hal), p_i2s[i2s_num]->hal_cfg.chan_bits, p_i2s[i2s_num]->hal_cfg.sample_bits);
  1421. i2s_hal_tx_set_channel_style(&(p_i2s[i2s_num]->hal), &(p_i2s[i2s_num]->hal_cfg));
  1422. }
  1423. static void i2s_rx_set_clk_and_channel(i2s_port_t i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1424. {
  1425. i2s_hal_rx_clock_config(&(p_i2s[i2s_num]->hal), clk_cfg);
  1426. i2s_hal_set_rx_sample_bit(&(p_i2s[i2s_num]->hal), p_i2s[i2s_num]->hal_cfg.chan_bits, p_i2s[i2s_num]->hal_cfg.sample_bits);
  1427. i2s_hal_rx_set_channel_style(&(p_i2s[i2s_num]->hal), &(p_i2s[i2s_num]->hal_cfg));
  1428. }
  1429. /**
  1430. * @brief Get clock set on particular port number.
  1431. *
  1432. * @param i2s_num I2S device number
  1433. * @return
  1434. * - sample rate
  1435. */
  1436. float i2s_get_clk(i2s_port_t i2s_num)
  1437. {
  1438. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1439. return (float)p_i2s[i2s_num]->hal_cfg.sample_rate;
  1440. }
  1441. /**
  1442. * @brief Set clock & bit width used for I2S RX and TX.
  1443. * Similar to i2s_set_sample_rates(), but also sets bit width.
  1444. *
  1445. * 1. stop i2s
  1446. * 2. calculate mclk, bck, bck_factor
  1447. * 3. set clock configurations
  1448. * 4. realloc dma buffer if DMA buffer size changed
  1449. * 5. start i2s
  1450. *
  1451. * @param i2s_num I2S device number
  1452. * @param rate I2S sample rate (ex: 8000, 44100...)
  1453. * @param bits_cfg I2S bits configuration
  1454. * the low 16 bits is for data bits per sample in one channel (see 'i2s_bits_per_sample_t')
  1455. * the high 16 bits is for total bits in one channel (see 'i2s_bits_per_chan_t')
  1456. * high 16bits =0 means same as the bits per sample.
  1457. * @param ch I2S channel, (I2S_CHANNEL_MONO, I2S_CHANNEL_STEREO or specific channel in TDM mode)
  1458. * @return
  1459. * - ESP_OK Success
  1460. * - ESP_ERR_INVALID_ARG Parameter error
  1461. * - ESP_ERR_NO_MEM Out of memory
  1462. */
  1463. esp_err_t i2s_set_clk(i2s_port_t i2s_num, uint32_t rate, uint32_t bits_cfg, i2s_channel_t ch)
  1464. {
  1465. esp_err_t ret = ESP_OK;
  1466. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1467. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_ERR_INVALID_ARG, TAG, "I2S%d has not installed yet", i2s_num);
  1468. i2s_hal_config_t *cfg = &p_i2s[i2s_num]->hal_cfg;
  1469. /* If not the first time, update configuration */
  1470. if (p_i2s[i2s_num]->last_buf_size) {
  1471. cfg->sample_rate = rate;
  1472. cfg->sample_bits = bits_cfg & 0xFFFF;
  1473. cfg->chan_bits = (bits_cfg >> 16) > cfg->sample_bits ? (bits_cfg >> 16) : cfg->sample_bits;
  1474. #if SOC_I2S_SUPPORTS_TDM
  1475. cfg->chan_mask = ch;
  1476. cfg->chan_fmt = ch == I2S_CHANNEL_MONO ? I2S_CHANNEL_FMT_ONLY_RIGHT : cfg->chan_fmt;
  1477. cfg->active_chan = i2s_get_active_channel_num(cfg);
  1478. uint32_t max_channel = i2s_get_max_channel_num(cfg->chan_mask);
  1479. /* If total channel is smaller than max actived channel number then set it to the max active channel number */
  1480. cfg->total_chan = p_i2s[i2s_num]->hal_cfg.total_chan < max_channel ? max_channel : p_i2s[i2s_num]->hal_cfg.total_chan;
  1481. #else
  1482. /* Default */
  1483. cfg->chan_fmt = ch == I2S_CHANNEL_MONO ? I2S_CHANNEL_FMT_ONLY_RIGHT : cfg->chan_fmt;
  1484. cfg->active_chan = i2s_get_active_channel_num(cfg);
  1485. cfg->total_chan = 2;
  1486. #endif
  1487. if (cfg->mode & I2S_MODE_TX) {
  1488. xSemaphoreTake(p_i2s[i2s_num]->tx->mux, (portTickType)portMAX_DELAY);
  1489. i2s_hal_tx_set_channel_style(&(p_i2s[i2s_num]->hal), cfg);
  1490. xSemaphoreGive(p_i2s[i2s_num]->tx->mux);
  1491. }
  1492. if (cfg->mode & I2S_MODE_RX) {
  1493. xSemaphoreTake(p_i2s[i2s_num]->rx->mux, (portTickType)portMAX_DELAY);
  1494. i2s_hal_rx_set_channel_style(&(p_i2s[i2s_num]->hal), cfg);
  1495. xSemaphoreGive(p_i2s[i2s_num]->rx->mux);
  1496. }
  1497. }
  1498. uint32_t data_bits = cfg->sample_bits;
  1499. /* Check the validity of sample bits */
  1500. ESP_RETURN_ON_FALSE((data_bits % 8 == 0), ESP_ERR_INVALID_ARG, TAG, "Invalid bits per sample");
  1501. ESP_RETURN_ON_FALSE((data_bits <= I2S_BITS_PER_SAMPLE_32BIT), ESP_ERR_INVALID_ARG, TAG, "Invalid bits per sample");
  1502. /* Stop I2S */
  1503. i2s_stop(i2s_num);
  1504. i2s_hal_clock_cfg_t clk_cfg;
  1505. /* To get sclk, mclk, mclk_div bclk and bclk_div */
  1506. i2s_calculate_clock(i2s_num, &clk_cfg);
  1507. uint32_t buf_size = i2s_get_buf_size(i2s_num);
  1508. bool need_realloc = p_i2s[i2s_num]->last_buf_size != buf_size;
  1509. /* TX mode clock reset */
  1510. if (cfg->mode & I2S_MODE_TX) {
  1511. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->tx, ESP_ERR_INVALID_ARG, TAG, "I2S TX DMA object has not initialized yet");
  1512. /* Waiting for transmit finish */
  1513. xSemaphoreTake(p_i2s[i2s_num]->tx->mux, (portTickType)portMAX_DELAY);
  1514. i2s_tx_set_clk_and_channel(i2s_num, &clk_cfg);
  1515. /* If buffer size changed, the DMA buffer need realloc */
  1516. if (need_realloc) {
  1517. p_i2s[i2s_num]->tx->buf_size = buf_size;
  1518. ret = i2s_realloc_dma_buffer(i2s_num, p_i2s[i2s_num]->tx);
  1519. }
  1520. /* If not the first time, update I2S tx channel style */
  1521. if (p_i2s[i2s_num]->last_buf_size) {
  1522. i2s_hal_tx_set_channel_style(&(p_i2s[i2s_num]->hal), &(p_i2s[i2s_num]->hal_cfg));
  1523. }
  1524. /* Reset the queue to avoid receive invalid data */
  1525. xQueueReset(p_i2s[i2s_num]->tx->queue);
  1526. xSemaphoreGive(p_i2s[i2s_num]->tx->mux);
  1527. ESP_RETURN_ON_ERROR(ret, TAG, "I2S%d tx DMA buffer malloc failed", i2s_num);
  1528. }
  1529. /* RX mode clock reset */
  1530. if (cfg->mode & I2S_MODE_RX) {
  1531. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->rx, ESP_ERR_INVALID_ARG, TAG, "I2S TX DMA object has not initialized yet");
  1532. /* Waiting for receive finish */
  1533. xSemaphoreTake(p_i2s[i2s_num]->rx->mux, (portTickType)portMAX_DELAY);
  1534. i2s_rx_set_clk_and_channel(i2s_num, &clk_cfg);
  1535. /* If buffer size changed, the DMA buffer need realloc */
  1536. if (need_realloc) {
  1537. p_i2s[i2s_num]->rx->buf_size = buf_size;
  1538. ret = i2s_realloc_dma_buffer(i2s_num, p_i2s[i2s_num]->rx);
  1539. /* Reset the end-of-frame number */
  1540. i2s_hal_set_rx_eof_num(&(p_i2s[i2s_num]->hal), buf_size);
  1541. }
  1542. /* If not the first time, update I2S rx channel style */
  1543. if (p_i2s[i2s_num]->last_buf_size) {
  1544. i2s_hal_rx_set_channel_style(&(p_i2s[i2s_num]->hal), &(p_i2s[i2s_num]->hal_cfg));
  1545. }
  1546. /* Reset the queue to avoid receiving invalid data */
  1547. xQueueReset(p_i2s[i2s_num]->rx->queue);
  1548. xSemaphoreGive(p_i2s[i2s_num]->rx->mux);
  1549. ESP_RETURN_ON_ERROR(ret, TAG, "I2S%d rx DMA buffer malloc failed", i2s_num);
  1550. }
  1551. /* Update last buffer size */
  1552. p_i2s[i2s_num]->last_buf_size = buf_size;
  1553. /* I2S start */
  1554. i2s_start(i2s_num);
  1555. return ESP_OK;
  1556. }
  1557. /*-------------------------------------------------------------
  1558. I2S driver operation
  1559. -------------------------------------------------------------*/
  1560. /**
  1561. * @brief Start I2S driver
  1562. * @note It is not necessary to call this function after i2s_driver_install() (it is started automatically), however it is necessary to call it after i2s_stop().
  1563. *
  1564. * @param i2s_num I2S device number
  1565. * @return
  1566. * - ESP_OK Success
  1567. * - ESP_ERR_INVALID_ARG Parameter error
  1568. */
  1569. esp_err_t i2s_start(i2s_port_t i2s_num)
  1570. {
  1571. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1572. //start DMA link
  1573. I2S_ENTER_CRITICAL(i2s_num);
  1574. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1575. i2s_tx_reset(i2s_num);
  1576. i2s_tx_start(i2s_num);
  1577. }
  1578. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1579. i2s_rx_reset(i2s_num);
  1580. i2s_rx_start(i2s_num);
  1581. }
  1582. #if !SOC_GDMA_SUPPORTED
  1583. esp_intr_enable(p_i2s[i2s_num]->i2s_isr_handle);
  1584. #endif
  1585. I2S_EXIT_CRITICAL(i2s_num);
  1586. return ESP_OK;
  1587. }
  1588. /**
  1589. * @brief Stop I2S driver
  1590. * @note There is no need to call i2s_stop() before calling i2s_driver_uninstall().
  1591. * Disables I2S TX/RX, until i2s_start() is called.
  1592. *
  1593. * @param i2s_num I2S device number
  1594. *
  1595. * @return
  1596. * - ESP_OK Success
  1597. * - ESP_ERR_INVALID_ARG Parameter error
  1598. */
  1599. esp_err_t i2s_stop(i2s_port_t i2s_num)
  1600. {
  1601. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1602. I2S_ENTER_CRITICAL(i2s_num);
  1603. #if !SOC_GDMA_SUPPORTED
  1604. esp_intr_disable(p_i2s[i2s_num]->i2s_isr_handle);
  1605. #endif
  1606. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1607. i2s_tx_stop(i2s_num);
  1608. }
  1609. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1610. i2s_rx_stop(i2s_num);
  1611. }
  1612. #if !SOC_GDMA_SUPPORTED
  1613. i2s_hal_clear_intr_status(&(p_i2s[i2s_num]->hal), I2S_INTR_MAX);
  1614. #endif
  1615. I2S_EXIT_CRITICAL(i2s_num);
  1616. return ESP_OK;
  1617. }
  1618. /**
  1619. * @brief Initialize I2S driver configurations
  1620. *
  1621. * @param i2s_num I2S device number
  1622. * @param i2s_config I2S configurations - see i2s_config_t struct
  1623. * @return
  1624. * - ESP_OK I2S initialize success
  1625. * - ESP_ERR_INVALID_ARG No channel enabled in multiple channel format
  1626. */
  1627. static esp_err_t i2s_driver_init(i2s_port_t i2s_num, const i2s_config_t *i2s_config)
  1628. {
  1629. ESP_RETURN_ON_FALSE(i2s_config, ESP_ERR_INVALID_ARG, TAG, "The pointer of I2S configuration structure is NULL");
  1630. /* I2S driver configuration assignment */
  1631. p_i2s[i2s_num]->i2s_num = i2s_num;
  1632. p_i2s[i2s_num]->dma_buf_count = i2s_config->dma_buf_count;
  1633. p_i2s[i2s_num]->dma_buf_len = i2s_config->dma_buf_len;
  1634. p_i2s[i2s_num]->last_buf_size = 0;
  1635. p_i2s[i2s_num]->use_apll = i2s_config->use_apll;
  1636. p_i2s[i2s_num]->fixed_mclk = i2s_config->fixed_mclk;
  1637. p_i2s[i2s_num]->mclk_multiple = i2s_config->mclk_multiple;
  1638. p_i2s[i2s_num]->tx_desc_auto_clear = i2s_config->tx_desc_auto_clear;
  1639. /* I2S HAL configuration assignment */
  1640. p_i2s[i2s_num]->hal_cfg.mode = i2s_config->mode;
  1641. p_i2s[i2s_num]->hal_cfg.sample_rate = i2s_config->sample_rate;
  1642. p_i2s[i2s_num]->hal_cfg.comm_fmt = i2s_config->communication_format;
  1643. p_i2s[i2s_num]->hal_cfg.chan_fmt = i2s_config->channel_format;
  1644. p_i2s[i2s_num]->hal_cfg.sample_bits = i2s_config->bits_per_sample;
  1645. p_i2s[i2s_num]->hal_cfg.chan_bits = (uint32_t)i2s_config->bits_per_chan < (uint32_t)i2s_config->bits_per_sample ?
  1646. (uint32_t)i2s_config->bits_per_sample : (uint32_t)i2s_config->bits_per_chan;
  1647. #if SOC_I2S_SUPPORTS_TDM
  1648. /* I2S HAL TDM configuration assignment */
  1649. p_i2s[i2s_num]->hal_cfg.left_align = i2s_config->left_align;
  1650. p_i2s[i2s_num]->hal_cfg.big_edin = i2s_config->big_edin;
  1651. p_i2s[i2s_num]->hal_cfg.bit_order_msb = i2s_config->bit_order_msb;
  1652. p_i2s[i2s_num]->hal_cfg.skip_msk = i2s_config->skip_msk;
  1653. /* Set chan_mask according to channel format */
  1654. switch (i2s_config->channel_format) {
  1655. case I2S_CHANNEL_FMT_RIGHT_LEFT: // fall through
  1656. case I2S_CHANNEL_FMT_ALL_RIGHT: // fall through
  1657. case I2S_CHANNEL_FMT_ALL_LEFT:
  1658. p_i2s[i2s_num]->hal_cfg.chan_mask = I2S_TDM_ACTIVE_CH0 | I2S_TDM_ACTIVE_CH1;
  1659. p_i2s[i2s_num]->hal_cfg.total_chan = 2;
  1660. break;
  1661. case I2S_CHANNEL_FMT_ONLY_RIGHT: // fall through
  1662. case I2S_CHANNEL_FMT_ONLY_LEFT:
  1663. p_i2s[i2s_num]->hal_cfg.chan_mask = I2S_TDM_ACTIVE_CH0;
  1664. p_i2s[i2s_num]->hal_cfg.total_chan = 2;
  1665. break;
  1666. case I2S_CHANNEL_FMT_MULTIPLE:
  1667. ESP_RETURN_ON_FALSE(i2s_config->chan_mask, ESP_ERR_INVALID_ARG, TAG, "i2s all channel are disabled");
  1668. p_i2s[i2s_num]->hal_cfg.chan_mask = i2s_config->chan_mask;
  1669. /* Get the max actived channel number */
  1670. uint32_t max_channel = i2s_get_max_channel_num(p_i2s[i2s_num]->hal_cfg.chan_mask);
  1671. /* If total channel is smaller than max actived channel number then set it to the max active channel number */
  1672. p_i2s[i2s_num]->hal_cfg.total_chan = p_i2s[i2s_num]->hal_cfg.total_chan < max_channel ? max_channel :
  1673. p_i2s[i2s_num]->hal_cfg.total_chan;
  1674. break;
  1675. default:
  1676. ESP_RETURN_ON_FALSE(false, ESP_ERR_INVALID_ARG, TAG, "wrong i2s channel format, going to uninstall i2s");
  1677. }
  1678. /* Calculate actived channel number in channel mask */
  1679. p_i2s[i2s_num]->hal_cfg.active_chan = i2s_get_active_channel_num(&p_i2s[i2s_num]->hal_cfg);
  1680. #else
  1681. /* Calculate actived channel number in channel mask */
  1682. p_i2s[i2s_num]->hal_cfg.active_chan = i2s_get_active_channel_num(&p_i2s[i2s_num]->hal_cfg);
  1683. /* Total channel number is equal to the actived channel number in non-TDM mode */
  1684. p_i2s[i2s_num]->hal_cfg.total_chan = 2;
  1685. #endif
  1686. return ESP_OK;
  1687. }
  1688. /**
  1689. * @brief Initialize I2S DMA object
  1690. *
  1691. * @param i2s_num I2S device number
  1692. * @return
  1693. * - ESP_OK DMA object initialize success
  1694. * - ESP_ERR_NO_MEM No memory for DMA object
  1695. */
  1696. static esp_err_t i2s_dma_object_init(i2s_port_t i2s_num)
  1697. {
  1698. uint32_t buf_size = i2s_get_buf_size(i2s_num);
  1699. /* Create DMA object */
  1700. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1701. ESP_RETURN_ON_ERROR(i2s_create_dma_object(i2s_num, &p_i2s[i2s_num]->tx), TAG, "I2S TX DMA object create failed");
  1702. p_i2s[i2s_num]->tx->buf_size = buf_size;
  1703. }
  1704. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1705. ESP_RETURN_ON_ERROR(i2s_create_dma_object(i2s_num, &p_i2s[i2s_num]->rx), TAG, "I2S RX DMA object create failed");
  1706. p_i2s[i2s_num]->rx->buf_size = buf_size;
  1707. }
  1708. return ESP_OK;
  1709. }
  1710. /**
  1711. * @brief Install and start I2S driver.
  1712. * @note This function must be called before any I2S driver read/write operations.
  1713. *
  1714. *
  1715. * @param i2s_num I2S device number
  1716. * @param i2s_config I2S configurations - see i2s_config_t struct
  1717. * @param queue_size I2S event queue size/depth.
  1718. * @param i2s_queue I2S event queue handle, if set NULL, driver will not use an event queue.
  1719. *
  1720. * @return
  1721. * - ESP_OK Success
  1722. * - ESP_ERR_INVALID_ARG Parameter error
  1723. * - ESP_ERR_NO_MEM Out of memory
  1724. * - ESP_ERR_INVALID_STATE Current I2S port is in use
  1725. */
  1726. esp_err_t i2s_driver_install(i2s_port_t i2s_num, const i2s_config_t *i2s_config, int queue_size, void *i2s_queue)
  1727. {
  1728. esp_err_t ret = ESP_OK;
  1729. /* Step 1: Check the validity of input parameters */
  1730. /* Check the validity of i2s device number */
  1731. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1732. ESP_RETURN_ON_FALSE(i2s_config, ESP_ERR_INVALID_ARG, TAG, "I2S configuration must not be NULL");
  1733. /* Check the size of DMA buffer */
  1734. ESP_RETURN_ON_FALSE((i2s_config->dma_buf_count >= 2 && i2s_config->dma_buf_count <= 128), ESP_ERR_INVALID_ARG, TAG, "I2S buffer count less than 128 and more than 2");
  1735. ESP_RETURN_ON_FALSE((i2s_config->dma_buf_len >= 8 && i2s_config->dma_buf_len <= 1024), ESP_ERR_INVALID_ARG, TAG, "I2S buffer length at most 1024 and more than 8");
  1736. /* Step 2: Allocate driver object and register to platform */
  1737. i2s_obj_t *pre_alloc_i2s_obj = calloc(1, sizeof(i2s_obj_t));
  1738. ESP_RETURN_ON_FALSE(pre_alloc_i2s_obj, ESP_ERR_NO_MEM, TAG, "no mem for I2S driver");
  1739. ret = i2s_priv_register_object(pre_alloc_i2s_obj, i2s_num);
  1740. if (ret != ESP_OK) {
  1741. free(pre_alloc_i2s_obj);
  1742. ESP_LOGE(TAG, "register I2S object to platform failed");
  1743. return ESP_ERR_INVALID_STATE;
  1744. }
  1745. /* Step 3: Initialize I2S object, assign configarations */
  1746. ESP_GOTO_ON_ERROR(i2s_driver_init(i2s_num, i2s_config), err, TAG, "I2S init failed");
  1747. /* Check the validity of I2S configuration */
  1748. ESP_GOTO_ON_ERROR(i2s_check_cfg_validity(i2s_num, &(pre_alloc_i2s_obj->hal_cfg)), err, TAG, "I2S configuration is invalid");
  1749. /* Get device instance */
  1750. i2s_hal_init(&(pre_alloc_i2s_obj->hal), i2s_num);
  1751. #ifdef CONFIG_PM_ENABLE
  1752. esp_pm_lock_type_t pm_lock = ESP_PM_APB_FREQ_MAX;
  1753. #if SOC_I2S_SUPPORTS_APLL
  1754. if (i2s_config->use_apll) {
  1755. pm_lock = ESP_PM_NO_LIGHT_SLEEP;
  1756. }
  1757. #endif // SOC_I2S_SUPPORTS_APLL
  1758. ESP_GOTO_ON_ERROR(esp_pm_lock_create(pm_lock, 0, "i2s_driver", &pre_alloc_i2s_obj->pm_lock), err, TAG, "I2S pm lock error");
  1759. #endif //CONFIG_PM_ENABLE
  1760. /* Step 4: Initialize I2S DMA interrupt and DMA object */
  1761. ESP_GOTO_ON_ERROR(i2s_dma_intr_init(i2s_num, i2s_config->intr_alloc_flags), err, TAG, "I2S interrupt initailze failed");
  1762. /* Initialize I2S DMA object */
  1763. ESP_GOTO_ON_ERROR(i2s_dma_object_init(i2s_num), err, TAG, "I2S dma object create failed");
  1764. #if SOC_I2S_SUPPORTS_ADC
  1765. /* If using built-in ADC, we need to enable ADC power manerge*/
  1766. if (pre_alloc_i2s_obj->hal_cfg.mode & I2S_MODE_ADC_BUILT_IN) {
  1767. adc_power_acquire();
  1768. }
  1769. #endif
  1770. /* Enable module clock */
  1771. i2s_hal_enable_module_clock(&p_i2s[i2s_num]->hal);
  1772. /* Step 5: Initialize I2S configuration and set the configurations to register */
  1773. i2s_hal_config_param(&(pre_alloc_i2s_obj->hal), &pre_alloc_i2s_obj->hal_cfg);
  1774. /* Step 6: Initialise i2s event queue if user needs */
  1775. if (i2s_queue) {
  1776. pre_alloc_i2s_obj->i2s_queue = xQueueCreate(queue_size, sizeof(i2s_event_t));
  1777. ESP_GOTO_ON_FALSE(pre_alloc_i2s_obj->i2s_queue, ESP_ERR_NO_MEM, err, TAG, "I2S queue create failed");
  1778. *((QueueHandle_t *) i2s_queue) = pre_alloc_i2s_obj->i2s_queue;
  1779. ESP_LOGI(TAG, "queue free spaces: %d", uxQueueSpacesAvailable(pre_alloc_i2s_obj->i2s_queue));
  1780. } else {
  1781. pre_alloc_i2s_obj->i2s_queue = NULL;
  1782. }
  1783. /* Step 7: Set I2S clocks and start. No need to give parameters since configurations has been set in 'i2s_driver_init' */
  1784. ESP_GOTO_ON_ERROR(i2s_set_clk(i2s_num, 0, 0, 0), err, TAG, "I2S set clock failed");
  1785. return ESP_OK;
  1786. err:
  1787. /* I2S install failed, prepare to uninstall */
  1788. i2s_driver_uninstall(i2s_num);
  1789. return ret;
  1790. }
  1791. /**
  1792. * @brief Uninstall I2S driver.
  1793. *
  1794. * @param i2s_num I2S device number
  1795. * @return
  1796. * - ESP_OK Success
  1797. * - ESP_ERR_INVALID_ARG Parameter error
  1798. */
  1799. esp_err_t i2s_driver_uninstall(i2s_port_t i2s_num)
  1800. {
  1801. ESP_RETURN_ON_FALSE(i2s_num < I2S_NUM_MAX, ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1802. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_ERR_INVALID_STATE, TAG, "I2S port %d has not installed", i2s_num);
  1803. i2s_obj_t *obj = p_i2s[i2s_num];
  1804. i2s_stop(i2s_num);
  1805. #if SOC_I2S_SUPPORTS_DAC
  1806. i2s_set_dac_mode(I2S_DAC_CHANNEL_DISABLE);
  1807. #endif
  1808. #if SOC_GDMA_SUPPORTED
  1809. if (p_i2s[i2s_num]->tx_dma_chan) {
  1810. gdma_disconnect(p_i2s[i2s_num]->tx_dma_chan);
  1811. gdma_del_channel(p_i2s[i2s_num]->tx_dma_chan);
  1812. }
  1813. if (p_i2s[i2s_num]->rx_dma_chan) {
  1814. gdma_disconnect(p_i2s[i2s_num]->rx_dma_chan);
  1815. gdma_del_channel(p_i2s[i2s_num]->rx_dma_chan);
  1816. }
  1817. #else
  1818. if (p_i2s[i2s_num]->i2s_isr_handle) {
  1819. esp_intr_free(p_i2s[i2s_num]->i2s_isr_handle);
  1820. }
  1821. #endif
  1822. /* Destroy dma object if exist */
  1823. i2s_destroy_dma_object(i2s_num, &p_i2s[i2s_num]->tx);
  1824. i2s_destroy_dma_object(i2s_num, &p_i2s[i2s_num]->rx);
  1825. if (p_i2s[i2s_num]->i2s_queue) {
  1826. vQueueDelete(p_i2s[i2s_num]->i2s_queue);
  1827. p_i2s[i2s_num]->i2s_queue = NULL;
  1828. }
  1829. #if SOC_I2S_SUPPORTS_APLL
  1830. if (p_i2s[i2s_num]->use_apll) {
  1831. // switch back to PLL clock source
  1832. i2s_hal_set_clock_src(&(p_i2s[i2s_num]->hal), I2S_CLK_D2CLK);
  1833. rtc_clk_apll_enable(0, 0, 0, 0, 0);
  1834. }
  1835. #endif
  1836. #ifdef CONFIG_PM_ENABLE
  1837. if (p_i2s[i2s_num]->pm_lock) {
  1838. esp_pm_lock_delete(p_i2s[i2s_num]->pm_lock);
  1839. p_i2s[i2s_num]->pm_lock = NULL;
  1840. }
  1841. #endif
  1842. /* Disable module clock */
  1843. i2s_hal_disable_module_clock(&p_i2s[i2s_num]->hal);
  1844. i2s_priv_deregister_object(i2s_num);
  1845. free(obj);
  1846. return ESP_OK;
  1847. }
  1848. /**
  1849. * @brief Write data to I2S DMA transmit buffer.
  1850. * @note Many ticks pass without space becoming available in the DMA
  1851. * transmit buffer, then the function will return (note that if the
  1852. * data is written to the DMA buffer in pieces, the overall operation
  1853. * may still take longer than this timeout.) Pass portMAX_DELAY for no
  1854. * timeout.
  1855. *
  1856. * @param i2s_num I2S device number
  1857. * @param src Source address to write from
  1858. * @param size Size of data in bytes
  1859. * @param[out] bytes_written Number of bytes written, if timeout, the result will be less than the size passed in.
  1860. * @param ticks_to_wait TX buffer wait timeout in RTOS ticks. If this
  1861. * @return
  1862. * - ESP_OK Success
  1863. * - ESP_ERR_INVALID_ARG Parameter error
  1864. */
  1865. esp_err_t i2s_write(i2s_port_t i2s_num, const void *src, size_t size, size_t *bytes_written, TickType_t ticks_to_wait)
  1866. {
  1867. char *data_ptr, *src_byte;
  1868. size_t bytes_can_write;
  1869. *bytes_written = 0;
  1870. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1871. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->tx), ESP_ERR_INVALID_ARG, TAG, "TX mode is not enabled");
  1872. xSemaphoreTake(p_i2s[i2s_num]->tx->mux, (portTickType)portMAX_DELAY);
  1873. #ifdef CONFIG_PM_ENABLE
  1874. esp_pm_lock_acquire(p_i2s[i2s_num]->pm_lock);
  1875. #endif
  1876. src_byte = (char *)src;
  1877. while (size > 0) {
  1878. if (p_i2s[i2s_num]->tx->rw_pos == p_i2s[i2s_num]->tx->buf_size || p_i2s[i2s_num]->tx->curr_ptr == NULL) {
  1879. if (xQueueReceive(p_i2s[i2s_num]->tx->queue, &p_i2s[i2s_num]->tx->curr_ptr, ticks_to_wait) == pdFALSE) {
  1880. break;
  1881. }
  1882. p_i2s[i2s_num]->tx->rw_pos = 0;
  1883. }
  1884. ESP_LOGD(TAG, "size: %d, rw_pos: %d, buf_size: %d, curr_ptr: %d", size, p_i2s[i2s_num]->tx->rw_pos, p_i2s[i2s_num]->tx->buf_size, (int)p_i2s[i2s_num]->tx->curr_ptr);
  1885. data_ptr = (char *)p_i2s[i2s_num]->tx->curr_ptr;
  1886. data_ptr += p_i2s[i2s_num]->tx->rw_pos;
  1887. bytes_can_write = p_i2s[i2s_num]->tx->buf_size - p_i2s[i2s_num]->tx->rw_pos;
  1888. if (bytes_can_write > size) {
  1889. bytes_can_write = size;
  1890. }
  1891. memcpy(data_ptr, src_byte, bytes_can_write);
  1892. size -= bytes_can_write;
  1893. src_byte += bytes_can_write;
  1894. p_i2s[i2s_num]->tx->rw_pos += bytes_can_write;
  1895. (*bytes_written) += bytes_can_write;
  1896. }
  1897. #ifdef CONFIG_PM_ENABLE
  1898. esp_pm_lock_release(p_i2s[i2s_num]->pm_lock);
  1899. #endif
  1900. xSemaphoreGive(p_i2s[i2s_num]->tx->mux);
  1901. return ESP_OK;
  1902. }
  1903. /**
  1904. * @brief Write data to I2S DMA transmit buffer while expanding the number of bits per sample. For example, expanding 16-bit PCM to 32-bit PCM.
  1905. * @note Many ticks pass without space becoming available in the DMA
  1906. * transmit buffer, then the function will return (note that if the
  1907. * data is written to the DMA buffer in pieces, the overall operation
  1908. * may still take longer than this timeout.) Pass portMAX_DELAY for no
  1909. * timeout.
  1910. * Format of the data in source buffer is determined by the I2S configuration (see i2s_config_t).
  1911. *
  1912. * @param i2s_num I2S device number
  1913. * @param src Source address to write from
  1914. * @param size Size of data in bytes
  1915. * @param src_bits Source audio bit
  1916. * @param aim_bits Bit wanted, no more than 32, and must be greater than src_bits
  1917. * @param[out] bytes_written Number of bytes written, if timeout, the result will be less than the size passed in.
  1918. * @param ticks_to_wait TX buffer wait timeout in RTOS ticks. If this
  1919. * @return
  1920. * - ESP_OK Success
  1921. * - ESP_ERR_INVALID_ARG Parameter error
  1922. */
  1923. esp_err_t i2s_write_expand(i2s_port_t i2s_num, const void *src, size_t size, size_t src_bits, size_t aim_bits, size_t *bytes_written, TickType_t ticks_to_wait)
  1924. {
  1925. char *data_ptr;
  1926. int bytes_can_write, tail;
  1927. int src_bytes, aim_bytes, zero_bytes;
  1928. *bytes_written = 0;
  1929. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1930. ESP_RETURN_ON_FALSE((size > 0), ESP_ERR_INVALID_ARG, TAG, "size must greater than zero");
  1931. ESP_RETURN_ON_FALSE((aim_bits >= src_bits), ESP_ERR_INVALID_ARG, TAG, "aim_bits mustn't be less than src_bits");
  1932. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->tx), ESP_ERR_INVALID_ARG, TAG, "TX mode is not enabled");
  1933. if (src_bits < I2S_BITS_PER_SAMPLE_8BIT || aim_bits < I2S_BITS_PER_SAMPLE_8BIT) {
  1934. ESP_LOGE(TAG, "bits mustn't be less than 8, src_bits %d aim_bits %d", src_bits, aim_bits);
  1935. return ESP_ERR_INVALID_ARG;
  1936. }
  1937. if (src_bits > I2S_BITS_PER_SAMPLE_32BIT || aim_bits > I2S_BITS_PER_SAMPLE_32BIT) {
  1938. ESP_LOGE(TAG, "bits mustn't be greater than 32, src_bits %d aim_bits %d", src_bits, aim_bits);
  1939. return ESP_ERR_INVALID_ARG;
  1940. }
  1941. if ((src_bits == I2S_BITS_PER_SAMPLE_16BIT || src_bits == I2S_BITS_PER_SAMPLE_32BIT) && (size % 2 != 0)) {
  1942. ESP_LOGE(TAG, "size must be a even number while src_bits is even, src_bits %d size %d", src_bits, size);
  1943. return ESP_ERR_INVALID_ARG;
  1944. }
  1945. if (src_bits == I2S_BITS_PER_SAMPLE_24BIT && (size % 3 != 0)) {
  1946. ESP_LOGE(TAG, "size must be a multiple of 3 while src_bits is 24, size %d", size);
  1947. return ESP_ERR_INVALID_ARG;
  1948. }
  1949. src_bytes = src_bits / 8;
  1950. aim_bytes = aim_bits / 8;
  1951. zero_bytes = aim_bytes - src_bytes;
  1952. xSemaphoreTake(p_i2s[i2s_num]->tx->mux, (portTickType)portMAX_DELAY);
  1953. size = size * aim_bytes / src_bytes;
  1954. ESP_LOGD(TAG, "aim_bytes %d src_bytes %d size %d", aim_bytes, src_bytes, size);
  1955. while (size > 0) {
  1956. if (p_i2s[i2s_num]->tx->rw_pos == p_i2s[i2s_num]->tx->buf_size || p_i2s[i2s_num]->tx->curr_ptr == NULL) {
  1957. if (xQueueReceive(p_i2s[i2s_num]->tx->queue, &p_i2s[i2s_num]->tx->curr_ptr, ticks_to_wait) == pdFALSE) {
  1958. break;
  1959. }
  1960. p_i2s[i2s_num]->tx->rw_pos = 0;
  1961. }
  1962. data_ptr = (char *)p_i2s[i2s_num]->tx->curr_ptr;
  1963. data_ptr += p_i2s[i2s_num]->tx->rw_pos;
  1964. bytes_can_write = p_i2s[i2s_num]->tx->buf_size - p_i2s[i2s_num]->tx->rw_pos;
  1965. if (bytes_can_write > (int)size) {
  1966. bytes_can_write = size;
  1967. }
  1968. tail = bytes_can_write % aim_bytes;
  1969. bytes_can_write = bytes_can_write - tail;
  1970. memset(data_ptr, 0, bytes_can_write);
  1971. for (int j = 0; j < bytes_can_write; j += (aim_bytes - zero_bytes)) {
  1972. j += zero_bytes;
  1973. memcpy(&data_ptr[j], (const char *)(src + *bytes_written), aim_bytes - zero_bytes);
  1974. (*bytes_written) += (aim_bytes - zero_bytes);
  1975. }
  1976. size -= bytes_can_write;
  1977. p_i2s[i2s_num]->tx->rw_pos += bytes_can_write;
  1978. }
  1979. xSemaphoreGive(p_i2s[i2s_num]->tx->mux);
  1980. return ESP_OK;
  1981. }
  1982. /**
  1983. * @brief Read data from I2S DMA receive buffer
  1984. * @note If the built-in ADC mode is enabled, we should call i2s_adc_enable and i2s_adc_disable around the whole reading process,
  1985. * to prevent the data getting corrupted.
  1986. *
  1987. * @param i2s_num I2S device number
  1988. * @param dest Destination address to read into
  1989. * @param size Size of data in bytes
  1990. * @param[out] bytes_read Number of bytes read, if timeout, bytes read will be less than the size passed in.
  1991. * @param ticks_to_wait RX buffer wait timeout in RTOS ticks. If this many ticks pass without bytes becoming available in the DMA receive buffer, then the function will return (note that if data is read from the DMA buffer in pieces, the overall operation may still take longer than this timeout.) Pass portMAX_DELAY for no timeout.
  1992. * @return
  1993. * - ESP_OK Success
  1994. * - ESP_ERR_INVALID_ARG Parameter error
  1995. */
  1996. esp_err_t i2s_read(i2s_port_t i2s_num, void *dest, size_t size, size_t *bytes_read, TickType_t ticks_to_wait)
  1997. {
  1998. char *data_ptr, *dest_byte;
  1999. int bytes_can_read;
  2000. *bytes_read = 0;
  2001. dest_byte = (char *)dest;
  2002. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  2003. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->rx), ESP_ERR_INVALID_ARG, TAG, "RX mode is not enabled");
  2004. xSemaphoreTake(p_i2s[i2s_num]->rx->mux, (portTickType)portMAX_DELAY);
  2005. #ifdef CONFIG_PM_ENABLE
  2006. esp_pm_lock_acquire(p_i2s[i2s_num]->pm_lock);
  2007. #endif
  2008. while (size > 0) {
  2009. if (p_i2s[i2s_num]->rx->rw_pos == p_i2s[i2s_num]->rx->buf_size || p_i2s[i2s_num]->rx->curr_ptr == NULL) {
  2010. if (xQueueReceive(p_i2s[i2s_num]->rx->queue, &p_i2s[i2s_num]->rx->curr_ptr, ticks_to_wait) == pdFALSE) {
  2011. break;
  2012. }
  2013. p_i2s[i2s_num]->rx->rw_pos = 0;
  2014. }
  2015. data_ptr = (char *)p_i2s[i2s_num]->rx->curr_ptr;
  2016. data_ptr += p_i2s[i2s_num]->rx->rw_pos;
  2017. bytes_can_read = p_i2s[i2s_num]->rx->buf_size - p_i2s[i2s_num]->rx->rw_pos;
  2018. if (bytes_can_read > (int)size) {
  2019. bytes_can_read = size;
  2020. }
  2021. memcpy(dest_byte, data_ptr, bytes_can_read);
  2022. size -= bytes_can_read;
  2023. dest_byte += bytes_can_read;
  2024. p_i2s[i2s_num]->rx->rw_pos += bytes_can_read;
  2025. (*bytes_read) += bytes_can_read;
  2026. }
  2027. #ifdef CONFIG_PM_ENABLE
  2028. esp_pm_lock_release(p_i2s[i2s_num]->pm_lock);
  2029. #endif
  2030. xSemaphoreGive(p_i2s[i2s_num]->rx->mux);
  2031. return ESP_OK;
  2032. }
  2033. esp_err_t i2s_priv_register_object(void *driver_obj, int port_id)
  2034. {
  2035. esp_err_t ret = ESP_ERR_NOT_FOUND;
  2036. ESP_RETURN_ON_FALSE(driver_obj && (port_id < SOC_I2S_NUM), ESP_ERR_INVALID_ARG, TAG, "invalid arguments");
  2037. portENTER_CRITICAL(&i2s_platform_spinlock);
  2038. if (!p_i2s[port_id]) {
  2039. ret = ESP_OK;
  2040. p_i2s[port_id] = driver_obj;
  2041. periph_module_enable(i2s_periph_signal[port_id].module);
  2042. }
  2043. portEXIT_CRITICAL(&i2s_platform_spinlock);
  2044. return ret;
  2045. }
  2046. esp_err_t i2s_priv_deregister_object(int port_id)
  2047. {
  2048. esp_err_t ret = ESP_ERR_INVALID_STATE;
  2049. ESP_RETURN_ON_FALSE(port_id < SOC_I2S_NUM, ESP_ERR_INVALID_ARG, TAG, "invalid arguments");
  2050. portENTER_CRITICAL(&i2s_platform_spinlock);
  2051. if (p_i2s[port_id]) {
  2052. ret = ESP_OK;
  2053. p_i2s[port_id] = NULL;
  2054. periph_module_disable(i2s_periph_signal[port_id].module);
  2055. }
  2056. portEXIT_CRITICAL(&i2s_platform_spinlock);
  2057. return ret;
  2058. }