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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
//! Driver for the Inter-IC Sound (I2S) peripheral(s).

use core::{ffi::c_void, marker::PhantomData, mem::MaybeUninit};

use esp_idf_sys::{esp, i2s_port_t, EspError, TickType_t};

#[cfg(not(esp_idf_version_major = "4"))]
use {
    core::ptr::null_mut,
    esp_idf_sys::{
        i2s_chan_config_t, i2s_chan_handle_t, i2s_channel_disable, i2s_channel_enable,
        i2s_channel_read, i2s_channel_register_event_callback, i2s_channel_write, i2s_del_channel,
        i2s_event_callbacks_t, i2s_event_data_t, i2s_new_channel,
    },
};

#[cfg(esp_idf_version_major = "4")]
use esp_idf_sys::{
    i2s_config_t, i2s_driver_install, i2s_driver_uninstall, i2s_read, i2s_start, i2s_stop,
    i2s_write,
};

#[cfg(not(esp_idf_version_major = "4"))]
use crate::interrupt::asynch::HalIsrNotification;
use crate::{delay, io::EspIOError};

// For v5+, we rely configuration options for PDM/TDM support.
// For v4, we have to examine the chip type.
#[cfg(any(
    all(
        not(esp_idf_version_major = "4"),
        any(esp_idf_soc_i2s_supports_pdm_rx, esp_idf_soc_i2s_supports_pdm_tx)
    ),
    all(esp_idf_version_major = "4", any(esp32, esp32s3, esp32c3, esp32c6))
))]
mod pdm;

mod std;

#[cfg(any(
    all(not(esp_idf_version_major = "4"), esp_idf_soc_i2s_supports_tdm),
    all(esp_idf_version_major = "4", any(esp32s3, esp32c3, esp32c6))
))]
mod tdm;

/// I2S channel base configuration.
pub type I2sConfig = config::Config;

/// I2S configuration
pub mod config {
    #[cfg(any(
        all(
            not(esp_idf_version_major = "4"),
            any(esp_idf_soc_i2s_supports_pdm_rx, esp_idf_soc_i2s_supports_pdm_tx)
        ),
        all(esp_idf_version_major = "4", any(esp32, esp32s3, esp32c3, esp32c6))
    ))]
    pub use super::pdm::config::*;

    pub use super::std::config::*;

    #[cfg(any(
        all(not(esp_idf_version_major = "4"), esp_idf_soc_i2s_supports_tdm),
        all(esp_idf_version_major = "4", any(esp32s3, esp32c3, esp32c6))
    ))]
    pub use super::tdm::config::*;

    use esp_idf_sys::{
        i2s_mclk_multiple_t, i2s_mclk_multiple_t_I2S_MCLK_MULTIPLE_128,
        i2s_mclk_multiple_t_I2S_MCLK_MULTIPLE_256, i2s_mclk_multiple_t_I2S_MCLK_MULTIPLE_384,
        EspError, ESP_ERR_INVALID_ARG,
    };

    #[cfg(not(esp_idf_version_major = "4"))]
    use esp_idf_sys::{
        i2s_chan_config_t, i2s_clock_src_t, i2s_data_bit_width_t,
        i2s_mclk_multiple_t_I2S_MCLK_MULTIPLE_512, i2s_port_t, i2s_role_t, i2s_slot_bit_width_t,
        i2s_slot_mode_t,
    };

    #[cfg(esp_idf_version_major = "4")]
    use esp_idf_sys::{
        i2s_bits_per_chan_t, i2s_bits_per_sample_t, i2s_mode_t, i2s_mode_t_I2S_MODE_MASTER,
        i2s_mode_t_I2S_MODE_SLAVE,
    };

    /// The default number of DMA buffers to use.
    pub const DEFAULT_DMA_BUFFER_COUNT: u32 = 6;

    /// The default number of frames per DMA buffer.
    pub const DEFAULT_FRAMES_PER_DMA_BUFFER: u32 = 240;

    /// I2S clock source.
    #[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
    pub enum ClockSource {
        /// Use PLL_F160M as the source clock
        #[cfg(not(any(esp32h2, esp32c2)))]
        #[default]
        Pll160M,

        /// Use PLL_F60M as the source clock
        #[cfg(esp32c2)]
        #[default]
        Pll60M,

        /// Use PLL_F64M as the source clock
        #[cfg(esp32h2)]
        #[default]
        Pll64M,

        /// Use APLL as the source clock
        #[cfg(any(esp32, esp32s2))]
        Apll,
    }

    impl ClockSource {
        #[cfg(not(esp_idf_version_major = "4"))]
        #[allow(clippy::unnecessary_cast)]
        pub(super) fn as_sdk(&self) -> i2s_clock_src_t {
            match self {
                #[cfg(not(any(esp32h2, esp32c2)))]
                Self::Pll160M => core::convert::TryInto::try_into(
                    esp_idf_sys::soc_module_clk_t_SOC_MOD_CLK_PLL_F160M,
                )
                .unwrap(),
                #[cfg(esp32c2)]
                Self::Pll60M => core::convert::TryInto::try_into(
                    esp_idf_sys::soc_module_clk_t_SOC_MOD_CLK_PLL_F60M,
                )
                .unwrap(),
                #[cfg(esp32h2)]
                Self::Pll64M => core::convert::TryInto::try_into(
                    esp_idf_sys::soc_module_clk_t_SOC_MOD_CLK_PLL_F64M,
                )
                .unwrap(),
                #[cfg(any(esp32, esp32s2))]
                Self::Apll => esp_idf_sys::soc_module_clk_t_SOC_MOD_CLK_APLL,
            }
        }
    }

    /// I2S common channel configuration.
    ///
    /// To create a custom configuration, use the builder pattern built-in to this struct. For example:
    /// ```
    /// use esp_idf_hal::i2s::config::{ChannelOpen, Config, Role};
    /// let config = Config::default().role(Role::Target).channels(ChannelOpen::Rx);
    /// ```
    ///
    /// The default configuration is:
    /// * [`role`][Config::role]: [`Role::Controller`] (master)
    /// * [`dma_buffer_count`][Config::dma_buffer_count]: 6 ([`DEFAULT_DMA_BUFFER_COUNT`])
    /// * [`frames_per_buffer`][Config::frames_per_buffer]: 240 ([`DEFAULT_FRAMES_PER_DMA_BUFFER`])
    /// * [`auto_clear`][Config::auto_clear]: `false`
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct Config {
        /// The role of this channel: controller (master) or target (slave)
        pub(super) role: Role,

        /// The number of DMA buffers number to use.
        pub(super) dma_buffer_count: u32,

        /// The number of I2S frames in one DMA buffer.
        pub(super) frames_per_buffer: u32,

        /// If true, the transmit buffer will be automatically cleared upon sending.
        pub(super) auto_clear: bool,
    }

    impl Default for Config {
        #[inline(always)]
        fn default() -> Self {
            Self::new()
        }
    }

    impl Config {
        #[inline(always)]
        /// Create a new Config with the default settings.
        pub const fn new() -> Self {
            Self {
                role: Role::Controller,
                dma_buffer_count: DEFAULT_DMA_BUFFER_COUNT,
                frames_per_buffer: DEFAULT_FRAMES_PER_DMA_BUFFER,
                auto_clear: false,
            }
        }

        /// Set the role of this channel: controller (master) or target (slave).
        #[must_use]
        #[inline(always)]
        pub fn role(mut self, role: Role) -> Self {
            self.role = role;
            self
        }

        /// Set the number of DMA buffers to use.
        #[must_use]
        #[inline(always)]
        pub fn dma_buffer_count(mut self, dma_buffer_count: u32) -> Self {
            self.dma_buffer_count = dma_buffer_count;
            self
        }

        /// Set the number of I2S frames in one DMA buffer.
        #[must_use]
        #[inline(always)]
        pub fn frames_per_buffer(mut self, frames: u32) -> Self {
            self.frames_per_buffer = frames;
            self
        }

        /// Set if the transmit buffer will be automatically cleared upon sending.
        #[must_use]
        #[inline(always)]
        pub fn auto_clear(mut self, auto_clear: bool) -> Self {
            self.auto_clear = auto_clear;
            self
        }

        /// Convert to the ESP-IDF SDK `i2s_chan_config_t` representation.
        #[allow(clippy::needless_update)]
        #[cfg(not(esp_idf_version_major = "4"))]
        #[inline(always)]
        pub(super) fn as_sdk(&self, id: i2s_port_t) -> i2s_chan_config_t {
            i2s_chan_config_t {
                id,
                role: self.role.as_sdk(),
                dma_desc_num: self.dma_buffer_count,
                dma_frame_num: self.frames_per_buffer,
                auto_clear: self.auto_clear,
                ..Default::default()
            }
        }
    }

    /// Available data bit width in one slot.
    #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
    pub enum DataBitWidth {
        /// Channel data bit width is 8 bits.
        Bits8,

        /// Channel data bit width is 16 bits.
        Bits16,

        /// Channel data bit width is 24 bits.
        Bits24,

        /// Channel data bit width is 32 bits.
        Bits32,
    }

    impl From<DataBitWidth> for u32 {
        #[inline(always)]
        fn from(value: DataBitWidth) -> Self {
            match value {
                DataBitWidth::Bits8 => 8,
                DataBitWidth::Bits16 => 16,
                DataBitWidth::Bits24 => 24,
                DataBitWidth::Bits32 => 32,
            }
        }
    }

    impl DataBitWidth {
        /// Convert to the ESP-IDF SDK `i2s_data_bit_width_t` representation.
        #[cfg(not(esp_idf_version_major = "4"))]
        #[inline(always)]
        pub(super) fn as_sdk(&self) -> i2s_data_bit_width_t {
            match self {
                Self::Bits8 => 8,
                Self::Bits16 => 16,
                Self::Bits24 => 24,
                Self::Bits32 => 32,
            }
        }

        /// Convert to the ESP-IDF SDK `i2s_bits_per_sample_t` representation.
        #[cfg(esp_idf_version_major = "4")]
        #[inline(always)]
        pub(super) fn as_sdk(&self) -> i2s_bits_per_sample_t {
            match self {
                Self::Bits8 => 8,
                Self::Bits16 => 16,
                Self::Bits24 => 24,
                Self::Bits32 => 32,
            }
        }
    }

    impl TryFrom<usize> for DataBitWidth {
        type Error = EspError;

        fn try_from(value: usize) -> Result<Self, Self::Error> {
            match value {
                8 => Ok(Self::Bits8),
                16 => Ok(Self::Bits16),
                24 => Ok(Self::Bits24),
                32 => Ok(Self::Bits32),
                _ => Err(EspError::from(ESP_ERR_INVALID_ARG).unwrap()),
            }
        }
    }

    /// The multiple of MCLK to the sample rate.
    #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
    pub enum MclkMultiple {
        /// MCLK = sample rate * 128
        M128,

        /// MCLK = sample rate * 256
        M256,

        /// MCLK = sample rate * 384
        M384,

        /// MCLK = sample rate * 512
        #[cfg(not(esp_idf_version_major = "4"))]
        M512,
    }

    impl MclkMultiple {
        /// Convert to the ESP-IDF SDK `i2s_mclk_multiple_t` representation.
        #[inline(always)]
        pub(super) fn as_sdk(&self) -> i2s_mclk_multiple_t {
            match self {
                Self::M128 => i2s_mclk_multiple_t_I2S_MCLK_MULTIPLE_128,
                Self::M256 => i2s_mclk_multiple_t_I2S_MCLK_MULTIPLE_256,
                Self::M384 => i2s_mclk_multiple_t_I2S_MCLK_MULTIPLE_384,
                #[cfg(not(esp_idf_version_major = "4"))]
                Self::M512 => i2s_mclk_multiple_t_I2S_MCLK_MULTIPLE_512,
            }
        }
    }

    impl From<MclkMultiple> for u32 {
        #[inline(always)]
        fn from(mclk_multiple: MclkMultiple) -> Self {
            match mclk_multiple {
                MclkMultiple::M128 => 128,
                MclkMultiple::M256 => 256,
                MclkMultiple::M384 => 384,
                #[cfg(not(esp_idf_version_major = "4"))]
                MclkMultiple::M512 => 512,
            }
        }
    }

    /// I2S channel operating role
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
    pub enum Role {
        /// Controller (master)
        #[default]
        Controller,

        /// Target (slave)
        Target,
    }

    /// I2S peripheral in controller (master) role, bclk and ws signal will be set to output.
    #[cfg(not(esp_idf_version_major = "4"))]
    const I2S_ROLE_CONTROLLER: i2s_role_t = 0;

    /// I2S peripheral in target (slave) role, bclk and ws signal will be set to input.
    #[cfg(not(esp_idf_version_major = "4"))]
    const I2S_ROLE_TARGET: i2s_role_t = 1;

    impl Role {
        /// Convert to the ESP-IDF SDK `i2s_role_t` representation.
        #[cfg(not(esp_idf_version_major = "4"))]
        #[inline(always)]
        pub(super) fn as_sdk(&self) -> i2s_role_t {
            match self {
                Self::Controller => I2S_ROLE_CONTROLLER,
                Self::Target => I2S_ROLE_TARGET,
            }
        }

        /// Convert to the ESP-IDF SDK `i2s_mode_t` representation.
        #[cfg(esp_idf_version_major = "4")]
        #[inline(always)]
        pub(super) fn as_sdk(&self) -> i2s_mode_t {
            match self {
                Self::Controller => i2s_mode_t_I2S_MODE_MASTER,
                Self::Target => i2s_mode_t_I2S_MODE_SLAVE,
            }
        }
    }

    /// The total slot bit width in one slot.
    ///
    /// This is not necessarily the number of data bits in one slot. A slot may have additional bits padded to fill out
    /// the slot.
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
    pub enum SlotBitWidth {
        /// Slot bit width is automatically set to the data bit width.
        #[default]
        Auto,

        /// Slot bit width is 8 bits.
        Bits8,

        /// Slot bit width is 16 bits.
        Bits16,

        /// Slot bit width is 24 bits.
        Bits24,

        /// Slot bit width is 32 bits.
        Bits32,
    }

    #[cfg(not(esp_idf_version_major = "4"))]
    type SlotBitWidthSdkType = i2s_slot_bit_width_t;

    #[cfg(esp_idf_version_major = "4")]
    type SlotBitWidthSdkType = i2s_bits_per_chan_t;

    impl SlotBitWidth {
        /// Convert this to the ESP-IDF SDK `i2s_slot_bit_width_t`/`i2s_bits_per_chan_t` representation.
        #[inline(always)]
        pub(super) fn as_sdk(&self) -> SlotBitWidthSdkType {
            match self {
                Self::Auto => 0,
                Self::Bits8 => 8,
                Self::Bits16 => 16,
                Self::Bits24 => 24,
                Self::Bits32 => 32,
            }
        }
    }

    impl TryFrom<u32> for SlotBitWidth {
        type Error = EspError;

        fn try_from(value: u32) -> Result<Self, Self::Error> {
            match value {
                0 => Ok(Self::Auto),
                8 => Ok(Self::Bits8),
                16 => Ok(Self::Bits16),
                24 => Ok(Self::Bits24),
                32 => Ok(Self::Bits32),
                _ => Err(EspError::from(ESP_ERR_INVALID_ARG).unwrap()),
            }
        }
    }

    /// I2S channel slot mode.
    ///
    /// See the documentation for the mode of operation to see how this affects the data layout:
    /// * [PDM Rx][PdmRxSlotConfig]
    /// * [PDM Tx][PdmTxSlotConfig]
    /// * [Standard Rx/Tx][StdSlotConfig]
    /// * [TDM Rx/Tx][TdmSlotConfig]
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
    pub enum SlotMode {
        /// Mono mode:
        /// * When transmitting, transmit the same data in all slots.
        /// * When receiving, only receive data from the first slot.
        Mono,

        /// Stereo mode:
        /// * When transmitting, transmit different data in each slot.
        /// * When receiving, receive data from all slots.
        #[default]
        Stereo,
    }

    impl SlotMode {
        /// Convert this to the ESP-IDF SDK `i2s_slot_mode_t` representation.
        #[cfg(not(esp_idf_version_major = "4"))]
        #[inline(always)]
        pub(super) fn as_sdk(&self) -> i2s_slot_mode_t {
            match self {
                Self::Mono => 1,
                Self::Stereo => 2,
            }
        }
    }
}

/// Trait implemented by I2S peripherals to obtain their port number.
pub trait I2s: Send + sealed::Sealed {
    /// Return the port number for the peripheral.
    fn port() -> i2s_port_t;
}

mod sealed {
    pub trait Sealed {}

    impl Sealed for super::I2S0 {}
    #[cfg(any(esp32, esp32s3))]
    impl Sealed for super::I2S1 {}
}

pub trait I2sPort {
    /// Returns the I2S port number of this driver.
    fn port(&self) -> i2s_port_t;
}

/// Marker trait indicating that a driver supports receiving data via the [`I2sRx`] trait.
pub trait I2sRxSupported {}

/// Concrete implementation of [`I2sRxSupported`] for use in clients.
///
/// Example usage:
/// ```
/// use esp_idf_hal::i2s::{config::{StdConfig, DataBitWidth}, gpio::*};
/// let std_config = StdConfig::philips(48000, DataBitWidth::Bits16);
/// let peripherals = Peripherals::take().unwrap();
/// let bclk = peripherals.pins.gpio1;
/// let din = peripherals.pins.gpio4;
/// let mclk = AnyIOPin::none();
/// let ws = peripherals.pins.gpio2;
/// let i2s = I2sDriver::<I2sRx>::new_std_rx(peripherals.i2s0, &std_config, bclk, din, mclk, ws).unwrap();
/// ```
pub struct I2sRx {}
impl I2sRxSupported for I2sRx {}

/// Marker trait indicating that a driver supports transmitting data via the [`I2sTx`] trait.
pub trait I2sTxSupported {}

/// Concrete implementation of [`I2sTxSupported`] for use in clients.
///
/// Example usage:
/// ```
/// use esp_idf_hal::i2s::{config::{StdConfig, DataBitWidth}, gpio::*};
/// let std_config = StdConfig::philips(48000, DataBitWidth::Bits16);
/// let peripherals = Peripherals::take().unwrap();
/// let bclk = peripherals.pins.gpio1;
/// let dout = peripherals.pins.gpio6;
/// let mclk = AnyIOPin::none();
/// let ws = peripherals.pins.gpio2;
/// let i2s = I2sDriver::<I2sTx>::new_std_tx(peripherals.i2s0, &std_config, bclk, dout, mclk, ws).unwrap();
/// ```
pub struct I2sTx {}
impl I2sTxSupported for I2sTx {}

/// Concrete implementation of both [`I2sRxSupported`] and [`I2sTxSupported`] for use in clients.
///
/// Example usage:
/// ```
/// use esp_idf_hal::i2s::{config::{StdConfig, DataBitWidth}, gpio::*, peripherals::Peripherals};
/// let std_config = StdConfig::philips(48000, DataBitWidth::Bits16);
/// let peripherals = Peripherals::take().unwrap();
/// let bclk = peripherals.pins.gpio1;
/// let din = peripherals.pins.gpio4;
/// let dout = peripherals.pins.gpio6;
/// let mclk = AnyIOPin::none();
/// let ws = peripherals.pins.gpio2;
/// let i2s = I2sDriver::<I2sBiDir>::new_std_bidir(peripherals.i2s0, &std_config, bclk, din, dout, mclk, ws).unwrap();
/// ```
pub struct I2sBiDir {}
impl I2sRxSupported for I2sBiDir {}
impl I2sTxSupported for I2sBiDir {}

/// Inter-IC Sound (I2S) driver.
pub struct I2sDriver<'d, Dir> {
    /// The Rx channel, possibly null.
    #[cfg(not(esp_idf_version_major = "4"))]
    rx_handle: i2s_chan_handle_t,

    /// The Tx channel, possibly null.
    #[cfg(not(esp_idf_version_major = "4"))]
    tx_handle: i2s_chan_handle_t,

    /// The I2S peripheral number. Either 0 (all devices) or 1 (ESP32 and ESP32-S3 only).
    port: u8,

    /// Driver lifetime -- mimics the lifetime of the peripheral.
    _p: PhantomData<&'d ()>,

    /// Directionality -- mimics the directionality of the peripheral.
    _dir: PhantomData<Dir>,
}

impl<'d, Dir> I2sDriver<'d, Dir> {
    /// Create a new standard mode driver for the given I2S peripheral with both the receive and transmit channels open.
    #[cfg(not(esp_idf_version_major = "4"))]
    fn internal_new<I2S: I2s>(
        config: &i2s_chan_config_t,
        rx: bool,
        tx: bool,
    ) -> Result<Self, EspError> {
        let port = I2S::port();

        let mut rx_handle: i2s_chan_handle_t = null_mut();
        let mut tx_handle: i2s_chan_handle_t = null_mut();

        unsafe {
            esp!(i2s_new_channel(
                config,
                if tx {
                    &mut tx_handle as _
                } else {
                    core::ptr::null_mut()
                },
                if rx {
                    &mut rx_handle as _
                } else {
                    core::ptr::null_mut()
                },
            ))?
        };

        let mut this = Self {
            port: port as u8,
            rx_handle,
            tx_handle,
            _p: PhantomData,
            _dir: PhantomData,
        };

        this.subscribe_channel(this.rx_handle)?;
        this.subscribe_channel(this.tx_handle)?;

        Ok(this)
    }

    #[cfg(esp_idf_version_major = "4")]
    #[allow(clippy::too_many_arguments)]
    pub fn internal_new<I2S: I2s>(config: &i2s_config_t) -> Result<Self, EspError> {
        let port = I2S::port();

        unsafe {
            esp!(i2s_driver_install(port, config, 0, core::ptr::null_mut()))?;
        }

        Ok(Self {
            port: port as u8,
            _p: PhantomData,
            _dir: PhantomData,
        })
    }

    #[cfg(not(esp_idf_version_major = "4"))]
    fn subscribe_channel(&mut self, handle: i2s_chan_handle_t) -> Result<(), EspError> {
        if !handle.is_null() {
            let callbacks = i2s_event_callbacks_t {
                on_recv: Some(dispatch_recv),
                on_recv_q_ovf: Some(dispatch_recv),
                on_sent: Some(dispatch_send),
                on_send_q_ovf: Some(dispatch_send),
            };

            // Safety: chan_handle is a valid pointer to an i2s_chan_handle_t and callbacks is initialized.
            esp!(unsafe {
                i2s_channel_register_event_callback(
                    handle,
                    &callbacks,
                    self.port as u32 as *mut core::ffi::c_void,
                )
            })?;
        }

        Ok(())
    }

    #[cfg(not(esp_idf_version_major = "4"))]
    fn unsubscribe_channel(&mut self, handle: i2s_chan_handle_t) -> Result<(), EspError> {
        if !handle.is_null() {
            let callbacks = i2s_event_callbacks_t {
                on_recv: None,
                on_recv_q_ovf: None,
                on_sent: None,
                on_send_q_ovf: None,
            };

            // Safety: chan_handle is a valid pointer to an i2s_chan_handle_t and callbacks is initialized.
            esp!(unsafe {
                i2s_channel_register_event_callback(
                    handle,
                    &callbacks,
                    self.port as u32 as *mut core::ffi::c_void,
                )
            })?;
        }

        Ok(())
    }

    #[cfg(not(esp_idf_version_major = "4"))]
    fn del_channel(&mut self, handle: i2s_chan_handle_t) -> Result<(), EspError> {
        if !handle.is_null() {
            let callbacks = i2s_event_callbacks_t {
                on_recv: None,
                on_recv_q_ovf: None,
                on_sent: None,
                on_send_q_ovf: None,
            };

            // Safety: chan_handle is a valid pointer to an i2s_chan_handle_t and callbacks is initialized.
            esp!(unsafe {
                i2s_channel_register_event_callback(handle, &callbacks, core::ptr::null_mut())
            })?;

            // Safety: chan_handle is a valid, non-null i2s_chan_handle_t.
            esp!(unsafe { i2s_del_channel(handle) })?;
        }

        Ok(())
    }

    fn remap_result(
        result: Result<(), EspError>,
        bytes_processed: usize,
    ) -> Result<usize, EspError> {
        match result {
            Ok(_) => Ok(bytes_processed),
            Err(err) if err.code() == esp_idf_sys::ESP_ERR_TIMEOUT && bytes_processed > 0 => {
                Ok(bytes_processed)
            }
            Err(err) => Err(err),
        }
    }
}

/// Functions for receive channels.
impl<'d, Dir> I2sDriver<'d, Dir>
where
    Dir: I2sRxSupported,
{
    /// Enable the I2S receive channel.
    ///
    /// # Note
    /// This can only be called when the channel is in the `READY` state: initialized but not yet started from a driver
    /// constructor, or disabled from the `RUNNING` state via [`rx_disable()`][I2sDriver::rx_disable]. The channel
    /// will enter the `RUNNING` state if it is enabled successfully.
    ///
    /// Enabling the channel will start I2S communications on the hardware. BCLK and WS signals will be generated if
    /// this is a controller. MCLK will be generated once initialization is finished.
    ///
    /// # Errors
    /// This will return an [`EspError`] with `ESP_ERR_INVALID_STATE` if the channel is not in the `READY` state.
    #[cfg(esp_idf_version_major = "4")]
    pub fn rx_enable(&mut self) -> Result<(), EspError> {
        unsafe { esp!(i2s_start(self.port as _)) }
    }

    /// Enable the I2S receive channel.
    ///
    /// # Note
    /// This can only be called when the channel is in the `READY` state: initialized but not yet started from a driver
    /// constructor, or disabled from the `RUNNING` state via [`rx_enable()`][I2sRxChannel::rx_disable]. The channel
    /// will enter the `RUNNING` state if it is enabled successfully.
    ///
    /// Enabling the channel will start I2S communications on the hardware. BCLK and WS signals will be generated if
    /// this is a controller. MCLK will be generated once initialization is finished.
    ///
    /// # Errors
    /// This will return an [`EspError`] with `ESP_ERR_INVALID_STATE` if the channel is not in the `READY` state.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn rx_enable(&mut self) -> Result<(), EspError> {
        unsafe { esp!(i2s_channel_enable(self.rx_handle)) }
    }

    /// Disable the I2S receive channel.
    ///
    /// # Note
    /// This can only be called when the channel is in the `RUNNING` state: the channel has been previously enabled
    /// via a call to [`rx_enable()`][I2sRxChannel::rx_enable]. The channel will enter the `READY` state if it is
    /// disabled successfully.
    ///
    /// Disabling the channel will stop I2S communications on the hardware. BCLK and WS signals will stop being
    /// generated if this is a controller. MCLK will continue to be generated.
    ///
    /// # Errors
    /// This will return an [`EspError`] with `ESP_ERR_INVALID_STATE` if the channel is not in the `RUNNING` state.
    #[cfg(esp_idf_version_major = "4")]
    pub fn rx_disable(&mut self) -> Result<(), EspError> {
        unsafe { esp!(i2s_stop(self.port as _)) }
    }

    /// Disable the I2S receive channel.
    ///
    /// # Note
    /// This can only be called when the channel is in the `RUNNING` state: the channel has been previously enabled
    /// via a call to [`rx_enable()`][I2sRxChannel::rx_enable]. The channel will enter the `READY` state if it is
    /// disabled successfully.
    ///
    /// Disabling the channel will stop I2S communications on the hardware. BCLK and WS signals will stop being
    /// generated if this is a controller. MCLK will continue to be generated.
    ///
    /// # Errors
    /// This will return an [`EspError`] with `ESP_ERR_INVALID_STATE` if the channel is not in the `RUNNING` state.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn rx_disable(&mut self) -> Result<(), EspError> {
        unsafe { esp!(i2s_channel_disable(self.rx_handle)) }
    }

    /// Read data from the channel asynchronously.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes read, or an [`EspError`] if an error occurred.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub async fn read_async(&mut self, buffer: &mut [u8]) -> Result<usize, EspError> {
        loop {
            match self.read(buffer, crate::delay::NON_BLOCK) {
                Err(err) if err.code() == esp_idf_sys::ESP_ERR_TIMEOUT => {
                    RECV_NOTIFIER[self.port as usize].wait().await;
                }
                other => break other,
            }
        }
    }

    /// Read data from the channel.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes read, or an [`EspError`] if an error occurred.
    #[cfg(esp_idf_version_major = "4")]
    pub fn read(&mut self, buffer: &mut [u8], timeout: TickType_t) -> Result<usize, EspError> {
        if buffer.is_empty() {
            Ok(0)
        } else {
            let mut bytes_read: usize = 0;

            Self::remap_result(
                unsafe {
                    esp!(i2s_read(
                        self.port as _,
                        buffer.as_mut_ptr() as *mut c_void,
                        buffer.len(),
                        &mut bytes_read,
                        crate::delay::TickType(timeout).as_millis_u32(),
                    ))
                },
                bytes_read,
            )
        }
    }

    /// Read data from the channel.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes read, or an [`EspError`] if an error occurred.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn read(&mut self, buffer: &mut [u8], timeout: TickType_t) -> Result<usize, EspError> {
        if buffer.is_empty() {
            Ok(0)
        } else {
            let mut bytes_read: usize = 0;

            Self::remap_result(
                unsafe {
                    esp!(i2s_channel_read(
                        self.rx_handle,
                        buffer.as_mut_ptr() as *mut c_void,
                        buffer.len(),
                        &mut bytes_read,
                        crate::delay::TickType(timeout).as_millis_u32(),
                    ))
                },
                bytes_read,
            )
        }
    }

    /// Read data from the channel into an uninitalized buffer asynchronously.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes read, or an [EspError] if an error occurred.
    ///
    /// # Safety
    /// Upon a successful return with `Ok(n_read)`, `buffer[..n_read]` will be initialized.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub async fn read_uninit_async(
        &mut self,
        buffer: &mut [MaybeUninit<u8>],
    ) -> Result<usize, EspError> {
        loop {
            match self.read_uninit(buffer, crate::delay::NON_BLOCK) {
                Err(err) if err.code() == esp_idf_sys::ESP_ERR_TIMEOUT => {
                    RECV_NOTIFIER[self.port as usize].wait().await;
                }
                other => break other,
            }
        }
    }

    /// Read data from the channel into an uninitalized buffer.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes read, or an [`EspError`] if an error occurred.
    ///
    /// # Safety
    /// Upon a successful return with `Ok(n_read)`, `buffer[..n_read]` will be initialized.
    #[cfg(esp_idf_version_major = "4")]
    pub fn read_uninit(
        &mut self,
        buffer: &mut [MaybeUninit<u8>],
        timeout: TickType_t,
    ) -> Result<usize, EspError> {
        if buffer.is_empty() {
            Ok(0)
        } else {
            let mut bytes_read: usize = 0;

            Self::remap_result(
                unsafe {
                    esp!(i2s_read(
                        self.port as _,
                        buffer.as_mut_ptr() as *mut c_void,
                        buffer.len(),
                        &mut bytes_read,
                        crate::delay::TickType(timeout).as_millis_u32(),
                    ))
                },
                bytes_read,
            )
        }
    }

    /// Read data from the channel into an uninitalized buffer.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes read, or an [`EspError`] if an error occurred.
    ///
    /// # Safety
    /// Upon a successful return with `Ok(n_read)`, `buffer[..n_read]` will be initialized.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn read_uninit(
        &mut self,
        buffer: &mut [MaybeUninit<u8>],
        timeout: TickType_t,
    ) -> Result<usize, EspError> {
        if buffer.is_empty() {
            Ok(0)
        } else {
            let mut bytes_read: usize = 0;

            Self::remap_result(
                unsafe {
                    esp!(i2s_channel_read(
                        self.rx_handle,
                        buffer.as_mut_ptr() as *mut c_void,
                        buffer.len(),
                        &mut bytes_read,
                        crate::delay::TickType(timeout).as_millis_u32(),
                    ))
                },
                bytes_read,
            )
        }
    }
}

/// Functions for transmit channels.
impl<'d, Dir> I2sDriver<'d, Dir>
where
    Dir: I2sTxSupported,
{
    /// Enable the I2S transmit channel.
    ///
    /// # Note
    /// This can only be called when the channel is in the `READY` state: initialized but not yet started from a driver
    /// constructor, or disabled from the `RUNNING` state via [`tx_disable()`][I2sTxChannel::tx_disable]. The channel
    /// will enter the `RUNNING` state if it is enabled successfully.
    ///
    /// Enabling the channel will start I2S communications on the hardware. BCLK and WS signals will be generated if
    /// this is a controller. MCLK will be generated once initialization is finished.
    ///
    /// # Errors
    /// This will return an [`EspError`] with `ESP_ERR_INVALID_STATE` if the channel is not in the `READY` state.
    #[cfg(esp_idf_version_major = "4")]
    pub fn tx_enable(&mut self) -> Result<(), EspError> {
        unsafe { esp!(i2s_start(self.port as _)) }
    }

    /// Enable the I2S transmit channel.
    ///
    /// # Note
    /// This can only be called when the channel is in the `READY` state: initialized but not yet started from a driver
    /// constructor, or disabled from the `RUNNING` state via [`tx_disable()`][I2sTxChannel::tx_disable]. The channel
    /// will enter the `RUNNING` state if it is enabled successfully.
    ///
    /// Enabling the channel will start I2S communications on the hardware. BCLK and WS signals will be generated if
    /// this is a controller. MCLK will be generated once initialization is finished.
    ///
    /// # Errors
    /// This will return an [`EspError`] with `ESP_ERR_INVALID_STATE` if the channel is not in the `READY` state.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn tx_enable(&mut self) -> Result<(), EspError> {
        unsafe { esp!(i2s_channel_enable(self.tx_handle)) }
    }

    /// Disable the I2S transmit channel.
    ///
    /// # Note
    /// This can only be called when the channel is in the `RUNNING` state: the channel has been previously enabled
    /// via a call to [`tx_enable()`][I2sTxChannel::tx_enable]. The channel will enter the `READY` state if it is
    /// disabled successfully.
    ///
    /// Disabling the channel will stop I2S communications on the hardware. BCLK and WS signals will stop being
    /// generated if this is a controller. MCLK will continue to be generated.
    ///
    /// # Errors
    /// This will return an [`EspError`] with `ESP_ERR_INVALID_STATE` if the channel is not in the `RUNNING` state.
    #[cfg(esp_idf_version_major = "4")]
    pub fn tx_disable(&mut self) -> Result<(), EspError> {
        unsafe { esp!(i2s_stop(self.port())) }
    }

    /// Disable the I2S transmit channel.
    ///
    /// # Note
    /// This can only be called when the channel is in the `RUNNING` state: the channel has been previously enabled
    /// via a call to [`tx_enable()`][I2sTxChannel::tx_enable]. The channel will enter the `READY` state if it is disabled
    /// successfully.
    ///
    /// Disabling the channel will stop I2S communications on the hardware. BCLK and WS signals will stop being
    /// generated if this is a controller. MCLK will continue to be generated.
    ///
    /// # Errors
    /// This will return an [`EspError`] with `ESP_ERR_INVALID_STATE` if the channel is not in the `RUNNING` state.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn tx_disable(&mut self) -> Result<(), EspError> {
        unsafe { esp!(i2s_channel_disable(self.tx_handle)) }
    }

    /// Preload data into the transmit channel DMA buffer.
    ///
    /// This may be called only when the channel is in the `READY` state: initialized but not yet started.
    ///
    /// This is used to preload data into the DMA buffer so that valid data can be transmitted immediately after the
    /// channel is enabled via [`tx_enable()`][I2sTxChannel::tx_enable]. If this function is not called before enabling the channel,
    /// empty data will be transmitted.
    ///
    /// This function can be called multiple times before enabling the channel. Additional calls will concatenate the
    /// data to the end of the buffer until the buffer is full.
    ///
    /// # Returns
    /// This returns the number of bytes that have been loaded into the buffer. If this is less than the length of
    /// the data provided, the buffer is full and no more data can be loaded.
    #[cfg(all(
        not(esp_idf_version_major = "4"),
        not(all(esp_idf_version_major = "5", esp_idf_version_minor = "0"))
    ))]
    pub fn preload_data(&mut self, data: &[u8]) -> Result<usize, EspError> {
        let mut bytes_loaded: usize = 0;

        unsafe {
            esp!(esp_idf_sys::i2s_channel_preload_data(
                self.tx_handle,
                data.as_ptr() as *const c_void,
                data.len(),
                &mut bytes_loaded as *mut usize
            ))?;
        }

        Ok(bytes_loaded)
    }

    /// Write data to the channel asynchronously.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes sent. This may be less than the length of the data provided.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub async fn write_async(&mut self, data: &[u8]) -> Result<usize, EspError> {
        loop {
            match self.write(data, crate::delay::NON_BLOCK) {
                Err(err) if err.code() == esp_idf_sys::ESP_ERR_TIMEOUT => {
                    SEND_NOTIFIER[self.port as usize].wait().await;
                }
                other => break other,
            }
        }
    }

    /// Write all data to the channel asynchronously.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub async fn write_all_async(&mut self, data: &[u8]) -> Result<(), EspError> {
        let mut offset = 0;

        while offset < data.len() {
            offset += self.write_async(&data[offset..]).await?;
        }

        Ok(())
    }

    /// Write data to the channel.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes sent. This may be less than the length of the data provided.
    #[cfg(esp_idf_version_major = "4")]
    pub fn write(&mut self, data: &[u8], timeout: TickType_t) -> Result<usize, EspError> {
        if data.is_empty() {
            Ok(0)
        } else {
            let mut bytes_written: usize = 0;

            Self::remap_result(
                unsafe {
                    esp!(i2s_write(
                        self.port(),
                        data.as_ptr() as *mut c_void,
                        data.len(),
                        &mut bytes_written,
                        crate::delay::TickType(timeout).as_millis_u32(),
                    ))
                },
                bytes_written,
            )
        }
    }

    /// Write data to the channel.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    ///
    /// # Returns
    /// This returns the number of bytes sent. This may be less than the length of the data provided.
    #[cfg(not(esp_idf_version_major = "4"))]
    pub fn write(&mut self, data: &[u8], timeout: TickType_t) -> Result<usize, EspError> {
        if data.is_empty() {
            Ok(0)
        } else {
            let mut bytes_written: usize = 0;

            Self::remap_result(
                unsafe {
                    esp!(i2s_channel_write(
                        self.tx_handle,
                        data.as_ptr() as *mut c_void,
                        data.len(),
                        &mut bytes_written,
                        crate::delay::TickType(timeout).as_millis_u32(),
                    ))
                },
                bytes_written,
            )
        }
    }

    /// Write all data to the channel.
    ///
    /// This may be called only when the channel is in the `RUNNING` state.
    pub fn write_all(&mut self, data: &[u8], timeout: TickType_t) -> Result<(), EspError> {
        let mut offset = 0;

        while offset < data.len() {
            offset += self.write(&data[offset..], timeout)?;
        }

        Ok(())
    }
}

impl<'d, Dir> Drop for I2sDriver<'d, Dir> {
    fn drop(&mut self) {
        #[cfg(esp_idf_version_major = "4")]
        {
            let _ = unsafe { esp!(i2s_stop(self.port as _)) };

            esp!(unsafe { i2s_driver_uninstall(self.port as _) }).unwrap();
        }

        #[cfg(not(esp_idf_version_major = "4"))]
        {
            if !self.rx_handle.is_null() {
                let _ = unsafe { esp!(i2s_channel_disable(self.rx_handle)) };
            }

            if !self.tx_handle.is_null() {
                let _ = unsafe { esp!(i2s_channel_disable(self.tx_handle)) };
            }

            self.unsubscribe_channel(self.rx_handle).unwrap();
            self.unsubscribe_channel(self.tx_handle).unwrap();

            if !self.rx_handle.is_null() {
                self.del_channel(self.rx_handle).unwrap();
            }

            if !self.tx_handle.is_null() {
                self.del_channel(self.tx_handle).unwrap();
            }

            SEND_NOTIFIER[self.port as usize].reset();
            RECV_NOTIFIER[self.port as usize].reset();
        }
    }
}

unsafe impl<'d, Dir> Send for I2sDriver<'d, Dir> {}

impl<'d, Dir> I2sPort for I2sDriver<'d, Dir> {
    fn port(&self) -> i2s_port_t {
        self.port as _
    }
}

impl<'d, Dir> embedded_io::ErrorType for I2sDriver<'d, Dir> {
    type Error = EspIOError;
}

impl<'d, Dir> embedded_io::Read for I2sDriver<'d, Dir>
where
    Dir: I2sRxSupported,
{
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.read(buf, delay::BLOCK).map_err(EspIOError)
    }
}

impl<'d, Dir> embedded_io::Write for I2sDriver<'d, Dir>
where
    Dir: I2sTxSupported,
{
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.write(buf, delay::BLOCK).map_err(EspIOError)
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

#[cfg(not(esp_idf_version_major = "4"))]
impl<'d, Dir> embedded_io_async::Read for I2sDriver<'d, Dir>
where
    Dir: I2sRxSupported,
{
    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        self.read_async(buf).await.map_err(EspIOError)
    }
}

#[cfg(not(esp_idf_version_major = "4"))]
impl<'d, Dir> embedded_io_async::Write for I2sDriver<'d, Dir>
where
    Dir: I2sTxSupported,
{
    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.write_async(buf).await.map_err(EspIOError)
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

/// C-facing ISR dispatcher for on_send_* callbacks.
#[cfg(not(esp_idf_version_major = "4"))]
unsafe extern "C" fn dispatch_send(
    _handle: i2s_chan_handle_t,
    _raw_event: *mut i2s_event_data_t,
    user_ctx: *mut c_void,
) -> bool {
    let port = user_ctx as u32 as i2s_port_t;

    SEND_NOTIFIER[port as usize].notify_lsb()
}

/// C-facing ISR dispatcher for on_recv_* callbacks.
#[cfg(not(esp_idf_version_major = "4"))]
unsafe extern "C" fn dispatch_recv(
    _handle: i2s_chan_handle_t,
    _raw_event: *mut i2s_event_data_t,
    user_ctx: *mut c_void,
) -> bool {
    let port = user_ctx as u32 as i2s_port_t;

    RECV_NOTIFIER[port as usize].notify_lsb()
}

macro_rules! impl_i2s {
    ($i2s:ident: $port:expr) => {
        crate::impl_peripheral!($i2s);

        impl I2s for $i2s {
            #[inline(always)]
            fn port() -> i2s_port_t {
                $port
            }
        }
    };
}

impl_i2s!(I2S0: 0);
#[cfg(any(esp32, esp32s3))]
impl_i2s!(I2S1: 1);

#[cfg(not(esp_idf_version_major = "4"))]
#[cfg(not(any(esp32, esp32s3)))]
static SEND_NOTIFIER: [HalIsrNotification; 1] = [HalIsrNotification::new()];
#[cfg(not(esp_idf_version_major = "4"))]
#[cfg(not(any(esp32, esp32s3)))]
static RECV_NOTIFIER: [HalIsrNotification; 1] = [HalIsrNotification::new()];

#[cfg(not(esp_idf_version_major = "4"))]
#[cfg(any(esp32, esp32s3))]
static SEND_NOTIFIER: [HalIsrNotification; 2] =
    [HalIsrNotification::new(), HalIsrNotification::new()];
#[cfg(not(esp_idf_version_major = "4"))]
#[cfg(any(esp32, esp32s3))]
static RECV_NOTIFIER: [HalIsrNotification; 2] =
    [HalIsrNotification::new(), HalIsrNotification::new()];