embassy_stm32/
i2s.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! Inter-IC Sound (I2S)

use embassy_futures::join::join;
use embassy_hal_internal::into_ref;
use stm32_metapac::spi::vals;

use crate::dma::{ringbuffer, ChannelAndRequest, ReadableRingBuffer, TransferOptions, WritableRingBuffer};
use crate::gpio::{AfType, AnyPin, OutputType, SealedPin, Speed};
use crate::mode::Async;
use crate::spi::{Config as SpiConfig, RegsExt as _, *};
use crate::time::Hertz;
use crate::{Peripheral, PeripheralRef};

/// I2S mode
#[derive(Copy, Clone)]
pub enum Mode {
    /// Master mode
    Master,
    /// Slave mode
    Slave,
}

/// I2S function
#[derive(Copy, Clone)]
#[allow(dead_code)]
enum Function {
    /// Transmit audio data
    Transmit,
    /// Receive audio data
    Receive,
    #[cfg(spi_v3)]
    /// Transmit and Receive audio data
    FullDuplex,
}

/// I2C standard
#[derive(Copy, Clone)]
pub enum Standard {
    /// Philips
    Philips,
    /// Most significant bit first.
    MsbFirst,
    /// Least significant bit first.
    LsbFirst,
    /// PCM with long sync.
    PcmLongSync,
    /// PCM with short sync.
    PcmShortSync,
}

/// SAI error
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// `write` called on a SAI in receive mode.
    NotATransmitter,
    /// `read` called on a SAI in transmit mode.
    NotAReceiver,
    /// Overrun
    Overrun,
}

impl From<ringbuffer::Error> for Error {
    fn from(#[allow(unused)] err: ringbuffer::Error) -> Self {
        #[cfg(feature = "defmt")]
        {
            if err == ringbuffer::Error::DmaUnsynced {
                defmt::error!("Ringbuffer broken invariants detected!");
            }
        }
        Self::Overrun
    }
}

impl Standard {
    #[cfg(any(spi_v1, spi_v3, spi_f1))]
    const fn i2sstd(&self) -> vals::I2sstd {
        match self {
            Standard::Philips => vals::I2sstd::PHILIPS,
            Standard::MsbFirst => vals::I2sstd::MSB,
            Standard::LsbFirst => vals::I2sstd::LSB,
            Standard::PcmLongSync => vals::I2sstd::PCM,
            Standard::PcmShortSync => vals::I2sstd::PCM,
        }
    }

    #[cfg(any(spi_v1, spi_v3, spi_f1))]
    const fn pcmsync(&self) -> vals::Pcmsync {
        match self {
            Standard::PcmLongSync => vals::Pcmsync::LONG,
            _ => vals::Pcmsync::SHORT,
        }
    }
}

/// I2S data format.
#[derive(Copy, Clone)]
pub enum Format {
    /// 16 bit data length on 16 bit wide channel
    Data16Channel16,
    /// 16 bit data length on 32 bit wide channel
    Data16Channel32,
    /// 24 bit data length on 32 bit wide channel
    Data24Channel32,
    /// 32 bit data length on 32 bit wide channel
    Data32Channel32,
}

impl Format {
    #[cfg(any(spi_v1, spi_v3, spi_f1))]
    const fn datlen(&self) -> vals::Datlen {
        match self {
            Format::Data16Channel16 => vals::Datlen::BITS16,
            Format::Data16Channel32 => vals::Datlen::BITS16,
            Format::Data24Channel32 => vals::Datlen::BITS24,
            Format::Data32Channel32 => vals::Datlen::BITS32,
        }
    }

    #[cfg(any(spi_v1, spi_v3, spi_f1))]
    const fn chlen(&self) -> vals::Chlen {
        match self {
            Format::Data16Channel16 => vals::Chlen::BITS16,
            Format::Data16Channel32 => vals::Chlen::BITS32,
            Format::Data24Channel32 => vals::Chlen::BITS32,
            Format::Data32Channel32 => vals::Chlen::BITS32,
        }
    }
}

/// Clock polarity
#[derive(Copy, Clone)]
pub enum ClockPolarity {
    /// Low on idle.
    IdleLow,
    /// High on idle.
    IdleHigh,
}

impl ClockPolarity {
    #[cfg(any(spi_v1, spi_v3, spi_f1))]
    const fn ckpol(&self) -> vals::Ckpol {
        match self {
            ClockPolarity::IdleHigh => vals::Ckpol::IDLE_HIGH,
            ClockPolarity::IdleLow => vals::Ckpol::IDLE_LOW,
        }
    }
}

/// [`I2S`] configuration.
///
///  - `MS`: `Master` or `Slave`
///  - `TR`: `Transmit` or `Receive`
///  - `STD`: I2S standard, eg `Philips`
///  - `FMT`: Frame Format marker, eg `Data16Channel16`
#[non_exhaustive]
#[derive(Copy, Clone)]
pub struct Config {
    /// Mode
    pub mode: Mode,
    /// Which I2S standard to use.
    pub standard: Standard,
    /// Data format.
    pub format: Format,
    /// Clock polarity.
    pub clock_polarity: ClockPolarity,
    /// True to enable master clock output from this instance.
    pub master_clock: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            mode: Mode::Master,
            standard: Standard::Philips,
            format: Format::Data16Channel16,
            clock_polarity: ClockPolarity::IdleLow,
            master_clock: true,
        }
    }
}

/// I2S driver writer. Useful for moving write functionality across tasks.
pub struct Writer<'s, 'd, W: Word>(&'s mut WritableRingBuffer<'d, W>);

impl<'s, 'd, W: Word> Writer<'s, 'd, W> {
    /// Write data to the I2S ringbuffer.
    /// This appends the data to the buffer and returns immediately. The data will be transmitted in the background.
    /// If thfre’s no space in the buffer, this waits until there is.
    pub async fn write(&mut self, data: &[W]) -> Result<(), Error> {
        self.0.write_exact(data).await?;
        Ok(())
    }

    /// Reset the ring buffer to its initial state.
    /// Can be used to recover from overrun.
    /// The ringbuffer will always auto-reset on Overrun in any case.
    pub fn reset(&mut self) {
        self.0.clear();
    }
}

/// I2S driver reader. Useful for moving read functionality across tasks.
pub struct Reader<'s, 'd, W: Word>(&'s mut ReadableRingBuffer<'d, W>);

impl<'s, 'd, W: Word> Reader<'s, 'd, W> {
    /// Read data from the I2S ringbuffer.
    /// SAI is always receiving data in the background. This function pops already-received data from the buffer.
    /// If there’s less than data.len() data in the buffer, this waits until there is.
    pub async fn read(&mut self, data: &mut [W]) -> Result<(), Error> {
        self.0.read_exact(data).await?;
        Ok(())
    }

    /// Reset the ring buffer to its initial state.
    /// Can be used to prevent overrun.
    /// The ringbuffer will always auto-reset on Overrun in any case.
    pub fn reset(&mut self) {
        self.0.clear();
    }
}

/// I2S driver.
pub struct I2S<'d, W: Word> {
    #[allow(dead_code)]
    mode: Mode,
    spi: Spi<'d, Async>,
    txsd: Option<PeripheralRef<'d, AnyPin>>,
    rxsd: Option<PeripheralRef<'d, AnyPin>>,
    ws: Option<PeripheralRef<'d, AnyPin>>,
    ck: Option<PeripheralRef<'d, AnyPin>>,
    mck: Option<PeripheralRef<'d, AnyPin>>,
    tx_ring_buffer: Option<WritableRingBuffer<'d, W>>,
    rx_ring_buffer: Option<ReadableRingBuffer<'d, W>>,
}

impl<'d, W: Word> I2S<'d, W> {
    /// Create a transmitter driver.
    pub fn new_txonly<T: Instance>(
        peri: impl Peripheral<P = T> + 'd,
        sd: impl Peripheral<P = impl MosiPin<T>> + 'd,
        ws: impl Peripheral<P = impl WsPin<T>> + 'd,
        ck: impl Peripheral<P = impl CkPin<T>> + 'd,
        mck: impl Peripheral<P = impl MckPin<T>> + 'd,
        txdma: impl Peripheral<P = impl TxDma<T>> + 'd,
        txdma_buf: &'d mut [W],
        freq: Hertz,
        config: Config,
    ) -> Self {
        Self::new_inner(
            peri,
            new_pin!(sd, AfType::output(OutputType::PushPull, Speed::VeryHigh)),
            None,
            ws,
            ck,
            new_pin!(mck, AfType::output(OutputType::PushPull, Speed::VeryHigh)),
            new_dma!(txdma).map(|d| (d, txdma_buf)),
            None,
            freq,
            config,
            Function::Transmit,
        )
    }

    /// Create a transmitter driver without a master clock pin.
    pub fn new_txonly_nomck<T: Instance>(
        peri: impl Peripheral<P = T> + 'd,
        sd: impl Peripheral<P = impl MosiPin<T>> + 'd,
        ws: impl Peripheral<P = impl WsPin<T>> + 'd,
        ck: impl Peripheral<P = impl CkPin<T>> + 'd,
        txdma: impl Peripheral<P = impl TxDma<T>> + 'd,
        txdma_buf: &'d mut [W],
        freq: Hertz,
        config: Config,
    ) -> Self {
        Self::new_inner(
            peri,
            new_pin!(sd, AfType::output(OutputType::PushPull, Speed::VeryHigh)),
            None,
            ws,
            ck,
            None,
            new_dma!(txdma).map(|d| (d, txdma_buf)),
            None,
            freq,
            config,
            Function::Transmit,
        )
    }

    /// Create a receiver driver.
    pub fn new_rxonly<T: Instance>(
        peri: impl Peripheral<P = T> + 'd,
        sd: impl Peripheral<P = impl MisoPin<T>> + 'd,
        ws: impl Peripheral<P = impl WsPin<T>> + 'd,
        ck: impl Peripheral<P = impl CkPin<T>> + 'd,
        mck: impl Peripheral<P = impl MckPin<T>> + 'd,
        rxdma: impl Peripheral<P = impl RxDma<T>> + 'd,
        rxdma_buf: &'d mut [W],
        freq: Hertz,
        config: Config,
    ) -> Self {
        Self::new_inner(
            peri,
            None,
            new_pin!(sd, AfType::output(OutputType::PushPull, Speed::VeryHigh)),
            ws,
            ck,
            new_pin!(mck, AfType::output(OutputType::PushPull, Speed::VeryHigh)),
            None,
            new_dma!(rxdma).map(|d| (d, rxdma_buf)),
            freq,
            config,
            Function::Receive,
        )
    }

    #[cfg(spi_v3)]
    /// Create a full duplex driver.
    pub fn new_full_duplex<T: Instance>(
        peri: impl Peripheral<P = T> + 'd,
        txsd: impl Peripheral<P = impl MosiPin<T>> + 'd,
        rxsd: impl Peripheral<P = impl MisoPin<T>> + 'd,
        ws: impl Peripheral<P = impl WsPin<T>> + 'd,
        ck: impl Peripheral<P = impl CkPin<T>> + 'd,
        mck: impl Peripheral<P = impl MckPin<T>> + 'd,
        txdma: impl Peripheral<P = impl TxDma<T>> + 'd,
        txdma_buf: &'d mut [W],
        rxdma: impl Peripheral<P = impl RxDma<T>> + 'd,
        rxdma_buf: &'d mut [W],
        freq: Hertz,
        config: Config,
    ) -> Self {
        Self::new_inner(
            peri,
            new_pin!(txsd, AfType::output(OutputType::PushPull, Speed::VeryHigh)),
            new_pin!(rxsd, AfType::output(OutputType::PushPull, Speed::VeryHigh)),
            ws,
            ck,
            new_pin!(mck, AfType::output(OutputType::PushPull, Speed::VeryHigh)),
            new_dma!(txdma).map(|d| (d, txdma_buf)),
            new_dma!(rxdma).map(|d| (d, rxdma_buf)),
            freq,
            config,
            Function::FullDuplex,
        )
    }

    /// Start I2S driver.
    pub fn start(&mut self) {
        self.spi.info.regs.cr1().modify(|w| {
            w.set_spe(false);
        });
        self.spi.set_word_size(W::CONFIG);
        if let Some(tx_ring_buffer) = &mut self.tx_ring_buffer {
            tx_ring_buffer.start();

            set_txdmaen(self.spi.info.regs, true);
        }
        if let Some(rx_ring_buffer) = &mut self.rx_ring_buffer {
            rx_ring_buffer.start();
            // SPIv3 clears rxfifo on SPE=0
            #[cfg(not(any(spi_v3, spi_v4, spi_v5)))]
            flush_rx_fifo(self.spi.info.regs);

            set_rxdmaen(self.spi.info.regs, true);
        }
        self.spi.info.regs.cr1().modify(|w| {
            w.set_spe(true);
        });
        #[cfg(any(spi_v3, spi_v4, spi_v5))]
        self.spi.info.regs.cr1().modify(|w| {
            w.set_cstart(true);
        });
    }

    /// Reset the ring buffer to its initial state.
    /// Can be used to recover from overrun.
    pub fn clear(&mut self) {
        if let Some(rx_ring_buffer) = &mut self.rx_ring_buffer {
            rx_ring_buffer.clear();
        }
        if let Some(tx_ring_buffer) = &mut self.tx_ring_buffer {
            tx_ring_buffer.clear();
        }
    }

    /// Stop I2S driver.
    pub async fn stop(&mut self) {
        let regs = self.spi.info.regs;

        let tx_f = async {
            if let Some(tx_ring_buffer) = &mut self.tx_ring_buffer {
                tx_ring_buffer.stop().await;

                set_txdmaen(regs, false);
            }
        };

        let rx_f = async {
            if let Some(rx_ring_buffer) = &mut self.rx_ring_buffer {
                rx_ring_buffer.stop().await;

                set_rxdmaen(regs, false);
            }
        };

        join(rx_f, tx_f).await;

        #[cfg(any(spi_v3, spi_v4, spi_v5))]
        {
            if let Mode::Master = self.mode {
                regs.cr1().modify(|w| {
                    w.set_csusp(true);
                });

                while regs.cr1().read().cstart() {}
            }
        }

        regs.cr1().modify(|w| {
            w.set_spe(false);
        });

        self.clear();
    }

    /// Split the driver into a Reader/Writer pair.
    /// Useful for splitting the reader/writer functionality across tasks or
    /// for calling the read/write methods in parallel.
    pub fn split<'s>(&'s mut self) -> Result<(Reader<'s, 'd, W>, Writer<'s, 'd, W>), Error> {
        match (&mut self.rx_ring_buffer, &mut self.tx_ring_buffer) {
            (None, _) => Err(Error::NotAReceiver),
            (_, None) => Err(Error::NotATransmitter),
            (Some(rx_ring), Some(tx_ring)) => Ok((Reader(rx_ring), Writer(tx_ring))),
        }
    }

    /// Read data from the I2S ringbuffer.
    /// SAI is always receiving data in the background. This function pops already-received data from the buffer.
    /// If there’s less than data.len() data in the buffer, this waits until there is.
    pub async fn read(&mut self, data: &mut [W]) -> Result<(), Error> {
        match &mut self.rx_ring_buffer {
            Some(ring) => Reader(ring).read(data).await,
            _ => Err(Error::NotAReceiver),
        }
    }

    /// Write data to the I2S ringbuffer.
    /// This appends the data to the buffer and returns immediately. The data will be transmitted in the background.
    /// If thfre’s no space in the buffer, this waits until there is.
    pub async fn write(&mut self, data: &[W]) -> Result<(), Error> {
        match &mut self.tx_ring_buffer {
            Some(ring) => Writer(ring).write(data).await,
            _ => Err(Error::NotATransmitter),
        }
    }

    /// Write data directly to the raw I2S ringbuffer.
    /// This can be used to fill the buffer before starting the DMA transfer.
    pub async fn write_immediate(&mut self, data: &[W]) -> Result<(usize, usize), Error> {
        match &mut self.tx_ring_buffer {
            Some(ring) => Ok(ring.write_immediate(data)?),
            _ => return Err(Error::NotATransmitter),
        }
    }

    fn new_inner<T: Instance>(
        peri: impl Peripheral<P = T> + 'd,
        txsd: Option<PeripheralRef<'d, AnyPin>>,
        rxsd: Option<PeripheralRef<'d, AnyPin>>,
        ws: impl Peripheral<P = impl WsPin<T>> + 'd,
        ck: impl Peripheral<P = impl CkPin<T>> + 'd,
        mck: Option<PeripheralRef<'d, AnyPin>>,
        txdma: Option<(ChannelAndRequest<'d>, &'d mut [W])>,
        rxdma: Option<(ChannelAndRequest<'d>, &'d mut [W])>,
        freq: Hertz,
        config: Config,
        function: Function,
    ) -> Self {
        into_ref!(ws, ck);

        ws.set_as_af(ws.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh));
        ck.set_as_af(ck.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh));

        let spi = Spi::new_internal(peri, None, None, {
            let mut config = SpiConfig::default();
            config.frequency = freq;
            config
        });

        let regs = T::info().regs;

        #[cfg(all(rcc_f4, not(stm32f410)))]
        let pclk = unsafe { crate::rcc::get_freqs() }.plli2s1_r.to_hertz().unwrap();
        #[cfg(not(all(rcc_f4, not(stm32f410))))]
        let pclk = T::frequency();

        let (odd, div) = compute_baud_rate(pclk, freq, config.master_clock, config.format);

        #[cfg(any(spi_v1, spi_v3, spi_f1))]
        {
            #[cfg(spi_v3)]
            {
                regs.cr1().modify(|w| w.set_spe(false));

                reset_incompatible_bitfields::<T>();
            }

            use stm32_metapac::spi::vals::{I2scfg, Odd};

            // 1. Select the I2SDIV[7:0] bits in the SPI_I2SPR/SPI_I2SCFGR register to define the serial clock baud
            // rate to reach the proper audio sample frequency. The ODD bit in the
            // SPI_I2SPR/SPI_I2SCFGR register also has to be defined.

            // 2. Select the CKPOL bit to define the steady level for the communication clock. Set the
            // MCKOE bit in the SPI_I2SPR/SPI_I2SCFGR register if the master clock MCK needs to be provided to
            // the external DAC/ADC audio component (the I2SDIV and ODD values should be
            // computed depending on the state of the MCK output, for more details refer to
            // Section 28.4.4: Clock generator).

            // 3. Set the I2SMOD bit in SPI_I2SCFGR to activate the I2S functionalities and choose the
            // I2S standard through the I2SSTD[1:0] and PCMSYNC bits, the data length through the
            // DATLEN[1:0] bits and the number of bits per channel by configuring the CHLEN bit.
            // Select also the I2S master mode and direction (Transmitter or Receiver) through the
            // I2SCFG[1:0] bits in the SPI_I2SCFGR register.

            // 4. If needed, select all the potential interruption sources and the DMA capabilities by
            // writing the SPI_CR2 register.

            // 5. The I2SE bit in SPI_I2SCFGR register must be set.

            let clk_reg = {
                #[cfg(any(spi_v1, spi_f1))]
                {
                    regs.i2spr()
                }
                #[cfg(spi_v3)]
                {
                    regs.i2scfgr()
                }
            };

            clk_reg.modify(|w| {
                w.set_i2sdiv(div);
                w.set_odd(match odd {
                    true => Odd::ODD,
                    false => Odd::EVEN,
                });

                w.set_mckoe(config.master_clock);
            });

            regs.i2scfgr().modify(|w| {
                w.set_ckpol(config.clock_polarity.ckpol());

                w.set_i2smod(true);

                w.set_i2sstd(config.standard.i2sstd());
                w.set_pcmsync(config.standard.pcmsync());

                w.set_datlen(config.format.datlen());
                w.set_chlen(config.format.chlen());

                w.set_i2scfg(match (config.mode, function) {
                    (Mode::Master, Function::Transmit) => I2scfg::MASTER_TX,
                    (Mode::Master, Function::Receive) => I2scfg::MASTER_RX,
                    #[cfg(spi_v3)]
                    (Mode::Master, Function::FullDuplex) => I2scfg::MASTER_FULL_DUPLEX,
                    (Mode::Slave, Function::Transmit) => I2scfg::SLAVE_TX,
                    (Mode::Slave, Function::Receive) => I2scfg::SLAVE_RX,
                    #[cfg(spi_v3)]
                    (Mode::Slave, Function::FullDuplex) => I2scfg::SLAVE_FULL_DUPLEX,
                });

                #[cfg(any(spi_v1, spi_f1))]
                w.set_i2se(true);
            });

            let mut opts = TransferOptions::default();
            opts.half_transfer_ir = true;

            Self {
                mode: config.mode,
                spi,
                txsd: txsd.map(|w| w.map_into()),
                rxsd: rxsd.map(|w| w.map_into()),
                ws: Some(ws.map_into()),
                ck: Some(ck.map_into()),
                mck: mck.map(|w| w.map_into()),
                tx_ring_buffer: txdma.map(|(ch, buf)| unsafe {
                    WritableRingBuffer::new(ch.channel, ch.request, regs.tx_ptr(), buf, opts)
                }),
                rx_ring_buffer: rxdma.map(|(ch, buf)| unsafe {
                    ReadableRingBuffer::new(ch.channel, ch.request, regs.rx_ptr(), buf, opts)
                }),
            }
        }
    }
}

impl<'d, W: Word> Drop for I2S<'d, W> {
    fn drop(&mut self) {
        self.txsd.as_ref().map(|x| x.set_as_disconnected());
        self.rxsd.as_ref().map(|x| x.set_as_disconnected());
        self.ws.as_ref().map(|x| x.set_as_disconnected());
        self.ck.as_ref().map(|x| x.set_as_disconnected());
        self.mck.as_ref().map(|x| x.set_as_disconnected());
    }
}

// Note, calculation details:
// Fs = i2s_clock / [256 * ((2 * div) + odd)] when master clock is enabled
// Fs = i2s_clock / [(channel_length * 2) * ((2 * div) + odd)]` when master clock is disabled
// channel_length is 16 or 32
//
// can be rewritten as
// Fs = i2s_clock / (coef * division)
// where coef is a constant equal to 256, 64 or 32 depending channel length and master clock
// and where division = (2 * div) + odd
//
// Equation can be rewritten as
// division = i2s_clock/ (coef * Fs)
//
// note: division = (2 * div) + odd = (div << 1) + odd
// in other word, from bits point of view, division[8:1] = div[7:0] and division[0] = odd
fn compute_baud_rate(i2s_clock: Hertz, request_freq: Hertz, mclk: bool, data_format: Format) -> (bool, u8) {
    let coef = if mclk {
        256
    } else if let Format::Data16Channel16 = data_format {
        32
    } else {
        64
    };

    let (n, d) = (i2s_clock.0, coef * request_freq.0);
    let division = (n + (d >> 1)) / d;

    if division < 4 {
        (false, 2)
    } else if division > 511 {
        (true, 255)
    } else {
        ((division & 1) == 1, (division >> 1) as u8)
    }
}

#[cfg(spi_v3)]
// The STM32H7 reference manual specifies that any incompatible bitfields should be reset
// to their reset values while operating in I2S mode.
fn reset_incompatible_bitfields<T: Instance>() {
    let regs = T::info().regs;
    regs.cr1().modify(|w| {
        let iolock = w.iolock();
        let csusp = w.csusp();
        let spe = w.cstart();
        let cstart = w.cstart();
        w.0 = 0;
        w.set_iolock(iolock);
        w.set_csusp(csusp);
        w.set_spe(spe);
        w.set_cstart(cstart);
    });

    regs.cr2().write(|w| w.0 = 0);

    regs.cfg1().modify(|w| {
        let txdmaen = w.txdmaen();
        let rxdmaen = w.rxdmaen();
        let fthlv = w.fthlv();
        w.0 = 0;
        w.set_txdmaen(txdmaen);
        w.set_rxdmaen(rxdmaen);
        w.set_fthlv(fthlv);
    });

    regs.cfg2().modify(|w| {
        let afcntr = w.afcntr();
        let lsbfirst = w.lsbfirst();
        let ioswp = w.ioswp();
        w.0 = 0;
        w.set_afcntr(afcntr);
        w.set_lsbfirst(lsbfirst);
        w.set_ioswp(ioswp);
    });

    regs.ier().modify(|w| {
        let tifreie = w.tifreie();
        let ovrie = w.ovrie();
        let udrie = w.udrie();
        let txpie = w.txpie();
        let rxpie = w.rxpie();

        w.0 = 0;

        w.set_tifreie(tifreie);
        w.set_ovrie(ovrie);
        w.set_udrie(udrie);
        w.set_txpie(txpie);
        w.set_rxpie(rxpie);
    });

    regs.ifcr().write(|w| {
        w.set_suspc(true);
        w.set_tifrec(true);
        w.set_ovrc(true);
        w.set_udrc(true);
    });

    regs.crcpoly().write(|w| w.0 = 0x107);
    regs.txcrc().write(|w| w.0 = 0);
    regs.rxcrc().write(|w| w.0 = 0);
    regs.udrdr().write(|w| w.0 = 0);
}