esp_hal/i2s/
master.rs

1//! # Inter-IC Sound (I2S)
2//!
3//! ## Overview
4//!
5//! I2S (Inter-IC Sound) is a synchronous serial communication protocol usually
6//! used for transmitting audio data between two digital audio devices.
7//! Espressif devices may contain more than one I2S peripheral(s). These
8//! peripherals can be configured to input and output sample data via the I2S
9//! driver.
10//!
11//! ## Configuration
12//!
13//! I2S supports different data formats, including varying data and channel
14//! widths, different standards, such as the Philips standard and configurable
15//! pin mappings for I2S clock (BCLK), word select (WS), and data input/output
16//! (DOUT/DIN).
17//!
18//! The driver uses DMA (Direct Memory Access) for efficient data transfer and
19//! supports various configurations, such as different data formats, standards
20//! (e.g., Philips) and pin configurations. It relies on other peripheral
21//! modules, such as
22//!   - `GPIO`
23//!   - `DMA`
24//!   - `system` (to configure and enable the I2S peripheral)
25//!
26//! ## Examples
27//!
28//! ### I2S Read
29//!
30//! ```rust, no_run
31#![doc = crate::before_snippet!()]
32//! # use esp_hal::i2s::master::{I2s, Standard, DataFormat};
33//! # use esp_hal::dma_buffers;
34#![cfg_attr(any(esp32, esp32s2), doc = "let dma_channel = peripherals.DMA_I2S0;")]
35#![cfg_attr(
36    not(any(esp32, esp32s2)),
37    doc = "let dma_channel = peripherals.DMA_CH0;"
38)]
39//! let (mut rx_buffer, rx_descriptors, _, _) = dma_buffers!(4 * 4092, 0);
40//!
41//! let i2s = I2s::new(
42//!     peripherals.I2S0,
43//!     Standard::Philips,
44//!     DataFormat::Data16Channel16,
45//!     Rate::from_hz(44100),
46//!     dma_channel,
47//! );
48#![cfg_attr(not(esp32), doc = "let i2s = i2s.with_mclk(peripherals.GPIO0);")]
49//! let mut i2s_rx = i2s.i2s_rx
50//!     .with_bclk(peripherals.GPIO1)
51//!     .with_ws(peripherals.GPIO2)
52//!     .with_din(peripherals.GPIO5)
53//!     .build(rx_descriptors);
54//!
55//! let mut transfer = i2s_rx.read_dma_circular(&mut rx_buffer)?;
56//!
57//! loop {
58//!     let avail = transfer.available()?;
59//!
60//!     if avail > 0 {
61//!         let mut rcv = [0u8; 5000];
62//!         transfer.pop(&mut rcv[..avail])?;
63//!     }
64//! }
65//! # }
66//! ```
67//! 
68//! ## Implementation State
69//!
70//! - Only TDM Philips standard is supported.
71
72use enumset::{EnumSet, EnumSetType};
73use private::*;
74
75use crate::{
76    Async,
77    Blocking,
78    DriverMode,
79    dma::{
80        Channel,
81        ChannelRx,
82        ChannelTx,
83        DescriptorChain,
84        DmaChannelFor,
85        DmaEligible,
86        DmaError,
87        DmaTransferRx,
88        DmaTransferRxCircular,
89        DmaTransferTx,
90        DmaTransferTxCircular,
91        PeripheralRxChannel,
92        PeripheralTxChannel,
93        ReadBuffer,
94        WriteBuffer,
95        dma_private::{DmaSupport, DmaSupportRx, DmaSupportTx},
96    },
97    gpio::{OutputConfig, interconnect::PeripheralOutput},
98    i2s::AnyI2s,
99    interrupt::{InterruptConfigurable, InterruptHandler},
100    system::PeripheralGuard,
101    time::Rate,
102};
103
104#[derive(Debug, EnumSetType)]
105#[cfg_attr(feature = "defmt", derive(defmt::Format))]
106/// Represents the various interrupt types for the I2S peripheral.
107pub enum I2sInterrupt {
108    /// Receive buffer hung, indicating a stall in data reception.
109    RxHung,
110    /// Transmit buffer hung, indicating a stall in data transmission.
111    TxHung,
112    #[cfg(not(any(esp32, esp32s2)))]
113    /// Reception of data is complete.
114    RxDone,
115    #[cfg(not(any(esp32, esp32s2)))]
116    /// Transmission of data is complete.
117    TxDone,
118}
119
120#[cfg(any(esp32, esp32s2, esp32s3))]
121pub(crate) const I2S_LL_MCLK_DIVIDER_BIT_WIDTH: usize = 6;
122
123#[cfg(any(esp32c3, esp32c6, esp32h2))]
124pub(crate) const I2S_LL_MCLK_DIVIDER_BIT_WIDTH: usize = 9;
125
126pub(crate) const I2S_LL_MCLK_DIVIDER_MAX: usize = (1 << I2S_LL_MCLK_DIVIDER_BIT_WIDTH) - 1;
127
128/// Data types that the I2S peripheral can work with.
129pub trait AcceptedWord: crate::private::Sealed {}
130impl AcceptedWord for u8 {}
131impl AcceptedWord for u16 {}
132impl AcceptedWord for u32 {}
133impl AcceptedWord for i8 {}
134impl AcceptedWord for i16 {}
135impl AcceptedWord for i32 {}
136
137/// I2S Error
138#[derive(Debug, Clone, Copy, PartialEq)]
139#[cfg_attr(feature = "defmt", derive(defmt::Format))]
140#[allow(clippy::enum_variant_names, reason = "peripheral is unstable")]
141pub enum Error {
142    /// An unspecified or unknown error occurred during an I2S operation.
143    Unknown,
144    /// A DMA-related error occurred during I2S operations.
145    DmaError(DmaError),
146    /// An illegal or invalid argument was passed to an I2S function or method.
147    IllegalArgument,
148}
149
150impl From<DmaError> for Error {
151    fn from(value: DmaError) -> Self {
152        Error::DmaError(value)
153    }
154}
155
156/// Supported standards.
157#[derive(Debug, Clone, Copy, PartialEq)]
158#[cfg_attr(feature = "defmt", derive(defmt::Format))]
159pub enum Standard {
160    /// The Philips I2S standard.
161    Philips,
162    // Tdm,
163    // Pdm,
164}
165
166/// Supported data formats
167#[derive(Debug, Clone, Copy, PartialEq)]
168#[cfg_attr(feature = "defmt", derive(defmt::Format))]
169#[cfg(not(any(esp32, esp32s2)))]
170pub enum DataFormat {
171    /// 32-bit data width and 32-bit channel width.
172    Data32Channel32,
173    /// 32-bit data width and 24-bit channel width.
174    Data32Channel24,
175    /// 32-bit data width and 16-bit channel width.
176    Data32Channel16,
177    /// 32-bit data width and 8-bit channel width.
178    Data32Channel8,
179    /// 16-bit data width and 16-bit channel width.
180    Data16Channel16,
181    /// 16-bit data width and 8-bit channel width.
182    Data16Channel8,
183    /// 8-bit data width and 8-bit channel width.
184    Data8Channel8,
185}
186
187/// Supported data formats
188#[derive(Debug, Clone, Copy, PartialEq)]
189#[cfg_attr(feature = "defmt", derive(defmt::Format))]
190#[cfg(any(esp32, esp32s2))]
191pub enum DataFormat {
192    /// 32-bit data width and 32-bit channel width.
193    Data32Channel32,
194    /// 16-bit data width and 16-bit channel width.
195    Data16Channel16,
196}
197
198#[cfg(not(any(esp32, esp32s2)))]
199impl DataFormat {
200    /// Returns the number of data bits for the selected data format.
201    pub fn data_bits(&self) -> u8 {
202        match self {
203            DataFormat::Data32Channel32 => 32,
204            DataFormat::Data32Channel24 => 32,
205            DataFormat::Data32Channel16 => 32,
206            DataFormat::Data32Channel8 => 32,
207            DataFormat::Data16Channel16 => 16,
208            DataFormat::Data16Channel8 => 16,
209            DataFormat::Data8Channel8 => 8,
210        }
211    }
212
213    /// Returns the number of channel bits for the selected data format.
214    pub fn channel_bits(&self) -> u8 {
215        match self {
216            DataFormat::Data32Channel32 => 32,
217            DataFormat::Data32Channel24 => 24,
218            DataFormat::Data32Channel16 => 16,
219            DataFormat::Data32Channel8 => 8,
220            DataFormat::Data16Channel16 => 16,
221            DataFormat::Data16Channel8 => 8,
222            DataFormat::Data8Channel8 => 8,
223        }
224    }
225}
226
227#[cfg(any(esp32, esp32s2))]
228impl DataFormat {
229    /// Returns the number of data bits for the selected data format.
230    pub fn data_bits(&self) -> u8 {
231        match self {
232            DataFormat::Data32Channel32 => 32,
233            DataFormat::Data16Channel16 => 16,
234        }
235    }
236
237    /// Returns the number of channel bits for the selected data format.
238    pub fn channel_bits(&self) -> u8 {
239        match self {
240            DataFormat::Data32Channel32 => 32,
241            DataFormat::Data16Channel16 => 16,
242        }
243    }
244}
245
246/// Instance of the I2S peripheral driver
247#[non_exhaustive]
248pub struct I2s<'d, Dm>
249where
250    Dm: DriverMode,
251{
252    /// Handles the reception (RX) side of the I2S peripheral.
253    pub i2s_rx: RxCreator<'d, Dm>,
254    /// Handles the transmission (TX) side of the I2S peripheral.
255    pub i2s_tx: TxCreator<'d, Dm>,
256}
257
258impl<Dm> I2s<'_, Dm>
259where
260    Dm: DriverMode,
261{
262    #[cfg_attr(
263        not(multi_core),
264        doc = "Registers an interrupt handler for the peripheral."
265    )]
266    #[cfg_attr(
267        multi_core,
268        doc = "Registers an interrupt handler for the peripheral on the current core."
269    )]
270    #[doc = ""]
271    /// Note that this will replace any previously registered interrupt
272    /// handlers.
273    ///
274    /// You can restore the default/unhandled interrupt handler by using
275    /// [crate::interrupt::DEFAULT_INTERRUPT_HANDLER]
276    #[instability::unstable]
277    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
278        // tx.i2s and rx.i2s is the same, we could use either one
279        self.i2s_tx.i2s.set_interrupt_handler(handler);
280    }
281
282    /// Listen for the given interrupts
283    #[instability::unstable]
284    pub fn listen(&mut self, interrupts: impl Into<EnumSet<I2sInterrupt>>) {
285        // tx.i2s and rx.i2s is the same, we could use either one
286        self.i2s_tx.i2s.enable_listen(interrupts.into(), true);
287    }
288
289    /// Unlisten the given interrupts
290    #[instability::unstable]
291    pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<I2sInterrupt>>) {
292        // tx.i2s and rx.i2s is the same, we could use either one
293        self.i2s_tx.i2s.enable_listen(interrupts.into(), false);
294    }
295
296    /// Gets asserted interrupts
297    #[instability::unstable]
298    pub fn interrupts(&mut self) -> EnumSet<I2sInterrupt> {
299        // tx.i2s and rx.i2s is the same, we could use either one
300        self.i2s_tx.i2s.interrupts()
301    }
302
303    /// Resets asserted interrupts
304    #[instability::unstable]
305    pub fn clear_interrupts(&mut self, interrupts: impl Into<EnumSet<I2sInterrupt>>) {
306        // tx.i2s and rx.i2s is the same, we could use either one
307        self.i2s_tx.i2s.clear_interrupts(interrupts.into());
308    }
309}
310
311impl<Dm> crate::private::Sealed for I2s<'_, Dm> where Dm: DriverMode {}
312
313impl<Dm> InterruptConfigurable for I2s<'_, Dm>
314where
315    Dm: DriverMode,
316{
317    fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) {
318        I2s::set_interrupt_handler(self, handler);
319    }
320}
321
322impl<'d> I2s<'d, Blocking> {
323    /// Construct a new I2S peripheral driver instance for the first I2S
324    /// peripheral
325    #[allow(clippy::too_many_arguments)]
326    pub fn new(
327        i2s: impl Instance + 'd,
328        standard: Standard,
329        data_format: DataFormat,
330        sample_rate: Rate,
331        channel: impl DmaChannelFor<AnyI2s<'d>>,
332    ) -> Self {
333        let channel = Channel::new(channel.degrade());
334        channel.runtime_ensure_compatible(&i2s);
335
336        let i2s = i2s.degrade();
337
338        // on ESP32-C3 / ESP32-S3 and later RX and TX are independent and
339        // could be configured totally independently but for now handle all
340        // the targets the same and force same configuration for both, TX and RX
341
342        // make sure the peripheral is enabled before configuring it
343        let peripheral = i2s.peripheral();
344        let rx_guard = PeripheralGuard::new(peripheral);
345        let tx_guard = PeripheralGuard::new(peripheral);
346
347        i2s.set_clock(calculate_clock(sample_rate, 2, data_format.channel_bits()));
348        i2s.configure(&standard, &data_format);
349        i2s.set_master();
350        i2s.update();
351
352        Self {
353            i2s_rx: RxCreator {
354                i2s: unsafe { i2s.clone_unchecked() },
355                rx_channel: channel.rx,
356                guard: rx_guard,
357            },
358            i2s_tx: TxCreator {
359                i2s,
360                tx_channel: channel.tx,
361                guard: tx_guard,
362            },
363        }
364    }
365
366    /// Converts the I2S instance into async mode.
367    pub fn into_async(self) -> I2s<'d, Async> {
368        I2s {
369            i2s_rx: RxCreator {
370                i2s: self.i2s_rx.i2s,
371                rx_channel: self.i2s_rx.rx_channel.into_async(),
372                guard: self.i2s_rx.guard,
373            },
374            i2s_tx: TxCreator {
375                i2s: self.i2s_tx.i2s,
376                tx_channel: self.i2s_tx.tx_channel.into_async(),
377                guard: self.i2s_tx.guard,
378            },
379        }
380    }
381}
382
383impl<'d, Dm> I2s<'d, Dm>
384where
385    Dm: DriverMode,
386{
387    /// Configures the I2S peripheral to use a master clock (MCLK) output pin.
388    pub fn with_mclk(self, mclk: impl PeripheralOutput<'d>) -> Self {
389        let mclk = mclk.into();
390
391        mclk.apply_output_config(&OutputConfig::default());
392        mclk.set_output_enable(true);
393
394        self.i2s_tx.i2s.mclk_signal().connect_to(&mclk);
395
396        self
397    }
398}
399
400/// I2S TX channel
401pub struct I2sTx<'d, Dm>
402where
403    Dm: DriverMode,
404{
405    i2s: AnyI2s<'d>,
406    tx_channel: ChannelTx<Dm, PeripheralTxChannel<AnyI2s<'d>>>,
407    tx_chain: DescriptorChain,
408    _guard: PeripheralGuard,
409}
410
411impl<Dm> core::fmt::Debug for I2sTx<'_, Dm>
412where
413    Dm: DriverMode,
414{
415    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
416        f.debug_struct("I2sTx").finish()
417    }
418}
419
420impl<Dm> DmaSupport for I2sTx<'_, Dm>
421where
422    Dm: DriverMode,
423{
424    type DriverMode = Dm;
425
426    fn peripheral_wait_dma(&mut self, _is_rx: bool, _is_tx: bool) {
427        self.i2s.wait_for_tx_done();
428    }
429
430    fn peripheral_dma_stop(&mut self) {
431        self.i2s.tx_stop();
432    }
433}
434
435impl<'d, Dm> DmaSupportTx for I2sTx<'d, Dm>
436where
437    Dm: DriverMode,
438{
439    type Channel = PeripheralTxChannel<AnyI2s<'d>>;
440
441    fn tx(&mut self) -> &mut ChannelTx<Dm, PeripheralTxChannel<AnyI2s<'d>>> {
442        &mut self.tx_channel
443    }
444
445    fn chain(&mut self) -> &mut DescriptorChain {
446        &mut self.tx_chain
447    }
448}
449
450impl<Dm> I2sTx<'_, Dm>
451where
452    Dm: DriverMode,
453{
454    fn write(&mut self, data: &[u8]) -> Result<(), Error> {
455        self.start_tx_transfer(&data, false)?;
456
457        // wait until I2S_TX_IDLE is 1
458        self.i2s.wait_for_tx_done();
459
460        Ok(())
461    }
462
463    fn start_tx_transfer<'t, TXBUF>(
464        &'t mut self,
465        words: &'t TXBUF,
466        circular: bool,
467    ) -> Result<(), Error>
468    where
469        TXBUF: ReadBuffer,
470        Dm: DriverMode,
471    {
472        let (ptr, len) = unsafe { words.read_buffer() };
473
474        // Reset TX unit and TX FIFO
475        self.i2s.reset_tx();
476
477        // Enable corresponding interrupts if needed
478
479        // configure DMA outlink
480        unsafe {
481            self.tx_chain.fill_for_tx(circular, ptr, len)?;
482            self.tx_channel
483                .prepare_transfer_without_start(self.i2s.dma_peripheral(), &self.tx_chain)
484                .and_then(|_| self.tx_channel.start_transfer())?;
485        }
486
487        // set I2S_TX_STOP_EN if needed
488
489        // start: set I2S_TX_START
490        self.i2s.tx_start();
491
492        Ok(())
493    }
494
495    /// Writes a slice of data to the I2S peripheral.
496    pub fn write_words(&mut self, words: &[impl AcceptedWord]) -> Result<(), Error> {
497        self.write(unsafe {
498            core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), core::mem::size_of_val(words))
499        })
500    }
501
502    /// Write I2S.
503    /// Returns [DmaTransferTx] which represents the in-progress DMA
504    /// transfer
505    pub fn write_dma<'t>(
506        &'t mut self,
507        words: &'t impl ReadBuffer,
508    ) -> Result<DmaTransferTx<'t, Self>, Error>
509    where
510        Self: DmaSupportTx,
511    {
512        self.start_tx_transfer(words, false)?;
513        Ok(DmaTransferTx::new(self))
514    }
515
516    /// Continuously write to I2S. Returns [DmaTransferTxCircular] which
517    /// represents the in-progress DMA transfer
518    pub fn write_dma_circular<'t>(
519        &'t mut self,
520        words: &'t impl ReadBuffer,
521    ) -> Result<DmaTransferTxCircular<'t, Self>, Error>
522    where
523        Self: DmaSupportTx,
524    {
525        self.start_tx_transfer(words, true)?;
526        Ok(DmaTransferTxCircular::new(self))
527    }
528}
529
530/// I2S RX channel
531pub struct I2sRx<'d, Dm>
532where
533    Dm: DriverMode,
534{
535    i2s: AnyI2s<'d>,
536    rx_channel: ChannelRx<Dm, PeripheralRxChannel<AnyI2s<'d>>>,
537    rx_chain: DescriptorChain,
538    _guard: PeripheralGuard,
539}
540
541impl<Dm> core::fmt::Debug for I2sRx<'_, Dm>
542where
543    Dm: DriverMode,
544{
545    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
546        f.debug_struct("I2sRx").finish()
547    }
548}
549
550impl<Dm> DmaSupport for I2sRx<'_, Dm>
551where
552    Dm: DriverMode,
553{
554    type DriverMode = Dm;
555
556    fn peripheral_wait_dma(&mut self, _is_rx: bool, _is_tx: bool) {
557        self.i2s.wait_for_rx_done();
558    }
559
560    fn peripheral_dma_stop(&mut self) {
561        self.i2s.reset_rx();
562    }
563}
564
565#[instability::unstable]
566impl<'d, Dm> DmaSupportRx for I2sRx<'d, Dm>
567where
568    Dm: DriverMode,
569{
570    type Channel = PeripheralRxChannel<AnyI2s<'d>>;
571
572    fn rx(&mut self) -> &mut ChannelRx<Dm, PeripheralRxChannel<AnyI2s<'d>>> {
573        &mut self.rx_channel
574    }
575
576    fn chain(&mut self) -> &mut DescriptorChain {
577        &mut self.rx_chain
578    }
579}
580
581impl<Dm> I2sRx<'_, Dm>
582where
583    Dm: DriverMode,
584{
585    fn read(&mut self, mut data: &mut [u8]) -> Result<(), Error> {
586        self.start_rx_transfer(&mut data, false)?;
587
588        // wait until I2S_RX_IDLE is 1
589        self.i2s.wait_for_rx_done();
590
591        Ok(())
592    }
593
594    fn start_rx_transfer<'t, RXBUF>(
595        &'t mut self,
596        words: &'t mut RXBUF,
597        circular: bool,
598    ) -> Result<(), Error>
599    where
600        RXBUF: WriteBuffer,
601    {
602        let (ptr, len) = unsafe { words.write_buffer() };
603
604        if len % 4 != 0 {
605            return Err(Error::IllegalArgument);
606        }
607
608        // Reset RX unit and RX FIFO
609        self.i2s.reset_rx();
610
611        // Enable corresponding interrupts if needed
612
613        // configure DMA inlink
614        unsafe {
615            self.rx_chain.fill_for_rx(circular, ptr, len)?;
616            self.rx_channel
617                .prepare_transfer_without_start(self.i2s.dma_peripheral(), &self.rx_chain)
618                .and_then(|_| self.rx_channel.start_transfer())?;
619        }
620
621        // start: set I2S_RX_START
622        self.i2s.rx_start(len);
623        Ok(())
624    }
625
626    /// Reads a slice of data from the I2S peripheral and stores it in the
627    /// provided buffer.
628    pub fn read_words(&mut self, words: &mut [impl AcceptedWord]) -> Result<(), Error> {
629        if core::mem::size_of_val(words) > 4096 || words.is_empty() {
630            return Err(Error::IllegalArgument);
631        }
632
633        self.read(unsafe {
634            core::slice::from_raw_parts_mut(
635                words.as_mut_ptr().cast::<u8>(),
636                core::mem::size_of_val(words),
637            )
638        })
639    }
640
641    /// Read I2S.
642    /// Returns [DmaTransferRx] which represents the in-progress DMA
643    /// transfer
644    pub fn read_dma<'t>(
645        &'t mut self,
646        words: &'t mut impl WriteBuffer,
647    ) -> Result<DmaTransferRx<'t, Self>, Error>
648    where
649        Self: DmaSupportRx,
650    {
651        self.start_rx_transfer(words, false)?;
652        Ok(DmaTransferRx::new(self))
653    }
654
655    /// Continuously read from I2S.
656    /// Returns [DmaTransferRxCircular] which represents the in-progress DMA
657    /// transfer
658    pub fn read_dma_circular<'t>(
659        &'t mut self,
660        words: &'t mut impl WriteBuffer,
661    ) -> Result<DmaTransferRxCircular<'t, Self>, Error>
662    where
663        Self: DmaSupportRx,
664    {
665        self.start_rx_transfer(words, true)?;
666        Ok(DmaTransferRxCircular::new(self))
667    }
668}
669
670/// A peripheral singleton compatible with the I2S master driver.
671pub trait Instance: RegisterAccessPrivate + super::IntoAnyI2s {}
672impl Instance for crate::peripherals::I2S0<'_> {}
673#[cfg(i2s1)]
674impl Instance for crate::peripherals::I2S1<'_> {}
675impl Instance for AnyI2s<'_> {}
676
677mod private {
678    use enumset::EnumSet;
679
680    use super::*;
681    #[cfg(not(i2s1))]
682    use crate::pac::i2s0::RegisterBlock;
683    use crate::{
684        DriverMode,
685        dma::{ChannelRx, ChannelTx, DescriptorChain, DmaDescriptor, DmaEligible},
686        gpio::{
687            InputConfig,
688            InputSignal,
689            OutputConfig,
690            OutputSignal,
691            interconnect::{PeripheralInput, PeripheralOutput},
692        },
693        i2s::AnyI2sInner,
694        interrupt::InterruptHandler,
695        peripherals::{I2S0, Interrupt},
696    };
697    // on ESP32-S3 I2S1 doesn't support all features - use that to avoid using those features
698    // by accident
699    #[cfg(i2s1)]
700    use crate::{pac::i2s1::RegisterBlock, peripherals::I2S1};
701
702    pub struct TxCreator<'d, Dm>
703    where
704        Dm: DriverMode,
705    {
706        pub i2s: AnyI2s<'d>,
707        pub tx_channel: ChannelTx<Dm, PeripheralTxChannel<AnyI2s<'d>>>,
708        pub(crate) guard: PeripheralGuard,
709    }
710
711    impl<'d, Dm> TxCreator<'d, Dm>
712    where
713        Dm: DriverMode,
714    {
715        pub fn build(self, descriptors: &'static mut [DmaDescriptor]) -> I2sTx<'d, Dm> {
716            let peripheral = self.i2s.peripheral();
717            I2sTx {
718                i2s: self.i2s,
719                tx_channel: self.tx_channel,
720                tx_chain: DescriptorChain::new(descriptors),
721                _guard: PeripheralGuard::new(peripheral),
722            }
723        }
724
725        pub fn with_bclk(self, bclk: impl PeripheralOutput<'d>) -> Self {
726            let bclk = bclk.into();
727
728            bclk.apply_output_config(&OutputConfig::default());
729            bclk.set_output_enable(true);
730
731            self.i2s.bclk_signal().connect_to(&bclk);
732
733            self
734        }
735
736        pub fn with_ws(self, ws: impl PeripheralOutput<'d>) -> Self {
737            let ws = ws.into();
738
739            ws.apply_output_config(&OutputConfig::default());
740            ws.set_output_enable(true);
741
742            self.i2s.ws_signal().connect_to(&ws);
743
744            self
745        }
746
747        pub fn with_dout(self, dout: impl PeripheralOutput<'d>) -> Self {
748            let dout = dout.into();
749
750            dout.apply_output_config(&OutputConfig::default());
751            dout.set_output_enable(true);
752
753            self.i2s.dout_signal().connect_to(&dout);
754
755            self
756        }
757    }
758
759    pub struct RxCreator<'d, Dm>
760    where
761        Dm: DriverMode,
762    {
763        pub i2s: AnyI2s<'d>,
764        pub rx_channel: ChannelRx<Dm, PeripheralRxChannel<AnyI2s<'d>>>,
765        pub(crate) guard: PeripheralGuard,
766    }
767
768    impl<'d, Dm> RxCreator<'d, Dm>
769    where
770        Dm: DriverMode,
771    {
772        pub fn build(self, descriptors: &'static mut [DmaDescriptor]) -> I2sRx<'d, Dm> {
773            let peripheral = self.i2s.peripheral();
774            I2sRx {
775                i2s: self.i2s,
776                rx_channel: self.rx_channel,
777                rx_chain: DescriptorChain::new(descriptors),
778                _guard: PeripheralGuard::new(peripheral),
779            }
780        }
781
782        pub fn with_bclk(self, bclk: impl PeripheralOutput<'d>) -> Self {
783            let bclk = bclk.into();
784
785            bclk.apply_output_config(&OutputConfig::default());
786            bclk.set_output_enable(true);
787
788            self.i2s.bclk_rx_signal().connect_to(&bclk);
789
790            self
791        }
792
793        pub fn with_ws(self, ws: impl PeripheralOutput<'d>) -> Self {
794            let ws = ws.into();
795
796            ws.apply_output_config(&OutputConfig::default());
797            ws.set_output_enable(true);
798
799            self.i2s.ws_rx_signal().connect_to(&ws);
800
801            self
802        }
803
804        pub fn with_din(self, din: impl PeripheralInput<'d>) -> Self {
805            let din = din.into();
806
807            din.apply_input_config(&InputConfig::default());
808            din.set_input_enable(true);
809
810            self.i2s.din_signal().connect_to(&din);
811
812            self
813        }
814    }
815
816    #[allow(private_bounds)]
817    pub trait RegBlock: DmaEligible {
818        fn regs(&self) -> &RegisterBlock;
819        fn peripheral(&self) -> crate::system::Peripheral;
820    }
821
822    pub trait Signals: RegBlock {
823        fn mclk_signal(&self) -> OutputSignal;
824        fn bclk_signal(&self) -> OutputSignal;
825        fn ws_signal(&self) -> OutputSignal;
826        fn dout_signal(&self) -> OutputSignal;
827        fn bclk_rx_signal(&self) -> OutputSignal;
828        fn ws_rx_signal(&self) -> OutputSignal;
829        fn din_signal(&self) -> InputSignal;
830    }
831
832    #[cfg(any(esp32, esp32s2))]
833    pub trait RegisterAccessPrivate: Signals + RegBlock {
834        fn set_interrupt_handler(&self, handler: InterruptHandler);
835
836        fn enable_listen(&self, interrupts: EnumSet<I2sInterrupt>, enable: bool) {
837            self.regs().int_ena().modify(|_, w| {
838                for interrupt in interrupts {
839                    match interrupt {
840                        I2sInterrupt::RxHung => w.rx_hung().bit(enable),
841                        I2sInterrupt::TxHung => w.tx_hung().bit(enable),
842                    };
843                }
844                w
845            });
846        }
847
848        fn interrupts(&self) -> EnumSet<I2sInterrupt> {
849            let mut res = EnumSet::new();
850            let ints = self.regs().int_st().read();
851
852            if ints.rx_hung().bit() {
853                res.insert(I2sInterrupt::RxHung);
854            }
855            if ints.tx_hung().bit() {
856                res.insert(I2sInterrupt::TxHung);
857            }
858
859            res
860        }
861
862        fn clear_interrupts(&self, interrupts: EnumSet<I2sInterrupt>) {
863            self.regs().int_clr().write(|w| {
864                for interrupt in interrupts {
865                    match interrupt {
866                        I2sInterrupt::RxHung => w.rx_hung().clear_bit_by_one(),
867                        I2sInterrupt::TxHung => w.tx_hung().clear_bit_by_one(),
868                    };
869                }
870                w
871            });
872        }
873
874        fn set_clock(&self, clock_settings: I2sClockDividers) {
875            self.regs().clkm_conf().modify(|r, w| unsafe {
876                // select PLL_160M
877                w.bits(r.bits() | (crate::soc::constants::I2S_DEFAULT_CLK_SRC << 21))
878            });
879
880            #[cfg(esp32)]
881            self.regs()
882                .clkm_conf()
883                .modify(|_, w| w.clka_ena().clear_bit());
884
885            self.regs().clkm_conf().modify(|_, w| unsafe {
886                w.clk_en().set_bit();
887                w.clkm_div_num().bits(clock_settings.mclk_divider as u8);
888                w.clkm_div_a().bits(clock_settings.denominator as u8);
889                w.clkm_div_b().bits(clock_settings.numerator as u8)
890            });
891
892            self.regs().sample_rate_conf().modify(|_, w| unsafe {
893                w.tx_bck_div_num().bits(clock_settings.bclk_divider as u8);
894                w.rx_bck_div_num().bits(clock_settings.bclk_divider as u8)
895            });
896        }
897
898        fn configure(&self, _standard: &Standard, data_format: &DataFormat) {
899            let fifo_mod = match data_format {
900                DataFormat::Data32Channel32 => 2,
901                DataFormat::Data16Channel16 => 0,
902            };
903
904            self.regs().sample_rate_conf().modify(|_, w| unsafe {
905                w.tx_bits_mod().bits(data_format.channel_bits());
906                w.rx_bits_mod().bits(data_format.channel_bits())
907            });
908
909            self.regs().conf().modify(|_, w| {
910                w.tx_slave_mod().clear_bit();
911                w.rx_slave_mod().clear_bit();
912                // If the I2S_RX_MSB_SHIFT bit and the I2S_TX_MSB_SHIFT bit of register
913                // I2S_CONF_REG are set to 1, respectively, the I2S module will use the Philips
914                // standard when receiving and transmitting data.
915                w.tx_msb_shift().set_bit();
916                w.rx_msb_shift().set_bit();
917                // Short frame synchronization
918                w.tx_short_sync().bit(false);
919                w.rx_short_sync().bit(false);
920                // Send MSB to the right channel to be consistent with ESP32-S3 et al.
921                w.tx_msb_right().set_bit();
922                w.rx_msb_right().set_bit();
923                // ESP32 generates two clock pulses first. If the WS is low, those first clock
924                // pulses are indistinguishable from real data, which corrupts the first few
925                // samples. So we send the right channel first (which means WS is high during
926                // the first sample) to prevent this issue.
927                w.tx_right_first().set_bit();
928                w.rx_right_first().set_bit();
929                w.tx_mono().clear_bit();
930                w.rx_mono().clear_bit();
931                w.sig_loopback().clear_bit()
932            });
933
934            self.regs().fifo_conf().modify(|_, w| unsafe {
935                w.tx_fifo_mod().bits(fifo_mod);
936                w.tx_fifo_mod_force_en().set_bit();
937                w.dscr_en().set_bit();
938                w.rx_fifo_mod().bits(fifo_mod);
939                w.rx_fifo_mod_force_en().set_bit()
940            });
941
942            self.regs().conf_chan().modify(|_, w| unsafe {
943                // for now only stereo
944                w.tx_chan_mod().bits(0);
945                w.rx_chan_mod().bits(0)
946            });
947
948            self.regs().conf1().modify(|_, w| {
949                w.tx_pcm_bypass().set_bit();
950                w.rx_pcm_bypass().set_bit()
951            });
952
953            self.regs().pd_conf().modify(|_, w| {
954                w.fifo_force_pu().set_bit();
955                w.fifo_force_pd().clear_bit()
956            });
957
958            self.regs().conf2().modify(|_, w| {
959                w.camera_en().clear_bit();
960                w.lcd_en().clear_bit()
961            });
962        }
963
964        fn set_master(&self) {
965            self.regs().conf().modify(|_, w| {
966                w.rx_slave_mod().clear_bit();
967                w.tx_slave_mod().clear_bit()
968            });
969        }
970
971        fn update(&self) {
972            // nothing to do
973        }
974
975        fn reset_tx(&self) {
976            self.regs().conf().modify(|_, w| {
977                w.tx_reset().set_bit();
978                w.tx_fifo_reset().set_bit()
979            });
980            self.regs().conf().modify(|_, w| {
981                w.tx_reset().clear_bit();
982                w.tx_fifo_reset().clear_bit()
983            });
984
985            self.regs().lc_conf().modify(|_, w| w.out_rst().set_bit());
986            self.regs().lc_conf().modify(|_, w| w.out_rst().clear_bit());
987
988            self.regs().int_clr().write(|w| {
989                w.out_done().clear_bit_by_one();
990                w.out_total_eof().clear_bit_by_one()
991            });
992        }
993
994        fn tx_start(&self) {
995            self.regs().conf().modify(|_, w| w.tx_start().set_bit());
996
997            while self.regs().state().read().tx_idle().bit_is_set() {
998                // wait
999            }
1000        }
1001
1002        fn tx_stop(&self) {
1003            self.regs().conf().modify(|_, w| w.tx_start().clear_bit());
1004        }
1005
1006        fn wait_for_tx_done(&self) {
1007            while self.regs().state().read().tx_idle().bit_is_clear() {
1008                // wait
1009            }
1010
1011            self.regs().conf().modify(|_, w| w.tx_start().clear_bit());
1012        }
1013
1014        fn reset_rx(&self) {
1015            self.regs().conf().modify(|_, w| {
1016                w.rx_reset().set_bit();
1017                w.rx_fifo_reset().set_bit()
1018            });
1019            self.regs().conf().modify(|_, w| {
1020                w.rx_reset().clear_bit();
1021                w.rx_fifo_reset().clear_bit()
1022            });
1023
1024            self.regs().lc_conf().modify(|_, w| w.in_rst().set_bit());
1025            self.regs().lc_conf().modify(|_, w| w.in_rst().clear_bit());
1026
1027            self.regs().int_clr().write(|w| {
1028                w.in_done().clear_bit_by_one();
1029                w.in_suc_eof().clear_bit_by_one()
1030            });
1031        }
1032
1033        fn rx_start(&self, len: usize) {
1034            self.regs()
1035                .int_clr()
1036                .write(|w| w.in_suc_eof().clear_bit_by_one());
1037
1038            cfg_if::cfg_if! {
1039                if #[cfg(esp32)] {
1040                    // On ESP32, the eof_num count in words.
1041                    let eof_num = len / 4;
1042                } else {
1043                    let eof_num = len - 1;
1044                }
1045            }
1046
1047            self.regs()
1048                .rxeof_num()
1049                .modify(|_, w| unsafe { w.rx_eof_num().bits(eof_num as u32) });
1050
1051            self.regs().conf().modify(|_, w| w.rx_start().set_bit());
1052        }
1053
1054        fn wait_for_rx_done(&self) {
1055            while self.regs().int_raw().read().in_suc_eof().bit_is_clear() {
1056                // wait
1057            }
1058
1059            self.regs()
1060                .int_clr()
1061                .write(|w| w.in_suc_eof().clear_bit_by_one());
1062        }
1063    }
1064
1065    #[cfg(any(esp32c3, esp32c6, esp32h2, esp32s3))]
1066    pub trait RegisterAccessPrivate: Signals + RegBlock {
1067        fn set_interrupt_handler(&self, handler: InterruptHandler);
1068
1069        fn enable_listen(&self, interrupts: EnumSet<I2sInterrupt>, enable: bool) {
1070            self.regs().int_ena().modify(|_, w| {
1071                for interrupt in interrupts {
1072                    match interrupt {
1073                        I2sInterrupt::RxHung => w.rx_hung().bit(enable),
1074                        I2sInterrupt::TxHung => w.tx_hung().bit(enable),
1075                        I2sInterrupt::RxDone => w.rx_done().bit(enable),
1076                        I2sInterrupt::TxDone => w.tx_done().bit(enable),
1077                    };
1078                }
1079                w
1080            });
1081        }
1082
1083        fn listen(&self, interrupts: impl Into<EnumSet<I2sInterrupt>>) {
1084            self.enable_listen(interrupts.into(), true);
1085        }
1086
1087        fn unlisten(&self, interrupts: impl Into<EnumSet<I2sInterrupt>>) {
1088            self.enable_listen(interrupts.into(), false);
1089        }
1090
1091        fn interrupts(&self) -> EnumSet<I2sInterrupt> {
1092            let mut res = EnumSet::new();
1093            let ints = self.regs().int_st().read();
1094
1095            if ints.rx_hung().bit() {
1096                res.insert(I2sInterrupt::RxHung);
1097            }
1098            if ints.tx_hung().bit() {
1099                res.insert(I2sInterrupt::TxHung);
1100            }
1101            if ints.rx_done().bit() {
1102                res.insert(I2sInterrupt::RxDone);
1103            }
1104            if ints.tx_done().bit() {
1105                res.insert(I2sInterrupt::TxDone);
1106            }
1107
1108            res
1109        }
1110
1111        fn clear_interrupts(&self, interrupts: EnumSet<I2sInterrupt>) {
1112            self.regs().int_clr().write(|w| {
1113                for interrupt in interrupts {
1114                    match interrupt {
1115                        I2sInterrupt::RxHung => w.rx_hung().clear_bit_by_one(),
1116                        I2sInterrupt::TxHung => w.tx_hung().clear_bit_by_one(),
1117                        I2sInterrupt::RxDone => w.rx_done().clear_bit_by_one(),
1118                        I2sInterrupt::TxDone => w.tx_done().clear_bit_by_one(),
1119                    };
1120                }
1121                w
1122            });
1123        }
1124
1125        #[cfg(any(esp32c3, esp32s3))]
1126        fn set_clock(&self, clock_settings: I2sClockDividers) {
1127            let clkm_div_x: u32;
1128            let clkm_div_y: u32;
1129            let clkm_div_z: u32;
1130            let clkm_div_yn1: u32;
1131
1132            if clock_settings.denominator == 0 || clock_settings.numerator == 0 {
1133                clkm_div_x = 0;
1134                clkm_div_y = 0;
1135                clkm_div_z = 0;
1136                clkm_div_yn1 = 1;
1137            } else if clock_settings.numerator > clock_settings.denominator / 2 {
1138                clkm_div_x = clock_settings
1139                    .denominator
1140                    .overflowing_div(
1141                        clock_settings
1142                            .denominator
1143                            .overflowing_sub(clock_settings.numerator)
1144                            .0,
1145                    )
1146                    .0
1147                    .overflowing_sub(1)
1148                    .0;
1149                clkm_div_y = clock_settings.denominator
1150                    % (clock_settings
1151                        .denominator
1152                        .overflowing_sub(clock_settings.numerator)
1153                        .0);
1154                clkm_div_z = clock_settings
1155                    .denominator
1156                    .overflowing_sub(clock_settings.numerator)
1157                    .0;
1158                clkm_div_yn1 = 1;
1159            } else {
1160                clkm_div_x = clock_settings.denominator / clock_settings.numerator - 1;
1161                clkm_div_y = clock_settings.denominator % clock_settings.numerator;
1162                clkm_div_z = clock_settings.numerator;
1163                clkm_div_yn1 = 0;
1164            }
1165
1166            self.regs().tx_clkm_div_conf().modify(|_, w| unsafe {
1167                w.tx_clkm_div_x().bits(clkm_div_x as u16);
1168                w.tx_clkm_div_y().bits(clkm_div_y as u16);
1169                w.tx_clkm_div_yn1().bit(clkm_div_yn1 != 0);
1170                w.tx_clkm_div_z().bits(clkm_div_z as u16)
1171            });
1172
1173            self.regs().tx_clkm_conf().modify(|_, w| unsafe {
1174                w.clk_en().set_bit();
1175                w.tx_clk_active().set_bit();
1176                w.tx_clk_sel()
1177                    .bits(crate::soc::constants::I2S_DEFAULT_CLK_SRC) // for now fixed at 160MHz
1178                    ;
1179                w.tx_clkm_div_num().bits(clock_settings.mclk_divider as u8)
1180            });
1181
1182            self.regs().tx_conf1().modify(|_, w| unsafe {
1183                w.tx_bck_div_num()
1184                    .bits((clock_settings.bclk_divider - 1) as u8)
1185            });
1186
1187            self.regs().rx_clkm_div_conf().modify(|_, w| unsafe {
1188                w.rx_clkm_div_x().bits(clkm_div_x as u16);
1189                w.rx_clkm_div_y().bits(clkm_div_y as u16);
1190                w.rx_clkm_div_yn1().bit(clkm_div_yn1 != 0);
1191                w.rx_clkm_div_z().bits(clkm_div_z as u16)
1192            });
1193
1194            self.regs().rx_clkm_conf().modify(|_, w| unsafe {
1195                w.rx_clk_active().set_bit();
1196                // for now fixed at 160MHz
1197                w.rx_clk_sel()
1198                    .bits(crate::soc::constants::I2S_DEFAULT_CLK_SRC);
1199                w.rx_clkm_div_num().bits(clock_settings.mclk_divider as u8);
1200                w.mclk_sel().bit(true)
1201            });
1202
1203            self.regs().rx_conf1().modify(|_, w| unsafe {
1204                w.rx_bck_div_num()
1205                    .bits((clock_settings.bclk_divider - 1) as u8)
1206            });
1207        }
1208
1209        #[cfg(any(esp32c6, esp32h2))]
1210        fn set_clock(&self, clock_settings: I2sClockDividers) {
1211            // I2S clocks are configured via PCR
1212            use crate::peripherals::PCR;
1213
1214            let clkm_div_x: u32;
1215            let clkm_div_y: u32;
1216            let clkm_div_z: u32;
1217            let clkm_div_yn1: u32;
1218
1219            if clock_settings.denominator == 0 || clock_settings.numerator == 0 {
1220                clkm_div_x = 0;
1221                clkm_div_y = 0;
1222                clkm_div_z = 0;
1223                clkm_div_yn1 = 1;
1224            } else if clock_settings.numerator > clock_settings.denominator / 2 {
1225                clkm_div_x = clock_settings
1226                    .denominator
1227                    .overflowing_div(
1228                        clock_settings
1229                            .denominator
1230                            .overflowing_sub(clock_settings.numerator)
1231                            .0,
1232                    )
1233                    .0
1234                    .overflowing_sub(1)
1235                    .0;
1236                clkm_div_y = clock_settings.denominator
1237                    % (clock_settings
1238                        .denominator
1239                        .overflowing_sub(clock_settings.numerator)
1240                        .0);
1241                clkm_div_z = clock_settings
1242                    .denominator
1243                    .overflowing_sub(clock_settings.numerator)
1244                    .0;
1245                clkm_div_yn1 = 1;
1246            } else {
1247                clkm_div_x = clock_settings.denominator / clock_settings.numerator - 1;
1248                clkm_div_y = clock_settings.denominator % clock_settings.numerator;
1249                clkm_div_z = clock_settings.numerator;
1250                clkm_div_yn1 = 0;
1251            }
1252
1253            PCR::regs().i2s_tx_clkm_div_conf().modify(|_, w| unsafe {
1254                w.i2s_tx_clkm_div_x().bits(clkm_div_x as u16);
1255                w.i2s_tx_clkm_div_y().bits(clkm_div_y as u16);
1256                w.i2s_tx_clkm_div_yn1().bit(clkm_div_yn1 != 0);
1257                w.i2s_tx_clkm_div_z().bits(clkm_div_z as u16)
1258            });
1259
1260            PCR::regs().i2s_tx_clkm_conf().modify(|_, w| unsafe {
1261                w.i2s_tx_clkm_en().set_bit();
1262                // for now fixed at 160MHz for C6 and 96MHz for H2
1263                w.i2s_tx_clkm_sel()
1264                    .bits(crate::soc::constants::I2S_DEFAULT_CLK_SRC);
1265                w.i2s_tx_clkm_div_num()
1266                    .bits(clock_settings.mclk_divider as u8)
1267            });
1268
1269            #[cfg(not(esp32h2))]
1270            self.regs().tx_conf1().modify(|_, w| unsafe {
1271                w.tx_bck_div_num()
1272                    .bits((clock_settings.bclk_divider - 1) as u8)
1273            });
1274            #[cfg(esp32h2)]
1275            self.regs().tx_conf().modify(|_, w| unsafe {
1276                w.tx_bck_div_num()
1277                    .bits((clock_settings.bclk_divider - 1) as u8)
1278            });
1279
1280            PCR::regs().i2s_rx_clkm_div_conf().modify(|_, w| unsafe {
1281                w.i2s_rx_clkm_div_x().bits(clkm_div_x as u16);
1282                w.i2s_rx_clkm_div_y().bits(clkm_div_y as u16);
1283                w.i2s_rx_clkm_div_yn1().bit(clkm_div_yn1 != 0);
1284                w.i2s_rx_clkm_div_z().bits(clkm_div_z as u16)
1285            });
1286
1287            PCR::regs().i2s_rx_clkm_conf().modify(|_, w| unsafe {
1288                w.i2s_rx_clkm_en().set_bit();
1289                // for now fixed at 160MHz for C6 and 96MHz for H2
1290                w.i2s_rx_clkm_sel()
1291                    .bits(crate::soc::constants::I2S_DEFAULT_CLK_SRC);
1292                w.i2s_rx_clkm_div_num()
1293                    .bits(clock_settings.mclk_divider as u8);
1294                w.i2s_mclk_sel().bit(true)
1295            });
1296            #[cfg(not(esp32h2))]
1297            self.regs().rx_conf1().modify(|_, w| unsafe {
1298                w.rx_bck_div_num()
1299                    .bits((clock_settings.bclk_divider - 1) as u8)
1300            });
1301            #[cfg(esp32h2)]
1302            self.regs().rx_conf().modify(|_, w| unsafe {
1303                w.rx_bck_div_num()
1304                    .bits((clock_settings.bclk_divider - 1) as u8)
1305            });
1306        }
1307
1308        fn configure(&self, _standard: &Standard, data_format: &DataFormat) {
1309            #[allow(clippy::useless_conversion)]
1310            self.regs().tx_conf1().modify(|_, w| unsafe {
1311                w.tx_tdm_ws_width()
1312                    .bits((data_format.channel_bits() - 1).into());
1313                w.tx_bits_mod().bits(data_format.data_bits() - 1);
1314                w.tx_tdm_chan_bits().bits(data_format.channel_bits() - 1);
1315                w.tx_half_sample_bits().bits(data_format.channel_bits() - 1)
1316            });
1317            #[cfg(not(esp32h2))]
1318            self.regs()
1319                .tx_conf1()
1320                .modify(|_, w| w.tx_msb_shift().set_bit());
1321            #[cfg(esp32h2)]
1322            self.regs()
1323                .tx_conf()
1324                .modify(|_, w| w.tx_msb_shift().set_bit());
1325            self.regs().tx_conf().modify(|_, w| unsafe {
1326                w.tx_mono().clear_bit();
1327                w.tx_mono_fst_vld().set_bit();
1328                w.tx_stop_en().set_bit();
1329                w.tx_chan_equal().clear_bit();
1330                w.tx_tdm_en().set_bit();
1331                w.tx_pdm_en().clear_bit();
1332                w.tx_pcm_bypass().set_bit();
1333                w.tx_big_endian().clear_bit();
1334                w.tx_bit_order().clear_bit();
1335                w.tx_chan_mod().bits(0)
1336            });
1337
1338            self.regs().tx_tdm_ctrl().modify(|_, w| unsafe {
1339                w.tx_tdm_tot_chan_num().bits(1);
1340                w.tx_tdm_chan0_en().set_bit();
1341                w.tx_tdm_chan1_en().set_bit();
1342                w.tx_tdm_chan2_en().clear_bit();
1343                w.tx_tdm_chan3_en().clear_bit();
1344                w.tx_tdm_chan4_en().clear_bit();
1345                w.tx_tdm_chan5_en().clear_bit();
1346                w.tx_tdm_chan6_en().clear_bit();
1347                w.tx_tdm_chan7_en().clear_bit();
1348                w.tx_tdm_chan8_en().clear_bit();
1349                w.tx_tdm_chan9_en().clear_bit();
1350                w.tx_tdm_chan10_en().clear_bit();
1351                w.tx_tdm_chan11_en().clear_bit();
1352                w.tx_tdm_chan12_en().clear_bit();
1353                w.tx_tdm_chan13_en().clear_bit();
1354                w.tx_tdm_chan14_en().clear_bit();
1355                w.tx_tdm_chan15_en().clear_bit()
1356            });
1357
1358            #[allow(clippy::useless_conversion)]
1359            self.regs().rx_conf1().modify(|_, w| unsafe {
1360                w.rx_tdm_ws_width()
1361                    .bits((data_format.channel_bits() - 1).into());
1362                w.rx_bits_mod().bits(data_format.data_bits() - 1);
1363                w.rx_tdm_chan_bits().bits(data_format.channel_bits() - 1);
1364                w.rx_half_sample_bits().bits(data_format.channel_bits() - 1)
1365            });
1366            #[cfg(not(esp32h2))]
1367            self.regs()
1368                .rx_conf1()
1369                .modify(|_, w| w.rx_msb_shift().set_bit());
1370            #[cfg(esp32h2)]
1371            self.regs()
1372                .rx_conf()
1373                .modify(|_, w| w.rx_msb_shift().set_bit());
1374
1375            self.regs().rx_conf().modify(|_, w| unsafe {
1376                w.rx_mono().clear_bit();
1377                w.rx_mono_fst_vld().set_bit();
1378                w.rx_stop_mode().bits(2);
1379                w.rx_tdm_en().set_bit();
1380                w.rx_pdm_en().clear_bit();
1381                w.rx_pcm_bypass().set_bit();
1382                w.rx_big_endian().clear_bit();
1383                w.rx_bit_order().clear_bit()
1384            });
1385
1386            self.regs().rx_tdm_ctrl().modify(|_, w| unsafe {
1387                w.rx_tdm_tot_chan_num().bits(1);
1388                w.rx_tdm_pdm_chan0_en().set_bit();
1389                w.rx_tdm_pdm_chan1_en().set_bit();
1390                w.rx_tdm_pdm_chan2_en().clear_bit();
1391                w.rx_tdm_pdm_chan3_en().clear_bit();
1392                w.rx_tdm_pdm_chan4_en().clear_bit();
1393                w.rx_tdm_pdm_chan5_en().clear_bit();
1394                w.rx_tdm_pdm_chan6_en().clear_bit();
1395                w.rx_tdm_pdm_chan7_en().clear_bit();
1396                w.rx_tdm_chan8_en().clear_bit();
1397                w.rx_tdm_chan9_en().clear_bit();
1398                w.rx_tdm_chan10_en().clear_bit();
1399                w.rx_tdm_chan11_en().clear_bit();
1400                w.rx_tdm_chan12_en().clear_bit();
1401                w.rx_tdm_chan13_en().clear_bit();
1402                w.rx_tdm_chan14_en().clear_bit();
1403                w.rx_tdm_chan15_en().clear_bit()
1404            });
1405        }
1406
1407        fn set_master(&self) {
1408            self.regs()
1409                .tx_conf()
1410                .modify(|_, w| w.tx_slave_mod().clear_bit());
1411            self.regs()
1412                .rx_conf()
1413                .modify(|_, w| w.rx_slave_mod().clear_bit());
1414        }
1415
1416        fn update(&self) {
1417            self.regs()
1418                .tx_conf()
1419                .modify(|_, w| w.tx_update().clear_bit());
1420            self.regs().tx_conf().modify(|_, w| w.tx_update().set_bit());
1421
1422            self.regs()
1423                .rx_conf()
1424                .modify(|_, w| w.rx_update().clear_bit());
1425            self.regs().rx_conf().modify(|_, w| w.rx_update().set_bit());
1426        }
1427
1428        fn reset_tx(&self) {
1429            self.regs().tx_conf().modify(|_, w| {
1430                w.tx_reset().set_bit();
1431                w.tx_fifo_reset().set_bit()
1432            });
1433            self.regs().tx_conf().modify(|_, w| {
1434                w.tx_reset().clear_bit();
1435                w.tx_fifo_reset().clear_bit()
1436            });
1437
1438            self.regs().int_clr().write(|w| {
1439                w.tx_done().clear_bit_by_one();
1440                w.tx_hung().clear_bit_by_one()
1441            });
1442        }
1443
1444        fn tx_start(&self) {
1445            self.regs().tx_conf().modify(|_, w| w.tx_start().set_bit());
1446        }
1447
1448        fn tx_stop(&self) {
1449            self.regs()
1450                .tx_conf()
1451                .modify(|_, w| w.tx_start().clear_bit());
1452        }
1453
1454        fn wait_for_tx_done(&self) {
1455            while self.regs().state().read().tx_idle().bit_is_clear() {
1456                // wait
1457            }
1458
1459            self.regs()
1460                .tx_conf()
1461                .modify(|_, w| w.tx_start().clear_bit());
1462        }
1463
1464        fn reset_rx(&self) {
1465            self.regs()
1466                .rx_conf()
1467                .modify(|_, w| w.rx_start().clear_bit());
1468
1469            self.regs().rx_conf().modify(|_, w| {
1470                w.rx_reset().set_bit();
1471                w.rx_fifo_reset().set_bit()
1472            });
1473            self.regs().rx_conf().modify(|_, w| {
1474                w.rx_reset().clear_bit();
1475                w.rx_fifo_reset().clear_bit()
1476            });
1477
1478            self.regs().int_clr().write(|w| {
1479                w.rx_done().clear_bit_by_one();
1480                w.rx_hung().clear_bit_by_one()
1481            });
1482        }
1483
1484        fn rx_start(&self, len: usize) {
1485            let len = len - 1;
1486
1487            self.regs()
1488                .rxeof_num()
1489                .write(|w| unsafe { w.rx_eof_num().bits(len as u16) });
1490            self.regs().rx_conf().modify(|_, w| w.rx_start().set_bit());
1491        }
1492
1493        fn wait_for_rx_done(&self) {
1494            while self.regs().int_raw().read().rx_done().bit_is_clear() {
1495                // wait
1496            }
1497
1498            self.regs()
1499                .int_clr()
1500                .write(|w| w.rx_done().clear_bit_by_one());
1501        }
1502    }
1503
1504    impl RegBlock for I2S0<'_> {
1505        fn regs(&self) -> &RegisterBlock {
1506            unsafe { &*I2S0::PTR.cast::<RegisterBlock>() }
1507        }
1508
1509        fn peripheral(&self) -> crate::system::Peripheral {
1510            crate::system::Peripheral::I2s0
1511        }
1512    }
1513
1514    impl RegisterAccessPrivate for I2S0<'_> {
1515        fn set_interrupt_handler(&self, handler: InterruptHandler) {
1516            for core in crate::system::Cpu::other() {
1517                crate::interrupt::disable(core, Interrupt::I2S0);
1518            }
1519            unsafe { crate::peripherals::I2S0::steal() }.bind_i2s0_interrupt(handler.handler());
1520            unwrap!(crate::interrupt::enable(
1521                Interrupt::I2S0,
1522                handler.priority()
1523            ));
1524        }
1525    }
1526
1527    impl Signals for crate::peripherals::I2S0<'_> {
1528        fn mclk_signal(&self) -> OutputSignal {
1529            cfg_if::cfg_if! {
1530                if #[cfg(esp32)] {
1531                    panic!("MCLK currently not supported on ESP32");
1532                } else if #[cfg(esp32s2)] {
1533                    OutputSignal::CLK_I2S
1534                } else if #[cfg(esp32s3)] {
1535                    OutputSignal::I2S0_MCLK
1536                } else {
1537                    OutputSignal::I2S_MCLK
1538                }
1539            }
1540        }
1541
1542        fn bclk_signal(&self) -> OutputSignal {
1543            cfg_if::cfg_if! {
1544                if #[cfg(any(esp32, esp32s2, esp32s3))] {
1545                    OutputSignal::I2S0O_BCK
1546                } else {
1547                    OutputSignal::I2SO_BCK
1548                }
1549            }
1550        }
1551
1552        fn ws_signal(&self) -> OutputSignal {
1553            cfg_if::cfg_if! {
1554                if #[cfg(any(esp32, esp32s2, esp32s3))] {
1555                    OutputSignal::I2S0O_WS
1556                } else {
1557                    OutputSignal::I2SO_WS
1558                }
1559            }
1560        }
1561
1562        fn dout_signal(&self) -> OutputSignal {
1563            cfg_if::cfg_if! {
1564                if #[cfg(esp32)] {
1565                    OutputSignal::I2S0O_DATA_23
1566                } else if #[cfg(esp32s2)] {
1567                    OutputSignal::I2S0O_DATA_OUT23
1568                } else if #[cfg(esp32s3)] {
1569                    OutputSignal::I2S0O_SD
1570                } else {
1571                    OutputSignal::I2SO_SD
1572                }
1573            }
1574        }
1575
1576        fn bclk_rx_signal(&self) -> OutputSignal {
1577            cfg_if::cfg_if! {
1578                if #[cfg(any(esp32, esp32s2, esp32s3))] {
1579                    OutputSignal::I2S0I_BCK
1580                } else {
1581                    OutputSignal::I2SI_BCK
1582                }
1583            }
1584        }
1585
1586        fn ws_rx_signal(&self) -> OutputSignal {
1587            cfg_if::cfg_if! {
1588                if #[cfg(any(esp32, esp32s2, esp32s3))] {
1589                    OutputSignal::I2S0I_WS
1590                } else {
1591                    OutputSignal::I2SI_WS
1592                }
1593            }
1594        }
1595
1596        fn din_signal(&self) -> InputSignal {
1597            cfg_if::cfg_if! {
1598                if #[cfg(esp32)] {
1599                    InputSignal::I2S0I_DATA_15
1600                } else if #[cfg(esp32s2)] {
1601                    InputSignal::I2S0I_DATA_IN15
1602                } else if #[cfg(esp32s3)] {
1603                    InputSignal::I2S0I_SD
1604                } else {
1605                    InputSignal::I2SI_SD
1606                }
1607            }
1608        }
1609    }
1610
1611    #[cfg(i2s1)]
1612    impl RegBlock for I2S1<'_> {
1613        fn regs(&self) -> &RegisterBlock {
1614            unsafe { &*I2S1::PTR.cast::<RegisterBlock>() }
1615        }
1616
1617        fn peripheral(&self) -> crate::system::Peripheral {
1618            crate::system::Peripheral::I2s1
1619        }
1620    }
1621
1622    #[cfg(i2s1)]
1623    impl RegisterAccessPrivate for I2S1<'_> {
1624        fn set_interrupt_handler(&self, handler: InterruptHandler) {
1625            for core in crate::system::Cpu::other() {
1626                crate::interrupt::disable(core, Interrupt::I2S1);
1627            }
1628            unsafe { crate::peripherals::I2S1::steal() }.bind_i2s1_interrupt(handler.handler());
1629            unwrap!(crate::interrupt::enable(
1630                Interrupt::I2S1,
1631                handler.priority()
1632            ));
1633        }
1634    }
1635
1636    #[cfg(i2s1)]
1637    impl Signals for crate::peripherals::I2S1<'_> {
1638        fn mclk_signal(&self) -> OutputSignal {
1639            cfg_if::cfg_if! {
1640                if #[cfg(esp32)] {
1641                    panic!("MCLK currently not supported on ESP32");
1642                } else {
1643                    OutputSignal::I2S1_MCLK
1644                }
1645            }
1646        }
1647
1648        fn bclk_signal(&self) -> OutputSignal {
1649            OutputSignal::I2S1O_BCK
1650        }
1651
1652        fn ws_signal(&self) -> OutputSignal {
1653            OutputSignal::I2S1O_WS
1654        }
1655
1656        fn dout_signal(&self) -> OutputSignal {
1657            cfg_if::cfg_if! {
1658                if #[cfg(esp32)] {
1659                    OutputSignal::I2S1O_DATA_23
1660                } else {
1661                    OutputSignal::I2S1O_SD
1662                }
1663            }
1664        }
1665
1666        fn bclk_rx_signal(&self) -> OutputSignal {
1667            OutputSignal::I2S1I_BCK
1668        }
1669
1670        fn ws_rx_signal(&self) -> OutputSignal {
1671            OutputSignal::I2S1I_WS
1672        }
1673
1674        fn din_signal(&self) -> InputSignal {
1675            cfg_if::cfg_if! {
1676                if #[cfg(esp32)] {
1677                    InputSignal::I2S1I_DATA_15
1678                } else {
1679                    InputSignal::I2S1I_SD
1680                }
1681            }
1682        }
1683    }
1684
1685    impl RegBlock for super::AnyI2s<'_> {
1686        fn regs(&self) -> &RegisterBlock {
1687            match &self.0 {
1688                AnyI2sInner::I2s0(i2s) => RegBlock::regs(i2s),
1689                #[cfg(i2s1)]
1690                AnyI2sInner::I2s1(i2s) => RegBlock::regs(i2s),
1691            }
1692        }
1693
1694        delegate::delegate! {
1695            to match &self.0 {
1696                AnyI2sInner::I2s0(i2s) => i2s,
1697                #[cfg(i2s1)]
1698                AnyI2sInner::I2s1(i2s) => i2s,
1699            } {
1700                fn peripheral(&self) -> crate::system::Peripheral;
1701            }
1702        }
1703    }
1704
1705    impl RegisterAccessPrivate for super::AnyI2s<'_> {
1706        delegate::delegate! {
1707            to match &self.0 {
1708                AnyI2sInner::I2s0(i2s) => i2s,
1709                #[cfg(i2s1)]
1710                AnyI2sInner::I2s1(i2s) => i2s,
1711            } {
1712                fn set_interrupt_handler(&self, handler: InterruptHandler);
1713            }
1714        }
1715    }
1716
1717    impl Signals for super::AnyI2s<'_> {
1718        delegate::delegate! {
1719            to match &self.0 {
1720                AnyI2sInner::I2s0(i2s) => i2s,
1721                #[cfg(i2s1)]
1722                AnyI2sInner::I2s1(i2s) => i2s,
1723            } {
1724                fn mclk_signal(&self) -> OutputSignal;
1725                fn bclk_signal(&self) -> OutputSignal;
1726                fn ws_signal(&self) -> OutputSignal;
1727                fn dout_signal(&self) -> OutputSignal;
1728                fn bclk_rx_signal(&self) -> OutputSignal;
1729                fn ws_rx_signal(&self) -> OutputSignal;
1730                fn din_signal(&self) -> InputSignal;
1731            }
1732        }
1733    }
1734
1735    pub struct I2sClockDividers {
1736        mclk_divider: u32,
1737        bclk_divider: u32,
1738        denominator: u32,
1739        numerator: u32,
1740    }
1741
1742    pub fn calculate_clock(sample_rate: Rate, channels: u8, data_bits: u8) -> I2sClockDividers {
1743        // this loosely corresponds to `i2s_std_calculate_clock` and
1744        // `i2s_ll_tx_set_mclk` in esp-idf
1745        //
1746        // main difference is we are using fixed-point arithmetic here
1747
1748        // If data_bits is a power of two, use 256 as the mclk_multiple
1749        // If data_bits is 24, use 192 (24 * 8) as the mclk_multiple
1750        let mclk_multiple = if data_bits == 24 { 192 } else { 256 };
1751        let sclk = crate::soc::constants::I2S_SCLK; // for now it's fixed 160MHz and 96MHz (just H2)
1752
1753        let rate = sample_rate.as_hz();
1754
1755        let bclk = rate * channels as u32 * data_bits as u32;
1756        let mclk = rate * mclk_multiple;
1757        let bclk_divider = mclk / bclk;
1758        let mut mclk_divider = sclk / mclk;
1759
1760        let mut ma: u32;
1761        let mut mb: u32;
1762        let mut denominator: u32 = 0;
1763        let mut numerator: u32 = 0;
1764
1765        let freq_diff = sclk.abs_diff(mclk * mclk_divider);
1766
1767        if freq_diff != 0 {
1768            let decimal = freq_diff as u64 * 10000 / mclk as u64;
1769
1770            // Carry bit if the decimal is greater than 1.0 - 1.0 / (63.0 * 2) = 125.0 /
1771            // 126.0
1772            if decimal > 1250000 / 126 {
1773                mclk_divider += 1;
1774            } else {
1775                let mut min: u32 = !0;
1776
1777                for a in 2..=I2S_LL_MCLK_DIVIDER_MAX {
1778                    let b = (a as u64) * (freq_diff as u64 * 10000u64 / mclk as u64) + 5000;
1779                    ma = ((freq_diff as u64 * 10000u64 * a as u64) / 10000) as u32;
1780                    mb = (mclk as u64 * (b / 10000)) as u32;
1781
1782                    if ma == mb {
1783                        denominator = a as u32;
1784                        numerator = (b / 10000) as u32;
1785                        break;
1786                    }
1787
1788                    if mb.abs_diff(ma) < min {
1789                        denominator = a as u32;
1790                        numerator = b as u32;
1791                        min = mb.abs_diff(ma);
1792                    }
1793                }
1794            }
1795        }
1796
1797        I2sClockDividers {
1798            mclk_divider,
1799            bclk_divider,
1800            denominator,
1801            numerator,
1802        }
1803    }
1804}
1805
1806/// Async functionality
1807pub mod asynch {
1808    use super::{Error, I2sRx, I2sTx, RegisterAccessPrivate};
1809    use crate::{
1810        Async,
1811        dma::{
1812            DmaEligible,
1813            ReadBuffer,
1814            RxCircularState,
1815            TxCircularState,
1816            WriteBuffer,
1817            asynch::{DmaRxDoneChFuture, DmaRxFuture, DmaTxDoneChFuture, DmaTxFuture},
1818        },
1819    };
1820
1821    impl<'d> I2sTx<'d, Async> {
1822        /// One-shot write I2S.
1823        pub async fn write_dma_async(&mut self, words: &mut [u8]) -> Result<(), Error> {
1824            let (ptr, len) = (words.as_ptr(), words.len());
1825
1826            self.i2s.reset_tx();
1827
1828            let future = DmaTxFuture::new(&mut self.tx_channel);
1829
1830            unsafe {
1831                self.tx_chain.fill_for_tx(false, ptr, len)?;
1832                future
1833                    .tx
1834                    .prepare_transfer_without_start(self.i2s.dma_peripheral(), &self.tx_chain)
1835                    .and_then(|_| future.tx.start_transfer())?;
1836            }
1837
1838            self.i2s.tx_start();
1839            future.await?;
1840
1841            Ok(())
1842        }
1843
1844        /// Continuously write to I2S. Returns [I2sWriteDmaTransferAsync]
1845        pub fn write_dma_circular_async<TXBUF: ReadBuffer>(
1846            mut self,
1847            words: TXBUF,
1848        ) -> Result<I2sWriteDmaTransferAsync<'d, TXBUF>, Error> {
1849            let (ptr, len) = unsafe { words.read_buffer() };
1850
1851            // Reset TX unit and TX FIFO
1852            self.i2s.reset_tx();
1853
1854            // Enable corresponding interrupts if needed
1855
1856            // configure DMA outlink
1857            unsafe {
1858                self.tx_chain.fill_for_tx(true, ptr, len)?;
1859                self.tx_channel
1860                    .prepare_transfer_without_start(self.i2s.dma_peripheral(), &self.tx_chain)
1861                    .and_then(|_| self.tx_channel.start_transfer())?;
1862            }
1863
1864            // set I2S_TX_STOP_EN if needed
1865
1866            // start: set I2S_TX_START
1867            self.i2s.tx_start();
1868
1869            let state = TxCircularState::new(&mut self.tx_chain);
1870            Ok(I2sWriteDmaTransferAsync {
1871                i2s_tx: self,
1872                state,
1873                _buffer: words,
1874            })
1875        }
1876    }
1877
1878    /// An in-progress async circular DMA write transfer.
1879    pub struct I2sWriteDmaTransferAsync<'d, BUFFER> {
1880        i2s_tx: I2sTx<'d, Async>,
1881        state: TxCircularState,
1882        _buffer: BUFFER,
1883    }
1884
1885    impl<BUFFER> I2sWriteDmaTransferAsync<'_, BUFFER> {
1886        /// How many bytes can be pushed into the DMA transaction.
1887        /// Will wait for more than 0 bytes available.
1888        pub async fn available(&mut self) -> Result<usize, Error> {
1889            loop {
1890                self.state.update(&self.i2s_tx.tx_channel)?;
1891                let res = self.state.available;
1892
1893                if res != 0 {
1894                    break Ok(res);
1895                }
1896
1897                DmaTxDoneChFuture::new(&mut self.i2s_tx.tx_channel).await?
1898            }
1899        }
1900
1901        /// Push bytes into the DMA transaction.
1902        pub async fn push(&mut self, data: &[u8]) -> Result<usize, Error> {
1903            let avail = self.available().await?;
1904            let to_send = usize::min(avail, data.len());
1905            Ok(self.state.push(&data[..to_send])?)
1906        }
1907
1908        /// Push bytes into the DMA buffer via the given closure.
1909        /// The closure *must* return the actual number of bytes written.
1910        /// The closure *might* get called with a slice which is smaller than
1911        /// the total available buffer. Only useful for circular DMA
1912        /// transfers
1913        pub async fn push_with(
1914            &mut self,
1915            f: impl FnOnce(&mut [u8]) -> usize,
1916        ) -> Result<usize, Error> {
1917            let _avail = self.available().await;
1918            Ok(self.state.push_with(f)?)
1919        }
1920    }
1921
1922    impl<'d> I2sRx<'d, Async> {
1923        /// One-shot read I2S.
1924        pub async fn read_dma_async(&mut self, words: &mut [u8]) -> Result<(), Error> {
1925            let (ptr, len) = (words.as_mut_ptr(), words.len());
1926
1927            if len % 4 != 0 {
1928                return Err(Error::IllegalArgument);
1929            }
1930
1931            // Reset RX unit and RX FIFO
1932            self.i2s.reset_rx();
1933
1934            let future = DmaRxFuture::new(&mut self.rx_channel);
1935
1936            // configure DMA inlink
1937            unsafe {
1938                self.rx_chain.fill_for_rx(false, ptr, len)?;
1939                future
1940                    .rx
1941                    .prepare_transfer_without_start(self.i2s.dma_peripheral(), &self.rx_chain)
1942                    .and_then(|_| future.rx.start_transfer())?;
1943            }
1944
1945            // start: set I2S_RX_START
1946            self.i2s.rx_start(len);
1947
1948            future.await?;
1949
1950            Ok(())
1951        }
1952
1953        /// Continuously read from I2S. Returns [I2sReadDmaTransferAsync]
1954        pub fn read_dma_circular_async<RXBUF>(
1955            mut self,
1956            mut words: RXBUF,
1957        ) -> Result<I2sReadDmaTransferAsync<'d, RXBUF>, Error>
1958        where
1959            RXBUF: WriteBuffer,
1960        {
1961            let (ptr, len) = unsafe { words.write_buffer() };
1962
1963            if len % 4 != 0 {
1964                return Err(Error::IllegalArgument);
1965            }
1966
1967            // Reset RX unit and RX FIFO
1968            self.i2s.reset_rx();
1969
1970            // Enable corresponding interrupts if needed
1971
1972            // configure DMA inlink
1973            unsafe {
1974                self.rx_chain.fill_for_rx(true, ptr, len)?;
1975                self.rx_channel
1976                    .prepare_transfer_without_start(self.i2s.dma_peripheral(), &self.rx_chain)
1977                    .and_then(|_| self.rx_channel.start_transfer())?;
1978            }
1979
1980            // start: set I2S_RX_START
1981            self.i2s.rx_start(len);
1982
1983            let state = RxCircularState::new(&mut self.rx_chain);
1984            Ok(I2sReadDmaTransferAsync {
1985                i2s_rx: self,
1986                state,
1987                _buffer: words,
1988            })
1989        }
1990    }
1991
1992    /// An in-progress async circular DMA read transfer.
1993    pub struct I2sReadDmaTransferAsync<'d, BUFFER> {
1994        i2s_rx: I2sRx<'d, Async>,
1995        state: RxCircularState,
1996        _buffer: BUFFER,
1997    }
1998
1999    impl<BUFFER> I2sReadDmaTransferAsync<'_, BUFFER> {
2000        /// How many bytes can be popped from the DMA transaction.
2001        /// Will wait for more than 0 bytes available.
2002        pub async fn available(&mut self) -> Result<usize, Error> {
2003            loop {
2004                self.state.update()?;
2005
2006                let res = self.state.available;
2007
2008                if res != 0 {
2009                    break Ok(res);
2010                }
2011
2012                DmaRxDoneChFuture::new(&mut self.i2s_rx.rx_channel).await?;
2013            }
2014        }
2015
2016        /// Pop bytes from the DMA transaction.
2017        pub async fn pop(&mut self, data: &mut [u8]) -> Result<usize, Error> {
2018            let avail = self.available().await?;
2019            let to_rcv = usize::min(avail, data.len());
2020            Ok(self.state.pop(&mut data[..to_rcv])?)
2021        }
2022    }
2023}