i2s_common.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <stdbool.h>
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/queue.h"
  10. #include "freertos/task.h"
  11. #include "freertos/idf_additions.h"
  12. #include "sdkconfig.h"
  13. #if CONFIG_I2S_ENABLE_DEBUG_LOG
  14. // The local log level must be defined before including esp_log.h
  15. // Set the maximum log level for this source file
  16. #define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
  17. #endif
  18. #include "esp_log.h"
  19. #include "soc/i2s_periph.h"
  20. #include "soc/soc_caps.h"
  21. #include "hal/gpio_hal.h"
  22. #include "hal/i2s_hal.h"
  23. #if SOC_I2S_SUPPORTS_ADC_DAC
  24. #include "hal/adc_ll.h"
  25. #include "driver/adc_i2s_legacy.h"
  26. #endif
  27. #if SOC_I2S_SUPPORTS_APLL
  28. #include "clk_ctrl_os.h"
  29. #endif
  30. #include "esp_private/i2s_platform.h"
  31. #include "esp_private/periph_ctrl.h"
  32. #include "esp_private/esp_clk.h"
  33. #include "driver/gpio.h"
  34. #include "driver/i2s_common.h"
  35. #include "i2s_private.h"
  36. #include "clk_ctrl_os.h"
  37. #include "esp_intr_alloc.h"
  38. #include "esp_check.h"
  39. #include "esp_attr.h"
  40. #include "esp_rom_gpio.h"
  41. #include "esp_memory_utils.h"
  42. /* The actual max size of DMA buffer is 4095
  43. * Set 4092 here to align with 4-byte, so that the position of the slot data in the buffer will be relatively fixed */
  44. #define I2S_DMA_BUFFER_MAX_SIZE (4092)
  45. /**
  46. * @brief Global i2s platform object
  47. * @note For saving all the I2S related information
  48. */
  49. i2s_platform_t g_i2s = {
  50. .spinlock = (portMUX_TYPE)portMUX_INITIALIZER_UNLOCKED,
  51. .controller[0 ... (SOC_I2S_NUM - 1)] = NULL, // groups will be lazy installed
  52. .comp_name[0 ... (SOC_I2S_NUM - 1)] = NULL,
  53. };
  54. static const char *TAG = "i2s_common";
  55. /*---------------------------------------------------------------------------
  56. I2S Static APIs
  57. ----------------------------------------------------------------------------
  58. Scope: This file only
  59. ----------------------------------------------------------------------------*/
  60. static void i2s_tx_channel_start(i2s_chan_handle_t handle)
  61. {
  62. i2s_hal_tx_reset(&(handle->controller->hal));
  63. #if SOC_GDMA_SUPPORTED
  64. gdma_reset((handle->dma.dma_chan));
  65. #else
  66. i2s_hal_tx_reset_dma(&(handle->controller->hal));
  67. #endif
  68. i2s_hal_tx_reset_fifo(&(handle->controller->hal));
  69. #if SOC_GDMA_SUPPORTED
  70. gdma_start((handle->dma.dma_chan), (uint32_t) handle->dma.desc[0]);
  71. #else
  72. esp_intr_enable(handle->dma.dma_chan);
  73. i2s_hal_tx_enable_intr(&(handle->controller->hal));
  74. i2s_hal_tx_enable_dma(&(handle->controller->hal));
  75. i2s_hal_tx_start_link(&(handle->controller->hal), (uint32_t) handle->dma.desc[0]);
  76. #endif
  77. i2s_hal_tx_start(&(handle->controller->hal));
  78. }
  79. static void i2s_rx_channel_start(i2s_chan_handle_t handle)
  80. {
  81. i2s_hal_rx_reset(&(handle->controller->hal));
  82. #if SOC_GDMA_SUPPORTED
  83. gdma_reset(handle->dma.dma_chan);
  84. #else
  85. i2s_hal_rx_reset_dma(&(handle->controller->hal));
  86. #endif
  87. i2s_hal_rx_reset_fifo(&(handle->controller->hal));
  88. #if SOC_GDMA_SUPPORTED
  89. gdma_start(handle->dma.dma_chan, (uint32_t) handle->dma.desc[0]);
  90. #else
  91. esp_intr_enable(handle->dma.dma_chan);
  92. i2s_hal_rx_enable_intr(&(handle->controller->hal));
  93. i2s_hal_rx_enable_dma(&(handle->controller->hal));
  94. i2s_hal_rx_start_link(&(handle->controller->hal), (uint32_t) handle->dma.desc[0]);
  95. #endif
  96. i2s_hal_rx_start(&(handle->controller->hal));
  97. }
  98. static void i2s_tx_channel_stop(i2s_chan_handle_t handle)
  99. {
  100. i2s_hal_tx_stop(&(handle->controller->hal));
  101. #if SOC_GDMA_SUPPORTED
  102. gdma_stop(handle->dma.dma_chan);
  103. #else
  104. i2s_hal_tx_stop_link(&(handle->controller->hal));
  105. i2s_hal_tx_disable_intr(&(handle->controller->hal));
  106. i2s_hal_tx_disable_dma(&(handle->controller->hal));
  107. esp_intr_disable(handle->dma.dma_chan);
  108. #endif
  109. }
  110. static void i2s_rx_channel_stop(i2s_chan_handle_t handle)
  111. {
  112. i2s_hal_rx_stop(&(handle->controller->hal));
  113. #if SOC_GDMA_SUPPORTED
  114. gdma_stop(handle->dma.dma_chan);
  115. #else
  116. i2s_hal_rx_stop_link(&(handle->controller->hal));
  117. i2s_hal_rx_disable_intr(&(handle->controller->hal));
  118. i2s_hal_rx_disable_dma(&(handle->controller->hal));
  119. esp_intr_disable(handle->dma.dma_chan);
  120. #endif
  121. }
  122. static esp_err_t i2s_destroy_controller_obj(i2s_controller_t **i2s_obj)
  123. {
  124. I2S_NULL_POINTER_CHECK(TAG, i2s_obj);
  125. I2S_NULL_POINTER_CHECK(TAG, *i2s_obj);
  126. ESP_RETURN_ON_FALSE(!(*i2s_obj)->rx_chan && !(*i2s_obj)->tx_chan,
  127. ESP_ERR_INVALID_STATE, TAG,
  128. "there still have channels under this i2s controller");
  129. int id = (*i2s_obj)->id;
  130. #if SOC_I2S_HW_VERSION_1
  131. i2s_ll_enable_dma((*i2s_obj)->hal.dev, false);
  132. #endif
  133. free(*i2s_obj);
  134. *i2s_obj = NULL;
  135. return i2s_platform_release_occupation(id);
  136. }
  137. /**
  138. * @brief Acquire i2s controller object
  139. *
  140. * @param id i2s port id
  141. * @param search_reverse reverse the sequence of port acquirement
  142. * set false to acquire from I2S_NUM_0 first
  143. * set true to acquire from SOC_I2S_NUM - 1 first
  144. * @return
  145. * - pointer of acquired i2s controller object
  146. */
  147. static i2s_controller_t *i2s_acquire_controller_obj(int id)
  148. {
  149. if (id < 0 || id >= SOC_I2S_NUM) {
  150. return NULL;
  151. }
  152. /* pre-alloc controller object */
  153. i2s_controller_t *pre_alloc = (i2s_controller_t *)heap_caps_calloc(1, sizeof(i2s_controller_t), I2S_MEM_ALLOC_CAPS);
  154. if (pre_alloc == NULL) {
  155. return NULL;
  156. }
  157. pre_alloc->id = id;
  158. i2s_hal_init(&pre_alloc->hal, id);
  159. pre_alloc->full_duplex = false;
  160. pre_alloc->tx_chan = NULL;
  161. pre_alloc->rx_chan = NULL;
  162. pre_alloc->mclk = I2S_GPIO_UNUSED;
  163. i2s_controller_t *i2s_obj = NULL;
  164. /* Try to occupy this i2s controller */
  165. if (i2s_platform_acquire_occupation(id, "i2s_driver") == ESP_OK) {
  166. portENTER_CRITICAL(&g_i2s.spinlock);
  167. i2s_obj = pre_alloc;
  168. g_i2s.controller[id] = i2s_obj;
  169. portEXIT_CRITICAL(&g_i2s.spinlock);
  170. #if SOC_I2S_SUPPORTS_ADC_DAC
  171. if (id == I2S_NUM_0) {
  172. adc_ll_digi_set_data_source(ADC_I2S_DATA_SRC_IO_SIG);
  173. }
  174. #endif
  175. } else {
  176. free(pre_alloc);
  177. portENTER_CRITICAL(&g_i2s.spinlock);
  178. if (g_i2s.controller[id]) {
  179. i2s_obj = g_i2s.controller[id];
  180. }
  181. portEXIT_CRITICAL(&g_i2s.spinlock);
  182. if (i2s_obj == NULL) {
  183. ESP_LOGE(TAG, "i2s%d might be occupied by other component", id);
  184. }
  185. }
  186. return i2s_obj;
  187. }
  188. static inline bool i2s_take_available_channel(i2s_controller_t *i2s_obj, uint8_t chan_search_mask)
  189. {
  190. bool is_available = false;
  191. #if SOC_I2S_HW_VERSION_1
  192. /* In ESP32 and ESP32-S2, tx channel and rx channel are not totally separated
  193. * Take both two channels in case one channel can affect another
  194. */
  195. chan_search_mask = I2S_DIR_RX | I2S_DIR_TX;
  196. #endif
  197. portENTER_CRITICAL(&g_i2s.spinlock);
  198. if (!(chan_search_mask & i2s_obj->chan_occupancy)) {
  199. i2s_obj->chan_occupancy |= chan_search_mask;
  200. is_available = true;
  201. }
  202. portEXIT_CRITICAL(&g_i2s.spinlock);
  203. return is_available;
  204. }
  205. static esp_err_t i2s_register_channel(i2s_controller_t *i2s_obj, i2s_dir_t dir, uint32_t desc_num)
  206. {
  207. I2S_NULL_POINTER_CHECK(TAG, i2s_obj);
  208. esp_err_t ret = ESP_OK;
  209. i2s_chan_handle_t new_chan = (i2s_chan_handle_t)heap_caps_calloc(1, sizeof(struct i2s_channel_obj_t), I2S_MEM_ALLOC_CAPS);
  210. ESP_RETURN_ON_FALSE(new_chan, ESP_ERR_NO_MEM, TAG, "No memory for new channel");
  211. new_chan->mode = I2S_COMM_MODE_NONE;
  212. new_chan->role = I2S_ROLE_MASTER; // Set default role to master
  213. new_chan->dir = dir;
  214. new_chan->state = I2S_CHAN_STATE_REGISTER;
  215. #if SOC_I2S_SUPPORTS_APLL
  216. new_chan->apll_en = false;
  217. #endif
  218. new_chan->mode_info = NULL;
  219. new_chan->controller = i2s_obj;
  220. #if CONFIG_PM_ENABLE
  221. new_chan->pm_lock = NULL; // Init in i2s_set_clock according to clock source
  222. #endif
  223. new_chan->msg_queue = xQueueCreateWithCaps(desc_num - 1, sizeof(uint8_t *), I2S_MEM_ALLOC_CAPS);
  224. ESP_GOTO_ON_FALSE(new_chan->msg_queue, ESP_ERR_NO_MEM, err, TAG, "No memory for message queue");
  225. new_chan->mutex = xSemaphoreCreateMutexWithCaps(I2S_MEM_ALLOC_CAPS);
  226. ESP_GOTO_ON_FALSE(new_chan->mutex, ESP_ERR_NO_MEM, err, TAG, "No memory for mutex semaphore");
  227. new_chan->binary = xSemaphoreCreateBinaryWithCaps(I2S_MEM_ALLOC_CAPS);
  228. ESP_GOTO_ON_FALSE(new_chan->binary, ESP_ERR_NO_MEM, err, TAG, "No memory for binary semaphore");
  229. new_chan->callbacks.on_recv = NULL;
  230. new_chan->callbacks.on_recv_q_ovf = NULL;
  231. new_chan->callbacks.on_sent = NULL;
  232. new_chan->callbacks.on_send_q_ovf = NULL;
  233. new_chan->dma.rw_pos = 0;
  234. new_chan->dma.curr_ptr = NULL;
  235. new_chan->start = NULL;
  236. new_chan->stop = NULL;
  237. if (dir == I2S_DIR_TX) {
  238. if (i2s_obj->tx_chan) {
  239. i2s_del_channel(i2s_obj->tx_chan);
  240. }
  241. i2s_obj->tx_chan = new_chan;
  242. } else {
  243. if (i2s_obj->rx_chan) {
  244. i2s_del_channel(i2s_obj->rx_chan);
  245. }
  246. i2s_obj->rx_chan = new_chan;
  247. }
  248. return ret;
  249. err:
  250. if (new_chan->msg_queue) {
  251. vQueueDeleteWithCaps(new_chan->msg_queue);
  252. }
  253. if (new_chan->mutex) {
  254. vSemaphoreDeleteWithCaps(new_chan->mutex);
  255. }
  256. if (new_chan->binary) {
  257. vSemaphoreDeleteWithCaps(new_chan->binary);
  258. }
  259. free(new_chan);
  260. return ret;
  261. }
  262. esp_err_t i2s_channel_register_event_callback(i2s_chan_handle_t handle, const i2s_event_callbacks_t *callbacks, void *user_data)
  263. {
  264. I2S_NULL_POINTER_CHECK(TAG, handle);
  265. I2S_NULL_POINTER_CHECK(TAG, callbacks);
  266. esp_err_t ret = ESP_OK;
  267. #if CONFIG_I2S_ISR_IRAM_SAFE
  268. if (callbacks->on_recv) {
  269. ESP_RETURN_ON_FALSE(esp_ptr_in_iram(callbacks->on_recv), ESP_ERR_INVALID_ARG, TAG, "on_recv callback not in IRAM");
  270. }
  271. if (callbacks->on_recv_q_ovf) {
  272. ESP_RETURN_ON_FALSE(esp_ptr_in_iram(callbacks->on_recv_q_ovf), ESP_ERR_INVALID_ARG, TAG, "on_recv_q_ovf callback not in IRAM");
  273. }
  274. if (callbacks->on_sent) {
  275. ESP_RETURN_ON_FALSE(esp_ptr_in_iram(callbacks->on_sent), ESP_ERR_INVALID_ARG, TAG, "on_sent callback not in IRAM");
  276. }
  277. if (callbacks->on_send_q_ovf) {
  278. ESP_RETURN_ON_FALSE(esp_ptr_in_iram(callbacks->on_send_q_ovf), ESP_ERR_INVALID_ARG, TAG, "on_send_q_ovf callback not in IRAM");
  279. }
  280. if (user_data) {
  281. ESP_RETURN_ON_FALSE(esp_ptr_internal(user_data), ESP_ERR_INVALID_ARG, TAG, "user context not in internal RAM");
  282. }
  283. #endif
  284. xSemaphoreTake(handle->mutex, portMAX_DELAY);
  285. ESP_GOTO_ON_FALSE(handle->state < I2S_CHAN_STATE_RUNNING, ESP_ERR_INVALID_STATE, err, TAG, "invalid state, I2S has enabled");
  286. memcpy(&(handle->callbacks), callbacks, sizeof(i2s_event_callbacks_t));
  287. handle->user_data = user_data;
  288. err:
  289. xSemaphoreGive(handle->mutex);
  290. return ret;
  291. }
  292. uint32_t i2s_get_buf_size(i2s_chan_handle_t handle, uint32_t data_bit_width, uint32_t dma_frame_num)
  293. {
  294. uint32_t active_chan = handle->active_slot;
  295. uint32_t bytes_per_sample = ((data_bit_width + 15) / 16) * 2;
  296. uint32_t bytes_per_frame = bytes_per_sample * active_chan;
  297. uint32_t bufsize = dma_frame_num * bytes_per_frame;
  298. /* Limit DMA buffer size if it is out of range (DMA buffer limitation is 4092 bytes) */
  299. if (bufsize > I2S_DMA_BUFFER_MAX_SIZE) {
  300. uint32_t frame_num = I2S_DMA_BUFFER_MAX_SIZE / bytes_per_frame;
  301. bufsize = frame_num * bytes_per_frame;
  302. ESP_LOGW(TAG, "dma frame num is out of dma buffer size, limited to %"PRIu32, frame_num);
  303. }
  304. return bufsize;
  305. }
  306. esp_err_t i2s_free_dma_desc(i2s_chan_handle_t handle)
  307. {
  308. I2S_NULL_POINTER_CHECK(TAG, handle);
  309. if (!handle->dma.desc) {
  310. return ESP_OK;
  311. }
  312. for (int i = 0; i < handle->dma.desc_num; i++) {
  313. if (handle->dma.bufs[i]) {
  314. free(handle->dma.bufs[i]);
  315. }
  316. if (handle->dma.desc[i]) {
  317. free(handle->dma.desc[i]);
  318. }
  319. }
  320. if (handle->dma.bufs) {
  321. free(handle->dma.bufs);
  322. }
  323. if (handle->dma.desc) {
  324. free(handle->dma.desc);
  325. }
  326. handle->dma.desc = NULL;
  327. return ESP_OK;
  328. }
  329. esp_err_t i2s_alloc_dma_desc(i2s_chan_handle_t handle, uint32_t num, uint32_t bufsize)
  330. {
  331. I2S_NULL_POINTER_CHECK(TAG, handle);
  332. esp_err_t ret = ESP_OK;
  333. ESP_RETURN_ON_FALSE(bufsize <= I2S_DMA_BUFFER_MAX_SIZE, ESP_ERR_INVALID_ARG, TAG, "dma buffer can't be bigger than %d", I2S_DMA_BUFFER_MAX_SIZE);
  334. handle->dma.desc_num = num;
  335. handle->dma.buf_size = bufsize;
  336. /* Descriptors must be in the internal RAM */
  337. handle->dma.desc = (lldesc_t **)heap_caps_calloc(num, sizeof(lldesc_t *), I2S_MEM_ALLOC_CAPS);
  338. ESP_GOTO_ON_FALSE(handle->dma.desc, ESP_ERR_NO_MEM, err, TAG, "create I2S DMA decriptor array failed");
  339. handle->dma.bufs = (uint8_t **)heap_caps_calloc(num, sizeof(uint8_t *), I2S_MEM_ALLOC_CAPS);
  340. for (int i = 0; i < num; i++) {
  341. /* Allocate DMA descriptor */
  342. handle->dma.desc[i] = (lldesc_t *) heap_caps_calloc(1, sizeof(lldesc_t), I2S_DMA_ALLOC_CAPS);
  343. ESP_GOTO_ON_FALSE(handle->dma.desc[i], ESP_ERR_NO_MEM, err, TAG, "allocate DMA description failed");
  344. handle->dma.desc[i]->owner = 1;
  345. handle->dma.desc[i]->eof = 1;
  346. handle->dma.desc[i]->sosf = 0;
  347. handle->dma.desc[i]->length = bufsize;
  348. handle->dma.desc[i]->size = bufsize;
  349. handle->dma.desc[i]->offset = 0;
  350. handle->dma.bufs[i] = (uint8_t *) heap_caps_calloc(1, bufsize * sizeof(uint8_t), I2S_DMA_ALLOC_CAPS);
  351. handle->dma.desc[i]->buf = handle->dma.bufs[i];
  352. ESP_GOTO_ON_FALSE(handle->dma.desc[i]->buf, ESP_ERR_NO_MEM, err, TAG, "allocate DMA buffer failed");
  353. ESP_LOGV(TAG, "desc addr: %8p\tbuffer addr:%8p", handle->dma.desc[i], handle->dma.bufs[i]);
  354. }
  355. /* Connect DMA descriptor as a circle */
  356. for (int i = 0; i < num; i++) {
  357. /* Link to the next descriptor */
  358. STAILQ_NEXT(handle->dma.desc[i], qe) = (i < (num - 1)) ? (handle->dma.desc[i + 1]) : handle->dma.desc[0];
  359. }
  360. if (handle->dir == I2S_DIR_RX) {
  361. i2s_ll_rx_set_eof_num(handle->controller->hal.dev, bufsize);
  362. }
  363. ESP_LOGD(TAG, "DMA malloc info: dma_desc_num = %"PRIu32", dma_desc_buf_size = dma_frame_num * slot_num * data_bit_width = %"PRIu32, num, bufsize);
  364. return ESP_OK;
  365. err:
  366. i2s_free_dma_desc(handle);
  367. return ret;
  368. }
  369. #if SOC_I2S_SUPPORTS_APLL
  370. static uint32_t i2s_set_get_apll_freq(uint32_t mclk_freq_hz)
  371. {
  372. /* Calculate the expected APLL */
  373. int mclk_div = (int)((SOC_APLL_MIN_HZ / mclk_freq_hz) + 1);
  374. /* apll_freq = mclk * div
  375. * when div = 1, hardware will still divide 2
  376. * when div = 0, the final mclk will be unpredictable
  377. * So the div here should be at least 2 */
  378. mclk_div = mclk_div < 2 ? 2 : mclk_div;
  379. uint32_t expt_freq = mclk_freq_hz * mclk_div;
  380. if (expt_freq > SOC_APLL_MAX_HZ) {
  381. ESP_LOGE(TAG, "The required APLL frequency exceed its maximum value");
  382. return 0;
  383. }
  384. uint32_t real_freq = 0;
  385. esp_err_t ret = periph_rtc_apll_freq_set(expt_freq, &real_freq);
  386. if (ret == ESP_ERR_INVALID_ARG) {
  387. ESP_LOGE(TAG, "set APLL freq failed due to invalid argument");
  388. return 0;
  389. }
  390. if (ret == ESP_ERR_INVALID_STATE) {
  391. ESP_LOGW(TAG, "APLL is occupied already, it is working at %"PRIu32" Hz while the expected frequency is %"PRIu32" Hz", real_freq, expt_freq);
  392. ESP_LOGW(TAG, "Trying to work at %"PRIu32" Hz...", real_freq);
  393. }
  394. ESP_LOGD(TAG, "APLL expected frequency is %"PRIu32" Hz, real frequency is %"PRIu32" Hz", expt_freq, real_freq);
  395. return real_freq;
  396. }
  397. #endif
  398. // [clk_tree] TODO: replace the following switch table by clk_tree API
  399. uint32_t i2s_get_source_clk_freq(i2s_clock_src_t clk_src, uint32_t mclk_freq_hz)
  400. {
  401. switch (clk_src)
  402. {
  403. #if SOC_I2S_SUPPORTS_APLL
  404. case I2S_CLK_SRC_APLL:
  405. return i2s_set_get_apll_freq(mclk_freq_hz);
  406. #endif
  407. #if SOC_I2S_SUPPORTS_XTAL
  408. case I2S_CLK_SRC_XTAL:
  409. (void)mclk_freq_hz;
  410. return esp_clk_xtal_freq();
  411. #endif
  412. #if SOC_I2S_SUPPORTS_PLL_F160M
  413. case I2S_CLK_SRC_PLL_160M:
  414. (void)mclk_freq_hz;
  415. return I2S_LL_PLL_F160M_CLK_FREQ;
  416. #endif
  417. #if SOC_I2S_SUPPORTS_PLL_F96M
  418. case I2S_CLK_SRC_PLL_96M:
  419. (void)mclk_freq_hz;
  420. return I2S_LL_PLL_F96M_CLK_FREQ;
  421. #endif
  422. #if SOC_I2S_SUPPORTS_PLL_F64M
  423. case I2S_CLK_SRC_PLL_64M:
  424. (void)mclk_freq_hz;
  425. return I2S_LL_PLL_F64M_CLK_FREQ;
  426. #endif
  427. default:
  428. // Invalid clock source
  429. return 0;
  430. }
  431. }
  432. #if SOC_GDMA_SUPPORTED
  433. static bool IRAM_ATTR i2s_dma_rx_callback(gdma_channel_handle_t dma_chan, gdma_event_data_t *event_data, void *user_data)
  434. {
  435. i2s_chan_handle_t handle = (i2s_chan_handle_t)user_data;
  436. BaseType_t need_yield1 = 0;
  437. BaseType_t need_yield2 = 0;
  438. BaseType_t user_need_yield = 0;
  439. lldesc_t *finish_desc;
  440. uint32_t dummy;
  441. finish_desc = (lldesc_t *)event_data->rx_eof_desc_addr;
  442. i2s_event_data_t evt = {
  443. .data = &(finish_desc->buf),
  444. .size = handle->dma.buf_size,
  445. };
  446. if (handle->callbacks.on_recv) {
  447. user_need_yield |= handle->callbacks.on_recv(handle, &evt, handle->user_data);
  448. }
  449. if (xQueueIsQueueFullFromISR(handle->msg_queue)) {
  450. xQueueReceiveFromISR(handle->msg_queue, &dummy, &need_yield1);
  451. if (handle->callbacks.on_recv_q_ovf) {
  452. evt.data = NULL;
  453. user_need_yield |= handle->callbacks.on_recv_q_ovf(handle, &evt, handle->user_data);
  454. }
  455. }
  456. xQueueSendFromISR(handle->msg_queue, &(finish_desc->buf), &need_yield2);
  457. return need_yield1 | need_yield2 | user_need_yield;
  458. }
  459. static bool IRAM_ATTR i2s_dma_tx_callback(gdma_channel_handle_t dma_chan, gdma_event_data_t *event_data, void *user_data)
  460. {
  461. i2s_chan_handle_t handle = (i2s_chan_handle_t)user_data;
  462. BaseType_t need_yield1 = 0;
  463. BaseType_t need_yield2 = 0;
  464. BaseType_t user_need_yield = 0;
  465. lldesc_t *finish_desc;
  466. uint32_t dummy;
  467. finish_desc = (lldesc_t *)(event_data->tx_eof_desc_addr);
  468. i2s_event_data_t evt = {
  469. .data = &(finish_desc->buf),
  470. .size = handle->dma.buf_size,
  471. };
  472. if (handle->callbacks.on_sent) {
  473. user_need_yield |= handle->callbacks.on_sent(handle, &evt, handle->user_data);
  474. }
  475. if (xQueueIsQueueFullFromISR(handle->msg_queue)) {
  476. xQueueReceiveFromISR(handle->msg_queue, &dummy, &need_yield1);
  477. if (handle->callbacks.on_send_q_ovf) {
  478. evt.data = NULL;
  479. user_need_yield |= handle->callbacks.on_send_q_ovf(handle, &evt, handle->user_data);
  480. }
  481. }
  482. if (handle->dma.auto_clear) {
  483. uint8_t *sent_buf = (uint8_t *)finish_desc->buf;
  484. memset(sent_buf, 0, handle->dma.buf_size);
  485. }
  486. xQueueSendFromISR(handle->msg_queue, &(finish_desc->buf), &need_yield2);
  487. return need_yield1 | need_yield2 | user_need_yield;
  488. }
  489. #else
  490. static void IRAM_ATTR i2s_dma_rx_callback(void *arg)
  491. {
  492. BaseType_t need_yield1 = 0;
  493. BaseType_t need_yield2 = 0;
  494. BaseType_t user_need_yield = 0;
  495. lldesc_t *finish_desc = NULL;
  496. i2s_event_data_t evt;
  497. i2s_chan_handle_t handle = (i2s_chan_handle_t)arg;
  498. uint32_t dummy;
  499. uint32_t status = i2s_hal_get_intr_status(&(handle->controller->hal));
  500. i2s_hal_clear_intr_status(&(handle->controller->hal), status);
  501. if (!status) {
  502. return;
  503. }
  504. if (handle && (status & I2S_LL_EVENT_RX_EOF)) {
  505. i2s_hal_get_in_eof_des_addr(&(handle->controller->hal), (uint32_t *)&finish_desc);
  506. evt.data = &(finish_desc->buf);
  507. evt.size = handle->dma.buf_size;
  508. if (handle->callbacks.on_recv) {
  509. user_need_yield |= handle->callbacks.on_recv(handle, &evt, handle->user_data);
  510. }
  511. if (xQueueIsQueueFullFromISR(handle->msg_queue)) {
  512. xQueueReceiveFromISR(handle->msg_queue, &dummy, &need_yield1);
  513. if (handle->callbacks.on_recv_q_ovf) {
  514. evt.data = NULL;
  515. user_need_yield |= handle->callbacks.on_recv_q_ovf(handle, &evt, handle->user_data);
  516. }
  517. }
  518. xQueueSendFromISR(handle->msg_queue, &(finish_desc->buf), &need_yield2);
  519. }
  520. if (need_yield1 || need_yield2 || user_need_yield) {
  521. portYIELD_FROM_ISR();
  522. }
  523. }
  524. static void IRAM_ATTR i2s_dma_tx_callback(void *arg)
  525. {
  526. BaseType_t need_yield1 = 0;
  527. BaseType_t need_yield2 = 0;
  528. BaseType_t user_need_yield = 0;
  529. lldesc_t *finish_desc = NULL;
  530. i2s_event_data_t evt;
  531. i2s_chan_handle_t handle = (i2s_chan_handle_t)arg;
  532. uint32_t dummy;
  533. uint32_t status = i2s_hal_get_intr_status(&(handle->controller->hal));
  534. i2s_hal_clear_intr_status(&(handle->controller->hal), status);
  535. if (!status) {
  536. return;
  537. }
  538. if (handle && (status & I2S_LL_EVENT_TX_EOF)) {
  539. i2s_hal_get_out_eof_des_addr(&(handle->controller->hal), (uint32_t *)&finish_desc);
  540. evt.data = &(finish_desc->buf);
  541. evt.size = handle->dma.buf_size;
  542. if (handle->callbacks.on_sent) {
  543. user_need_yield |= handle->callbacks.on_sent(handle, &evt, handle->user_data);
  544. }
  545. if (xQueueIsQueueFullFromISR(handle->msg_queue)) {
  546. xQueueReceiveFromISR(handle->msg_queue, &dummy, &need_yield1);
  547. if (handle->callbacks.on_send_q_ovf) {
  548. evt.data = NULL;
  549. user_need_yield |= handle->callbacks.on_send_q_ovf(handle, &evt, handle->user_data);
  550. }
  551. }
  552. // Auto clear the dma buffer after data sent
  553. if (handle->dma.auto_clear) {
  554. uint8_t *buff = (uint8_t *)finish_desc->buf;
  555. memset(buff, 0, handle->dma.buf_size);
  556. }
  557. xQueueSendFromISR(handle->msg_queue, &(finish_desc->buf), &need_yield2);
  558. }
  559. if (need_yield1 || need_yield2 || user_need_yield) {
  560. portYIELD_FROM_ISR();
  561. }
  562. }
  563. #endif
  564. /**
  565. * @brief I2S DMA interrupt initialization
  566. * @note I2S will use GDMA if chip supports, and the interrupt is triggered by GDMA.
  567. *
  568. * @param handle I2S channel handle
  569. * @param intr_flag Interrupt allocation flag
  570. * @return
  571. * - ESP_OK I2S DMA interrupt initialize success
  572. * - ESP_ERR_NOT_FOUND GDMA channel not found
  573. * - ESP_ERR_INVALID_ARG Invalid arguments
  574. * - ESP_ERR_INVALID_STATE GDMA state error
  575. */
  576. esp_err_t i2s_init_dma_intr(i2s_chan_handle_t handle, int intr_flag)
  577. {
  578. i2s_port_t port_id = handle->controller->id;
  579. ESP_RETURN_ON_FALSE((port_id >= 0) && (port_id < SOC_I2S_NUM), ESP_ERR_INVALID_ARG, TAG, "invalid handle");
  580. #if SOC_GDMA_SUPPORTED
  581. /* Set GDMA trigger module */
  582. gdma_trigger_t trig = {.periph = GDMA_TRIG_PERIPH_I2S};
  583. switch (port_id) {
  584. #if SOC_I2S_NUM > 1
  585. case I2S_NUM_1:
  586. trig.instance_id = SOC_GDMA_TRIG_PERIPH_I2S1;
  587. break;
  588. #endif
  589. default:
  590. trig.instance_id = SOC_GDMA_TRIG_PERIPH_I2S0;
  591. break;
  592. }
  593. /* Set GDMA config */
  594. gdma_channel_alloc_config_t dma_cfg = {};
  595. if (handle->dir == I2S_DIR_TX) {
  596. dma_cfg.direction = GDMA_CHANNEL_DIRECTION_TX;
  597. /* Register a new GDMA tx channel */
  598. ESP_RETURN_ON_ERROR(gdma_new_channel(&dma_cfg, &handle->dma.dma_chan), TAG, "Register tx dma channel error");
  599. ESP_RETURN_ON_ERROR(gdma_connect(handle->dma.dma_chan, trig), TAG, "Connect tx dma channel error");
  600. gdma_tx_event_callbacks_t cb = {.on_trans_eof = i2s_dma_tx_callback};
  601. /* Set callback function for GDMA, the interrupt is triggered by GDMA, then the GDMA ISR will call the callback function */
  602. gdma_register_tx_event_callbacks(handle->dma.dma_chan, &cb, handle);
  603. } else {
  604. dma_cfg.direction = GDMA_CHANNEL_DIRECTION_RX;
  605. /* Register a new GDMA rx channel */
  606. ESP_RETURN_ON_ERROR(gdma_new_channel(&dma_cfg, &handle->dma.dma_chan), TAG, "Register rx dma channel error");
  607. ESP_RETURN_ON_ERROR(gdma_connect(handle->dma.dma_chan, trig), TAG, "Connect rx dma channel error");
  608. gdma_rx_event_callbacks_t cb = {.on_recv_eof = i2s_dma_rx_callback};
  609. /* Set callback function for GDMA, the interrupt is triggered by GDMA, then the GDMA ISR will call the callback function */
  610. gdma_register_rx_event_callbacks(handle->dma.dma_chan, &cb, handle);
  611. }
  612. #else
  613. intr_flag |= ESP_INTR_FLAG_SHARED;
  614. /* Initialize I2S module interrupt */
  615. if (handle->dir == I2S_DIR_TX) {
  616. esp_intr_alloc_intrstatus(i2s_periph_signal[port_id].irq, intr_flag,
  617. (uint32_t)i2s_ll_get_interrupt_status_reg(handle->controller->hal.dev), I2S_LL_TX_EVENT_MASK,
  618. i2s_dma_tx_callback, handle, &handle->dma.dma_chan);
  619. } else {
  620. esp_intr_alloc_intrstatus(i2s_periph_signal[port_id].irq, intr_flag,
  621. (uint32_t)i2s_ll_get_interrupt_status_reg(handle->controller->hal.dev), I2S_LL_RX_EVENT_MASK,
  622. i2s_dma_rx_callback, handle, &handle->dma.dma_chan);
  623. }
  624. /* Start DMA */
  625. i2s_ll_enable_dma(handle->controller->hal.dev, true);
  626. #endif // SOC_GDMA_SUPPORTED
  627. return ESP_OK;
  628. }
  629. void i2s_gpio_check_and_set(gpio_num_t gpio, uint32_t signal_idx, bool is_input, bool is_invert)
  630. {
  631. /* Ignore the pin if pin = I2S_GPIO_UNUSED */
  632. if (gpio != I2S_GPIO_UNUSED) {
  633. gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[gpio], PIN_FUNC_GPIO);
  634. if (is_input) {
  635. /* Set direction, for some GPIOs, the input function are not enabled as default */
  636. gpio_set_direction(gpio, GPIO_MODE_INPUT);
  637. esp_rom_gpio_connect_in_signal(gpio, signal_idx, is_invert);
  638. } else {
  639. gpio_set_direction(gpio, GPIO_MODE_OUTPUT);
  640. esp_rom_gpio_connect_out_signal(gpio, signal_idx, is_invert, 0);
  641. }
  642. }
  643. }
  644. void i2s_gpio_loopback_set(gpio_num_t gpio, uint32_t out_sig_idx, uint32_t in_sig_idx)
  645. {
  646. if (gpio != I2S_GPIO_UNUSED) {
  647. gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[gpio], PIN_FUNC_GPIO);
  648. gpio_set_direction(gpio, GPIO_MODE_INPUT_OUTPUT);
  649. esp_rom_gpio_connect_out_signal(gpio, out_sig_idx, 0, 0);
  650. esp_rom_gpio_connect_in_signal(gpio, in_sig_idx, 0);
  651. }
  652. }
  653. esp_err_t i2s_check_set_mclk(i2s_port_t id, gpio_num_t gpio_num, bool is_apll, bool is_invert)
  654. {
  655. if (gpio_num == I2S_GPIO_UNUSED) {
  656. return ESP_OK;
  657. }
  658. #if CONFIG_IDF_TARGET_ESP32
  659. ESP_RETURN_ON_FALSE((gpio_num == GPIO_NUM_0 || gpio_num == GPIO_NUM_1 || gpio_num == GPIO_NUM_3),
  660. ESP_ERR_INVALID_ARG, TAG,
  661. "ESP32 only support to set GPIO0/GPIO1/GPIO3 as mclk signal, error GPIO number:%d", gpio_num);
  662. bool is_i2s0 = id == I2S_NUM_0;
  663. if (gpio_num == GPIO_NUM_0) {
  664. gpio_hal_iomux_func_sel(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0_CLK_OUT1);
  665. gpio_ll_iomux_pin_ctrl(is_apll ? 0xFFF6 : (is_i2s0 ? 0xFFF0 : 0xFFFF));
  666. } else if (gpio_num == GPIO_NUM_1) {
  667. gpio_hal_iomux_func_sel(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD_CLK_OUT3);
  668. gpio_ll_iomux_pin_ctrl(is_apll ? 0xF6F6 : (is_i2s0 ? 0xF0F0 : 0xF0FF));
  669. } else {
  670. gpio_hal_iomux_func_sel(PERIPHS_IO_MUX_U0RXD_U, FUNC_U0RXD_CLK_OUT2);
  671. gpio_ll_iomux_pin_ctrl(is_apll ? 0xFF66 : (is_i2s0 ? 0xFF00 : 0xFF0F));
  672. }
  673. #else
  674. ESP_RETURN_ON_FALSE(GPIO_IS_VALID_GPIO(gpio_num), ESP_ERR_INVALID_ARG, TAG, "mck_io_num invalid");
  675. i2s_gpio_check_and_set(gpio_num, i2s_periph_signal[id].mck_out_sig, false, is_invert);
  676. #endif
  677. ESP_LOGD(TAG, "MCLK is pinned to GPIO%d on I2S%d", id, gpio_num);
  678. return ESP_OK;
  679. }
  680. /*---------------------------------------------------------------------------
  681. I2S bus Public APIs
  682. ----------------------------------------------------------------------------
  683. Scope: Public
  684. ----------------------------------------------------------------------------*/
  685. esp_err_t i2s_new_channel(const i2s_chan_config_t *chan_cfg, i2s_chan_handle_t *tx_handle, i2s_chan_handle_t *rx_handle)
  686. {
  687. #if CONFIG_I2S_ENABLE_DEBUG_LOG
  688. esp_log_level_set(TAG, ESP_LOG_DEBUG);
  689. #endif
  690. /* Parameter validity check */
  691. I2S_NULL_POINTER_CHECK(TAG, chan_cfg);
  692. I2S_NULL_POINTER_CHECK(TAG, tx_handle || rx_handle);
  693. ESP_RETURN_ON_FALSE(chan_cfg->id < SOC_I2S_NUM || chan_cfg->id == I2S_NUM_AUTO, ESP_ERR_INVALID_ARG, TAG, "invalid I2S port id");
  694. ESP_RETURN_ON_FALSE(chan_cfg->dma_desc_num >= 2, ESP_ERR_INVALID_ARG, TAG, "there should be at least 2 DMA buffers");
  695. esp_err_t ret = ESP_OK;
  696. i2s_controller_t *i2s_obj = NULL;
  697. i2s_port_t id = chan_cfg->id;
  698. bool channel_found = false;
  699. uint8_t chan_search_mask = 0;
  700. chan_search_mask |= tx_handle ? I2S_DIR_TX : 0;
  701. chan_search_mask |= rx_handle ? I2S_DIR_RX : 0;
  702. /* Channel will be registered to one i2s port automatically if id is I2S_NUM_AUTO
  703. * Otherwise, the channel will be registered to the specific port. */
  704. if (id == I2S_NUM_AUTO) {
  705. for (int i = 0; i < SOC_I2S_NUM && !channel_found; i++) {
  706. i2s_obj = i2s_acquire_controller_obj(i);
  707. if (!i2s_obj) {
  708. continue;
  709. }
  710. channel_found = i2s_take_available_channel(i2s_obj, chan_search_mask);
  711. }
  712. ESP_RETURN_ON_FALSE(i2s_obj, ESP_ERR_NOT_FOUND, TAG, "get i2s object failed");
  713. } else {
  714. i2s_obj = i2s_acquire_controller_obj(id);
  715. ESP_RETURN_ON_FALSE(i2s_obj, ESP_ERR_NOT_FOUND, TAG, "get i2s object failed");
  716. channel_found = i2s_take_available_channel(i2s_obj, chan_search_mask);
  717. }
  718. ESP_GOTO_ON_FALSE(channel_found, ESP_ERR_NOT_FOUND, err, TAG, "no available channel found");
  719. /* Register and specify the tx handle */
  720. if (tx_handle) {
  721. ESP_GOTO_ON_ERROR(i2s_register_channel(i2s_obj, I2S_DIR_TX, chan_cfg->dma_desc_num),
  722. err, TAG, "register I2S tx channel failed");
  723. i2s_obj->tx_chan->role = chan_cfg->role;
  724. i2s_obj->tx_chan->dma.auto_clear = chan_cfg->auto_clear;
  725. i2s_obj->tx_chan->dma.desc_num = chan_cfg->dma_desc_num;
  726. i2s_obj->tx_chan->dma.frame_num = chan_cfg->dma_frame_num;
  727. i2s_obj->tx_chan->start = i2s_tx_channel_start;
  728. i2s_obj->tx_chan->stop = i2s_tx_channel_stop;
  729. *tx_handle = i2s_obj->tx_chan;
  730. ESP_LOGD(TAG, "tx channel is registered on I2S%d successfully", i2s_obj->id);
  731. }
  732. /* Register and specify the rx handle */
  733. if (rx_handle) {
  734. ESP_GOTO_ON_ERROR(i2s_register_channel(i2s_obj, I2S_DIR_RX, chan_cfg->dma_desc_num),
  735. err, TAG, "register I2S rx channel failed");
  736. i2s_obj->rx_chan->role = chan_cfg->role;
  737. i2s_obj->rx_chan->dma.desc_num = chan_cfg->dma_desc_num;
  738. i2s_obj->rx_chan->dma.frame_num = chan_cfg->dma_frame_num;
  739. i2s_obj->rx_chan->start = i2s_rx_channel_start;
  740. i2s_obj->rx_chan->stop = i2s_rx_channel_stop;
  741. *rx_handle = i2s_obj->rx_chan;
  742. ESP_LOGD(TAG, "rx channel is registered on I2S%d successfully", i2s_obj->id);
  743. }
  744. if ((tx_handle != NULL) && (rx_handle != NULL)) {
  745. i2s_obj->full_duplex = true;
  746. }
  747. return ESP_OK;
  748. /* i2s_obj allocated but register channel failed */
  749. err:
  750. /* if the controller object has no channel, find the corresponding global object and destroy it */
  751. if (i2s_obj != NULL && i2s_obj->rx_chan == NULL && i2s_obj->tx_chan == NULL) {
  752. for (int i = 0; i < SOC_I2S_NUM; i++) {
  753. if (i2s_obj == g_i2s.controller[i]) {
  754. i2s_destroy_controller_obj(&g_i2s.controller[i]);
  755. break;
  756. }
  757. }
  758. }
  759. return ret;
  760. }
  761. esp_err_t i2s_del_channel(i2s_chan_handle_t handle)
  762. {
  763. I2S_NULL_POINTER_CHECK(TAG, handle);
  764. ESP_RETURN_ON_FALSE(handle->state < I2S_CHAN_STATE_RUNNING, ESP_ERR_INVALID_STATE, TAG, "the channel can't be deleted unless it is disabled");
  765. i2s_controller_t *i2s_obj = handle->controller;
  766. int __attribute__((unused)) id = i2s_obj->id;
  767. i2s_dir_t __attribute__((unused)) dir = handle->dir;
  768. bool is_bound = true;
  769. #if SOC_I2S_HW_VERSION_2
  770. if (dir == I2S_DIR_TX) {
  771. i2s_ll_tx_disable_clock(handle->controller->hal.dev);
  772. } else {
  773. i2s_ll_rx_disable_clock(handle->controller->hal.dev);
  774. }
  775. #endif
  776. #if SOC_I2S_SUPPORTS_APLL
  777. if (handle->apll_en) {
  778. /* Must switch back to D2CLK on ESP32-S2,
  779. * because the clock of some registers are bound to APLL,
  780. * otherwise, once APLL is disabled, the registers can't be updated anymore */
  781. if (handle->dir == I2S_DIR_TX) {
  782. i2s_ll_tx_clk_set_src(handle->controller->hal.dev, I2S_CLK_SRC_DEFAULT);
  783. } else {
  784. i2s_ll_rx_clk_set_src(handle->controller->hal.dev, I2S_CLK_SRC_DEFAULT);
  785. }
  786. periph_rtc_apll_release();
  787. }
  788. #endif
  789. #if CONFIG_PM_ENABLE
  790. if (handle->pm_lock) {
  791. esp_pm_lock_delete(handle->pm_lock);
  792. }
  793. #endif
  794. if (handle->mode_info) {
  795. free(handle->mode_info);
  796. }
  797. if (handle->dma.desc) {
  798. i2s_free_dma_desc(handle);
  799. }
  800. if (handle->msg_queue) {
  801. vQueueDeleteWithCaps(handle->msg_queue);
  802. }
  803. if (handle->mutex) {
  804. vSemaphoreDeleteWithCaps(handle->mutex);
  805. }
  806. if (handle->binary) {
  807. vSemaphoreDeleteWithCaps(handle->binary);
  808. }
  809. #if SOC_I2S_HW_VERSION_1
  810. i2s_obj->chan_occupancy = 0;
  811. #else
  812. i2s_obj->chan_occupancy &= ~(uint32_t)dir;
  813. #endif
  814. if (handle->dma.dma_chan) {
  815. #if SOC_GDMA_SUPPORTED
  816. gdma_disconnect(handle->dma.dma_chan);
  817. gdma_del_channel(handle->dma.dma_chan);
  818. #else
  819. esp_intr_free(handle->dma.dma_chan);
  820. #endif
  821. }
  822. if (handle == i2s_obj->tx_chan) {
  823. free(i2s_obj->tx_chan);
  824. i2s_obj->tx_chan = NULL;
  825. i2s_obj->full_duplex = false;
  826. } else if (handle == i2s_obj->rx_chan) {
  827. free(i2s_obj->rx_chan);
  828. i2s_obj->rx_chan = NULL;
  829. i2s_obj->full_duplex = false;
  830. } else {
  831. /* Indicate the delete channel is an unbound free channel */
  832. is_bound = false;
  833. free(handle);
  834. }
  835. /* If the delete channel was bound to a controller before,
  836. we need to destroy this controller object if there is no channel any more */
  837. if (is_bound) {
  838. if (!(i2s_obj->tx_chan) && !(i2s_obj->rx_chan)) {
  839. i2s_destroy_controller_obj(&g_i2s.controller[i2s_obj->id]);
  840. }
  841. ESP_LOGD(TAG, "%s channel on I2S%d deleted", dir == I2S_DIR_TX ? "tx" : "rx", id);
  842. }
  843. return ESP_OK;
  844. }
  845. esp_err_t i2s_channel_get_info(i2s_chan_handle_t handle, i2s_chan_info_t *chan_info)
  846. {
  847. I2S_NULL_POINTER_CHECK(TAG, handle);
  848. I2S_NULL_POINTER_CHECK(TAG, chan_info);
  849. /* Find whether the handle is a registered i2s handle or still available */
  850. for (int i = 0; i < SOC_I2S_NUM; i++) {
  851. if (g_i2s.controller[i] != NULL) {
  852. if (g_i2s.controller[i]->tx_chan == handle ||
  853. g_i2s.controller[i]->rx_chan == handle) {
  854. goto found;
  855. }
  856. }
  857. }
  858. return ESP_ERR_NOT_FOUND;
  859. found:
  860. /* Assign the handle information */
  861. xSemaphoreTake(handle->mutex, portMAX_DELAY);
  862. chan_info->id = handle->controller->id;
  863. chan_info->dir = handle->dir;
  864. chan_info->role = handle->role;
  865. chan_info->mode = handle->mode;
  866. if (handle->controller->full_duplex) {
  867. if (handle->dir == I2S_DIR_TX) {
  868. chan_info->pair_chan = handle->controller->rx_chan;
  869. } else {
  870. chan_info->pair_chan = handle->controller->tx_chan;
  871. }
  872. } else {
  873. chan_info->pair_chan = NULL;
  874. }
  875. xSemaphoreGive(handle->mutex);
  876. return ESP_OK;
  877. }
  878. esp_err_t i2s_channel_enable(i2s_chan_handle_t handle)
  879. {
  880. I2S_NULL_POINTER_CHECK(TAG, handle);
  881. esp_err_t ret = ESP_OK;
  882. xSemaphoreTake(handle->mutex, portMAX_DELAY);
  883. ESP_GOTO_ON_FALSE(handle->state == I2S_CHAN_STATE_READY, ESP_ERR_INVALID_STATE, err, TAG, "the channel has already enabled or not initialized");
  884. #if CONFIG_PM_ENABLE
  885. esp_pm_lock_acquire(handle->pm_lock);
  886. #endif
  887. handle->start(handle);
  888. handle->state = I2S_CHAN_STATE_RUNNING;
  889. /* Reset queue */
  890. xQueueReset(handle->msg_queue);
  891. xSemaphoreGive(handle->mutex);
  892. /* Give the binary semaphore to enable reading / writing task */
  893. xSemaphoreGive(handle->binary);
  894. ESP_LOGD(TAG, "i2s %s channel enabled", handle->dir == I2S_DIR_TX ? "tx" : "rx");
  895. return ret;
  896. err:
  897. xSemaphoreGive(handle->mutex);
  898. return ret;
  899. }
  900. esp_err_t i2s_channel_disable(i2s_chan_handle_t handle)
  901. {
  902. I2S_NULL_POINTER_CHECK(TAG, handle);
  903. esp_err_t ret = ESP_OK;
  904. xSemaphoreTake(handle->mutex, portMAX_DELAY);
  905. ESP_GOTO_ON_FALSE(handle->state > I2S_CHAN_STATE_READY, ESP_ERR_INVALID_STATE, err, TAG, "the channel has not been enabled yet");
  906. /* Update the state to force quit the current reading/writing operation */
  907. handle->state = I2S_CHAN_STATE_READY;
  908. /* Waiting for reading/wrinting operation quit
  909. * It should be acquired before assigning the pointer to NULL,
  910. * otherwise may cause NULL pointer panic while reading/writing threads haven't release the lock */
  911. xSemaphoreTake(handle->binary, portMAX_DELAY);
  912. /* Reset the descriptor pointer */
  913. handle->dma.curr_ptr = NULL;
  914. handle->dma.rw_pos = 0;
  915. handle->stop(handle);
  916. #if CONFIG_PM_ENABLE
  917. esp_pm_lock_release(handle->pm_lock);
  918. #endif
  919. xSemaphoreGive(handle->mutex);
  920. ESP_LOGD(TAG, "i2s %s channel disabled", handle->dir == I2S_DIR_TX ? "tx" : "rx");
  921. return ret;
  922. err:
  923. xSemaphoreGive(handle->mutex);
  924. return ret;
  925. }
  926. esp_err_t i2s_channel_preload_data(i2s_chan_handle_t tx_handle, const void *src, size_t size, size_t *bytes_loaded)
  927. {
  928. I2S_NULL_POINTER_CHECK(TAG, tx_handle);
  929. ESP_RETURN_ON_FALSE(tx_handle->dir == I2S_DIR_TX, ESP_ERR_INVALID_ARG, TAG, "this channel is not tx channel");
  930. ESP_RETURN_ON_FALSE(tx_handle->state == I2S_CHAN_STATE_READY, ESP_ERR_INVALID_STATE, TAG, "data can only be preloaded when the channel is READY");
  931. uint8_t *data_ptr = (uint8_t *)src;
  932. size_t remain_bytes = size;
  933. size_t total_loaded_bytes = 0;
  934. xSemaphoreTake(tx_handle->mutex, portMAX_DELAY);
  935. /* The pre-load data will be loaded from the first descriptor */
  936. if (tx_handle->dma.curr_ptr == NULL) {
  937. tx_handle->dma.curr_ptr = tx_handle->dma.desc[0];
  938. tx_handle->dma.rw_pos = 0;
  939. }
  940. lldesc_t *desc_ptr = (lldesc_t *)tx_handle->dma.curr_ptr;
  941. /* Loop until no bytes in source buff remain or the descriptors are full */
  942. while (remain_bytes) {
  943. size_t bytes_can_load = remain_bytes > (tx_handle->dma.buf_size - tx_handle->dma.rw_pos) ?
  944. (tx_handle->dma.buf_size - tx_handle->dma.rw_pos) : remain_bytes;
  945. /* When all the descriptors has loaded data, no more bytes can be loaded, break directly */
  946. if (bytes_can_load == 0) {
  947. break;
  948. }
  949. /* Load the data from the last loaded position */
  950. memcpy((uint8_t *)(desc_ptr->buf + tx_handle->dma.rw_pos), data_ptr, bytes_can_load);
  951. data_ptr += bytes_can_load; // Move forward the data pointer
  952. total_loaded_bytes += bytes_can_load; // Add to the total loaded bytes
  953. remain_bytes -= bytes_can_load; // Update the remaining bytes to be loaded
  954. tx_handle->dma.rw_pos += bytes_can_load; // Move forward the dma buffer position
  955. /* When the current position reach the end of the dma buffer */
  956. if (tx_handle->dma.rw_pos == tx_handle->dma.buf_size) {
  957. /* If the next descriptor is not the first descriptor, keep load to the first descriptor
  958. * otherwise all descriptor has been loaded, break directly, the dma buffer position
  959. * will remain at the end of the last dma buffer */
  960. if (STAILQ_NEXT(desc_ptr, qe) != tx_handle->dma.desc[0]) {
  961. desc_ptr = STAILQ_NEXT(desc_ptr, qe);
  962. tx_handle->dma.curr_ptr = (void *)desc_ptr;
  963. tx_handle->dma.rw_pos = 0;
  964. } else {
  965. break;
  966. }
  967. }
  968. }
  969. *bytes_loaded = total_loaded_bytes;
  970. xSemaphoreGive(tx_handle->mutex);
  971. return ESP_OK;
  972. }
  973. esp_err_t i2s_channel_write(i2s_chan_handle_t handle, const void *src, size_t size, size_t *bytes_written, uint32_t timeout_ms)
  974. {
  975. I2S_NULL_POINTER_CHECK(TAG, handle);
  976. ESP_RETURN_ON_FALSE(handle->dir == I2S_DIR_TX, ESP_ERR_INVALID_ARG, TAG, "this channel is not tx channel");
  977. esp_err_t ret = ESP_OK;
  978. char *data_ptr;
  979. char *src_byte;
  980. size_t bytes_can_write;
  981. if (bytes_written) {
  982. *bytes_written = 0;
  983. }
  984. /* The binary semaphore can only be taken when the channel has been enabled and no other writing operation in progress */
  985. ESP_RETURN_ON_FALSE(xSemaphoreTake(handle->binary, pdMS_TO_TICKS(timeout_ms)) == pdTRUE, ESP_ERR_INVALID_STATE, TAG, "The channel is not enabled");
  986. src_byte = (char *)src;
  987. while (size > 0 && handle->state == I2S_CHAN_STATE_RUNNING) {
  988. if (handle->dma.rw_pos == handle->dma.buf_size || handle->dma.curr_ptr == NULL) {
  989. if (xQueueReceive(handle->msg_queue, &(handle->dma.curr_ptr), pdMS_TO_TICKS(timeout_ms)) == pdFALSE) {
  990. ret = ESP_ERR_TIMEOUT;
  991. break;
  992. }
  993. handle->dma.rw_pos = 0;
  994. }
  995. data_ptr = (char *)handle->dma.curr_ptr;
  996. data_ptr += handle->dma.rw_pos;
  997. bytes_can_write = handle->dma.buf_size - handle->dma.rw_pos;
  998. if (bytes_can_write > size) {
  999. bytes_can_write = size;
  1000. }
  1001. memcpy(data_ptr, src_byte, bytes_can_write);
  1002. size -= bytes_can_write;
  1003. src_byte += bytes_can_write;
  1004. handle->dma.rw_pos += bytes_can_write;
  1005. if (bytes_written) {
  1006. (*bytes_written) += bytes_can_write;
  1007. }
  1008. }
  1009. xSemaphoreGive(handle->binary);
  1010. return ret;
  1011. }
  1012. esp_err_t i2s_channel_read(i2s_chan_handle_t handle, void *dest, size_t size, size_t *bytes_read, uint32_t timeout_ms)
  1013. {
  1014. I2S_NULL_POINTER_CHECK(TAG, handle);
  1015. ESP_RETURN_ON_FALSE(handle->dir == I2S_DIR_RX, ESP_ERR_INVALID_ARG, TAG, "this channel is not rx channel");
  1016. esp_err_t ret = ESP_OK;
  1017. uint8_t *data_ptr;
  1018. uint8_t *dest_byte;
  1019. int bytes_can_read;
  1020. if (bytes_read) {
  1021. *bytes_read = 0;
  1022. }
  1023. dest_byte = (uint8_t *)dest;
  1024. /* The binary semaphore can only be taken when the channel has been enabled and no other reading operation in progress */
  1025. ESP_RETURN_ON_FALSE(xSemaphoreTake(handle->binary, pdMS_TO_TICKS(timeout_ms)) == pdTRUE, ESP_ERR_INVALID_STATE, TAG, "The channel is not enabled");
  1026. while (size > 0 && handle->state == I2S_CHAN_STATE_RUNNING) {
  1027. if (handle->dma.rw_pos == handle->dma.buf_size || handle->dma.curr_ptr == NULL) {
  1028. if (xQueueReceive(handle->msg_queue, &(handle->dma.curr_ptr), pdMS_TO_TICKS(timeout_ms)) == pdFALSE) {
  1029. ret = ESP_ERR_TIMEOUT;
  1030. break;
  1031. }
  1032. handle->dma.rw_pos = 0;
  1033. }
  1034. data_ptr = (uint8_t *)handle->dma.curr_ptr;
  1035. data_ptr += handle->dma.rw_pos;
  1036. bytes_can_read = handle->dma.buf_size - handle->dma.rw_pos;
  1037. if (bytes_can_read > (int)size) {
  1038. bytes_can_read = size;
  1039. }
  1040. memcpy(dest_byte, data_ptr, bytes_can_read);
  1041. size -= bytes_can_read;
  1042. dest_byte += bytes_can_read;
  1043. handle->dma.rw_pos += bytes_can_read;
  1044. if (bytes_read) {
  1045. (*bytes_read) += bytes_can_read;
  1046. }
  1047. }
  1048. xSemaphoreGive(handle->binary);
  1049. return ret;
  1050. }
  1051. /*---------------------------------------------------------------------------
  1052. I2S Platform APIs
  1053. ----------------------------------------------------------------------------
  1054. Scope: This file and ADC/DAC/LCD driver
  1055. ----------------------------------------------------------------------------*/
  1056. esp_err_t i2s_platform_acquire_occupation(int id, const char *comp_name)
  1057. {
  1058. esp_err_t ret = ESP_OK;
  1059. const char *occupied_comp = NULL;
  1060. ESP_RETURN_ON_FALSE(id < SOC_I2S_NUM, ESP_ERR_INVALID_ARG, TAG, "invalid i2s port id");
  1061. portENTER_CRITICAL(&g_i2s.spinlock);
  1062. if ((!g_i2s.controller[id]) && (g_i2s.comp_name[id] == NULL)) {
  1063. g_i2s.comp_name[id] = comp_name;
  1064. /* Enable module clock */
  1065. periph_module_enable(i2s_periph_signal[id].module);
  1066. i2s_ll_enable_clock(I2S_LL_GET_HW(id));
  1067. } else {
  1068. occupied_comp = g_i2s.comp_name[id];
  1069. ret = ESP_ERR_NOT_FOUND;
  1070. }
  1071. portEXIT_CRITICAL(&g_i2s.spinlock);
  1072. if (occupied_comp != NULL) {
  1073. ESP_LOGW(TAG, "i2s controller %d has been occupied by %s", id, occupied_comp);
  1074. }
  1075. return ret;
  1076. }
  1077. esp_err_t i2s_platform_release_occupation(int id)
  1078. {
  1079. esp_err_t ret = ESP_OK;
  1080. ESP_RETURN_ON_FALSE(id < SOC_I2S_NUM, ESP_ERR_INVALID_ARG, TAG, "invalid i2s port id");
  1081. portENTER_CRITICAL(&g_i2s.spinlock);
  1082. if (!g_i2s.controller[id]) {
  1083. g_i2s.comp_name[id] = NULL;
  1084. /* Disable module clock */
  1085. periph_module_disable(i2s_periph_signal[id].module);
  1086. i2s_ll_disable_clock(I2S_LL_GET_HW(id));
  1087. } else {
  1088. ret = ESP_ERR_INVALID_STATE;
  1089. }
  1090. portEXIT_CRITICAL(&g_i2s.spinlock);
  1091. return ret;
  1092. }
  1093. // Only used in `test_i2s_iram.c` to write DMA buffer directly
  1094. size_t inline i2s_platform_get_dma_buffer_offset(void)
  1095. {
  1096. /* Force to transfer address '0' into 'i2s_chan_handle_t' type,
  1097. * then find the corresponding field , the address of this field is the offset of this type */
  1098. return (size_t)&(((i2s_chan_handle_t)0)->dma.bufs);
  1099. }