i2s.c 91 KB

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