i2s.c 87 KB

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