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