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
//! Streaming WAV file reader for memory-efficient audio processing.
//!
//! This module provides `StreamedWavFile`, a streaming reader that parses WAV headers
//! on construction but reads audio data on-demand, enabling processing of large files
//! without loading them entirely into memory.

use std::{
    io::SeekFrom,
    num::{NonZeroU32, NonZeroUsize},
    path::{Path, PathBuf},
    time::Duration,
};

use audio_samples::{
    AudioSamples, CastFrom, CastInto, ConvertFrom, ConvertTo, I24, nzu, traits::StandardSample,
};
use non_empty_slice::NonEmptyVec;

use crate::{
    ReadSeek,
    error::{AudioIOError, AudioIOResult, ErrorPosition},
    traits::{AudioFileMetadata, AudioInfoMarker, AudioStreamRead, AudioStreamReader},
    types::{BaseAudioInfo, FileType, ValidatedSampleType},
    wav::{
        FormatCode,
        chunks::{ChunkDesc, ChunkID, DATA_CHUNK, FMT_CHUNK, RIFF_CHUNK, WAVE_CHUNK},
        fmt::FmtChunk,
        wav_file::WavFileInfo,
    },
};

/// A streaming WAV file reader that reads audio data on-demand.
///
/// Unlike `WavFile` which loads or memory-maps the entire file, `StreamedWavFile`
/// only parses headers at construction and reads audio frames incrementally.
/// This is ideal for:
/// - Processing files larger than available memory
/// - Real-time streaming applications
/// - Network sources implementing `Read + Seek`
///
/// # Example
///
/// ```no_run
/// use audio_samples_io::wav::StreamedWavFile;
/// use audio_samples_io::traits::AudioFileMetadata;
/// use audio_samples::{AudioSamples, nzu};
/// use std::fs::File;
/// use std::io::BufReader;
/// use std::num::NonZeroU32;
///
/// let file = BufReader::new(File::open("audio.wav")?);
/// let mut streamed = StreamedWavFile::new(file)?;
///
/// // Read 1024 frames at a time
/// let channels = NonZeroU32::new(streamed.num_channels() as u32).ok_or_else(|| audio_samples_io::error::AudioIOError::UnsupportedFormat("channels must be non-zero".to_string()))?;
/// let sample_rate = NonZeroU32::new(streamed.sample_rate()).ok_or_else(|| audio_samples_io::error::AudioIOError::UnsupportedFormat("sample_rate must be non-zero".to_string()))?;
/// let mut buffer = AudioSamples::<f32>::zeros_multi(channels, nzu!(1024), sample_rate);
/// while streamed.remaining_frames() > 0 {
///     let frames_read = streamed.read_frames_into(&mut buffer, nzu!(1024))?;
///     // Process buffer...
/// }
/// # Ok::<(), audio_samples_io::error::AudioIOError>(())
/// ```
#[derive(Debug)]
pub struct StreamedWavFile<R>
where
    R: ReadSeek,
{
    /// The underlying reader
    reader: R,
    /// File path (if opened from path, otherwise synthetic)
    file_path: PathBuf,
    /// Discovered chunks (for metadata)
    chunks: Vec<ChunkDesc>,
    /// Cached format code
    format_code: FormatCode,
    /// Sample rate in Hz
    sample_rate: NonZeroU32,
    /// Number of channels
    channels: u16,
    /// Bits per sample
    bits_per_sample: u16,
    /// Bytes per sample
    bytes_per_sample: u16,
    /// Byte rate
    byte_rate: u32,
    /// Block align (bytes per frame)
    block_align: u16,
    /// Validated sample type
    sample_type: ValidatedSampleType,
    /// Total number of samples (all channels)
    total_samples: usize,
    /// Total number of frames
    total_frames: usize,
    /// Byte offset where audio data starts (absolute file position)
    data_offset: u64,
    /// Current frame position (0-indexed)
    current_frame: usize,
    /// Reusable byte buffer for reading
    byte_buffer: Vec<u8>,
}

impl<R> StreamedWavFile<R>
where
    R: ReadSeek,
{
    /// Create a new streaming WAV reader from any `Read + Seek` source.
    ///
    /// Parses the WAV header to extract format information and locates the
    /// data chunk, but does not read any audio samples.
    ///
    /// # Arguments
    ///
    /// * `reader` - Any type implementing `Read + Seek` (e.g., `BufReader<File>`)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The source is not a valid WAV file
    /// - Required chunks (fmt, data) are missing
    /// - The format is unsupported
    pub fn new(reader: R) -> AudioIOResult<Self> {
        Self::new_with_path(reader, PathBuf::from("<stream>"))
    }

    /// Create a new streaming WAV reader with an associated path.
    ///
    /// The path is used for error messages and metadata; the reader
    /// is the actual data source.
    pub fn new_with_path(mut reader: R, file_path: PathBuf) -> AudioIOResult<Self> {
        // Read enough bytes for RIFF header + reasonable chunk scanning
        // We'll read in chunks to handle headers of various sizes
        let mut header_buf = vec![0u8; 4096];
        let bytes_read = reader.read(&mut header_buf)?;
        header_buf.truncate(bytes_read);

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

        // Parse RIFF header
        let riff_bytes: [u8; 4] = header_buf
            .get(0..4)
            .and_then(|s| s.try_into().ok())
            .ok_or_else(|| {
                AudioIOError::corrupted_data(
                    "Cannot read RIFF header",
                    format!("Read {} bytes", header_buf.len()),
                    ErrorPosition::new(0).with_description("RIFF header at file start"),
                )
            })?;
        let riff = ChunkID::new(&riff_bytes);

        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 riff_size_bytes: [u8; 4] = header_buf
            .get(4..8)
            .and_then(|s| s.try_into().ok())
            .ok_or_else(|| {
                AudioIOError::corrupted_data(
                    "Cannot read RIFF chunk size",
                    format!("Read {} bytes", header_buf.len()),
                    ErrorPosition::new(4).with_description("RIFF chunk size"),
                )
            })?;
        let riff_size = u32::from_le_bytes(riff_size_bytes);

        let wave_bytes: [u8; 4] = header_buf
            .get(8..12)
            .and_then(|s| s.try_into().ok())
            .ok_or_else(|| {
                AudioIOError::corrupted_data(
                    "Cannot read WAVE identifier",
                    format!("Read {} bytes", header_buf.len()),
                    ErrorPosition::new(8).with_description("WAVE identifier"),
                )
            })?;
        let wave = ChunkID::new(&wave_bytes);

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

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

        let mut fmt_chunk_data: Option<Vec<u8>> = None;
        let mut data_chunk_desc: Option<ChunkDesc> = None;
        let mut offset = 12usize;

        // Parse chunks from buffer, seeking for more data if needed
        loop {
            // Ensure we have enough data for chunk header
            while offset + 8 > header_buf.len() {
                let current_len = header_buf.len();
                header_buf.resize(current_len + 4096, 0);
                let additional = reader.read(&mut header_buf[current_len..])?;
                if additional == 0 {
                    // EOF reached
                    header_buf.truncate(current_len);
                    break;
                }
                header_buf.truncate(current_len + additional);
            }

            if offset + 8 > header_buf.len() {
                break; // No more chunks
            }

            let id = ChunkID::new(header_buf[offset..offset + 4].try_into().map_err(|_| {
                AudioIOError::corrupted_data(
                    "Cannot read chunk ID",
                    "Insufficient data",
                    ErrorPosition::new(offset),
                )
            })?);

            let size =
                u32::from_le_bytes(header_buf[offset + 4..offset + 8].try_into().map_err(|_| {
                    AudioIOError::corrupted_data(
                        "Cannot read chunk size",
                        "Insufficient data",
                        ErrorPosition::new(offset + 4),
                    )
                })?) as usize;

            let padded = size + (size & 1);
            let header_and_data_size = 8 + padded;

            chunks.push(ChunkDesc {
                id,
                offset,
                logical_size: size,
                total_size: header_and_data_size,
            });

            // Handle fmt chunk - need to read its content
            if id == FMT_CHUNK {
                let fmt_start = offset + 8;
                let fmt_end = fmt_start + size;

                // Ensure we have the fmt data in buffer
                while fmt_end > header_buf.len() {
                    let current_len = header_buf.len();
                    header_buf.resize(current_len + 4096, 0);
                    let additional = reader.read(&mut header_buf[current_len..])?;
                    if additional == 0 {
                        return Err(AudioIOError::corrupted_data(
                            "Unexpected EOF reading fmt chunk",
                            format!("Need {} bytes, have {}", fmt_end, header_buf.len()),
                            ErrorPosition::new(fmt_start),
                        ));
                    }
                    header_buf.truncate(current_len + additional);
                }

                fmt_chunk_data = Some(header_buf[fmt_start..fmt_end].to_vec());
            }

            // Handle data chunk - just record its location
            if id == DATA_CHUNK {
                data_chunk_desc = Some(ChunkDesc {
                    id,
                    offset,
                    logical_size: size,
                    total_size: header_and_data_size,
                });
                // Don't read data chunk content - that's the point of streaming!
                break;
            }

            offset += header_and_data_size;
        }

        // Validate we found required chunks
        let fmt_bytes = fmt_chunk_data.ok_or_else(|| {
            AudioIOError::corrupted_data(
                "FMT chunk not found in WAV file",
                format!(
                    "Found chunks: {:?}",
                    chunks.iter().map(|c| c.id).collect::<Vec<_>>()
                ),
                ErrorPosition::new(12),
            )
        })?;

        let data_desc = data_chunk_desc.ok_or_else(|| {
            AudioIOError::corrupted_data(
                "DATA chunk not found in WAV file",
                format!(
                    "Found chunks: {:?}",
                    chunks.iter().map(|c| c.id).collect::<Vec<_>>()
                ),
                ErrorPosition::new(12),
            )
        })?;

        // Parse fmt chunk
        let fmt_chunk =
            FmtChunk::from_bytes_validated(&fmt_bytes).map_err(AudioIOError::WavError)?;
        let sample_type = fmt_chunk.actual_sample_type()?;

        let (format_code, channels, sample_rate, byte_rate, block_align, bits_per_sample) =
            fmt_chunk.fmt_chunk();
        let sample_rate = NonZeroU32::new(sample_rate).ok_or_else(|| {
            AudioIOError::corrupted_data_simple(
                "Invalid sample rate in FMT chunk",
                "Sample rate cannot be zero",
            )
        })?;
        let bytes_per_sample = bits_per_sample / 8;

        // Calculate frame info
        let data_offset = (data_desc.offset + 8) as u64;
        let data_size = data_desc.logical_size as u64;
        let total_samples = data_size as usize / sample_type.bytes_per_sample();
        let total_frames = total_samples / channels as usize;

        // Seek to start of audio data
        reader.seek(SeekFrom::Start(data_offset))?;

        Ok(StreamedWavFile {
            reader,
            file_path,
            chunks,
            format_code,
            sample_rate,
            channels,
            bits_per_sample,
            bytes_per_sample,
            byte_rate,
            block_align,
            sample_type,
            total_samples,
            total_frames,
            data_offset,
            current_frame: 0,
            byte_buffer: Vec::new(),
        })
    }

    /// Get the current frame position.
    #[inline]
    pub const fn current_frame(&self) -> usize {
        self.current_frame
    }

    /// Get the number of remaining frames from current position.
    #[inline]
    pub const fn remaining_frames(&self) -> usize {
        self.total_frames.saturating_sub(self.current_frame)
    }

    /// Get the total number of frames in the file.
    #[inline]
    pub const fn total_frames(&self) -> usize {
        self.total_frames
    }

    /// Get the sample rate.
    #[inline]
    pub const fn sample_rate(&self) -> u32 {
        self.sample_rate.get()
    }

    /// Get the bytes per frame (block_align).
    #[inline]
    pub const fn bytes_per_frame(&self) -> usize {
        self.block_align as usize
    }

    /// Seek to a specific frame position.
    ///
    /// # Arguments
    ///
    /// * `frame` - The frame index to seek to (0-indexed)
    ///
    /// # Errors
    ///
    /// Returns an error if the frame is beyond the end of the file or seek fails.
    pub fn seek_to_frame(&mut self, frame: usize) -> AudioIOResult<()> {
        if frame > self.total_frames {
            return Err(AudioIOError::SeekError(format!(
                "Frame {} is beyond end of file (total frames: {})",
                frame, self.total_frames
            )));
        }

        let byte_offset = frame as u64 * self.block_align as u64;
        self.reader
            .seek(SeekFrom::Start(self.data_offset + byte_offset))?;
        self.current_frame = frame;
        Ok(())
    }

    /// Reset to the beginning of the audio data.
    pub fn reset(&mut self) -> AudioIOResult<()> {
        self.seek_to_frame(0)
    }

    /// Read frames into a pre-allocated `AudioSamples` buffer.
    ///
    /// This is the primary zero-allocation read method. After initial buffer
    /// allocation, repeated calls reuse the same memory.
    ///
    /// # Arguments
    ///
    /// * `buffer` - Pre-allocated `AudioSamples` to fill with frame data
    /// * `frame_count` - Maximum number of frames to read
    ///
    /// # Returns
    ///
    /// The actual number of frames read (may be less at end of file).
    ///
    /// # Errors
    ///
    /// Returns an error if reading fails or data is corrupted.
    pub fn read_frames_into<T>(
        &mut self,
        buffer: &mut AudioSamples<'_, T>,
        frame_count: NonZeroUsize,
    ) -> AudioIOResult<usize>
    where
        T: StandardSample + 'static,
    {
        let frames_available = self.remaining_frames();
        let frames_to_read = frame_count.get().min(frames_available);

        if frames_to_read == 0 {
            return Ok(0);
        }

        let bytes_to_read = frames_to_read * self.bytes_per_frame();

        // Resize byte buffer if needed (only grows, never shrinks during iteration)
        if self.byte_buffer.len() < bytes_to_read {
            self.byte_buffer.resize(bytes_to_read, 0);
        }

        // Read bytes from source
        let bytes_read = self.reader.read(&mut self.byte_buffer[..bytes_to_read])?;
        let frames_read = bytes_read / self.bytes_per_frame();

        if frames_read == 0 {
            return Ok(0);
        }

        let actual_bytes = frames_read * self.bytes_per_frame();

        // Convert bytes to samples based on file's sample type
        let converted = self.convert_bytes_to_samples::<T>(&self.byte_buffer[..actual_bytes])?;

        // safety: We have already verified that converted.len() == total samples to read
        let converted = unsafe { NonEmptyVec::new_unchecked(converted) };
        // Deinterleave and replace buffer contents
        // safety: channels is guaranteed > 0 from parsing, and converted length matches frames read
        let num_channels = unsafe { NonZeroU32::new_unchecked(self.channels as u32) };

        if buffer.is_mono() {
            buffer.replace_with_vec(&converted)?;
        } else {
            let planar =
                audio_samples::simd_conversions::deinterleave_multi_vec(&converted, num_channels)
                    .map_err(|e| {
                    AudioIOError::corrupted_data_simple("Deinterleave failed", e.to_string())
                })?;
            buffer.replace_with_vec(&planar)?;
        }

        self.current_frame += frames_read;
        Ok(frames_read)
    }

    /// Convert raw bytes to samples of type T based on file's sample type.
    fn convert_bytes_to_samples<T>(&self, bytes: &[u8]) -> AudioIOResult<Vec<T>>
    where
        T: StandardSample + 'static,
    {
        match self.sample_type {
            ValidatedSampleType::U8 => Ok(bytes.iter().map(|&b| T::convert_from(b)).collect()),
            ValidatedSampleType::I16 => Ok(bytes
                .chunks_exact(2)
                .map(|c| i16::from_le_bytes([c[0], c[1]]))
                .map(T::convert_from)
                .collect()),
            ValidatedSampleType::I24 => Ok(bytes
                .chunks_exact(3)
                .map(|c| I24::from_le_bytes([c[0], c[1], c[2]]))
                .map(T::convert_from)
                .collect()),
            ValidatedSampleType::I32 => Ok(bytes
                .chunks_exact(4)
                .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]))
                .map(T::convert_from)
                .collect()),
            ValidatedSampleType::F32 => Ok(bytes
                .chunks_exact(4)
                .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
                .map(T::convert_from)
                .collect()),
            ValidatedSampleType::F64 => Ok(bytes
                .chunks_exact(8)
                .map(|c| f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]))
                .map(T::convert_from)
                .collect()),
        }
    }

    /// Create a frame iterator over this streamed file.
    ///
    /// Returns frames one at a time, reusing an internal buffer.
    ///
    /// # Panics
    ///
    /// Does not panic since the sample rate is guaranteed to be non-zero during parsing.
    pub fn frames<T>(&mut self) -> StreamedFrameIter<'_, R, T>
    where
        T: StandardSample + ConvertTo<T> + ConvertFrom<T> + 'static,
        f64: CastInto<T> + CastFrom<T> + ConvertTo<T> + ConvertFrom<T>,
    {
        let sample_rate = self.sample_rate;
        let frame_buffer = if self.channels == 1 {
            AudioSamples::zeros_mono(audio_samples::nzu!(1), sample_rate)
        } else {
            // safe: channels is guaranteed > 0
            AudioSamples::zeros_multi(
                unsafe { NonZeroU32::new_unchecked(self.channels as u32) },
                audio_samples::nzu!(1),
                sample_rate,
            )
        };
        StreamedFrameIter {
            source: self,
            frame_buffer,
        }
    }

    /// Create a windowed iterator over this streamed file.
    ///
    /// # Arguments
    ///
    /// * `window_size` - Number of frames per window
    /// * `hop_size` - Number of frames to advance between windows
    ///
    /// # Panics
    ///
    /// Does not panic since the sample rate is guaranteed to be non-zero during parsing.
    pub fn windows<T>(
        &mut self,
        window_size: NonZeroUsize,
        hop_size: NonZeroUsize,
    ) -> StreamedWindowIter<'_, R, T>
    where
        T: StandardSample + ConvertTo<T> + ConvertFrom<T> + 'static,
        f64: CastInto<T> + CastFrom<T> + ConvertTo<T> + ConvertFrom<T>,
    {
        let sample_rate = self.sample_rate;
        let window_buffer = if self.channels == 1 {
            AudioSamples::zeros_mono(window_size, sample_rate)
        } else {
            AudioSamples::zeros_multi(
                unsafe { NonZeroU32::new_unchecked(self.channels as u32) },
                window_size,
                sample_rate,
            )
        };
        StreamedWindowIter {
            source: self,
            window_buffer,
            window_size,
            hop_size,
            first_window: true,
        }
    }
}

// Implement AudioFileMetadata for StreamedWavFile
impl<R> AudioFileMetadata for StreamedWavFile<R>
where
    R: ReadSeek,
{
    fn open_metadata<P: AsRef<Path>>(_path: P) -> AudioIOResult<Self>
    where
        Self: Sized,
    {
        // This doesn't make sense for StreamedWavFile since we need a reader
        Err(AudioIOError::corrupted_data_simple(
            "StreamedWavFile requires a reader",
            "Use StreamedWavFile::new() instead",
        ))
    }

    fn base_info(&self) -> AudioIOResult<BaseAudioInfo> {
        let duration =
            Duration::from_secs_f64(self.total_frames as f64 / self.sample_rate.get() as f64);
        Ok(BaseAudioInfo::new(
            self.sample_rate,
            self.channels,
            self.bits_per_sample,
            self.bytes_per_sample,
            self.byte_rate,
            self.block_align,
            self.total_samples,
            duration,
            FileType::WAV,
            self.sample_type.into(),
        ))
    }

    fn specific_info(&self) -> impl AudioInfoMarker {
        WavFileInfo {
            available_chunks: self.chunks.iter().map(|c| c.id).collect(),
            encoding: self.format_code,
        }
    }

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

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

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

    fn duration(&self) -> AudioIOResult<Duration> {
        Ok(Duration::from_secs_f64(
            self.total_frames as f64 / self.sample_rate.get() as f64,
        ))
    }

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

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

// Implement AudioStreamReader for StreamedWavFile (object-safe streaming trait)
impl<R> AudioStreamReader for StreamedWavFile<R>
where
    R: ReadSeek,
{
    #[inline]
    fn current_frame(&self) -> usize {
        self.current_frame
    }

    #[inline]
    fn remaining_frames(&self) -> usize {
        self.total_frames.saturating_sub(self.current_frame)
    }

    #[inline]
    fn total_frames(&self) -> usize {
        self.total_frames
    }

    #[inline]
    fn sample_rate(&self) -> u32 {
        self.sample_rate.get()
    }

    #[inline]
    fn bytes_per_frame(&self) -> usize {
        self.block_align as usize
    }

    fn seek_to_frame(&mut self, frame: usize) -> AudioIOResult<()> {
        StreamedWavFile::seek_to_frame(self, frame)
    }

    fn reset(&mut self) -> AudioIOResult<()> {
        StreamedWavFile::reset(self)
    }
}

// Implement AudioStreamRead for StreamedWavFile (generic streaming read trait)
impl<R> AudioStreamRead for StreamedWavFile<R>
where
    R: ReadSeek,
{
    fn read_frames_into<T>(
        &mut self,
        buffer: &mut AudioSamples<'_, T>,
        frame_count: NonZeroUsize,
    ) -> AudioIOResult<usize>
    where
        T: StandardSample + 'static,
    {
        StreamedWavFile::read_frames_into(self, buffer, frame_count)
    }
}

/// Iterator over individual frames from a streamed WAV file.
///
/// Each call to `next()` reads one frame from the source and returns
/// a reference to the internal buffer containing that frame's samples.
pub struct StreamedFrameIter<'a, R, T>
where
    R: ReadSeek,
    T: StandardSample + 'static,
{
    source: &'a mut StreamedWavFile<R>,
    frame_buffer: AudioSamples<'static, T>,
}

impl<'a, R, T> Iterator for StreamedFrameIter<'a, R, T>
where
    R: ReadSeek,
    T: StandardSample + 'static,
{
    type Item = AudioIOResult<AudioSamples<'static, T>>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.source.remaining_frames() == 0 {
            return None;
        }

        match self
            .source
            .read_frames_into(&mut self.frame_buffer, nzu!(1))
        {
            Ok(0) => None,
            Ok(_) => Some(Ok(self.frame_buffer.clone())),
            Err(e) => Some(Err(e)),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.source.remaining_frames();
        (remaining, Some(remaining))
    }
}

impl<'a, R, T> ExactSizeIterator for StreamedFrameIter<'a, R, T>
where
    R: ReadSeek,
    T: StandardSample + 'static,
{
}

/// Iterator over windows of frames from a streamed WAV file.
///
/// Supports overlapping windows via configurable hop size.
pub struct StreamedWindowIter<'a, R, T>
where
    R: ReadSeek,
    T: StandardSample + 'static,
{
    source: &'a mut StreamedWavFile<R>,
    window_buffer: AudioSamples<'static, T>,
    window_size: NonZeroUsize,
    hop_size: NonZeroUsize,
    first_window: bool,
}

impl<'a, R, T> Iterator for StreamedWindowIter<'a, R, T>
where
    R: ReadSeek,
    T: StandardSample + 'static,
{
    type Item = AudioIOResult<AudioSamples<'static, T>>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.source.remaining_frames() == 0 {
            return None;
        }

        // For overlapping windows after the first, we need to seek back
        if !self.first_window && self.hop_size < self.window_size {
            let overlap = self.window_size.get() - self.hop_size.get();
            let new_frame = self.source.current_frame.saturating_sub(overlap);
            if let Err(e) = self.source.seek_to_frame(new_frame) {
                return Some(Err(e));
            }
        }
        self.first_window = false;

        match self
            .source
            .read_frames_into(&mut self.window_buffer, self.window_size)
        {
            Ok(0) => None,
            Ok(_) => Some(Ok(self.window_buffer.clone())),
            Err(e) => Some(Err(e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use audio_samples::{nzu, sample_rate};

    use super::*;
    use std::fs::File;
    use std::io::BufReader;

    #[test]
    fn test_streamed_wav_file_open() {
        let file = BufReader::new(File::open("resources/test.wav").expect("Test file not found"));
        let streamed = StreamedWavFile::new(file);
        assert!(streamed.is_ok(), "Failed to open streamed WAV file");

        let streamed = streamed.expect("Failed to open streamed WAV file");
        assert!(streamed.total_frames() > 0);
        assert_eq!(streamed.current_frame(), 0);
    }

    #[test]
    fn test_streamed_wav_metadata() {
        let file = BufReader::new(File::open("resources/test.wav").expect("Test file not found"));
        let streamed = StreamedWavFile::new(file).expect("Failed to open");

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

    #[test]
    fn test_streamed_read_frames() {
        let file = BufReader::new(File::open("resources/test.wav").expect("Test file not found"));
        let mut streamed = StreamedWavFile::new(file).expect("Failed to open");

        let channels = streamed.num_channels() as usize;
        let sample_rate = NonZeroU32::new(streamed.sample_rate()).expect("sample rate is non-zero");

        let mut buffer = if channels == 1 {
            AudioSamples::<f32>::zeros_mono(nzu!(1024), sample_rate)
        } else {
            // safety: channels is guaranteed > 0
            let channels = unsafe { NonZeroU32::new_unchecked(channels as u32) };
            AudioSamples::<f32>::zeros_multi(channels, nzu!(1024), sample_rate)
        };
        let frames_read = streamed
            .read_frames_into(&mut buffer, nzu!(1024))
            .expect("Read failed");

        assert!(frames_read > 0);
        assert_eq!(streamed.current_frame(), frames_read);
    }

    #[test]
    fn test_streamed_seek() {
        let file = BufReader::new(File::open("resources/test.wav").expect("Test file not found"));
        let mut streamed = StreamedWavFile::new(file).expect("Failed to open");

        let mid_frame = streamed.total_frames() / 2;
        streamed.seek_to_frame(mid_frame).expect("Seek failed");
        assert_eq!(streamed.current_frame(), mid_frame);

        streamed.reset().expect("Reset failed");
        assert_eq!(streamed.current_frame(), 0);
    }

    #[test]
    fn test_streamed_frame_iterator() {
        let file = BufReader::new(File::open("resources/test.wav").expect("Test file not found"));
        let mut streamed = StreamedWavFile::new(file).expect("Failed to open");

        let total = streamed.total_frames();
        let mut count = 0;

        for frame_result in streamed.frames::<f32>() {
            let _frame = frame_result.expect("Frame read failed");
            count += 1;
            if count >= 100 {
                break; // Don't iterate entire file in test
            }
        }

        assert_eq!(count, 100.min(total));
    }
}