1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #pragma once
8 
9 #include "esp_types.h"
10 #include "esp_err.h"
11 #include "freertos/FreeRTOS.h"
12 #include "freertos/semphr.h"
13 #include "soc/i2s_periph.h"
14 #include "soc/rtc_periph.h"
15 #include "soc/soc_caps.h"
16 #include "hal/i2s_types.h"
17 #include "driver/periph_ctrl.h"
18 #include "esp_intr_alloc.h"
19 
20 #if SOC_I2S_SUPPORTS_ADC
21 #include "driver/adc.h"
22 #endif
23 
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27 
28 #define I2S_PIN_NO_CHANGE (-1) /*!< Use in i2s_pin_config_t for pins which should not be changed */
29 
30 /**
31  * @brief I2S port number, the max port number is (I2S_NUM_MAX -1).
32  */
33 typedef enum {
34     I2S_NUM_0 = 0,                 /*!< I2S port 0 */
35 #if SOC_I2S_NUM > 1
36     I2S_NUM_1 = 1,                 /*!< I2S port 1 */
37 #endif
38     I2S_NUM_MAX,                   /*!< I2S port max */
39 } i2s_port_t;
40 
41 #if SOC_I2S_SUPPORTS_PCM
42 /**
43  * @brief I2S PCM configuration
44  *
45  */
46 typedef struct {
47     i2s_pcm_compress_t  pcm_type;       /*!< I2S PCM a/u-law decompress or compress type */
48 } i2s_pcm_cfg_t;
49 #endif
50 
51 #if SOC_I2S_SUPPORTS_PDM_TX
52 /**
53  * @brief Default I2S PDM Up-Sampling Rate configuration
54  */
55 #define I2S_PDM_DEFAULT_UPSAMPLE_CONFIG(rate) { \
56         .sample_rate = rate,                    \
57         .fp = 960,                              \
58         .fs = (rate) / 100,                     \
59     }
60 
61 /**
62  * @brief I2S PDM up-sample rate configuration
63  * @note  TX PDM can only be set to the following two upsampling rate configurations:
64  *        1: fp = 960, fs = sample_rate / 100, in this case, Fpdm = 128*48000
65  *        2: fp = 960, fs = 480, in this case, Fpdm = 128*Fpcm = 128*sample_rate
66  *        If the pdm receiver do not care the pdm serial clock, it's recommended set Fpdm = 128*48000.
67  *        Otherwise, the second configuration should be applied.
68  */
69 typedef struct  {
70     int sample_rate;                    /*!< I2S PDM sample rate */
71     int fp;                             /*!< I2S PDM TX upsampling paramater. Normally it should be set to 960 */
72     int fs;                             /*!< I2S PDM TX upsampling paramater. When it is set to 480, the pdm clock frequency Fpdm = 128 * sample_rate, when it is set to sample_rate / 100, Fpdm will be fixed to 128*48000 */
73 } i2s_pdm_tx_upsample_cfg_t;
74 #endif
75 
76 /**
77  * @brief I2S pin number for i2s_set_pin
78  *
79  */
80 typedef struct {
81     int mck_io_num;     /*!< MCK in out pin. Note that ESP32 supports setting MCK on GPIO0/GPIO1/GPIO3 only*/
82     int bck_io_num;     /*!< BCK in out pin*/
83     int ws_io_num;      /*!< WS in out pin*/
84     int data_out_num;   /*!< DATA out pin*/
85     int data_in_num;    /*!< DATA in pin*/
86 } i2s_pin_config_t;
87 
88 /**
89  * @brief I2S driver configuration parameters
90  *
91  */
92 typedef struct {
93 
94     i2s_mode_t              mode;                       /*!< I2S work mode */
95     uint32_t                sample_rate;                /*!< I2S sample rate */
96     i2s_bits_per_sample_t   bits_per_sample;            /*!< I2S sample bits in one channel */
97     i2s_channel_fmt_t       channel_format;             /*!< I2S channel format.*/
98     i2s_comm_format_t       communication_format;       /*!< I2S communication format */
99     int                     intr_alloc_flags;           /*!< Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info */
100     int                     dma_buf_count;              /**< The total number of DMA buffers to receive/transmit data.
101                                                           * A descriptor includes some information such as buffer address,
102                                                           * the address of the next descriptor, and the buffer length.
103                                                           * Since one descriptor points to one buffer, therefore, 'dma_desc_num' can be interpreted as the total number of DMA buffers used to store data from DMA interrupt.
104                                                           * Notice that these buffers are internal to'i2s_read' and descriptors are created automatically inside of the I2S driver.
105                                                           * Users only need to set the buffer number while the length is derived from the parameter described below.
106                                                           */
107     int                     dma_buf_len;                /**< Number of frames in a DMA buffer.
108                                                           *  A frame means the data of all channels in a WS cycle.
109                                                           *  The real_dma_buf_size = dma_buf_len * chan_num * bits_per_chan / 8.
110                                                           *  For example, if two channels in stereo mode (i.e., 'channel_format' is set to 'I2S_CHANNEL_FMT_RIGHT_LEFT') are active,
111                                                           *  and each channel transfers 32 bits (i.e., 'bits_per_sample' is set to 'I2S_BITS_PER_CHAN_32BIT'),
112                                                           *  then the total number of bytes of a frame is 'channel_format' * 'bits_per_sample' = 2 * 32 / 8 = 8 bytes.
113                                                           *  We assume that the current 'dma_buf_len' is 100, then the real length of the DMA buffer is 8 * 100 = 800 bytes.
114                                                           *  Note that the length of an internal real DMA buffer shouldn't be greater than 4092.
115                                                           */
116     bool                    use_apll;                   /*!< I2S using APLL as main I2S clock, enable it to get accurate clock */
117     bool                    tx_desc_auto_clear;         /*!< I2S auto clear tx descriptor if there is underflow condition (helps in avoiding noise in case of data unavailability) */
118     int                     fixed_mclk;                 /*!< I2S using fixed MCLK output. If use_apll = true and fixed_mclk > 0, then the clock output for i2s is fixed and equal to the fixed_mclk value. If fixed_mclk set, mclk_multiple won't take effect */
119     i2s_mclk_multiple_t     mclk_multiple;              /*!< The multiple of I2S master clock(MCLK) to sample rate */
120     i2s_bits_per_chan_t     bits_per_chan;              /*!< I2S total bits in one channel, only take effect when larger than 'bits_per_sample', default '0' means equal to 'bits_per_sample' */
121 
122 #if SOC_I2S_SUPPORTS_TDM
123     i2s_channel_t           chan_mask;                  /*!< I2S active channel bit mask, set value in `i2s_channel_t` to enable specific channel, the bit map of active channel can not exceed (0x1<<total_chan). */
124     uint32_t                total_chan;                 /*!< I2S Total number of channels. If it is smaller than the biggest active channel number, it will be set to this number automatically. */
125     bool                    left_align;                 /*!< Set to enable left alignment */
126     bool                    big_edin;                   /*!< Set to enable big edin */
127     bool                    bit_order_msb;              /*!< Set to enable msb order */
128     bool                    skip_msk;                   /*!< Set to enable skip mask. If it is enabled, only the data of the enabled channels will be sent, otherwise all data stored in DMA TX buffer will be sent */
129 #endif // SOC_I2S_SUPPORTS_TDM
130 
131 } i2s_driver_config_t;
132 
133 typedef i2s_driver_config_t i2s_config_t;       // for backward compatible
134 typedef intr_handle_t i2s_isr_handle_t;         // for backward compatible
135 
136 /**
137  * @brief I2S event queue types
138  *
139  */
140 typedef enum {
141     I2S_EVENT_DMA_ERROR,
142     I2S_EVENT_TX_DONE,     /*!< I2S DMA finish sent 1 buffer*/
143     I2S_EVENT_RX_DONE,     /*!< I2S DMA finish received 1 buffer*/
144     I2S_EVENT_TX_Q_OVF,    /*!< I2S DMA sent queue overflow*/
145     I2S_EVENT_RX_Q_OVF,    /*!< I2S DMA receive queue overflow*/
146     I2S_EVENT_MAX,         /*!< I2S event max index*/
147 } i2s_event_type_t;
148 
149 /**
150  * @brief Event structure used in I2S event queue
151  *
152  */
153 typedef struct {
154     i2s_event_type_t    type;   /*!< I2S event type */
155     size_t              size;   /*!< I2S data size for I2S_DATA event*/
156 } i2s_event_t;
157 
158 /**
159  * @brief Set I2S pin number
160  *
161  * @note
162  * The I2S peripheral output signals can be connected to multiple GPIO pads.
163  * However, the I2S peripheral input signal can only be connected to one GPIO pad.
164  *
165  * @param   i2s_num     I2S port number
166  *
167  * @param   pin         I2S Pin structure, or NULL to set 2-channel 8-bit internal DAC pin configuration (GPIO25 & GPIO26)
168  *
169  * Inside the pin configuration structure, set I2S_PIN_NO_CHANGE for any pin where
170  * the current configuration should not be changed.
171  *
172  * @note if *pin is set as NULL, this function will initialize both of the built-in DAC channels by default.
173  *       if you don't want this to happen and you want to initialize only one of the DAC channels, you can call i2s_set_dac_mode instead.
174  *
175  * @return
176  *     - ESP_OK              Success
177  *     - ESP_ERR_INVALID_ARG Parameter error
178  *     - ESP_FAIL            IO error
179  */
180 esp_err_t i2s_set_pin(i2s_port_t i2s_num, const i2s_pin_config_t *pin);
181 
182 #if SOC_I2S_SUPPORTS_PDM_RX
183 /**
184  * @brief Set PDM mode down-sample rate
185  *        In PDM RX mode, there would be 2 rounds of downsample process in hardware.
186  *        In the first downsample process, the sampling number can be 16 or 8.
187  *        In the second downsample process, the sampling number is fixed as 8.
188  *        So the clock frequency in PDM RX mode would be (fpcm * 64) or (fpcm * 128) accordingly.
189  * @param i2s_num I2S port number
190  * @param downsample i2s RX down sample rate for PDM mode.
191  *
192  * @note After calling this function, it would call i2s_set_clk inside to update the clock frequency.
193  *       Please call this function after I2S driver has been initialized.
194  *
195  * @return
196  *     - ESP_OK Success
197  *     - ESP_ERR_INVALID_ARG Parameter error
198  *     - ESP_ERR_NO_MEM      Out of memory
199  */
200 esp_err_t i2s_set_pdm_rx_down_sample(i2s_port_t i2s_num, i2s_pdm_dsr_t downsample);
201 #endif
202 
203 #if SOC_I2S_SUPPORTS_PDM_TX
204 /**
205  * @brief Set TX PDM mode up-sample rate
206  * @note  If you have set PDM mode while calling 'i2s_driver_install',
207  *        default PDM TX upsample parameters have already been set,
208  *        no need to call this function again if you don't have to change the default configuration
209  *
210  * @param i2s_num I2S port number
211  * @param upsample_cfg Set I2S PDM up-sample rate configuration
212  *
213  * @return
214  *     - ESP_OK              Success
215  *     - ESP_ERR_INVALID_ARG Parameter error
216  *     - ESP_ERR_NO_MEM      Out of memory
217  */
218 esp_err_t i2s_set_pdm_tx_up_sample(i2s_port_t i2s_num, const i2s_pdm_tx_upsample_cfg_t *upsample_cfg);
219 #endif
220 
221 /**
222  * @brief Install and start I2S driver.
223  *
224  * @param i2s_num         I2S port number
225  *
226  * @param i2s_config      I2S configurations - see i2s_config_t struct
227  *
228  * @param queue_size      I2S event queue size/depth.
229  *
230  * @param i2s_queue       I2S event queue handle, if set NULL, driver will not use an event queue.
231  *
232  * This function must be called before any I2S driver read/write operations.
233  *
234  * @return
235  *     - ESP_OK              Success
236  *     - ESP_ERR_INVALID_ARG Parameter error
237  *     - ESP_ERR_NO_MEM      Out of memory
238  *     - ESP_ERR_INVALID_STATE  Current I2S port is in use
239  */
240 esp_err_t i2s_driver_install(i2s_port_t i2s_num, const i2s_config_t *i2s_config, int queue_size, void *i2s_queue);
241 
242 /**
243  * @brief Uninstall I2S driver.
244  *
245  * @param i2s_num  I2S port number
246  *
247  * @return
248  *     - ESP_OK              Success
249  *     - ESP_ERR_INVALID_ARG Parameter error
250  *     - ESP_ERR_INVALID_STATE I2S port has been uninstalled by others (e.g. LCD i80)
251  */
252 esp_err_t i2s_driver_uninstall(i2s_port_t i2s_num);
253 
254 /**
255  * @brief Write data to I2S DMA transmit buffer.
256  *
257  * @param i2s_num             I2S port number
258  *
259  * @param src                 Source address to write from
260  *
261  * @param size                Size of data in bytes
262  *
263  * @param[out] bytes_written  Number of bytes written, if timeout, the result will be less than the size passed in.
264  *
265  * @param ticks_to_wait       TX buffer wait timeout in RTOS ticks. If this
266  * many ticks pass without space becoming available in the DMA
267  * transmit buffer, then the function will return (note that if the
268  * data is written to the DMA buffer in pieces, the overall operation
269  * may still take longer than this timeout.) Pass portMAX_DELAY for no
270  * timeout.
271  *
272  * @return
273  *     - ESP_OK               Success
274  *     - ESP_ERR_INVALID_ARG  Parameter error
275  */
276 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);
277 
278 /**
279  * @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.
280  *
281  * @param i2s_num             I2S port number
282  *
283  * @param src                 Source address to write from
284  *
285  * @param size                Size of data in bytes
286  *
287  * @param src_bits            Source audio bit
288  *
289  * @param aim_bits            Bit wanted, no more than 32, and must be greater than src_bits
290  *
291  * @param[out] bytes_written  Number of bytes written, if timeout, the result will be less than the size passed in.
292  *
293  * @param ticks_to_wait       TX buffer wait timeout in RTOS ticks. If this
294  * many ticks pass without space becoming available in the DMA
295  * transmit buffer, then the function will return (note that if the
296  * data is written to the DMA buffer in pieces, the overall operation
297  * may still take longer than this timeout.) Pass portMAX_DELAY for no
298  * timeout.
299  *
300  * Format of the data in source buffer is determined by the I2S
301  * configuration (see i2s_config_t).
302  *
303  * @return
304  *     - ESP_OK              Success
305  *     - ESP_ERR_INVALID_ARG Parameter error
306  */
307 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);
308 
309 /**
310  * @brief Read data from I2S DMA receive buffer
311  *
312  * @param i2s_num         I2S port number
313  *
314  * @param dest            Destination address to read into
315  *
316  * @param size            Size of data in bytes
317  *
318  * @param[out] bytes_read Number of bytes read, if timeout, bytes read will be less than the size passed in.
319  *
320  * @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.
321  *
322  * @note If the built-in ADC mode is enabled, we should call i2s_adc_enable and i2s_adc_disable around the whole reading process,
323  *       to prevent the data getting corrupted.
324  *
325  * @return
326  *     - ESP_OK               Success
327  *     - ESP_ERR_INVALID_ARG  Parameter error
328  */
329 esp_err_t i2s_read(i2s_port_t i2s_num, void *dest, size_t size, size_t *bytes_read, TickType_t ticks_to_wait);
330 
331 /**
332  * @brief Set sample rate used for I2S RX and TX.
333  *
334  * The bit clock rate is determined by the sample rate and i2s_config_t configuration parameters (number of channels, bits_per_sample).
335  *
336  * `bit_clock = rate * (number of channels) * bits_per_sample`
337  *
338  * @param i2s_num  I2S port number
339  *
340  * @param rate I2S sample rate (ex: 8000, 44100...)
341  *
342  * @return
343  *     - ESP_OK              Success
344  *     - ESP_ERR_INVALID_ARG Parameter error
345  *     - ESP_ERR_NO_MEM      Out of memory
346  */
347 esp_err_t i2s_set_sample_rates(i2s_port_t i2s_num, uint32_t rate);
348 
349 /**
350  * @brief Stop I2S driver
351  *
352  * There is no need to call i2s_stop() before calling i2s_driver_uninstall().
353  *
354  * Disables I2S TX/RX, until i2s_start() is called.
355  *
356  * @param i2s_num  I2S port number
357  *
358  * @return
359  *     - ESP_OK              Success
360  *     - ESP_ERR_INVALID_ARG Parameter error
361  */
362 esp_err_t i2s_stop(i2s_port_t i2s_num);
363 
364 /**
365  * @brief Start I2S driver
366  *
367  * 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().
368  *
369  *
370  * @param i2s_num  I2S port number
371  *
372  * @return
373  *     - ESP_OK              Success
374  *     - ESP_ERR_INVALID_ARG Parameter error
375  */
376 esp_err_t i2s_start(i2s_port_t i2s_num);
377 
378 /**
379  * @brief Zero the contents of the TX DMA buffer.
380  *
381  * Pushes zero-byte samples into the TX DMA buffer, until it is full.
382  *
383  * @param i2s_num  I2S port number
384  *
385  * @return
386  *     - ESP_OK              Success
387  *     - ESP_ERR_INVALID_ARG Parameter error
388  */
389 esp_err_t i2s_zero_dma_buffer(i2s_port_t i2s_num);
390 
391 #if SOC_I2S_SUPPORTS_PCM
392 /**
393  * @brief Configure I2S a/u-law decompress or compress
394  *
395  * @note  This function should be called after i2s driver installed
396  *        Only take effecttive when the i2s 'communication_format' is set to 'I2S_COMM_FORMAT_STAND_PCM_SHORT' or 'I2S_COMM_FORMAT_STAND_PCM_LONG'
397  *
398  * @param i2s_num  I2S port number
399  *
400  * @param pcm_cfg  including mode selection and a/u-law decompress or compress configuration paramater
401  *
402  * @return
403  *     - ESP_OK              Success
404  *     - ESP_ERR_INVALID_ARG Parameter error
405  */
406 esp_err_t i2s_pcm_config(i2s_port_t i2s_num, const i2s_pcm_cfg_t *pcm_cfg);
407 #endif
408 
409 /**
410  * @brief Set clock & bit width used for I2S RX and TX.
411  *
412  * Similar to i2s_set_sample_rates(), but also sets bit width.
413  *
414  * 1. stop i2s;
415  * 2. calculate mclk, bck, bck_factor
416  * 3. malloc dma buffer;
417  * 4. start i2s
418  *
419  * @param i2s_num  I2S port number
420  *
421  * @param rate I2S sample rate (ex: 8000, 44100...)
422  *
423  * @param bits_cfg I2S bits configuration
424  *             the low 16 bits is for data bits per sample in one channel (see 'i2s_bits_per_sample_t')
425  *             the high 16 bits is for total bits in one channel (see 'i2s_bits_per_chan_t')
426  *             high 16bits =0 means same as the bits per sample.
427  *
428  * @param ch I2S channel, (I2S_CHANNEL_MONO, I2S_CHANNEL_STEREO or specific channel in TDM mode)
429  *
430  * @return
431  *     - ESP_OK              Success
432  *     - ESP_ERR_INVALID_ARG Parameter error
433  *     - ESP_ERR_NO_MEM      Out of memory
434  */
435 esp_err_t i2s_set_clk(i2s_port_t i2s_num, uint32_t rate, uint32_t bits_cfg, i2s_channel_t ch);
436 
437 /**
438  * @brief get clock set on particular port number.
439  *
440  * @param i2s_num  I2S port number
441  *
442  * @return
443  *     - actual clock set by i2s driver
444  */
445 float i2s_get_clk(i2s_port_t i2s_num);
446 
447 #if SOC_I2S_SUPPORTS_ADC
448 /**
449  * @brief Set built-in ADC mode for I2S DMA, this function will initialize ADC pad,
450  *        and set ADC parameters.
451  * @note  In this mode, the ADC maximum sampling rate is 150KHz. Set the sampling rate through ``i2s_config_t``.
452  * @param adc_unit    SAR ADC unit index
453  * @param adc_channel ADC channel index
454  * @return
455  *     - ESP_OK              Success
456  *     - ESP_ERR_INVALID_ARG Parameter error
457  */
458 esp_err_t i2s_set_adc_mode(adc_unit_t adc_unit, adc1_channel_t adc_channel);
459 
460 /**
461  * @brief Start to use I2S built-in ADC mode
462  * @note This function would acquire the lock of ADC to prevent the data getting corrupted
463  *       during the I2S peripheral is being used to do fully continuous ADC sampling.
464  *
465  * @param i2s_num i2s port index
466  * @return
467  *     - ESP_OK                Success
468  *     - ESP_ERR_INVALID_ARG   Parameter error
469  *     - ESP_ERR_INVALID_STATE Driver state error
470  */
471 esp_err_t i2s_adc_enable(i2s_port_t i2s_num);
472 
473 /**
474  * @brief Stop to use I2S built-in ADC mode
475  * @param i2s_num i2s port index
476  * @note This function would release the lock of ADC so that other tasks can use ADC.
477  * @return
478  *     - ESP_OK                 Success
479  *     - ESP_ERR_INVALID_ARG    Parameter error
480  *     - ESP_ERR_INVALID_STATE  Driver state error
481  */
482 esp_err_t i2s_adc_disable(i2s_port_t i2s_num);
483 #endif // SOC_I2S_SUPPORTS_ADC
484 
485 #if SOC_I2S_SUPPORTS_DAC
486 /**
487  * @brief Set I2S dac mode, I2S built-in DAC is disabled by default
488  *
489  * @param dac_mode DAC mode configurations - see i2s_dac_mode_t
490  *
491  * @note Built-in DAC functions are only supported on I2S0 for current ESP32 chip.
492  *       If either of the built-in DAC channel are enabled, the other one can not
493  *       be used as RTC DAC function at the same time.
494  *
495  * @return
496  *     - ESP_OK               Success
497  *     - ESP_ERR_INVALID_ARG  Parameter error
498  */
499 esp_err_t i2s_set_dac_mode(i2s_dac_mode_t dac_mode);
500 #endif //SOC_I2S_SUPPORTS_DAC
501 
502 
503 #ifdef __cplusplus
504 }
505 #endif
506