audio_samples_io 0.1.5

A Rust library for audio input and output operations.
Documentation
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
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
use audio_samples::{
    AudioSamples, I24, SampleType,
    traits::{ConvertFrom, StandardSample},
};
use core::fmt::{Display, Formatter, Result as FmtResult};
use memmap2::MmapOptions;
use ndarray::{Array1, Array2};
use non_empty_slice::NonEmptyVec;
use std::{
    any::TypeId,
    fs::File,
    io::{BufReader, BufWriter, Read, Write},
    mem,
    num::NonZeroU32,
    ops::Range,
    path::{Path, PathBuf},
    time::Duration,
};

use crate::{
    MAX_MMAP_SIZE, MAX_WAV_SIZE,
    error::{AudioIOError, AudioIOResult, ErrorPosition},
    traits::{AudioFile, AudioFileMetadata, AudioFileRead, AudioFileWrite, AudioInfoMarker},
    types::{AudioDataSource, BaseAudioInfo, FileType, OpenOptions, ValidatedSampleType},
    wav::{
        FormatCode,
        chunks::{ChunkDesc, ChunkID, DATA_CHUNK, FMT_CHUNK, RIFF_CHUNK, WAVE_CHUNK},
        data::DataChunk,
        error::WavError,
        fmt::FmtChunk,
    },
};

#[derive(Debug, Clone)]
pub struct WavFileInfo {
    pub available_chunks: Vec<ChunkID>,
    pub encoding: FormatCode,
}

impl Display for WavFileInfo {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        writeln!(f, "WAV File Info:")?;
        writeln!(f, "Encoding: {}", self.encoding)?;
        writeln!(f, "Available Chunks: {:?}", self.available_chunks)?;
        Ok(())
    }
}

impl AudioInfoMarker for WavFileInfo {}

/// High-level WAV file representation
#[derive(Debug)]
pub struct WavFile<'a> {
    /// Data source (owned or memory-mapped)
    data_source: AudioDataSource<'a>,
    /// File path if loaded from file
    file_path: PathBuf,
    /// Chunk Storage
    chunks: Vec<ChunkDesc>,
    /// fmt chunk byte range (excludes 8-byte chunk header)
    fmt_range: Range<usize>,
    /// data chunk byte range (excludes 8-byte chunk header)
    data_range: Range<usize>,
    /// Validated sample type
    sample_type: ValidatedSampleType,
    total_samples: usize,
}

impl<'a> WavFile<'a> {
    /// Get the file path if available
    pub fn file_path(&self) -> Option<&Path> {
        Some(self.file_path.as_path())
    }

    /// Get the FMT chunk
    ///
    /// # Panics
    ///
    /// This function will panic if the FMT chunk is not valid.
    /// However, this should never happen as it will have been validated during file opening.
    pub fn fmt_chunk(&self) -> FmtChunk<'_> {
        FmtChunk::from_bytes(self.fmt_bytes()).expect("fmt chunk validated during open")
    }

    /// Get the DATA chunk
    pub fn data(&self) -> DataChunk<'_> {
        DataChunk::from_bytes(self.data_bytes())
    }

    #[inline]
    fn fmt_bytes(&self) -> &[u8] {
        &self.data_source[self.fmt_range.clone()]
    }

    #[inline]
    fn data_bytes(&self) -> &[u8] {
        &self.data_source[self.data_range.clone()]
    }

    pub fn fact(&'a self) -> Result<(), WavError> {
        todo!()
    }

    pub fn list(&'a self) -> Result<(), WavError> {
        todo!()
    }

    pub fn plst(&'a self) -> Result<(), WavError> {
        todo!()
    }

    pub fn cue(&'a self) -> Result<(), WavError> {
        todo!()
    }

    #[allow(dead_code)]
    fn chunk_bytes(&self, chunk: &ChunkDesc) -> &[u8] {
        // Return entire chunk including header (8 bytes) + logical data (no padding)
        &self.data_source[chunk.offset..chunk.offset + 8 + chunk.logical_size]
    }

    pub const fn total_samples(&self) -> usize {
        self.total_samples
    }

    pub fn sample_rate(&self) -> u32 {
        self.fmt_chunk().sample_rate()
    }

    pub fn is_mono(&self) -> bool {
        self.fmt_chunk().channels() == 1
    }

    pub fn is_mulit_channel(&self) -> bool {
        self.fmt_chunk().channels() > 1
    }
}

impl<'a> AudioFileMetadata for WavFile<'a> {
    fn open_metadata<P: AsRef<Path>>(path: P) -> AudioIOResult<Self>
    where
        Self: Sized,
    {
        // For metadata-only operations, we can use the same implementation as regular open
        // but with memory mapping enabled by default for efficiency
        Self::open_with_options(path, OpenOptions::default())
    }

    fn base_info(&self) -> AudioIOResult<BaseAudioInfo> {
        let fmt_chunk = self.fmt_chunk();
        let (_, channels, sample_rate, byte_rate, block_align, bits_per_sample) =
            fmt_chunk.fmt_chunk();
        let sample_rate = match NonZeroU32::new(sample_rate) {
            Some(sr) => sr,
            None => {
                return Err(AudioIOError::corrupted_data_simple(
                    "Invalid sample rate in FMT chunk",
                    "Sample rate cannot be zero",
                ));
            }
        };
        let (total_samples, duration) = {
            let data_chunk = self.data();
            // safety: channels is non-zero as per WAV spec
            let total_frames = data_chunk.total_frames(self.sample_type, unsafe {
                NonZeroU32::new_unchecked(channels as u32)
            });
            // Duration is based on frames, not total samples
            let duration = Duration::from_secs_f64(total_frames as f64 / sample_rate.get() as f64);
            (self.total_samples(), duration)
        };
        let file_type = FileType::WAV;
        let sample_type = self.sample_type();
        let bytes_per_sample = (bits_per_sample as usize / 8) as u16;

        Ok(BaseAudioInfo::new(
            sample_rate,
            channels,
            bits_per_sample,
            bytes_per_sample,
            byte_rate,
            block_align,
            total_samples,
            duration,
            file_type,
            sample_type.into(),
        ))
    }

    #[allow(refining_impl_trait)]
    fn specific_info(&self) -> WavFileInfo {
        WavFileInfo {
            available_chunks: self.chunks.iter().map(|c| c.id).collect(),
            encoding: self.fmt_chunk().format_code(),
        }
    }

    fn file_type(&self) -> FileType {
        FileType::WAV
    }

    fn file_path(&self) -> &Path {
        self.file_path.as_path()
    }

    fn total_samples(&self) -> usize {
        self.total_samples
    }

    fn duration(&self) -> AudioIOResult<Duration> {
        let base_info = self.base_info()?;
        Ok(base_info.duration)
    }

    fn sample_type(&self) -> ValidatedSampleType {
        self.sample_type
    }

    fn num_channels(&self) -> u16 {
        self.fmt_chunk().channels()
    }
}

impl<'a> AudioFile for WavFile<'a> {
    fn open_with_options<P: AsRef<Path>>(fp: P, options: OpenOptions) -> AudioIOResult<Self>
    where
        Self: Sized,
    {
        let path = fp.as_ref().to_path_buf();
        let file = File::open(&path)?;

        let file_size = file.metadata()?.len();

        if file_size > MAX_WAV_SIZE {
            return Err(AudioIOError::corrupted_data_simple(
                "File too large",
                format!("File size {file_size} exceeds maximum {MAX_WAV_SIZE} bytes"),
            ));
        }

        let use_mmap = options.use_memory_map && file_size <= MAX_MMAP_SIZE;

        let audio_data_source: AudioDataSource<'a> = if use_mmap {
            AudioDataSource::MemoryMapped(unsafe { MmapOptions::new().map(&file)? })
        } else {
            // Fallback to buffered read for large files or when mmap is disabled
            let mut buf_reader = BufReader::new(file);
            let mut bytes = Vec::new();
            buf_reader.read_to_end(&mut bytes)?;
            AudioDataSource::Owned(bytes)
        };
        let bytes = audio_data_source.as_bytes();

        if bytes.len() < 12 {
            return Err(AudioIOError::corrupted_data(
                "File too small to be a valid WAV file",
                format!("File size: {}", audio_data_source.len()),
                ErrorPosition::new(0).with_description("start of file"),
            ));
        }

        // 1. Parse the RIFF header + File size + WAVE identifier
        // Assume the first 12 bytes are the RIFF header
        let riff = ChunkID::new(
            bytes[0..4]
                .try_into()
                .expect("Guaranteed to be at least 12 bytes now"),
        );

        if riff != RIFF_CHUNK {
            return Err(AudioIOError::corrupted_data(
                "Data does not start with RIFF header",
                format!("Found: {riff:?}"),
                ErrorPosition::new(0).with_description("RIFF header at file start"),
            ));
        }

        let file_size = u32::from_le_bytes(
            bytes[4..8]
                .try_into()
                .expect("Guaranteed to be at least 12 bytes now"),
        );

        if file_size as usize + 8 > bytes.len() {
            return Err(AudioIOError::corrupted_data(
                "File size in RIFF header does not match actual file size",
                format!(
                    "Header size: {}, Actual size: {}",
                    file_size + 8,
                    bytes.len()
                ),
                ErrorPosition::new(4).with_description("file size field in RIFF header"),
            ));
        }

        let wave = ChunkID::new(
            bytes[8..12]
                .try_into()
                .expect("Guaranteed to be at least 12 bytes now"),
        );

        if wave != WAVE_CHUNK {
            return Err(AudioIOError::corrupted_data(
                "Data does not contain WAVE identifier after RIFF header",
                format!("Found: {wave:?}"),
                ErrorPosition::new(8).with_description("WAVE identifier after RIFF header"),
            ));
        }

        let mut chunks: Vec<ChunkDesc> = Vec::new();
        chunks.push(ChunkDesc {
            id: riff,
            offset: 0,
            logical_size: file_size as usize,
            total_size: file_size as usize + 8, // RIFF header + data
        });
        chunks.push(ChunkDesc {
            id: wave,
            offset: 8,
            logical_size: 4,
            total_size: 4,
        });

        // 2. Iterate through the rest of the file to find chunks
        let mut offset = 12;

        while offset + 8 <= bytes.len() {
            let id = ChunkID::new(bytes[offset..offset + 4].try_into().map_err(|_| {
                AudioIOError::corrupted_data(
                    "Cannot read chunk ID",
                    "Insufficient data for chunk header",
                    ErrorPosition::new(offset).with_description("chunk ID bytes"),
                )
            })?);
            let size_bytes = bytes[offset + 4..offset + 8].try_into().map_err(|_| {
                AudioIOError::corrupted_data(
                    "Cannot read chunk size",
                    "Insufficient data for chunk header",
                    ErrorPosition::new(offset + 4).with_description("chunk size bytes"),
                )
            })?;
            let size = u32::from_le_bytes(size_bytes) as usize;
            let padded = size.checked_add(size & 1).ok_or_else(|| {
                AudioIOError::corrupted_data(
                    "Integer overflow in chunk size calculation",
                    format!("Chunk size: {size}"),
                    ErrorPosition::new(offset + 4).with_description("chunk size field"),
                )
            })?;
            let header_and_data_size = 8_usize.checked_add(padded).ok_or_else(|| {
                AudioIOError::corrupted_data(
                    "Integer overflow in chunk total size calculation",
                    format!("Header size: 8, Data size: {padded}"),
                    ErrorPosition::new(offset).with_description("chunk header"),
                )
            })?;
            let end = offset.checked_add(header_and_data_size).ok_or_else(|| {
                AudioIOError::corrupted_data(
                    "Integer overflow in chunk end position calculation",
                    format!("Offset: {offset}, Size: {header_and_data_size}"),
                    ErrorPosition::new(offset).with_description("chunk position"),
                )
            })?;

            if end > bytes.len() {
                return Err(AudioIOError::corrupted_data(
                    "Chunk extends beyond end of file",
                    format!("Chunk {id:?} at offset {offset}"),
                    ErrorPosition::new(offset).with_description(format!("chunk {id:?}")),
                ));
            }

            chunks.push(ChunkDesc {
                id,
                offset,
                logical_size: size, // Original chunk size without padding
                total_size: header_and_data_size, // Header + data + padding for file positioning
            });

            offset = end;
        }

        // 3. Ensure fmt and data chunks are present
        let fmt_chunk_desc = chunks.iter().find(|c| c.id == FMT_CHUNK);
        let data_chunk_desc = chunks.iter().find(|c| c.id == DATA_CHUNK);

        let (fmt_range, sample_type) = match fmt_chunk_desc {
            Some(fmt_chunk) => {
                let start = fmt_chunk.offset + 8; // skip 8-byte header
                let end = start + fmt_chunk.logical_size; // exclude padding if any
                let fmt_chunk = FmtChunk::from_bytes_validated(&bytes[start..end])
                    .map_err(AudioIOError::WavError)?;
                let sample_type = fmt_chunk.actual_sample_type()?;
                (start..end, sample_type)
            }
            None => {
                return Err(AudioIOError::corrupted_data(
                    "FMT chunk not found in WAV file",
                    format!(
                        "Found chunks: {:?}",
                        chunks.iter().map(|c| c.id).collect::<Vec<_>>()
                    ),
                    ErrorPosition::new(12).with_description("chunk data section"),
                ));
            }
        };

        let data_range = match data_chunk_desc {
            Some(data_chunk) => {
                let start = data_chunk.offset + 8; // skip 8-byte header
                let end = start + data_chunk.logical_size; // exclude padding byte
                start..end
            }
            None => {
                return Err(AudioIOError::corrupted_data(
                    "DATA chunk not found in WAV file",
                    format!(
                        "Found chunks: {:?}",
                        chunks.iter().map(|c| c.id).collect::<Vec<_>>()
                    ),
                    ErrorPosition::new(12).with_description("chunk data section"),
                ));
            }
        };

        let total_samples = {
            let data_chunk = DataChunk::from_bytes(&bytes[data_range.clone()]);
            data_chunk.total_samples(sample_type)
        };

        let wav_file = WavFile {
            data_source: audio_data_source,
            file_path: path,
            chunks,
            fmt_range,
            data_range,
            sample_type,
            total_samples,
        };

        Ok(wav_file)
    }

    fn len(&self) -> u64 {
        self.data_source.len() as u64
    }
}

impl<'a> AudioFileRead<'a> for WavFile<'a> {
    /// Reads all samples from the audio file
    fn read<T>(&'a self) -> AudioIOResult<AudioSamples<'a, T>>
    where
        T: StandardSample + 'static,
    {
        let data_chunk = self.data();
        let fmt_chunk = self.fmt_chunk();

        let sample_type = self.sample_type;
        let sample_rate = fmt_chunk.sample_rate();
        // safety: sample_rate is guaranteed to be non-zero due to WAV spec validation during fmt chunk parsing
        let sample_rate = unsafe { NonZeroU32::new_unchecked(sample_rate) };
        let num_channels = fmt_chunk.channels() as u32;
        // safety: num_channels == 0 would have been rejected during fmt chunk parsing.
        let num_channels = unsafe {
            NonZeroU32::new_unchecked(num_channels) // WAV spec requires channels > 0
        };

        match sample_type {
            ValidatedSampleType::U8 => {
                read_typed_internal::<u8, T>(&data_chunk, num_channels, sample_rate)
            }
            ValidatedSampleType::I16 => {
                read_typed_internal::<i16, T>(&data_chunk, num_channels, sample_rate)
            }
            ValidatedSampleType::I24 => {
                read_typed_internal::<I24, T>(&data_chunk, num_channels, sample_rate)
            }
            ValidatedSampleType::I32 => {
                read_typed_internal::<i32, T>(&data_chunk, num_channels, sample_rate)
            }
            ValidatedSampleType::F32 => {
                read_typed_internal::<f32, T>(&data_chunk, num_channels, sample_rate)
            }
            ValidatedSampleType::F64 => {
                read_typed_internal::<f64, T>(&data_chunk, num_channels, sample_rate)
            }
        }
    }

    fn read_into<T>(&'a self, audio: &mut AudioSamples<'a, T>) -> AudioIOResult<()>
    where
        T: StandardSample + 'static,
    {
        let data_chunk = self.data();

        match self.sample_type {
            ValidatedSampleType::U8 => read_into_typed_internal::<u8, T>(&data_chunk, audio), // technicaly not part of the wav spec, but it does not disallow it either, so we support it
            ValidatedSampleType::I16 => read_into_typed_internal::<i16, T>(&data_chunk, audio),
            ValidatedSampleType::I24 => read_into_typed_internal::<I24, T>(&data_chunk, audio),
            ValidatedSampleType::I32 => read_into_typed_internal::<i32, T>(&data_chunk, audio),
            ValidatedSampleType::F32 => read_into_typed_internal::<f32, T>(&data_chunk, audio),
            ValidatedSampleType::F64 => read_into_typed_internal::<f64, T>(&data_chunk, audio),
        }
    }
}

/// Convert interleaved samples to planar AudioSamples format
///
/// WAV files store samples in interleaved format: [L0, R0, L1, R1, ...]
/// AudioSamples expects planar format: [[L0, L1, ...], [R0, R1, ...]]
///
/// Uses optimized SIMD deinterleave when the simd feature is enabled.
fn build_samples_from_interleaved_vec<'a, T>(
    interleaved_data: NonEmptyVec<T>,
    num_channels: NonZeroU32,
    sample_rate: NonZeroU32,
) -> AudioIOResult<AudioSamples<'a, T>>
where
    T: StandardSample + 'static,
{
    // SAFETY: sample_rate comes from validated WAV header which requires non-zero sample rate
    if num_channels.get() == 1 {
        // Mono: data is already in correct format
        AudioSamples::new_mono(Array1::from_vec(interleaved_data.to_vec()), sample_rate)
            .map_err(Into::into)
    } else {
        let total_samples = interleaved_data.len();
        let frames = total_samples.get() / num_channels.get() as usize;

        if frames == 0 {
            return Err(AudioIOError::corrupted_data_simple(
                "No frames in audio data",
                format!("total_samples={total_samples}, channels={num_channels}"),
            ));
        }

        // Use optimized deinterleave from audio_samples
        let planar_data = audio_samples::simd_conversions::deinterleave_multi_vec(
            &interleaved_data,
            num_channels,
        )
        .map_err(|e| AudioIOError::corrupted_data_simple("Deinterleave failed", e.to_string()))?;

        // Create the planar array with shape (num_channels, frames)

        let arr =
            Array2::from_shape_vec((num_channels.get() as usize, frames), planar_data.to_vec())
                .map_err(|e| {
                    AudioIOError::corrupted_data_simple("Array shape error", e.to_string())
                })?;

        AudioSamples::new_multi_channel(arr, sample_rate).map_err(Into::into)
    }
}

fn read_into_typed_internal<'a, S, T>(
    data_chunk: &DataChunk<'a>,
    audio: &mut AudioSamples<'a, T>,
) -> AudioIOResult<()>
where
    S: StandardSample + 'static,
    T: StandardSample + ConvertFrom<S> + 'static,
{
    let bytes_per_sample = S::BITS as usize / 8;
    if !data_chunk.len().is_multiple_of(bytes_per_sample) {
        return Err(AudioIOError::corrupted_data_simple(
            "Data chunk size not aligned to sample size",
            format!(
                "Data chunk size {} not divisible by sample size {}",
                data_chunk.len(),
                bytes_per_sample
            ),
        ));
    }

    let converted = data_chunk.read_samples::<S, T>()?;
    let num_channels = audio.num_channels();

    if !converted
        .len()
        .get()
        .is_multiple_of(num_channels.get() as usize)
    {
        return Err(AudioIOError::corrupted_data_simple(
            "Channel alignment error",
            format!(
                "Sample count {} not divisible by channel count {}",
                converted.len(),
                num_channels,
            ),
        ));
    }

    if converted.len() != audio.total_samples() {
        return Err(AudioIOError::corrupted_data_simple(
            "Sample count mismatch",
            format!(
                "Converted sample count {} does not match target audio sample count {}",
                converted.len(),
                audio.total_samples(),
            ),
        ));
    }

    // For mono audio, data is already in correct format
    if audio.is_mono() {
        audio.replace_with_vec(&converted).map_err(|e| e.into())
    } else {
        // Multi-channel: deinterleave the converted data before replacing
        // Use optimized deinterleave from audio_samples
        let planar_data =
            audio_samples::simd_conversions::deinterleave_multi_vec(&converted, num_channels)
                .map_err(|e| {
                    AudioIOError::corrupted_data_simple("Deinterleave failed", e.to_string())
                })?;
        audio.replace_with_vec(&planar_data).map_err(|e| e.into())
    }
}

fn read_typed_internal<'a, S, T>(
    data_chunk: &DataChunk<'a>,
    num_channels: NonZeroU32,
    sample_rate: NonZeroU32,
) -> AudioIOResult<AudioSamples<'a, T>>
where
    S: StandardSample + 'static,
    T: StandardSample + ConvertFrom<S> + 'static,
{
    let bytes_per_sample = S::BYTES as usize;
    if !data_chunk.len().is_multiple_of(bytes_per_sample) {
        return Err(AudioIOError::corrupted_data_simple(
            "Data chunk size not aligned to sample size",
            format!(
                "Data chunk size {} not divisible by sample size {}",
                data_chunk.len(),
                bytes_per_sample
            ),
        ));
    }

    let converted = data_chunk.read_samples::<S, T>()?;

    if !converted
        .len()
        .get()
        .is_multiple_of(num_channels.get() as usize)
    {
        return Err(AudioIOError::corrupted_data_simple(
            "Channel alignment error",
            format!(
                "Sample count {} not divisible by channel count {}",
                converted.len(),
                num_channels,
            ),
        ));
    }

    build_samples_from_interleaved_vec(converted, num_channels, sample_rate)
}

// Helper functions for WAV writing

/// Maps SampleType to WAV FormatCode
///
/// Returns `None` if the SampleType is not supported for WAV writing.
/// This function validates that the sample type is valid before conversion.
const fn sample_type_to_format(sample_type: SampleType) -> Option<FormatCode> {
    match sample_type {
        SampleType::U8 | SampleType::I16 | SampleType::I24 | SampleType::I32 => {
            Some(FormatCode::Pcm)
        }
        SampleType::F32 | SampleType::F64 => Some(FormatCode::IeeeFloat),
        _ => None,
    }
}

/// Get SampleType from AudioSample type parameter
const fn get_sample_type<T>() -> SampleType
where
    T: StandardSample,
{
    T::SAMPLE_TYPE
}

/// Write 16-byte base FMT chunk
fn write_base_fmt<T, W>(writer: &mut W, channels: u16, sample_rate: u32) -> AudioIOResult<()>
where
    T: StandardSample + 'static,
    W: Write,
{
    let sample_type = get_sample_type::<T>();
    let format_code = sample_type_to_format(sample_type)
        .ok_or(AudioIOError::WavError(WavError::UnsupportedSampleType))?;
    let bits_per_sample = T::BITS as u16;
    let bytes_per_sample = T::BYTES as u16;
    let block_align = channels * bytes_per_sample;
    let byte_rate = sample_rate * block_align as u32;

    // FMT chunk header
    writer.write_all(b"fmt ")?;
    writer.write_all(&16u32.to_le_bytes())?; // Chunk size (16 bytes)

    // FMT chunk data (16 bytes)
    writer.write_all(&format_code.as_u16().to_le_bytes())?; // Format code
    writer.write_all(&channels.to_le_bytes())?; // Channels
    writer.write_all(&sample_rate.to_le_bytes())?; // Sample rate
    writer.write_all(&byte_rate.to_le_bytes())?; // Byte rate
    writer.write_all(&block_align.to_le_bytes())?; // Block align
    writer.write_all(&bits_per_sample.to_le_bytes())?; // Bits per sample

    Ok(())
}

/// Determine if extensible format is needed
const fn needs_extensible_format<T>(channels: u16) -> bool
where
    T: StandardSample,
{
    // Use extensible format for more than 2 channels or non-standard bit depths.
    // 8-bit, 16-bit, and 32-bit PCM/float formats use base format for 1-2 channels
    // for maximum compatibility (e.g. soundfile/libsndfile doesn't support
    // WAVE_FORMAT_EXTENSIBLE with 8-bit PCM).
    channels > 2 || (T::BITS != 8 && T::BITS != 16 && T::BITS != 32)
}

/// Write 40-byte extensible FMT chunk
fn write_extensible_fmt<T, W>(writer: &mut W, channels: u16, sample_rate: u32) -> AudioIOResult<()>
where
    T: StandardSample + 'static,
    W: Write,
{
    let sample_type = get_sample_type::<T>();
    let format_code = sample_type_to_format(sample_type)
        .ok_or(AudioIOError::WavError(WavError::UnsupportedSampleType))?;
    let bits_per_sample = T::BITS as u16;
    let bytes_per_sample = T::BYTES as u16;
    let block_align = channels * bytes_per_sample;
    let byte_rate = sample_rate * block_align as u32;

    // Windows standard speaker position channel masks
    // Based on WAVE_FORMAT_EXTENSIBLE specification
    let channel_mask: u32 = match channels {
        1 => 0x4,   // SPEAKER_FRONT_CENTER
        2 => 0x3,   // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
        3 => 0x7,   // FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER
        4 => 0x33,  // FRONT_LEFT | FRONT_RIGHT | BACK_LEFT | BACK_RIGHT
        5 => 0x37,  // 4.0 + FRONT_CENTER
        6 => 0x3F,  // 5.0 + LFE (5.1)
        7 => 0x13F, // 5.1 + BACK_CENTER
        8 => 0x63F, // 5.1 + SIDE_LEFT | SIDE_RIGHT (7.1)
        _ => {
            // For >8 channels, saturate to all bits set
            // This is a reasonable fallback for non-standard channel configurations
            if channels < 32 {
                (1u32 << channels) - 1
            } else {
                0xFFFFFFFF
            }
        }
    };

    // FMT chunk header
    writer.write_all(b"fmt ")?;
    writer.write_all(&40u32.to_le_bytes())?; // Chunk size (40 bytes)

    // Base FMT chunk data (16 bytes)
    writer.write_all(&FormatCode::Extensible.as_u16().to_le_bytes())?;
    writer.write_all(&channels.to_le_bytes())?;
    writer.write_all(&sample_rate.to_le_bytes())?;
    writer.write_all(&byte_rate.to_le_bytes())?;
    writer.write_all(&block_align.to_le_bytes())?;
    writer.write_all(&bits_per_sample.to_le_bytes())?;

    // Extension size (2 bytes)
    writer.write_all(&22u16.to_le_bytes())?;

    // Extended format info (22 bytes)
    writer.write_all(&bits_per_sample.to_le_bytes())?; // Valid bits per sample
    writer.write_all(&channel_mask.to_le_bytes())?; // Channel mask

    // Sub-format GUID (16 bytes)
    // Standard KSDATAFORMAT_SUBTYPE_PCM:       {00000001-0000-0010-8000-00AA00389B71}
    // Standard KSDATAFORMAT_SUBTYPE_IEEE_FLOAT: {00000003-0000-0010-8000-00AA00389B71}
    // In memory: Data1 (4 bytes LE), Data2 (2 bytes LE), Data3 (2 bytes LE), Data4 (8 bytes BE)
    let mut sub_format = [0u8; 16];
    // Data1: format_code as u32 LE (e.g. 1 for PCM, 3 for IEEE float)
    sub_format[0..4].copy_from_slice(&(u32::from(format_code.as_u16())).to_le_bytes());
    // Data2: 0x0000
    sub_format[4..6].copy_from_slice(&0u16.to_le_bytes());
    // Data3: 0x0010
    sub_format[6..8].copy_from_slice(&0x0010u16.to_le_bytes());
    // Data4: 0x8000-00AA00389B71 (big-endian)
    sub_format[8..16].copy_from_slice(&[0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]);
    writer.write_all(&sub_format)?;

    Ok(())
}

/// Build an interleaved byte buffer for WAV output and write it in one go.
/// Mono fast-path uses the underlying contiguous bytes view; multi-channel
/// uses optimized interleave functions for better cache locality.
fn write_audio_data_interleaved<T, W>(writer: &mut W, audio: &AudioSamples<T>) -> AudioIOResult<()>
where
    T: StandardSample + 'static,
    W: Write,
{
    let num_channels = audio.num_channels();

    // Mono data is already laid out correctly; respect I24 packing via AudioSamples::bytes
    if audio.is_mono() {
        let bytes = audio.bytes()?;
        writer.write_all(bytes.as_slice())?;
        return Ok(());
    }

    let bytes_per_sample = if TypeId::of::<T>() == TypeId::of::<I24>() {
        3usize
    } else {
        mem::size_of::<T>()
    };

    // Use optimized interleave: get interleaved samples using AudioSamples' method
    // which now uses SIMD-accelerated interleave internally
    let interleaved = audio.data.as_interleaved_vec();
    let total_samples = interleaved.len();

    // Stream in chunks to cap peak allocation and improve cache locality
    const TARGET_CHUNK_BYTES: usize = 256 * 1024; // 256 KiB target buffer
    let chunk_samples = TARGET_CHUNK_BYTES
        .checked_div(bytes_per_sample)
        .ok_or(AudioIOError::corrupted_data_simple(
            "Chunk size calculation overflow",
            "TARGET_CHUNK_BYTES / bytes_per_sample",
        ))?
        .max(num_channels.get() as usize); // At least one frame

    let mut buf = vec![0u8; chunk_samples * bytes_per_sample];

    let mut sample_start = 0;
    while sample_start < total_samples.get() {
        let remaining = total_samples.get() - sample_start;
        let samples_this_chunk = remaining.min(chunk_samples);
        let bytes_this_chunk = samples_this_chunk * bytes_per_sample;

        // Convert interleaved samples to bytes
        let mut write_idx = 0;
        for sample in interleaved
            .iter()
            .skip(sample_start)
            .take(samples_this_chunk)
        {
            let bytes = sample.to_le_bytes();
            let dst = &mut buf[write_idx..write_idx + bytes_per_sample];
            dst.copy_from_slice(bytes.as_ref());
            write_idx += bytes_per_sample;
        }

        debug_assert_eq!(write_idx, bytes_this_chunk);
        writer.write_all(&buf[..bytes_this_chunk])?;
        sample_start += samples_this_chunk;
    }

    Ok(())
}

// Write complete WAV file to a writer
pub(crate) fn write_wav<T, W>(writer: W, audio: &AudioSamples<T>) -> AudioIOResult<()>
where
    T: StandardSample + 'static,
    W: Write,
{
    let sample_rate = audio.sample_rate().get();
    let channels = audio.num_channels().get() as u16;
    let bytes_per_sample_disk = if TypeId::of::<T>() == TypeId::of::<I24>() {
        3usize
    } else {
        mem::size_of::<T>()
    };
    let data_size = audio
        .samples_per_channel()
        .get()
        .checked_mul(audio.num_channels().get() as usize)
        .and_then(|v| v.checked_mul(bytes_per_sample_disk))
        .ok_or_else(|| {
            AudioIOError::corrupted_data_simple(
                "Byte size overflow during header calculation",
                format!(
                    "channels={}, samples_per_channel={}, bytes_per_sample={}",
                    channels,
                    audio.samples_per_channel().get(),
                    bytes_per_sample_disk
                ),
            )
        })?;

    // Calculate padded data size (must be even)
    let padded_data_size = if data_size % 2 == 1 {
        data_size + 1
    } else {
        data_size
    };

    // Determine FMT chunk size
    let fmt_chunk_size = if needs_extensible_format::<T>(channels) {
        40
    } else {
        16
    };
    let fmt_total_size = 8 + fmt_chunk_size; // chunk header + data

    // Calculate total file size
    let file_size = 4 + fmt_total_size + 8 + padded_data_size; // WAVE + FMT + DATA

    // Always buffer writes to avoid caller-dependent performance cliffs
    let mut writer = BufWriter::new(writer);

    // Write RIFF header
    writer.write_all(b"RIFF")?;
    writer.write_all(&(file_size as u32).to_le_bytes())?;
    writer.write_all(b"WAVE")?;

    // Write FMT chunk
    if needs_extensible_format::<T>(channels) {
        write_extensible_fmt::<T, _>(&mut writer, channels, sample_rate)?;
    } else {
        write_base_fmt::<T, _>(&mut writer, channels, sample_rate)?;
    }

    // Write DATA chunk header
    writer.write_all(b"data")?;
    writer.write_all(&(data_size as u32).to_le_bytes())?;

    // Write audio data (interleaved for multi-channel)
    write_audio_data_interleaved(&mut writer, audio)?;

    // Add padding byte if needed
    if data_size % 2 == 1 {
        writer.write_all(&[0])?;
    }

    writer.flush()?;
    Ok(())
}

impl<'a> AudioFileWrite for WavFile<'a> {
    fn write<P, T>(&mut self, out_fp: P) -> AudioIOResult<()>
    where
        P: AsRef<Path>,
        T: StandardSample + 'static,
    {
        // Read audio data as the target type T
        let audio = self.read::<T>()?;

        // Create output file with buffered writer
        let file = File::create(out_fp)?;
        let buf_writer = BufWriter::new(file);

        // Write WAV using the core function
        write_wav(buf_writer, &audio)?;

        Ok(())
    }
}

impl Display for WavFile<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        writeln!(f, "WAV File:")?;
        writeln!(f, "File Path: {:?}", self.file_path)?;
        writeln!(f, "Chunks:")?;
        for chunk in &self.chunks {
            writeln!(
                f,
                "  ID: {}, Offset: {}, Logical Size: {}, Total Size: {}",
                chunk.id, chunk.offset, chunk.logical_size, chunk.total_size
            )?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod wav_tests {
    use audio_samples::sample_rate;
    use non_empty_slice::NonEmptySlice;

    use crate::wav::FormatCode;

    use super::*;

    #[allow(dead_code)]
    fn make_base_fmt_bytes(
        format_code: u16,
        channels: u16,
        sample_rate: u32,
        byte_rate: u32,
        block_align: u16,
        bits_per_sample: u16,
    ) -> [u8; 16] {
        let mut bytes = [0u8; 16];
        bytes[0..2].copy_from_slice(&format_code.to_le_bytes());
        bytes[2..4].copy_from_slice(&channels.to_le_bytes());
        bytes[4..8].copy_from_slice(&sample_rate.to_le_bytes());
        bytes[8..12].copy_from_slice(&byte_rate.to_le_bytes());
        bytes[12..14].copy_from_slice(&block_align.to_le_bytes());
        bytes[14..16].copy_from_slice(&bits_per_sample.to_le_bytes());
        bytes
    }

    #[test]
    fn test_wav_open() {
        let wav_path = Path::new("resources/test.wav");
        let wav_file = WavFile::open_with_options(wav_path, OpenOptions::default());
        assert!(wav_file.is_ok(), "Failed to open test WAV file");
    }

    #[test]
    fn test_wav_fmt_chunk() {
        let wav_path = Path::new("resources/test.wav");
        let wav_file = WavFile::open_with_options(wav_path, OpenOptions::default())
            .expect("Failed to open test WAV file");
        let fmt_chunk = wav_file.fmt_chunk();
        assert_eq!(
            fmt_chunk.format_code(),
            FormatCode::Pcm,
            "Format code mismatch"
        );
        assert_eq!(fmt_chunk.sample_rate(), 44100, "Sample rate mismatch");
        assert_eq!(fmt_chunk.channels(), 2, "Channel count mismatch");
    }

    #[test]
    fn test_wav_data_chunk() {
        let wav_path = Path::new("resources/test.wav");
        let wav_file = WavFile::open_with_options(wav_path, OpenOptions::default())
            .expect("Failed to open test WAV file");

        let audio = wav_file.read::<i16>();
        assert!(
            audio.is_ok(),
            "Failed to read audio samples from DATA chunk"
        );
    }

    #[test]
    fn test_wav_properties() {
        let wav_path = Path::new("resources/test.wav");
        let wav_file = WavFile::open_with_options(wav_path, OpenOptions::default())
            .expect("Failed to open test WAV file");

        let base_info = wav_file.base_info().expect("Failed to get base info");
        assert_eq!(
            base_info.sample_rate,
            sample_rate!(44100),
            "Sample rate mismatch"
        );
        assert_eq!(base_info.channels, 2, "Channel count mismatch");
        assert_eq!(base_info.bits_per_sample, 16, "Bits per sample mismatch");

        let specific_info = wav_file.specific_info();
        assert_eq!(specific_info.encoding, FormatCode::Pcm, "Encoding mismatch");
        assert!(
            specific_info.available_chunks.contains(&FMT_CHUNK),
            "FMT chunk should be available"
        );
        assert!(
            specific_info.available_chunks.contains(&DATA_CHUNK),
            "DATA chunk should be available"
        );

        println!("Base Info: {base_info:#}");
    }

    #[test]
    fn test_wav_write_i16() {
        use audio_samples::{AudioTypeConversion, sine_wave};
        use std::fs;

        // Generate a sine wave
        let sample_rate = sample_rate!(44100);
        let frequency = 440.0;
        let duration = Duration::from_secs_f64(1.0); // 1 second
        let amplitude = 0.5;
        let sine_samples = sine_wave::<f32>(frequency, duration, sample_rate, amplitude);
        let sine_i16 = sine_samples.to_format::<i16>();

        // Write to file
        let output_path = std::env::temp_dir().join("test_write_i16.wav");
        write_wav(
            std::io::BufWriter::new(
                std::fs::File::create(&output_path).expect("Failed to create output file"),
            ),
            &sine_i16,
        )
        .expect("Failed to write WAV file");

        // Verify file was created and has reasonable size
        let metadata = fs::metadata(&output_path).expect("Failed to get file metadata");
        assert!(metadata.len() > 44, "WAV file too small"); // At least header size

        // Read back and verify
        let wav_file = WavFile::open_with_options(&output_path, OpenOptions::default())
            .expect("Failed to open written WAV file");

        let base_info = wav_file.base_info().expect("Failed to get base info");
        assert_eq!(base_info.sample_rate, sample_rate!(44100));
        assert_eq!(base_info.channels, 1);
        assert_eq!(base_info.bits_per_sample, 16);

        let read_samples = wav_file.read::<i16>().expect("Failed to read samples");
        assert_eq!(read_samples.total_samples(), sine_i16.total_samples());

        // // Clean up
        // fs::remove_file(&output_path).ok();
    }

    #[test]
    fn test_wav_write_f32() {
        use audio_samples::sine_wave;
        use std::fs;

        // Generate a sine wave
        let sample_rate = sample_rate!(48000);
        let frequency = 1000.0;
        let duration = Duration::from_secs_f64(0.5); // 0.5 seconds
        let amplitude = 0.8;
        let sine_samples = sine_wave::<f32>(frequency, duration, sample_rate, amplitude);

        // Write to file
        let output_path = std::env::temp_dir().join("test_write_f32.wav");
        write_wav(
            std::io::BufWriter::new(
                std::fs::File::create(&output_path).expect("Failed to create output file"),
            ),
            &sine_samples,
        )
        .expect("Failed to write WAV file");

        // Read back and verify
        let wav_file = WavFile::open_with_options(&output_path, OpenOptions::default())
            .expect("Failed to open written WAV file");

        let base_info = wav_file.base_info().expect("Failed to get base info");
        assert_eq!(base_info.sample_rate, sample_rate!(48000));
        assert_eq!(base_info.channels, 1);
        assert_eq!(base_info.bits_per_sample, 32);

        let read_samples = wav_file.read::<f32>().expect("Failed to read samples");
        assert_eq!(read_samples.total_samples(), sine_samples.total_samples());

        // Verify format is IEEE Float
        let fmt_chunk = wav_file.fmt_chunk();
        assert_eq!(fmt_chunk.format_code(), FormatCode::IeeeFloat);

        // Clean up
        fs::remove_file(&output_path).ok();
    }

    #[test]
    fn test_wav_read_i24_roundtrip() {
        use audio_samples::sine_wave;
        use std::fs;

        let sample_rate = sample_rate!(48_000);
        let duration = Duration::from_millis(20);
        let audio = sine_wave::<I24>(440.0, duration, sample_rate, 0.5);

        let output_path = std::env::temp_dir().join(format!(
            "test_read_i24_roundtrip_{}.wav",
            std::process::id()
        ));
        write_wav(
            std::io::BufWriter::new(
                std::fs::File::create(&output_path).expect("Failed to create output file"),
            ),
            &audio,
        )
        .expect("Failed to write I24 WAV file");

        let wav_file = WavFile::open_with_options(&output_path, OpenOptions::default())
            .expect("Failed to reopen written WAV file");
        let read_samples = wav_file.read::<I24>().expect("Failed to read I24 samples");

        assert_eq!(
            read_samples.total_samples(),
            audio.total_samples(),
            "Roundtrip sample count mismatch"
        );
        assert_eq!(read_samples.num_channels(), audio.num_channels());
        assert_eq!(read_samples.sample_rate(), audio.sample_rate());

        let original = audio.to_interleaved_vec();
        let roundtrip = read_samples.to_interleaved_vec();
        assert_eq!(original, roundtrip, "I24 roundtrip data mismatch");

        fs::remove_file(&output_path).ok();
    }

    #[test]
    fn test_wav_write_stereo() {
        use audio_samples::sine_wave;
        use std::fs;

        // Generate stereo sine waves (left: 440Hz, right: 880Hz)
        let sample_rate = sample_rate!(44100);
        let duration = Duration::from_secs_f64(0.25);
        let left = sine_wave::<f32>(440.0, duration, sample_rate, 0.6);
        let right = sine_wave::<f32>(880.0, duration, sample_rate, 0.4);

        // Combine into stereo
        let stereo =
            audio_samples::AudioEditing::stack(NonEmptySlice::new(&[left, right]).unwrap())
                .expect("Failed to create stereo");

        // Write to file
        let output_path = std::env::temp_dir().join("test_write_stereo.wav");
        write_wav(
            std::io::BufWriter::new(
                std::fs::File::create(&output_path).expect("Failed to create output file"),
            ),
            &stereo,
        )
        .expect("Failed to write stereo WAV file");

        // Read back and verify
        let wav_file = WavFile::open_with_options(&output_path, OpenOptions::default())
            .expect("Failed to open written WAV file");

        let base_info = wav_file.base_info().expect("Failed to get base info");
        assert_eq!(base_info.sample_rate, sample_rate!(44100));
        assert_eq!(base_info.channels, 2);
        assert_eq!(base_info.bits_per_sample, 32);

        let read_samples = wav_file.read::<f32>().expect("Failed to read samples");
        assert_eq!(read_samples.total_samples(), stereo.total_samples());
        assert_eq!(read_samples.num_channels().get(), 2);

        // Clean up
        fs::remove_file(&output_path).ok();
    }

    #[test]
    fn test_wav_write_type_conversion() {
        use audio_samples::{AudioTypeConversion, sine_wave};
        use std::fs;

        // Generate f32 sine wave
        let sample_rate = sample_rate!(44100);
        let sine_f32 = sine_wave::<f32>(440.0, Duration::from_secs_f64(0.1), sample_rate, 0.7);

        // Write as i16 (should convert)
        let output_path = std::env::temp_dir().join("test_conversion.wav");
        let sine_i16 = sine_f32.to_format::<i16>();
        write_wav(
            std::io::BufWriter::new(
                std::fs::File::create(&output_path).expect("Failed to create output file"),
            ),
            &sine_i16,
        )
        .expect("Failed to write converted WAV file");

        // Verify it's written as i16 PCM
        let wav_file = WavFile::open_with_options(&output_path, OpenOptions::default())
            .expect("Failed to open written WAV file");

        let base_info = wav_file.base_info().expect("Failed to get base info");
        assert_eq!(base_info.bits_per_sample, 16);

        let fmt_chunk = wav_file.fmt_chunk();
        assert_eq!(fmt_chunk.format_code(), FormatCode::Pcm);

        // Clean up
        fs::remove_file(&output_path).ok();
    }

    #[test]
    fn test_audiofilewrite_trait() {
        use audio_samples::sine_wave;
        use std::fs;

        // Create a test WAV file first
        let sample_rate = sample_rate!(22050);
        let sine_samples = sine_wave::<i16>(330.0, Duration::from_secs_f64(0.2), sample_rate, 0.5);
        let input_path = std::env::temp_dir().join("test_input.wav");
        write_wav(
            std::io::BufWriter::new(
                std::fs::File::create(&input_path).expect("Failed to create input file"),
            ),
            &sine_samples,
        )
        .expect("Failed to write input WAV file");

        // Open the WAV file and use the trait method to write as f32
        let mut wav_file = WavFile::open_with_options(&input_path, OpenOptions::default())
            .expect("Failed to open input WAV file");

        let output_path = std::env::temp_dir().join("test_trait_output.wav");
        wav_file
            .write::<_, f32>(&output_path)
            .expect("Failed to write using trait method");

        // Verify the output is f32
        let output_wav = WavFile::open_with_options(&output_path, OpenOptions::default())
            .expect("Failed to open output WAV file");

        let base_info = output_wav.base_info().expect("Failed to get base info");
        assert_eq!(base_info.bits_per_sample, 32);
        assert_eq!(base_info.sample_rate, sample_rate!(22050));

        let fmt_chunk = output_wav.fmt_chunk();
        assert_eq!(fmt_chunk.format_code(), FormatCode::IeeeFloat);

        // Clean up
        fs::remove_file(&input_path).ok();
        fs::remove_file(&output_path).ok();
    }

    #[test]
    fn test_wav_write_read_roundtrip_validation() {
        use audio_samples::{AudioTypeConversion, sine_wave};
        use std::fs;

        // Test multiple sample types with comprehensive validation
        let sample_rate = sample_rate!(44100);
        let duration = Duration::from_secs_f64(0.5);
        let base_sine = sine_wave::<f32>(440.0, duration, sample_rate, 0.5);

        // Test cases: (type_name, bits_per_sample, format_code)
        let test_cases = [
            ("i16", 16, FormatCode::Pcm),
            ("i32", 32, FormatCode::Pcm),
            ("f32", 32, FormatCode::IeeeFloat),
        ];

        for (type_name, expected_bits, expected_format) in test_cases.iter() {
            let output_path = std::env::temp_dir().join(format!("test_roundtrip_{type_name}.wav"));

            match *type_name {
                "i16" => {
                    let samples = base_sine.to_format::<i16>();
                    write_wav(
                        std::io::BufWriter::new(
                            std::fs::File::create(&output_path)
                                .expect("Failed to create output file"),
                        ),
                        &samples,
                    )
                    .expect("Failed to write WAV file");

                    // Validate WAV structure
                    let wav_file = WavFile::open_with_options(&output_path, OpenOptions::default())
                        .expect("Failed to open WAV file");
                    let base_info = wav_file.base_info().expect("Failed to get WAV base info");
                    let fmt_chunk = wav_file.fmt_chunk();

                    assert_eq!(base_info.sample_rate, sample_rate!(44100));
                    assert_eq!(base_info.bits_per_sample, *expected_bits);
                    assert_eq!(fmt_chunk.format_code(), *expected_format);

                    // Read back and verify data integrity
                    let read_samples = wav_file.read::<i16>().expect("Failed to read WAV samples");
                    let read_bytes = read_samples
                        .bytes()
                        .expect("Failed to get bytes from read samples");
                    let written_bytes = samples
                        .bytes()
                        .expect("Failed to get bytes from written samples");
                    assert_eq!(read_bytes.as_slice(), written_bytes.as_slice());
                }
                "i32" => {
                    let samples = base_sine.to_format::<i32>();
                    write_wav(
                        std::io::BufWriter::new(
                            std::fs::File::create(&output_path)
                                .expect("Failed to create output file"),
                        ),
                        &samples,
                    )
                    .expect("Failed to write WAV file");

                    // Validate WAV structure
                    let wav_file = WavFile::open_with_options(&output_path, OpenOptions::default())
                        .expect("Failed to open WAV file");
                    let base_info = wav_file.base_info().expect("Failed to get WAV base info");
                    let fmt_chunk = wav_file.fmt_chunk();

                    assert_eq!(base_info.sample_rate, sample_rate!(44100));
                    assert_eq!(base_info.bits_per_sample, *expected_bits);
                    assert_eq!(fmt_chunk.format_code(), *expected_format);

                    // Read back and verify data integrity
                    let read_samples = wav_file.read::<i32>().expect("Failed to read WAV samples");
                    let read_bytes = read_samples
                        .bytes()
                        .expect("Failed to get bytes from read samples");
                    let written_bytes = samples
                        .bytes()
                        .expect("Failed to get bytes from written samples");
                    assert_eq!(read_bytes.as_slice(), written_bytes.as_slice());
                }
                "f32" => {
                    write_wav(
                        std::io::BufWriter::new(
                            std::fs::File::create(&output_path)
                                .expect("Failed to create output file"),
                        ),
                        &base_sine,
                    )
                    .expect("Failed to write WAV file");

                    // Validate WAV structure
                    let wav_file = WavFile::open_with_options(&output_path, OpenOptions::default())
                        .expect("Failed to open WAV file");
                    let base_info = wav_file.base_info().expect("Failed to get WAV base info");
                    let fmt_chunk = wav_file.fmt_chunk();

                    assert_eq!(base_info.sample_rate, sample_rate!(44100));
                    assert_eq!(base_info.bits_per_sample, *expected_bits);
                    assert_eq!(fmt_chunk.format_code(), *expected_format);

                    // Read back and verify data integrity (with small tolerance for f32)
                    let read_samples = wav_file.read::<f32>().expect("Failed to read WAV samples");
                    let orig_bytes = base_sine
                        .bytes()
                        .expect("Failed to get bytes from original samples");
                    let read_bytes = read_samples
                        .bytes()
                        .expect("Failed to get bytes from read samples");

                    let orig_f32: &[f32] = bytemuck::cast_slice(orig_bytes.as_slice());
                    let read_f32: &[f32] = bytemuck::cast_slice(read_bytes.as_slice());

                    for (orig, read) in orig_f32.iter().zip(read_f32.iter()) {
                        assert!(
                            (orig - read).abs() < 1e-6,
                            "f32 samples should be nearly identical"
                        );
                    }
                }
                _ => unreachable!(),
            }

            // Verify file is readable by external tools (basic structure check)
            let file_bytes = std::fs::read(&output_path).expect("Failed to read output file");
            assert!(
                file_bytes.len() > 44,
                "WAV file should have proper header + data"
            );
            assert_eq!(&file_bytes[0..4], b"RIFF");
            assert_eq!(&file_bytes[8..12], b"WAVE");

            // Find and validate FMT and DATA chunks exist
            let mut has_fmt = false;
            let mut has_data = false;
            let mut pos = 12;

            while pos + 8 <= file_bytes.len() {
                let chunk_id = &file_bytes[pos..pos + 4];
                let chunk_size = u32::from_le_bytes([
                    file_bytes[pos + 4],
                    file_bytes[pos + 5],
                    file_bytes[pos + 6],
                    file_bytes[pos + 7],
                ]) as usize;

                if chunk_id == b"fmt " {
                    has_fmt = true;
                    assert!(chunk_size >= 16, "FMT chunk should be at least 16 bytes");
                } else if chunk_id == b"data" {
                    has_data = true;
                    assert!(chunk_size > 0, "DATA chunk should contain audio data");
                }

                pos += 8 + chunk_size + (chunk_size % 2); // Add padding if odd size
            }

            assert!(has_fmt, "WAV file should have FMT chunk");
            assert!(has_data, "WAV file should have DATA chunk");

            // Clean up
            fs::remove_file(&output_path).ok();
        }
    }
}