i2s.c 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2021 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/rtc.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. /**
  835. * @brief Get APLL frequency
  836. */
  837. static float i2s_apll_get_freq(int bits_per_sample, int sdm0, int sdm1, int sdm2, int odir)
  838. {
  839. int f_xtal = (int)rtc_clk_xtal_freq_get() * 1000000;
  840. #if CONFIG_IDF_TARGET_ESP32
  841. /* ESP32 rev0 silicon issue for APLL range/accuracy, please see ESP32 ECO document for more information on this */
  842. if (esp_efuse_get_chip_ver() == 0) {
  843. sdm0 = 0;
  844. sdm1 = 0;
  845. }
  846. #endif
  847. float fout = f_xtal * (sdm2 + sdm1 / 256.0f + sdm0 / 65536.0f + 4);
  848. if (fout < SOC_I2S_APLL_MIN_FREQ || fout > SOC_I2S_APLL_MAX_FREQ) {
  849. return SOC_I2S_APLL_MAX_FREQ;
  850. }
  851. float fpll = fout / (2 * (odir + 2)); //== fi2s (N=1, b=0, a=1)
  852. return fpll / 2;
  853. }
  854. /**
  855. * @brief APLL calculate function, was described by following:
  856. * APLL Output frequency is given by the formula:
  857. *
  858. * apll_freq = xtal_freq * (4 + sdm2 + sdm1/256 + sdm0/65536)/((o_div + 2) * 2)
  859. * apll_freq = fout / ((o_div + 2) * 2)
  860. *
  861. * The dividend in this expression should be in the range of 240 - 600 MHz.
  862. * In rev. 0 of ESP32, sdm0 and sdm1 are unused and always set to 0.
  863. * * sdm0 frequency adjustment parameter, 0..255
  864. * * sdm1 frequency adjustment parameter, 0..255
  865. * * sdm2 frequency adjustment parameter, 0..63
  866. * * o_div frequency divider, 0..31
  867. *
  868. * The most accurate way to find the sdm0..2 and odir parameters is to loop through them all,
  869. * then apply the above formula, finding the closest frequency to the desired one.
  870. * But 256*256*64*32 = 134,217,728 loops are too slow with ESP32
  871. * 1. We will choose the parameters with the highest level of change,
  872. * With 350MHz<fout<500MHz, we limit the sdm2 from 4 to 9,
  873. * Take average frequency close to the desired frequency, and select sdm2
  874. * 2. Next, we look for sequences of less influential and more detailed parameters,
  875. * also by taking the average of the largest and smallest frequencies closer to the desired frequency.
  876. * 3. And finally, loop through all the most detailed of the parameters, finding the best desired frequency
  877. *
  878. * @param[in] rate The I2S Frequency (MCLK)
  879. * @param[in] bits_per_sample The bits per sample
  880. * @param[out] sdm0 The sdm 0
  881. * @param[out] sdm1 The sdm 1
  882. * @param[out] sdm2 The sdm 2
  883. * @param[out] odir The odir
  884. */
  885. static void i2s_apll_calculate_fi2s(int rate, int bits_per_sample, int *sdm0, int *sdm1, int *sdm2, int *odir)
  886. {
  887. int _odir, _sdm0, _sdm1, _sdm2;
  888. float avg;
  889. float min_rate, max_rate, min_diff;
  890. *sdm0 = 0;
  891. *sdm1 = 0;
  892. *sdm2 = 0;
  893. *odir = 0;
  894. min_diff = SOC_I2S_APLL_MAX_FREQ;
  895. for (_sdm2 = 4; _sdm2 < 9; _sdm2 ++) {
  896. max_rate = i2s_apll_get_freq(bits_per_sample, 255, 255, _sdm2, 0);
  897. min_rate = i2s_apll_get_freq(bits_per_sample, 0, 0, _sdm2, 31);
  898. avg = (max_rate + min_rate) / 2;
  899. if (abs(avg - rate) < min_diff) {
  900. min_diff = abs(avg - rate);
  901. *sdm2 = _sdm2;
  902. }
  903. }
  904. min_diff = SOC_I2S_APLL_MAX_FREQ;
  905. for (_odir = 0; _odir < 32; _odir ++) {
  906. max_rate = i2s_apll_get_freq(bits_per_sample, 255, 255, *sdm2, _odir);
  907. min_rate = i2s_apll_get_freq(bits_per_sample, 0, 0, *sdm2, _odir);
  908. avg = (max_rate + min_rate) / 2;
  909. if (abs(avg - rate) < min_diff) {
  910. min_diff = abs(avg - rate);
  911. *odir = _odir;
  912. }
  913. }
  914. min_diff = SOC_I2S_APLL_MAX_FREQ;
  915. for (_sdm2 = 4; _sdm2 < 9; _sdm2 ++) {
  916. max_rate = i2s_apll_get_freq(bits_per_sample, 255, 255, _sdm2, *odir);
  917. min_rate = i2s_apll_get_freq(bits_per_sample, 0, 0, _sdm2, *odir);
  918. avg = (max_rate + min_rate) / 2;
  919. if (abs(avg - rate) < min_diff) {
  920. min_diff = abs(avg - rate);
  921. *sdm2 = _sdm2;
  922. }
  923. }
  924. min_diff = SOC_I2S_APLL_MAX_FREQ;
  925. for (_sdm1 = 0; _sdm1 < 256; _sdm1 ++) {
  926. max_rate = i2s_apll_get_freq(bits_per_sample, 255, _sdm1, *sdm2, *odir);
  927. min_rate = i2s_apll_get_freq(bits_per_sample, 0, _sdm1, *sdm2, *odir);
  928. avg = (max_rate + min_rate) / 2;
  929. if (abs(avg - rate) < min_diff) {
  930. min_diff = abs(avg - rate);
  931. *sdm1 = _sdm1;
  932. }
  933. }
  934. min_diff = SOC_I2S_APLL_MAX_FREQ;
  935. for (_sdm0 = 0; _sdm0 < 256; _sdm0 ++) {
  936. avg = i2s_apll_get_freq(bits_per_sample, _sdm0, *sdm1, *sdm2, *odir);
  937. if (abs(avg - rate) < min_diff) {
  938. min_diff = abs(avg - rate);
  939. *sdm0 = _sdm0;
  940. }
  941. }
  942. }
  943. #endif
  944. /**
  945. * @brief Config I2S source clock and get its frequency
  946. *
  947. * @param i2s_num I2S device number
  948. * @param use_apll Whether use apll, only take effect when chip supports
  949. * @param mclk module clock
  950. *
  951. * @return
  952. * - 0 use I2S_CLK_APLL as clock source, no I2S system clock to set
  953. * - I2S_LL_BASE_CLK use I2S_CLK_D2CLK as clock source, return APB clock frequency
  954. */
  955. static uint32_t i2s_config_source_clock(i2s_port_t i2s_num, bool use_apll, uint32_t mclk)
  956. {
  957. #if SOC_I2S_SUPPORTS_APLL
  958. if (use_apll) {
  959. int sdm0 = 0;
  960. int sdm1 = 0;
  961. int sdm2 = 0;
  962. int odir = 0;
  963. if ((mclk / p_i2s[i2s_num]->hal_cfg.chan_bits / p_i2s[i2s_num]->hal_cfg.total_chan) < SOC_I2S_APLL_MIN_RATE) {
  964. ESP_LOGE(TAG, "mclk is too small");
  965. return 0;
  966. }
  967. i2s_apll_calculate_fi2s(mclk, p_i2s[i2s_num]->hal_cfg.sample_bits, &sdm0, &sdm1, &sdm2, &odir);
  968. ESP_LOGI(TAG, "APLL Enabled, coefficient: sdm0=%d, sdm1=%d, sdm2=%d, odir=%d", sdm0, sdm1, sdm2, odir);
  969. rtc_clk_apll_enable(true, sdm0, sdm1, sdm2, odir);
  970. /* Set I2S_APLL as I2S module clock source */
  971. i2s_hal_set_clock_src(&(p_i2s[i2s_num]->hal), I2S_CLK_APLL);
  972. /* In APLL mode, there is no sclk but only mclk, so return 0 here to indicate APLL mode */
  973. return 0;
  974. }
  975. /* Set I2S_D2CLK (160M) as default I2S module clock source */
  976. i2s_hal_set_clock_src(&(p_i2s[i2s_num]->hal), I2S_CLK_D2CLK);
  977. return I2S_LL_BASE_CLK;
  978. #else
  979. if (use_apll) {
  980. ESP_LOGW(TAG, "APLL not supported on current chip, use I2S_CLK_D2CLK as default clock source");
  981. }
  982. /* Set I2S_D2CLK (160M) as I2S module clock source */
  983. i2s_hal_set_clock_src(&(p_i2s[i2s_num]->hal), I2S_CLK_D2CLK);
  984. return I2S_LL_BASE_CLK;
  985. #endif
  986. }
  987. #if SOC_I2S_SUPPORTS_ADC || SOC_I2S_SUPPORTS_DAC
  988. /**
  989. * @brief I2S calculate clock for built-in ADC/DAC mode
  990. *
  991. * @param i2s_num I2S device number
  992. * @param clk_cfg Struct to restore clock confiuration
  993. * @return
  994. * - ESP_OK Get clock success
  995. * - ESP_ERR_INVALID_ARG Invalid args
  996. */
  997. static esp_err_t i2s_calculate_adc_dac_clock(int i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  998. {
  999. ESP_RETURN_ON_FALSE(clk_cfg, ESP_ERR_INVALID_ARG, TAG, "input clk_cfg is NULL");
  1000. 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");
  1001. /* Set I2S bit clock */
  1002. clk_cfg->bclk = p_i2s[i2s_num]->hal_cfg.sample_rate * I2S_LL_AD_BCK_FACTOR * 2;
  1003. /* Set I2S bit clock default division */
  1004. clk_cfg->bclk_div = I2S_LL_AD_BCK_FACTOR;
  1005. /* If fixed_mclk and use_apll are set, use fixed_mclk as mclk frequency, otherwise calculate by mclk = sample_rate * multiple */
  1006. clk_cfg->mclk = (p_i2s[i2s_num]->use_apll && p_i2s[i2s_num]->fixed_mclk) ?
  1007. p_i2s[i2s_num]->fixed_mclk : clk_cfg->bclk * clk_cfg->bclk_div;
  1008. /* Calculate bclk_div = mclk / bclk */
  1009. clk_cfg->bclk_div = clk_cfg->mclk / clk_cfg->bclk;
  1010. /* Get I2S system clock by config source clock */
  1011. clk_cfg->sclk = i2s_config_source_clock(i2s_num, p_i2s[i2s_num]->use_apll, clk_cfg->mclk);
  1012. /* Get I2S master clock rough division, later will calculate the fine division parameters in HAL */
  1013. clk_cfg->mclk_div = clk_cfg->sclk / clk_cfg->mclk;
  1014. /* Check if the configuration is correct */
  1015. ESP_RETURN_ON_FALSE(!clk_cfg->sclk || clk_cfg->mclk <= clk_cfg->sclk, ESP_ERR_INVALID_ARG, TAG, "sample rate is too large");
  1016. return ESP_OK;
  1017. }
  1018. #endif // SOC_I2S_SUPPORTS_ADC || SOC_I2S_SUPPORTS_DAC
  1019. #if SOC_I2S_SUPPORTS_PDM_TX
  1020. /**
  1021. * @brief I2S calculate clock for PDM tx mode
  1022. *
  1023. * @param i2s_num I2S device number
  1024. * @param clk_cfg Struct to restore clock confiuration
  1025. * @return
  1026. * - ESP_OK Get clock success
  1027. * - ESP_ERR_INVALID_ARG Invalid args
  1028. */
  1029. static esp_err_t i2s_calculate_pdm_tx_clock(int i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1030. {
  1031. ESP_RETURN_ON_FALSE(clk_cfg, ESP_ERR_INVALID_ARG, TAG, "input clk_cfg is NULL");
  1032. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_PDM, ESP_ERR_INVALID_ARG, TAG, "current mode is not PDM");
  1033. int fp = i2s_hal_get_tx_pdm_fp(&(p_i2s[i2s_num]->hal));
  1034. int fs = i2s_hal_get_tx_pdm_fs(&(p_i2s[i2s_num]->hal));
  1035. /* Set I2S bit clock */
  1036. clk_cfg->bclk = p_i2s[i2s_num]->hal_cfg.sample_rate * I2S_LL_PDM_BCK_FACTOR * fp / fs;
  1037. /* Set I2S bit clock default division */
  1038. clk_cfg->bclk_div = 8;
  1039. /* If fixed_mclk and use_apll are set, use fixed_mclk as mclk frequency, otherwise calculate by mclk = sample_rate * multiple */
  1040. clk_cfg->mclk = (p_i2s[i2s_num]->use_apll && p_i2s[i2s_num]->fixed_mclk) ?
  1041. p_i2s[i2s_num]->fixed_mclk : clk_cfg->bclk * clk_cfg->bclk_div;
  1042. /* Calculate bclk_div = mclk / bclk */
  1043. clk_cfg->bclk_div = clk_cfg->mclk / clk_cfg->bclk;
  1044. /* Get I2S system clock by config source clock */
  1045. clk_cfg->sclk = i2s_config_source_clock(i2s_num, p_i2s[i2s_num]->use_apll, clk_cfg->mclk);
  1046. /* Get I2S master clock rough division, later will calculate the fine division parameters in HAL */
  1047. clk_cfg->mclk_div = clk_cfg->sclk / clk_cfg->mclk;
  1048. /* Check if the configuration is correct */
  1049. ESP_RETURN_ON_FALSE(!clk_cfg->sclk || clk_cfg->mclk <= clk_cfg->sclk, ESP_ERR_INVALID_ARG, TAG, "sample rate is too large");
  1050. return ESP_OK;
  1051. }
  1052. #endif // SOC_I2S_SUPPORTS_PDM_TX
  1053. #if SOC_I2S_SUPPORTS_PDM_RX
  1054. /**
  1055. * @brief I2S calculate clock for PDM rx mode
  1056. *
  1057. * @param i2s_num I2S device number
  1058. * @param clk_cfg Struct to restore clock confiuration
  1059. * @return
  1060. * - ESP_OK Get clock success
  1061. * - ESP_ERR_INVALID_ARG Invalid args
  1062. */
  1063. static esp_err_t i2s_calculate_pdm_rx_clock(int i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1064. {
  1065. ESP_RETURN_ON_FALSE(clk_cfg, ESP_ERR_INVALID_ARG, TAG, "input clk_cfg is NULL");
  1066. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_PDM, ESP_ERR_INVALID_ARG, TAG, "current mode is not PDM");
  1067. i2s_pdm_dsr_t dsr;
  1068. i2s_hal_get_rx_pdm_dsr(&(p_i2s[i2s_num]->hal), &dsr);
  1069. /* Set I2S bit clock */
  1070. clk_cfg->bclk = p_i2s[i2s_num]->hal_cfg.sample_rate * I2S_LL_PDM_BCK_FACTOR * (dsr == I2S_PDM_DSR_16S ? 2 : 1);
  1071. /* Set I2S bit clock default division */
  1072. clk_cfg->bclk_div = 8;
  1073. /* If fixed_mclk and use_apll are set, use fixed_mclk as mclk frequency, otherwise calculate by mclk = sample_rate * multiple */
  1074. clk_cfg->mclk = (p_i2s[i2s_num]->use_apll && p_i2s[i2s_num]->fixed_mclk) ?
  1075. p_i2s[i2s_num]->fixed_mclk : clk_cfg->bclk * clk_cfg->bclk_div;
  1076. /* Calculate bclk_div = mclk / bclk */
  1077. clk_cfg->bclk_div = clk_cfg->mclk / clk_cfg->bclk;
  1078. /* Get I2S system clock by config source clock */
  1079. clk_cfg->sclk = i2s_config_source_clock(i2s_num, p_i2s[i2s_num]->use_apll, clk_cfg->mclk);
  1080. /* Get I2S master clock rough division, later will calculate the fine division parameters in HAL */
  1081. clk_cfg->mclk_div = clk_cfg->sclk / clk_cfg->mclk;
  1082. /* Check if the configuration is correct */
  1083. ESP_RETURN_ON_FALSE(!clk_cfg->sclk || clk_cfg->mclk <= clk_cfg->sclk, ESP_ERR_INVALID_ARG, TAG, "sample rate is too large");
  1084. return ESP_OK;
  1085. }
  1086. #endif // SOC_I2S_SUPPORTS_PDM_RX
  1087. /**
  1088. * @brief I2S calculate clock for common mode (philip, MSB, PCM)
  1089. *
  1090. * @param i2s_num I2S device number
  1091. * @param clk_cfg Struct to restore clock confiuration
  1092. * @return
  1093. * - ESP_OK Get clock success
  1094. * - ESP_ERR_INVALID_ARG Invalid args
  1095. */
  1096. static esp_err_t i2s_calculate_common_clock(int i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1097. {
  1098. ESP_RETURN_ON_FALSE(clk_cfg, ESP_ERR_INVALID_ARG, TAG, "input clk_cfg is NULL");
  1099. uint32_t rate = p_i2s[i2s_num]->hal_cfg.sample_rate;
  1100. uint32_t chan_num = p_i2s[i2s_num]->hal_cfg.total_chan < 2 ? 2 : p_i2s[i2s_num]->hal_cfg.total_chan;
  1101. uint32_t chan_bit = p_i2s[i2s_num]->hal_cfg.chan_bits;
  1102. uint32_t multi;
  1103. /* Calculate multiple */
  1104. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_MASTER || p_i2s[i2s_num]->use_apll) {
  1105. multi = p_i2s[i2s_num]->mclk_multiple ? p_i2s[i2s_num]->mclk_multiple : I2S_MCLK_MULTIPLE_256;
  1106. } else {
  1107. /* Only need to set the multiple of mclk to sample rate for MASTER mode,
  1108. * because BCK and WS clock are provided by the external codec in SLAVE mode.
  1109. * The multiple should be big enough to get a high module clock which could detect the edges of externel clock more accurately,
  1110. * otherwise the data we receive or send would get a large latency and go wrong due to the slow module clock.
  1111. * But on ESP32 and ESP32S2, due to the different clock work mode in hardware,
  1112. * their multiple should be set to an appropriate range according to the sample bits,
  1113. * and this particular multiple finally aims at guaranteeing the bclk_div not smaller than 8,
  1114. * if not, the I2S may can't send data or send wrong data.
  1115. * Here use 'SOC_I2S_SUPPORTS_TDM' to differentialize other chips with ESP32 and ESP32S2.
  1116. */
  1117. #if SOC_I2S_SUPPORTS_TDM
  1118. multi = I2S_LL_BASE_CLK / rate;
  1119. #else
  1120. multi = 64 * chan_bit;
  1121. #endif
  1122. }
  1123. /* Set I2S bit clock */
  1124. clk_cfg->bclk = rate * chan_num * chan_bit;
  1125. /* If fixed_mclk and use_apll are set, use fixed_mclk as mclk frequency, otherwise calculate by mclk = sample_rate * multiple */
  1126. clk_cfg->mclk = (p_i2s[i2s_num]->use_apll && p_i2s[i2s_num]->fixed_mclk) ?
  1127. p_i2s[i2s_num]->fixed_mclk : (rate * multi);
  1128. /* Calculate bclk_div = mclk / bclk */
  1129. clk_cfg->bclk_div = clk_cfg->mclk / clk_cfg->bclk;
  1130. /* Get I2S system clock by config source clock */
  1131. clk_cfg->sclk = i2s_config_source_clock(i2s_num, p_i2s[i2s_num]->use_apll, clk_cfg->mclk);
  1132. /* Get I2S master clock rough division, later will calculate the fine division parameters in HAL */
  1133. clk_cfg->mclk_div = clk_cfg->sclk / clk_cfg->mclk;
  1134. /* Check if the configuration is correct */
  1135. ESP_RETURN_ON_FALSE(!clk_cfg->sclk || clk_cfg->mclk <= clk_cfg->sclk, ESP_ERR_INVALID_ARG, TAG, "sample rate is too large");
  1136. return ESP_OK;
  1137. }
  1138. /**
  1139. * @brief I2S calculate clocks according to the selected I2S mode
  1140. *
  1141. * @param i2s_num I2S device number
  1142. * @param clk_cfg Struct to restore clock confiuration
  1143. * @return
  1144. * - ESP_OK Claculate clock success
  1145. * - ESP_ERR_INVALID_ARG Invalid args
  1146. */
  1147. static esp_err_t i2s_calculate_clock(i2s_port_t i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1148. {
  1149. /* Calculate clock for ADC mode */
  1150. #if SOC_I2S_SUPPORTS_ADC
  1151. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_ADC_BUILT_IN) {
  1152. ESP_RETURN_ON_ERROR(i2s_calculate_adc_dac_clock(i2s_num, clk_cfg), TAG, "ADC clock calculate failed");
  1153. return ESP_OK;
  1154. }
  1155. #endif // SOC_I2S_SUPPORTS_ADC
  1156. /* Calculate clock for DAC mode */
  1157. #if SOC_I2S_SUPPORTS_DAC
  1158. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_DAC_BUILT_IN) {
  1159. ESP_RETURN_ON_ERROR(i2s_calculate_adc_dac_clock(i2s_num, clk_cfg), TAG, "DAC clock calculate failed");
  1160. return ESP_OK;
  1161. }
  1162. #endif // SOC_I2S_SUPPORTS_DAC
  1163. /* Calculate clock for PDM mode */
  1164. #if SOC_I2S_SUPPORTS_PDM_TX || SOC_I2S_SUPPORTS_PDM_RX
  1165. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_PDM) {
  1166. #if SOC_I2S_SUPPORTS_PDM_TX
  1167. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1168. ESP_RETURN_ON_ERROR(i2s_calculate_pdm_tx_clock(i2s_num, clk_cfg), TAG, "PDM TX clock calculate failed");
  1169. }
  1170. #endif // SOC_I2S_SUPPORTS_PDM_TX
  1171. #if SOC_I2S_SUPPORTS_PDM_RX
  1172. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1173. ESP_RETURN_ON_ERROR(i2s_calculate_pdm_rx_clock(i2s_num, clk_cfg), TAG, "PDM RX clock calculate failed");
  1174. }
  1175. #endif // SOC_I2S_SUPPORTS_PDM_RX
  1176. return ESP_OK;
  1177. }
  1178. #endif // SOC_I2S_SUPPORTS_PDM_TX || SOC_I2S_SUPPORTS_PDM_RX
  1179. /* Calculate clock for common mode */
  1180. ESP_RETURN_ON_ERROR(i2s_calculate_common_clock(i2s_num, clk_cfg), TAG, "Common clock calculate failed");
  1181. return ESP_OK;
  1182. }
  1183. /*-------------------------------------------------------------
  1184. I2S configuration
  1185. -------------------------------------------------------------*/
  1186. #if SOC_I2S_SUPPORTS_TDM
  1187. /**
  1188. * @brief Get max actived channel number
  1189. *
  1190. * @param chan_mask I2S channel mask that indicates which channels are actived
  1191. * @return
  1192. * - Max actived channel number
  1193. */
  1194. static uint32_t i2s_get_max_channel_num(i2s_channel_t chan_mask)
  1195. {
  1196. uint32_t max_chan = 0;
  1197. uint32_t channel = chan_mask & 0xFFFF;
  1198. for (int i = 0; channel && i < 16; i++, channel >>= 1) {
  1199. if (channel & 0x01) {
  1200. max_chan = i + 1;
  1201. }
  1202. }
  1203. /* Can't be smaller than 2 */
  1204. return max_chan < 2 ? 2 : max_chan;
  1205. }
  1206. #endif
  1207. /**
  1208. * @brief Get active channel number according to channel format
  1209. * @note In 'I2S_CHANNEL_FMT_MULTIPLE' format, this function will check
  1210. * 'total_chan' and fix it if it is not correct.
  1211. *
  1212. * @param hal_cfg [input/output] I2S hal configuration structer
  1213. * @return
  1214. * - Active channel number
  1215. */
  1216. static uint32_t i2s_get_active_channel_num(const i2s_hal_config_t *hal_cfg)
  1217. {
  1218. switch (hal_cfg->chan_fmt) {
  1219. case I2S_CHANNEL_FMT_RIGHT_LEFT: //fall through
  1220. case I2S_CHANNEL_FMT_ALL_RIGHT: //fall through
  1221. case I2S_CHANNEL_FMT_ALL_LEFT:
  1222. return 2;
  1223. case I2S_CHANNEL_FMT_ONLY_RIGHT: //fall through
  1224. case I2S_CHANNEL_FMT_ONLY_LEFT:
  1225. return 1;
  1226. #if SOC_I2S_SUPPORTS_TDM
  1227. case I2S_CHANNEL_FMT_MULTIPLE: {
  1228. uint32_t num = 0;
  1229. uint32_t chan_mask = hal_cfg->chan_mask & 0xFFFF;
  1230. for (int i = 0; chan_mask && i < 16; i++, chan_mask >>= 1) {
  1231. if (chan_mask & 0x01) {
  1232. num++;
  1233. }
  1234. }
  1235. return num;
  1236. }
  1237. #endif
  1238. default:
  1239. return 0;
  1240. }
  1241. }
  1242. #if SOC_I2S_SUPPORTS_DAC
  1243. /**
  1244. * @brief I2S set built-in DAC mode
  1245. *
  1246. * @param dac_mode DAC mode
  1247. * @return
  1248. * - ESP_OK Set DAC success
  1249. * - ESP_ERR_INVALID_ARG Wrong DAC mode
  1250. */
  1251. esp_err_t i2s_set_dac_mode(i2s_dac_mode_t dac_mode)
  1252. {
  1253. ESP_RETURN_ON_FALSE((dac_mode < I2S_DAC_CHANNEL_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s dac mode error");
  1254. if (dac_mode == I2S_DAC_CHANNEL_DISABLE) {
  1255. dac_output_disable(DAC_CHANNEL_1);
  1256. dac_output_disable(DAC_CHANNEL_2);
  1257. dac_i2s_disable();
  1258. } else {
  1259. dac_i2s_enable();
  1260. }
  1261. if (dac_mode & I2S_DAC_CHANNEL_RIGHT_EN) {
  1262. //DAC1, right channel
  1263. dac_output_enable(DAC_CHANNEL_1);
  1264. }
  1265. if (dac_mode & I2S_DAC_CHANNEL_LEFT_EN) {
  1266. //DAC2, left channel
  1267. dac_output_enable(DAC_CHANNEL_2);
  1268. }
  1269. return ESP_OK;
  1270. }
  1271. #endif // SOC_I2S_SUPPORTS_DAC
  1272. #if SOC_I2S_SUPPORTS_ADC
  1273. /**
  1274. * @brief ADC mode recover
  1275. *
  1276. * @return
  1277. * - ESP_OK ADC Recover success
  1278. * - ESP_ERR_INVALID_ARG ADC not initialized yet
  1279. */
  1280. static esp_err_t _i2s_adc_mode_recover(void)
  1281. {
  1282. ESP_RETURN_ON_FALSE(((_i2s_adc_unit != -1) && (_i2s_adc_channel != -1)), ESP_ERR_INVALID_ARG, TAG, "i2s ADC recover error, not initialized...");
  1283. return adc_i2s_mode_init(_i2s_adc_unit, _i2s_adc_channel);
  1284. }
  1285. /**
  1286. * @brief I2S set adc mode
  1287. *
  1288. * @param adc_unit ADC unit number
  1289. * @param adc_channel ADC channel
  1290. * @return
  1291. * - ESP_OK ADC Recover success
  1292. * - ESP_ERR_INVALID_ARG ADC not initialized yet
  1293. */
  1294. esp_err_t i2s_set_adc_mode(adc_unit_t adc_unit, adc1_channel_t adc_channel)
  1295. {
  1296. ESP_RETURN_ON_FALSE((adc_unit < ADC_UNIT_2), ESP_ERR_INVALID_ARG, TAG, "i2s ADC unit error, only support ADC1 for now");
  1297. // For now, we only support SAR ADC1.
  1298. _i2s_adc_unit = adc_unit;
  1299. _i2s_adc_channel = adc_channel;
  1300. return adc_i2s_mode_init(adc_unit, adc_channel);
  1301. }
  1302. /**
  1303. * @brief I2S enable ADC mode
  1304. *
  1305. * @param i2s_num I2S device number
  1306. * @return
  1307. * - ESP_OK Enable ADC success
  1308. * - ESP_ERR_INVALID_ARG Invalid argument
  1309. * - ESP_ERR_INVALID_STATE Current I2S mode is not built-in ADC
  1310. */
  1311. esp_err_t i2s_adc_enable(i2s_port_t i2s_num)
  1312. {
  1313. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1314. ESP_RETURN_ON_FALSE((p_i2s[i2s_num] != NULL), ESP_ERR_INVALID_STATE, TAG, "Not initialized yet");
  1315. 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");
  1316. adc1_dma_mode_acquire();
  1317. _i2s_adc_mode_recover();
  1318. i2s_rx_reset(i2s_num);
  1319. 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);
  1320. }
  1321. /**
  1322. * @brief I2S disable ADC
  1323. *
  1324. * @param i2s_num I2S device number
  1325. * @return
  1326. * - ESP_OK I2S ADC mode successfully disabled
  1327. * - ESP_ERR_INVALID_ARG Invalid argument
  1328. * - ESP_ERR_INVALID_STATE Current I2S mode is not built-in ADC
  1329. */
  1330. esp_err_t i2s_adc_disable(i2s_port_t i2s_num)
  1331. {
  1332. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1333. ESP_RETURN_ON_FALSE((p_i2s[i2s_num] != NULL), ESP_ERR_INVALID_STATE, TAG, "Not initialized yet");
  1334. 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");
  1335. i2s_hal_stop_rx(&(p_i2s[i2s_num]->hal));
  1336. adc1_lock_release();
  1337. return ESP_OK;
  1338. }
  1339. #endif
  1340. /**
  1341. * @brief Set sample rate used for I2S RX and TX.
  1342. * @note The bit clock rate is determined by the sample rate and i2s_config_t configuration parameters (number of channels, bits_per_sample).
  1343. * `bit_clock = rate * (number of channels) * bits_per_sample`
  1344. *
  1345. * @param i2s_num I2S device number
  1346. * @param rate I2S sample rate (ex: 8000, 44100...)
  1347. * @return
  1348. * - ESP_OK Success
  1349. * - ESP_ERR_INVALID_ARG Parameter error
  1350. * - ESP_ERR_NO_MEM Out of memory
  1351. */
  1352. esp_err_t i2s_set_sample_rates(i2s_port_t i2s_num, uint32_t rate)
  1353. {
  1354. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1355. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->hal_cfg.sample_bits > 0), ESP_ERR_INVALID_ARG, TAG, "sample bits not set");
  1356. return i2s_set_clk(i2s_num, rate, p_i2s[i2s_num]->hal_cfg.sample_bits, p_i2s[i2s_num]->hal_cfg.active_chan);
  1357. }
  1358. #if SOC_I2S_SUPPORTS_PCM
  1359. /**
  1360. * @brief Configure I2S a/u-law decompress or compress
  1361. * @note This function should be called after i2s driver installed
  1362. * Only take effect when the i2s 'communication_format' is set to 'I2S_COMM_FORMAT_STAND_PCM_SHORT' or 'I2S_COMM_FORMAT_STAND_PCM_LONG'
  1363. *
  1364. * @param i2s_num I2S_NUM_0
  1365. * @param pcm_cfg Including mode selection and a/u-law decompress or compress configuration paramater
  1366. * @return
  1367. * - ESP_OK Success
  1368. * - ESP_ERR_INVALID_ARG Parameter error
  1369. */
  1370. esp_err_t i2s_pcm_config(i2s_port_t i2s_num, const i2s_pcm_cfg_t *pcm_cfg)
  1371. {
  1372. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_FAIL, TAG, "i2s has not installed yet");
  1373. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->hal_cfg.comm_fmt & I2S_COMM_FORMAT_STAND_PCM_SHORT),
  1374. ESP_ERR_INVALID_ARG, TAG, "i2s communication mode is not PCM mode");
  1375. i2s_stop(i2s_num);
  1376. I2S_ENTER_CRITICAL(i2s_num);
  1377. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1378. i2s_hal_tx_pcm_cfg(&(p_i2s[i2s_num]->hal), pcm_cfg->pcm_type);
  1379. } else if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1380. i2s_hal_rx_pcm_cfg(&(p_i2s[i2s_num]->hal), pcm_cfg->pcm_type);
  1381. }
  1382. I2S_EXIT_CRITICAL(i2s_num);
  1383. i2s_start(i2s_num);
  1384. return ESP_OK;
  1385. }
  1386. #endif
  1387. #if SOC_I2S_SUPPORTS_PDM_RX
  1388. /**
  1389. * @brief Set PDM mode down-sample rate
  1390. * In PDM RX mode, there would be 2 rounds of downsample process in hardware.
  1391. * In the first downsample process, the sampling number can be 16 or 8.
  1392. * In the second downsample process, the sampling number is fixed as 8.
  1393. * So the clock frequency in PDM RX mode would be (fpcm * 64) or (fpcm * 128) accordingly.
  1394. * @note After calling this function, it would call i2s_set_clk inside to update the clock frequency.
  1395. * Please call this function after I2S driver has been initialized.
  1396. *
  1397. * @param i2s_num I2S device number
  1398. * @param downsample i2s RX down sample rate for PDM mode.
  1399. * @return
  1400. * - ESP_OK Success
  1401. * - ESP_ERR_INVALID_ARG Parameter error
  1402. * - ESP_ERR_NO_MEM Out of memory
  1403. */
  1404. esp_err_t i2s_set_pdm_rx_down_sample(i2s_port_t i2s_num, i2s_pdm_dsr_t downsample)
  1405. {
  1406. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_FAIL, TAG, "i2s has not installed yet");
  1407. 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");
  1408. i2s_stop(i2s_num);
  1409. i2s_hal_set_rx_pdm_dsr(&(p_i2s[i2s_num]->hal), downsample);
  1410. // i2s will start in 'i2s_set_clk'
  1411. 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);
  1412. }
  1413. #endif
  1414. #if SOC_I2S_SUPPORTS_PDM_TX
  1415. /**
  1416. * @brief Set TX PDM mode up-sample rate
  1417. * @note If you have set PDM mode while calling 'i2s_driver_install',
  1418. * default PDM TX upsample parameters have already been set,
  1419. * no need to call this function again if you don't have to change the default configuration
  1420. *
  1421. * @param i2s_num I2S device number
  1422. * @param upsample_cfg Set I2S PDM up-sample rate configuration
  1423. * @return
  1424. * - ESP_OK Success
  1425. * - ESP_ERR_INVALID_ARG Parameter error
  1426. * - ESP_ERR_NO_MEM Out of memory
  1427. */
  1428. esp_err_t i2s_set_pdm_tx_up_sample(i2s_port_t i2s_num, const i2s_pdm_tx_upsample_cfg_t *upsample_cfg)
  1429. {
  1430. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_FAIL, TAG, "i2s has not installed yet");
  1431. 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");
  1432. i2s_stop(i2s_num);
  1433. i2s_hal_set_tx_pdm_fpfs(&(p_i2s[i2s_num]->hal), upsample_cfg->fp, upsample_cfg->fs);
  1434. // i2s will start in 'i2s_set_clk'
  1435. 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);
  1436. }
  1437. #endif
  1438. /**
  1439. * @brief I2S check the validity of configuration
  1440. *
  1441. * @param i2s_num I2S device number
  1442. * @param cfg I2S HAL configuration
  1443. * @return
  1444. * - ESP_OK I2S configuration is valid
  1445. * - ESP_ERR_INVALID_ARG I2S configuration is invalid
  1446. */
  1447. static esp_err_t i2s_check_cfg_validity(i2s_port_t i2s_num, i2s_hal_config_t *cfg)
  1448. {
  1449. #if SOC_I2S_SUPPORTS_PDM_TX || SOC_I2S_SUPPORTS_PDM_RX
  1450. /* Check PDM mode */
  1451. if (cfg->mode & I2S_MODE_PDM) {
  1452. ESP_RETURN_ON_FALSE(i2s_num == I2S_NUM_0, ESP_ERR_INVALID_ARG, TAG, "I2S PDM mode only support on I2S0");
  1453. #if !SOC_I2S_SUPPORTS_PDM_TX
  1454. ESP_RETURN_ON_FALSE(!(cfg->mode & I2S_MODE_TX), ESP_ERR_INVALID_ARG, TAG, "PDM does not support TX on this chip");
  1455. #endif // SOC_I2S_SUPPORTS_PDM_TX
  1456. #if !SOC_I2S_SUPPORTS_PDM_RX
  1457. ESP_RETURN_ON_FALSE(!(cfg->mode & I2S_MODE_RX), ESP_ERR_INVALID_ARG, TAG, "PDM does not support RX on this chip");
  1458. #endif // SOC_I2S_SUPPORTS_PDM_RX
  1459. }
  1460. #else
  1461. ESP_RETURN_ON_FALSE(!(cfg->mode & I2S_MODE_PDM), ESP_ERR_INVALID_ARG, TAG, "I2S PDM mode not supported on current chip");
  1462. #endif // SOC_I2S_SUPPORTS_PDM_TX || SOC_I2S_SUPPORTS_PDM_RX
  1463. #if SOC_I2S_SUPPORTS_ADC || SOC_I2S_SUPPORTS_DAC
  1464. /* Check built-in ADC/DAC mode */
  1465. if (cfg->mode & (I2S_MODE_ADC_BUILT_IN | I2S_MODE_DAC_BUILT_IN)) {
  1466. ESP_RETURN_ON_FALSE(i2s_num == I2S_NUM_0, ESP_ERR_INVALID_ARG, TAG, "I2S built-in ADC/DAC only support on I2S0");
  1467. }
  1468. #else
  1469. /* Check the transmit/receive mode */
  1470. 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");
  1471. /* Check communication format */
  1472. ESP_RETURN_ON_FALSE(cfg->comm_fmt && (cfg->comm_fmt < I2S_COMM_FORMAT_STAND_MAX), ESP_ERR_INVALID_ARG, TAG, "invalid communication formats");
  1473. #endif // SOC_I2S_SUPPORTS_ADC || SOC_I2S_SUPPORTS_DAC
  1474. return ESP_OK;
  1475. }
  1476. static void i2s_tx_set_clk_and_channel(i2s_port_t i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1477. {
  1478. i2s_hal_tx_clock_config(&(p_i2s[i2s_num]->hal), clk_cfg);
  1479. 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);
  1480. i2s_hal_tx_set_channel_style(&(p_i2s[i2s_num]->hal), &(p_i2s[i2s_num]->hal_cfg));
  1481. }
  1482. static void i2s_rx_set_clk_and_channel(i2s_port_t i2s_num, i2s_hal_clock_cfg_t *clk_cfg)
  1483. {
  1484. i2s_hal_rx_clock_config(&(p_i2s[i2s_num]->hal), clk_cfg);
  1485. 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);
  1486. i2s_hal_rx_set_channel_style(&(p_i2s[i2s_num]->hal), &(p_i2s[i2s_num]->hal_cfg));
  1487. }
  1488. /**
  1489. * @brief Get clock set on particular port number.
  1490. *
  1491. * @param i2s_num I2S device number
  1492. * @return
  1493. * - sample rate
  1494. */
  1495. float i2s_get_clk(i2s_port_t i2s_num)
  1496. {
  1497. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1498. return (float)p_i2s[i2s_num]->hal_cfg.sample_rate;
  1499. }
  1500. /**
  1501. * @brief Set clock & bit width used for I2S RX and TX.
  1502. * Similar to i2s_set_sample_rates(), but also sets bit width.
  1503. *
  1504. * 1. stop i2s
  1505. * 2. calculate mclk, bck, bck_factor
  1506. * 3. set clock configurations
  1507. * 4. realloc dma buffer if DMA buffer size changed
  1508. * 5. start i2s
  1509. *
  1510. * @param i2s_num I2S device number
  1511. * @param rate I2S sample rate (ex: 8000, 44100...)
  1512. * @param bits_cfg I2S bits configuration
  1513. * the low 16 bits is for data bits per sample in one channel (see 'i2s_bits_per_sample_t')
  1514. * the high 16 bits is for total bits in one channel (see 'i2s_bits_per_chan_t')
  1515. * high 16bits =0 means same as the bits per sample.
  1516. * @param ch I2S channel, (I2S_CHANNEL_MONO, I2S_CHANNEL_STEREO or specific channel in TDM mode)
  1517. * @return
  1518. * - ESP_OK Success
  1519. * - ESP_ERR_INVALID_ARG Parameter error
  1520. * - ESP_ERR_NO_MEM Out of memory
  1521. */
  1522. esp_err_t i2s_set_clk(i2s_port_t i2s_num, uint32_t rate, uint32_t bits_cfg, i2s_channel_t ch)
  1523. {
  1524. esp_err_t ret = ESP_OK;
  1525. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1526. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_ERR_INVALID_ARG, TAG, "I2S%d has not installed yet", i2s_num);
  1527. i2s_hal_config_t *cfg = &p_i2s[i2s_num]->hal_cfg;
  1528. /* If not the first time, update configuration */
  1529. if (p_i2s[i2s_num]->last_buf_size) {
  1530. cfg->sample_rate = rate;
  1531. cfg->sample_bits = bits_cfg & 0xFFFF;
  1532. cfg->chan_bits = (bits_cfg >> 16) > cfg->sample_bits ? (bits_cfg >> 16) : cfg->sample_bits;
  1533. #if SOC_I2S_SUPPORTS_TDM
  1534. cfg->chan_mask = ch;
  1535. cfg->chan_fmt = ch == I2S_CHANNEL_MONO ? I2S_CHANNEL_FMT_ONLY_RIGHT : cfg->chan_fmt;
  1536. cfg->active_chan = i2s_get_active_channel_num(cfg);
  1537. uint32_t max_channel = i2s_get_max_channel_num(cfg->chan_mask);
  1538. /* If total channel is smaller than max actived channel number then set it to the max active channel number */
  1539. cfg->total_chan = p_i2s[i2s_num]->hal_cfg.total_chan < max_channel ? max_channel : p_i2s[i2s_num]->hal_cfg.total_chan;
  1540. #else
  1541. /* Default */
  1542. cfg->chan_fmt = ch == I2S_CHANNEL_MONO ? I2S_CHANNEL_FMT_ONLY_RIGHT : cfg->chan_fmt;
  1543. cfg->active_chan = i2s_get_active_channel_num(cfg);
  1544. cfg->total_chan = 2;
  1545. #endif
  1546. if (cfg->mode & I2S_MODE_TX) {
  1547. xSemaphoreTake(p_i2s[i2s_num]->tx->mux, (portTickType)portMAX_DELAY);
  1548. i2s_hal_tx_set_channel_style(&(p_i2s[i2s_num]->hal), cfg);
  1549. xSemaphoreGive(p_i2s[i2s_num]->tx->mux);
  1550. }
  1551. if (cfg->mode & I2S_MODE_RX) {
  1552. xSemaphoreTake(p_i2s[i2s_num]->rx->mux, (portTickType)portMAX_DELAY);
  1553. i2s_hal_rx_set_channel_style(&(p_i2s[i2s_num]->hal), cfg);
  1554. xSemaphoreGive(p_i2s[i2s_num]->rx->mux);
  1555. }
  1556. }
  1557. uint32_t data_bits = cfg->sample_bits;
  1558. /* Check the validity of sample bits */
  1559. ESP_RETURN_ON_FALSE((data_bits % 8 == 0), ESP_ERR_INVALID_ARG, TAG, "Invalid bits per sample");
  1560. ESP_RETURN_ON_FALSE((data_bits <= I2S_BITS_PER_SAMPLE_32BIT), ESP_ERR_INVALID_ARG, TAG, "Invalid bits per sample");
  1561. /* Stop I2S */
  1562. i2s_stop(i2s_num);
  1563. i2s_hal_clock_cfg_t clk_cfg;
  1564. /* To get sclk, mclk, mclk_div bclk and bclk_div */
  1565. i2s_calculate_clock(i2s_num, &clk_cfg);
  1566. uint32_t buf_size = i2s_get_buf_size(i2s_num);
  1567. bool need_realloc = p_i2s[i2s_num]->last_buf_size != buf_size;
  1568. /* TX mode clock reset */
  1569. if (cfg->mode & I2S_MODE_TX) {
  1570. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->tx, ESP_ERR_INVALID_ARG, TAG, "I2S TX DMA object has not initialized yet");
  1571. /* Waiting for transmit finish */
  1572. xSemaphoreTake(p_i2s[i2s_num]->tx->mux, (portTickType)portMAX_DELAY);
  1573. i2s_tx_set_clk_and_channel(i2s_num, &clk_cfg);
  1574. /* If buffer size changed, the DMA buffer need realloc */
  1575. if (need_realloc) {
  1576. p_i2s[i2s_num]->tx->buf_size = buf_size;
  1577. ret = i2s_realloc_dma_buffer(i2s_num, p_i2s[i2s_num]->tx);
  1578. }
  1579. /* If not the first time, update I2S tx channel style */
  1580. if (p_i2s[i2s_num]->last_buf_size) {
  1581. i2s_hal_tx_set_channel_style(&(p_i2s[i2s_num]->hal), &(p_i2s[i2s_num]->hal_cfg));
  1582. }
  1583. /* Reset the queue to avoid receive invalid data */
  1584. xQueueReset(p_i2s[i2s_num]->tx->queue);
  1585. xSemaphoreGive(p_i2s[i2s_num]->tx->mux);
  1586. ESP_RETURN_ON_ERROR(ret, TAG, "I2S%d tx DMA buffer malloc failed", i2s_num);
  1587. }
  1588. /* RX mode clock reset */
  1589. if (cfg->mode & I2S_MODE_RX) {
  1590. ESP_RETURN_ON_FALSE(p_i2s[i2s_num]->rx, ESP_ERR_INVALID_ARG, TAG, "I2S TX DMA object has not initialized yet");
  1591. /* Waiting for receive finish */
  1592. xSemaphoreTake(p_i2s[i2s_num]->rx->mux, (portTickType)portMAX_DELAY);
  1593. i2s_rx_set_clk_and_channel(i2s_num, &clk_cfg);
  1594. /* If buffer size changed, the DMA buffer need realloc */
  1595. if (need_realloc) {
  1596. p_i2s[i2s_num]->rx->buf_size = buf_size;
  1597. ret = i2s_realloc_dma_buffer(i2s_num, p_i2s[i2s_num]->rx);
  1598. /* Reset the end-of-frame number */
  1599. i2s_hal_set_rx_eof_num(&(p_i2s[i2s_num]->hal), buf_size);
  1600. }
  1601. /* If not the first time, update I2S rx channel style */
  1602. if (p_i2s[i2s_num]->last_buf_size) {
  1603. i2s_hal_rx_set_channel_style(&(p_i2s[i2s_num]->hal), &(p_i2s[i2s_num]->hal_cfg));
  1604. }
  1605. /* Reset the queue to avoid receiving invalid data */
  1606. xQueueReset(p_i2s[i2s_num]->rx->queue);
  1607. xSemaphoreGive(p_i2s[i2s_num]->rx->mux);
  1608. ESP_RETURN_ON_ERROR(ret, TAG, "I2S%d rx DMA buffer malloc failed", i2s_num);
  1609. }
  1610. /* Update last buffer size */
  1611. p_i2s[i2s_num]->last_buf_size = buf_size;
  1612. /* I2S start */
  1613. i2s_start(i2s_num);
  1614. return ESP_OK;
  1615. }
  1616. /*-------------------------------------------------------------
  1617. I2S driver operation
  1618. -------------------------------------------------------------*/
  1619. /**
  1620. * @brief Start I2S driver
  1621. * @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().
  1622. *
  1623. * @param i2s_num I2S device number
  1624. * @return
  1625. * - ESP_OK Success
  1626. * - ESP_ERR_INVALID_ARG Parameter error
  1627. */
  1628. esp_err_t i2s_start(i2s_port_t i2s_num)
  1629. {
  1630. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1631. //start DMA link
  1632. I2S_ENTER_CRITICAL(i2s_num);
  1633. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1634. i2s_tx_reset(i2s_num);
  1635. i2s_tx_start(i2s_num);
  1636. }
  1637. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1638. i2s_rx_reset(i2s_num);
  1639. i2s_rx_start(i2s_num);
  1640. }
  1641. #if !SOC_GDMA_SUPPORTED
  1642. esp_intr_enable(p_i2s[i2s_num]->i2s_isr_handle);
  1643. #endif
  1644. I2S_EXIT_CRITICAL(i2s_num);
  1645. return ESP_OK;
  1646. }
  1647. /**
  1648. * @brief Stop I2S driver
  1649. * @note There is no need to call i2s_stop() before calling i2s_driver_uninstall().
  1650. * Disables I2S TX/RX, until i2s_start() is called.
  1651. *
  1652. * @param i2s_num I2S device number
  1653. *
  1654. * @return
  1655. * - ESP_OK Success
  1656. * - ESP_ERR_INVALID_ARG Parameter error
  1657. */
  1658. esp_err_t i2s_stop(i2s_port_t i2s_num)
  1659. {
  1660. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1661. I2S_ENTER_CRITICAL(i2s_num);
  1662. #if !SOC_GDMA_SUPPORTED
  1663. esp_intr_disable(p_i2s[i2s_num]->i2s_isr_handle);
  1664. #endif
  1665. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1666. i2s_tx_stop(i2s_num);
  1667. }
  1668. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1669. i2s_rx_stop(i2s_num);
  1670. }
  1671. #if !SOC_GDMA_SUPPORTED
  1672. i2s_hal_clear_intr_status(&(p_i2s[i2s_num]->hal), I2S_INTR_MAX);
  1673. #endif
  1674. I2S_EXIT_CRITICAL(i2s_num);
  1675. return ESP_OK;
  1676. }
  1677. /**
  1678. * @brief Initialize I2S driver configurations
  1679. *
  1680. * @param i2s_num I2S device number
  1681. * @param i2s_config I2S configurations - see i2s_config_t struct
  1682. * @return
  1683. * - ESP_OK I2S initialize success
  1684. * - ESP_ERR_INVALID_ARG No channel enabled in multiple channel format
  1685. */
  1686. static esp_err_t i2s_driver_init(i2s_port_t i2s_num, const i2s_config_t *i2s_config)
  1687. {
  1688. ESP_RETURN_ON_FALSE(i2s_config, ESP_ERR_INVALID_ARG, TAG, "The pointer of I2S configuration structure is NULL");
  1689. /* I2S driver configuration assignment */
  1690. p_i2s[i2s_num]->i2s_num = i2s_num;
  1691. p_i2s[i2s_num]->dma_buf_count = i2s_config->dma_buf_count;
  1692. p_i2s[i2s_num]->dma_buf_len = i2s_config->dma_buf_len;
  1693. p_i2s[i2s_num]->last_buf_size = 0;
  1694. p_i2s[i2s_num]->use_apll = i2s_config->use_apll;
  1695. p_i2s[i2s_num]->fixed_mclk = i2s_config->fixed_mclk;
  1696. p_i2s[i2s_num]->mclk_multiple = i2s_config->mclk_multiple;
  1697. p_i2s[i2s_num]->tx_desc_auto_clear = i2s_config->tx_desc_auto_clear;
  1698. /* I2S HAL configuration assignment */
  1699. p_i2s[i2s_num]->hal_cfg.mode = i2s_config->mode;
  1700. p_i2s[i2s_num]->hal_cfg.sample_rate = i2s_config->sample_rate;
  1701. p_i2s[i2s_num]->hal_cfg.comm_fmt = i2s_config->communication_format;
  1702. p_i2s[i2s_num]->hal_cfg.chan_fmt = i2s_config->channel_format;
  1703. p_i2s[i2s_num]->hal_cfg.sample_bits = i2s_config->bits_per_sample;
  1704. p_i2s[i2s_num]->hal_cfg.chan_bits = (uint32_t)i2s_config->bits_per_chan < (uint32_t)i2s_config->bits_per_sample ?
  1705. (uint32_t)i2s_config->bits_per_sample : (uint32_t)i2s_config->bits_per_chan;
  1706. #if SOC_I2S_SUPPORTS_TDM
  1707. /* I2S HAL TDM configuration assignment */
  1708. p_i2s[i2s_num]->hal_cfg.left_align = i2s_config->left_align;
  1709. p_i2s[i2s_num]->hal_cfg.big_edin = i2s_config->big_edin;
  1710. p_i2s[i2s_num]->hal_cfg.bit_order_msb = i2s_config->bit_order_msb;
  1711. p_i2s[i2s_num]->hal_cfg.skip_msk = i2s_config->skip_msk;
  1712. /* Set chan_mask according to channel format */
  1713. switch (i2s_config->channel_format) {
  1714. case I2S_CHANNEL_FMT_RIGHT_LEFT: // fall through
  1715. case I2S_CHANNEL_FMT_ALL_RIGHT: // fall through
  1716. case I2S_CHANNEL_FMT_ALL_LEFT:
  1717. p_i2s[i2s_num]->hal_cfg.chan_mask = I2S_TDM_ACTIVE_CH0 | I2S_TDM_ACTIVE_CH1;
  1718. p_i2s[i2s_num]->hal_cfg.total_chan = 2;
  1719. break;
  1720. case I2S_CHANNEL_FMT_ONLY_RIGHT: // fall through
  1721. case I2S_CHANNEL_FMT_ONLY_LEFT:
  1722. p_i2s[i2s_num]->hal_cfg.chan_mask = I2S_TDM_ACTIVE_CH0;
  1723. p_i2s[i2s_num]->hal_cfg.total_chan = 2;
  1724. break;
  1725. case I2S_CHANNEL_FMT_MULTIPLE:
  1726. ESP_RETURN_ON_FALSE(i2s_config->chan_mask, ESP_ERR_INVALID_ARG, TAG, "i2s all channel are disabled");
  1727. p_i2s[i2s_num]->hal_cfg.chan_mask = i2s_config->chan_mask;
  1728. /* Get the max actived channel number */
  1729. uint32_t max_channel = i2s_get_max_channel_num(p_i2s[i2s_num]->hal_cfg.chan_mask);
  1730. /* If total channel is smaller than max actived channel number then set it to the max active channel number */
  1731. p_i2s[i2s_num]->hal_cfg.total_chan = p_i2s[i2s_num]->hal_cfg.total_chan < max_channel ? max_channel :
  1732. p_i2s[i2s_num]->hal_cfg.total_chan;
  1733. break;
  1734. default:
  1735. ESP_RETURN_ON_FALSE(false, ESP_ERR_INVALID_ARG, TAG, "wrong i2s channel format, going to uninstall i2s");
  1736. }
  1737. /* Calculate actived channel number in channel mask */
  1738. p_i2s[i2s_num]->hal_cfg.active_chan = i2s_get_active_channel_num(&p_i2s[i2s_num]->hal_cfg);
  1739. #else
  1740. /* Calculate actived channel number in channel mask */
  1741. p_i2s[i2s_num]->hal_cfg.active_chan = i2s_get_active_channel_num(&p_i2s[i2s_num]->hal_cfg);
  1742. /* Total channel number is equal to the actived channel number in non-TDM mode */
  1743. p_i2s[i2s_num]->hal_cfg.total_chan = 2;
  1744. #endif
  1745. return ESP_OK;
  1746. }
  1747. /**
  1748. * @brief Initialize I2S DMA object
  1749. *
  1750. * @param i2s_num I2S device number
  1751. * @return
  1752. * - ESP_OK DMA object initialize success
  1753. * - ESP_ERR_NO_MEM No memory for DMA object
  1754. */
  1755. static esp_err_t i2s_dma_object_init(i2s_port_t i2s_num)
  1756. {
  1757. uint32_t buf_size = i2s_get_buf_size(i2s_num);
  1758. /* Create DMA object */
  1759. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_TX) {
  1760. ESP_RETURN_ON_ERROR(i2s_create_dma_object(i2s_num, &p_i2s[i2s_num]->tx), TAG, "I2S TX DMA object create failed");
  1761. p_i2s[i2s_num]->tx->buf_size = buf_size;
  1762. }
  1763. if (p_i2s[i2s_num]->hal_cfg.mode & I2S_MODE_RX) {
  1764. ESP_RETURN_ON_ERROR(i2s_create_dma_object(i2s_num, &p_i2s[i2s_num]->rx), TAG, "I2S RX DMA object create failed");
  1765. p_i2s[i2s_num]->rx->buf_size = buf_size;
  1766. }
  1767. return ESP_OK;
  1768. }
  1769. /**
  1770. * @brief Install and start I2S driver.
  1771. * @note This function must be called before any I2S driver read/write operations.
  1772. *
  1773. *
  1774. * @param i2s_num I2S device number
  1775. * @param i2s_config I2S configurations - see i2s_config_t struct
  1776. * @param queue_size I2S event queue size/depth.
  1777. * @param i2s_queue I2S event queue handle, if set NULL, driver will not use an event queue.
  1778. *
  1779. * @return
  1780. * - ESP_OK Success
  1781. * - ESP_ERR_INVALID_ARG Parameter error
  1782. * - ESP_ERR_NO_MEM Out of memory
  1783. * - ESP_ERR_INVALID_STATE Current I2S port is in use
  1784. */
  1785. esp_err_t i2s_driver_install(i2s_port_t i2s_num, const i2s_config_t *i2s_config, int queue_size, void *i2s_queue)
  1786. {
  1787. esp_err_t ret = ESP_OK;
  1788. /* Step 1: Check the validity of input parameters */
  1789. /* Check the validity of i2s device number */
  1790. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1791. ESP_RETURN_ON_FALSE(i2s_config, ESP_ERR_INVALID_ARG, TAG, "I2S configuration must not be NULL");
  1792. /* Check the size of DMA buffer */
  1793. 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");
  1794. 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");
  1795. /* Step 2: Allocate driver object and register to platform */
  1796. i2s_obj_t *pre_alloc_i2s_obj = calloc(1, sizeof(i2s_obj_t));
  1797. ESP_RETURN_ON_FALSE(pre_alloc_i2s_obj, ESP_ERR_NO_MEM, TAG, "no mem for I2S driver");
  1798. ret = i2s_priv_register_object(pre_alloc_i2s_obj, i2s_num);
  1799. if (ret != ESP_OK) {
  1800. free(pre_alloc_i2s_obj);
  1801. ESP_LOGE(TAG, "register I2S object to platform failed");
  1802. return ESP_ERR_INVALID_STATE;
  1803. }
  1804. /* Step 3: Initialize I2S object, assign configarations */
  1805. ESP_GOTO_ON_ERROR(i2s_driver_init(i2s_num, i2s_config), err, TAG, "I2S init failed");
  1806. /* Check the validity of I2S configuration */
  1807. ESP_GOTO_ON_ERROR(i2s_check_cfg_validity(i2s_num, &(pre_alloc_i2s_obj->hal_cfg)), err, TAG, "I2S configuration is invalid");
  1808. /* Get device instance */
  1809. i2s_hal_init(&(pre_alloc_i2s_obj->hal), i2s_num);
  1810. #ifdef CONFIG_PM_ENABLE
  1811. esp_pm_lock_type_t pm_lock = ESP_PM_APB_FREQ_MAX;
  1812. #if SOC_I2S_SUPPORTS_APLL
  1813. if (i2s_config->use_apll) {
  1814. pm_lock = ESP_PM_NO_LIGHT_SLEEP;
  1815. }
  1816. #endif // SOC_I2S_SUPPORTS_APLL
  1817. 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");
  1818. #endif //CONFIG_PM_ENABLE
  1819. /* Step 4: Initialize I2S DMA interrupt and DMA object */
  1820. ESP_GOTO_ON_ERROR(i2s_dma_intr_init(i2s_num, i2s_config->intr_alloc_flags), err, TAG, "I2S interrupt initailze failed");
  1821. /* Initialize I2S DMA object */
  1822. ESP_GOTO_ON_ERROR(i2s_dma_object_init(i2s_num), err, TAG, "I2S dma object create failed");
  1823. #if SOC_I2S_SUPPORTS_ADC
  1824. /* If using built-in ADC, we need to enable ADC power manerge*/
  1825. if (pre_alloc_i2s_obj->hal_cfg.mode & I2S_MODE_ADC_BUILT_IN) {
  1826. adc_power_acquire();
  1827. }
  1828. #endif
  1829. /* Enable module clock */
  1830. i2s_hal_enable_module_clock(&p_i2s[i2s_num]->hal);
  1831. /* Step 5: Initialize I2S configuration and set the configurations to register */
  1832. i2s_hal_config_param(&(pre_alloc_i2s_obj->hal), &pre_alloc_i2s_obj->hal_cfg);
  1833. /* Step 6: Initialise i2s event queue if user needs */
  1834. if (i2s_queue) {
  1835. pre_alloc_i2s_obj->i2s_queue = xQueueCreate(queue_size, sizeof(i2s_event_t));
  1836. ESP_GOTO_ON_FALSE(pre_alloc_i2s_obj->i2s_queue, ESP_ERR_NO_MEM, err, TAG, "I2S queue create failed");
  1837. *((QueueHandle_t *) i2s_queue) = pre_alloc_i2s_obj->i2s_queue;
  1838. ESP_LOGI(TAG, "queue free spaces: %d", uxQueueSpacesAvailable(pre_alloc_i2s_obj->i2s_queue));
  1839. } else {
  1840. pre_alloc_i2s_obj->i2s_queue = NULL;
  1841. }
  1842. /* Step 7: Set I2S clocks and start. No need to give parameters since configurations has been set in 'i2s_driver_init' */
  1843. ESP_GOTO_ON_ERROR(i2s_set_clk(i2s_num, 0, 0, 0), err, TAG, "I2S set clock failed");
  1844. return ESP_OK;
  1845. err:
  1846. /* I2S install failed, prepare to uninstall */
  1847. i2s_driver_uninstall(i2s_num);
  1848. return ret;
  1849. }
  1850. /**
  1851. * @brief Uninstall I2S driver.
  1852. *
  1853. * @param i2s_num I2S device number
  1854. * @return
  1855. * - ESP_OK Success
  1856. * - ESP_ERR_INVALID_ARG Parameter error
  1857. */
  1858. esp_err_t i2s_driver_uninstall(i2s_port_t i2s_num)
  1859. {
  1860. ESP_RETURN_ON_FALSE(i2s_num < I2S_NUM_MAX, ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1861. ESP_RETURN_ON_FALSE(p_i2s[i2s_num], ESP_ERR_INVALID_STATE, TAG, "I2S port %d has not installed", i2s_num);
  1862. i2s_obj_t *obj = p_i2s[i2s_num];
  1863. i2s_stop(i2s_num);
  1864. #if SOC_I2S_SUPPORTS_DAC
  1865. i2s_set_dac_mode(I2S_DAC_CHANNEL_DISABLE);
  1866. #endif
  1867. #if SOC_GDMA_SUPPORTED
  1868. if (p_i2s[i2s_num]->tx_dma_chan) {
  1869. gdma_disconnect(p_i2s[i2s_num]->tx_dma_chan);
  1870. gdma_del_channel(p_i2s[i2s_num]->tx_dma_chan);
  1871. }
  1872. if (p_i2s[i2s_num]->rx_dma_chan) {
  1873. gdma_disconnect(p_i2s[i2s_num]->rx_dma_chan);
  1874. gdma_del_channel(p_i2s[i2s_num]->rx_dma_chan);
  1875. }
  1876. #else
  1877. if (p_i2s[i2s_num]->i2s_isr_handle) {
  1878. esp_intr_free(p_i2s[i2s_num]->i2s_isr_handle);
  1879. }
  1880. #endif
  1881. /* Destroy dma object if exist */
  1882. i2s_destroy_dma_object(i2s_num, &p_i2s[i2s_num]->tx);
  1883. i2s_destroy_dma_object(i2s_num, &p_i2s[i2s_num]->rx);
  1884. if (p_i2s[i2s_num]->i2s_queue) {
  1885. vQueueDelete(p_i2s[i2s_num]->i2s_queue);
  1886. p_i2s[i2s_num]->i2s_queue = NULL;
  1887. }
  1888. #if SOC_I2S_SUPPORTS_APLL
  1889. if (p_i2s[i2s_num]->use_apll) {
  1890. // switch back to PLL clock source
  1891. i2s_hal_set_clock_src(&(p_i2s[i2s_num]->hal), I2S_CLK_D2CLK);
  1892. rtc_clk_apll_enable(0, 0, 0, 0, 0);
  1893. }
  1894. #endif
  1895. #ifdef CONFIG_PM_ENABLE
  1896. if (p_i2s[i2s_num]->pm_lock) {
  1897. esp_pm_lock_delete(p_i2s[i2s_num]->pm_lock);
  1898. p_i2s[i2s_num]->pm_lock = NULL;
  1899. }
  1900. #endif
  1901. /* Disable module clock */
  1902. i2s_hal_disable_module_clock(&p_i2s[i2s_num]->hal);
  1903. i2s_priv_deregister_object(i2s_num);
  1904. free(obj);
  1905. return ESP_OK;
  1906. }
  1907. /**
  1908. * @brief Write data to I2S DMA transmit buffer.
  1909. * @note Many ticks pass without space becoming available in the DMA
  1910. * transmit buffer, then the function will return (note that if the
  1911. * data is written to the DMA buffer in pieces, the overall operation
  1912. * may still take longer than this timeout.) Pass portMAX_DELAY for no
  1913. * timeout.
  1914. *
  1915. * @param i2s_num I2S device number
  1916. * @param src Source address to write from
  1917. * @param size Size of data in bytes
  1918. * @param[out] bytes_written Number of bytes written, if timeout, the result will be less than the size passed in.
  1919. * @param ticks_to_wait TX buffer wait timeout in RTOS ticks. If this
  1920. * @return
  1921. * - ESP_OK Success
  1922. * - ESP_ERR_INVALID_ARG Parameter error
  1923. */
  1924. 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)
  1925. {
  1926. esp_err_t ret = ESP_OK;
  1927. char *data_ptr, *src_byte;
  1928. size_t bytes_can_write;
  1929. *bytes_written = 0;
  1930. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1931. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->tx), ESP_ERR_INVALID_ARG, TAG, "TX mode is not enabled");
  1932. xSemaphoreTake(p_i2s[i2s_num]->tx->mux, (portTickType)portMAX_DELAY);
  1933. #ifdef CONFIG_PM_ENABLE
  1934. esp_pm_lock_acquire(p_i2s[i2s_num]->pm_lock);
  1935. #endif
  1936. src_byte = (char *)src;
  1937. while (size > 0) {
  1938. if (p_i2s[i2s_num]->tx->rw_pos == p_i2s[i2s_num]->tx->buf_size || p_i2s[i2s_num]->tx->curr_ptr == NULL) {
  1939. if (xQueueReceive(p_i2s[i2s_num]->tx->queue, &p_i2s[i2s_num]->tx->curr_ptr, ticks_to_wait) == pdFALSE) {
  1940. ret = ESP_ERR_TIMEOUT;
  1941. break;
  1942. }
  1943. p_i2s[i2s_num]->tx->rw_pos = 0;
  1944. }
  1945. 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);
  1946. data_ptr = (char *)p_i2s[i2s_num]->tx->curr_ptr;
  1947. data_ptr += p_i2s[i2s_num]->tx->rw_pos;
  1948. bytes_can_write = p_i2s[i2s_num]->tx->buf_size - p_i2s[i2s_num]->tx->rw_pos;
  1949. if (bytes_can_write > size) {
  1950. bytes_can_write = size;
  1951. }
  1952. memcpy(data_ptr, src_byte, bytes_can_write);
  1953. size -= bytes_can_write;
  1954. src_byte += bytes_can_write;
  1955. p_i2s[i2s_num]->tx->rw_pos += bytes_can_write;
  1956. (*bytes_written) += bytes_can_write;
  1957. }
  1958. #ifdef CONFIG_PM_ENABLE
  1959. esp_pm_lock_release(p_i2s[i2s_num]->pm_lock);
  1960. #endif
  1961. xSemaphoreGive(p_i2s[i2s_num]->tx->mux);
  1962. return ret;
  1963. }
  1964. /**
  1965. * @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.
  1966. * @note Many ticks pass without space becoming available in the DMA
  1967. * transmit buffer, then the function will return (note that if the
  1968. * data is written to the DMA buffer in pieces, the overall operation
  1969. * may still take longer than this timeout.) Pass portMAX_DELAY for no
  1970. * timeout.
  1971. * Format of the data in source buffer is determined by the I2S configuration (see i2s_config_t).
  1972. *
  1973. * @param i2s_num I2S device number
  1974. * @param src Source address to write from
  1975. * @param size Size of data in bytes
  1976. * @param src_bits Source audio bit
  1977. * @param aim_bits Bit wanted, no more than 32, and must be greater than src_bits
  1978. * @param[out] bytes_written Number of bytes written, if timeout, the result will be less than the size passed in.
  1979. * @param ticks_to_wait TX buffer wait timeout in RTOS ticks. If this
  1980. * @return
  1981. * - ESP_OK Success
  1982. * - ESP_ERR_INVALID_ARG Parameter error
  1983. */
  1984. 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)
  1985. {
  1986. esp_err_t ret = ESP_OK;
  1987. char *data_ptr;
  1988. int bytes_can_write, tail;
  1989. int src_bytes, aim_bytes, zero_bytes;
  1990. *bytes_written = 0;
  1991. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  1992. ESP_RETURN_ON_FALSE((size > 0), ESP_ERR_INVALID_ARG, TAG, "size must greater than zero");
  1993. ESP_RETURN_ON_FALSE((aim_bits >= src_bits), ESP_ERR_INVALID_ARG, TAG, "aim_bits mustn't be less than src_bits");
  1994. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->tx), ESP_ERR_INVALID_ARG, TAG, "TX mode is not enabled");
  1995. if (src_bits < I2S_BITS_PER_SAMPLE_8BIT || aim_bits < I2S_BITS_PER_SAMPLE_8BIT) {
  1996. ESP_LOGE(TAG, "bits mustn't be less than 8, src_bits %d aim_bits %d", src_bits, aim_bits);
  1997. return ESP_ERR_INVALID_ARG;
  1998. }
  1999. if (src_bits > I2S_BITS_PER_SAMPLE_32BIT || aim_bits > I2S_BITS_PER_SAMPLE_32BIT) {
  2000. ESP_LOGE(TAG, "bits mustn't be greater than 32, src_bits %d aim_bits %d", src_bits, aim_bits);
  2001. return ESP_ERR_INVALID_ARG;
  2002. }
  2003. if ((src_bits == I2S_BITS_PER_SAMPLE_16BIT || src_bits == I2S_BITS_PER_SAMPLE_32BIT) && (size % 2 != 0)) {
  2004. ESP_LOGE(TAG, "size must be a even number while src_bits is even, src_bits %d size %d", src_bits, size);
  2005. return ESP_ERR_INVALID_ARG;
  2006. }
  2007. if (src_bits == I2S_BITS_PER_SAMPLE_24BIT && (size % 3 != 0)) {
  2008. ESP_LOGE(TAG, "size must be a multiple of 3 while src_bits is 24, size %d", size);
  2009. return ESP_ERR_INVALID_ARG;
  2010. }
  2011. src_bytes = src_bits / 8;
  2012. aim_bytes = aim_bits / 8;
  2013. zero_bytes = aim_bytes - src_bytes;
  2014. xSemaphoreTake(p_i2s[i2s_num]->tx->mux, (portTickType)portMAX_DELAY);
  2015. size = size * aim_bytes / src_bytes;
  2016. ESP_LOGD(TAG, "aim_bytes %d src_bytes %d size %d", aim_bytes, src_bytes, size);
  2017. while (size > 0) {
  2018. if (p_i2s[i2s_num]->tx->rw_pos == p_i2s[i2s_num]->tx->buf_size || p_i2s[i2s_num]->tx->curr_ptr == NULL) {
  2019. if (xQueueReceive(p_i2s[i2s_num]->tx->queue, &p_i2s[i2s_num]->tx->curr_ptr, ticks_to_wait) == pdFALSE) {
  2020. ret = ESP_ERR_TIMEOUT;
  2021. break;
  2022. }
  2023. p_i2s[i2s_num]->tx->rw_pos = 0;
  2024. }
  2025. data_ptr = (char *)p_i2s[i2s_num]->tx->curr_ptr;
  2026. data_ptr += p_i2s[i2s_num]->tx->rw_pos;
  2027. bytes_can_write = p_i2s[i2s_num]->tx->buf_size - p_i2s[i2s_num]->tx->rw_pos;
  2028. if (bytes_can_write > (int)size) {
  2029. bytes_can_write = size;
  2030. }
  2031. tail = bytes_can_write % aim_bytes;
  2032. bytes_can_write = bytes_can_write - tail;
  2033. memset(data_ptr, 0, bytes_can_write);
  2034. for (int j = 0; j < bytes_can_write; j += (aim_bytes - zero_bytes)) {
  2035. j += zero_bytes;
  2036. memcpy(&data_ptr[j], (const char *)(src + *bytes_written), aim_bytes - zero_bytes);
  2037. (*bytes_written) += (aim_bytes - zero_bytes);
  2038. }
  2039. size -= bytes_can_write;
  2040. p_i2s[i2s_num]->tx->rw_pos += bytes_can_write;
  2041. }
  2042. xSemaphoreGive(p_i2s[i2s_num]->tx->mux);
  2043. return ret;
  2044. }
  2045. /**
  2046. * @brief Read data from I2S DMA receive buffer
  2047. * @note If the built-in ADC mode is enabled, we should call i2s_adc_enable and i2s_adc_disable around the whole reading process,
  2048. * to prevent the data getting corrupted.
  2049. *
  2050. * @param i2s_num I2S device number
  2051. * @param dest Destination address to read into
  2052. * @param size Size of data in bytes
  2053. * @param[out] bytes_read Number of bytes read, if timeout, bytes read will be less than the size passed in.
  2054. * @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.
  2055. * @return
  2056. * - ESP_OK Success
  2057. * - ESP_ERR_INVALID_ARG Parameter error
  2058. */
  2059. esp_err_t i2s_read(i2s_port_t i2s_num, void *dest, size_t size, size_t *bytes_read, TickType_t ticks_to_wait)
  2060. {
  2061. esp_err_t ret = ESP_OK;
  2062. char *data_ptr, *dest_byte;
  2063. int bytes_can_read;
  2064. *bytes_read = 0;
  2065. dest_byte = (char *)dest;
  2066. ESP_RETURN_ON_FALSE((i2s_num < I2S_NUM_MAX), ESP_ERR_INVALID_ARG, TAG, "i2s_num error");
  2067. ESP_RETURN_ON_FALSE((p_i2s[i2s_num]->rx), ESP_ERR_INVALID_ARG, TAG, "RX mode is not enabled");
  2068. xSemaphoreTake(p_i2s[i2s_num]->rx->mux, (portTickType)portMAX_DELAY);
  2069. #ifdef CONFIG_PM_ENABLE
  2070. esp_pm_lock_acquire(p_i2s[i2s_num]->pm_lock);
  2071. #endif
  2072. while (size > 0) {
  2073. if (p_i2s[i2s_num]->rx->rw_pos == p_i2s[i2s_num]->rx->buf_size || p_i2s[i2s_num]->rx->curr_ptr == NULL) {
  2074. if (xQueueReceive(p_i2s[i2s_num]->rx->queue, &p_i2s[i2s_num]->rx->curr_ptr, ticks_to_wait) == pdFALSE) {
  2075. ret = ESP_ERR_TIMEOUT;
  2076. break;
  2077. }
  2078. p_i2s[i2s_num]->rx->rw_pos = 0;
  2079. }
  2080. data_ptr = (char *)p_i2s[i2s_num]->rx->curr_ptr;
  2081. data_ptr += p_i2s[i2s_num]->rx->rw_pos;
  2082. bytes_can_read = p_i2s[i2s_num]->rx->buf_size - p_i2s[i2s_num]->rx->rw_pos;
  2083. if (bytes_can_read > (int)size) {
  2084. bytes_can_read = size;
  2085. }
  2086. memcpy(dest_byte, data_ptr, bytes_can_read);
  2087. size -= bytes_can_read;
  2088. dest_byte += bytes_can_read;
  2089. p_i2s[i2s_num]->rx->rw_pos += bytes_can_read;
  2090. (*bytes_read) += bytes_can_read;
  2091. }
  2092. #ifdef CONFIG_PM_ENABLE
  2093. esp_pm_lock_release(p_i2s[i2s_num]->pm_lock);
  2094. #endif
  2095. xSemaphoreGive(p_i2s[i2s_num]->rx->mux);
  2096. return ret;
  2097. }
  2098. esp_err_t i2s_priv_register_object(void *driver_obj, int port_id)
  2099. {
  2100. esp_err_t ret = ESP_ERR_NOT_FOUND;
  2101. ESP_RETURN_ON_FALSE(driver_obj && (port_id < SOC_I2S_NUM), ESP_ERR_INVALID_ARG, TAG, "invalid arguments");
  2102. portENTER_CRITICAL(&i2s_platform_spinlock);
  2103. if (!p_i2s[port_id]) {
  2104. ret = ESP_OK;
  2105. p_i2s[port_id] = driver_obj;
  2106. periph_module_enable(i2s_periph_signal[port_id].module);
  2107. }
  2108. portEXIT_CRITICAL(&i2s_platform_spinlock);
  2109. return ret;
  2110. }
  2111. esp_err_t i2s_priv_deregister_object(int port_id)
  2112. {
  2113. esp_err_t ret = ESP_ERR_INVALID_STATE;
  2114. ESP_RETURN_ON_FALSE(port_id < SOC_I2S_NUM, ESP_ERR_INVALID_ARG, TAG, "invalid arguments");
  2115. portENTER_CRITICAL(&i2s_platform_spinlock);
  2116. if (p_i2s[port_id]) {
  2117. ret = ESP_OK;
  2118. p_i2s[port_id] = NULL;
  2119. periph_module_disable(i2s_periph_signal[port_id].module);
  2120. }
  2121. portEXIT_CRITICAL(&i2s_platform_spinlock);
  2122. return ret;
  2123. }