audio-codec-bsd 0.1.1

FLAC/PCM/WAV multi-format audio container decoder (symphonia + hound, pure Rust) emitting planar audio-core-bsd AudioFrames
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
//! FLAC + PCM container decoder backed by [`symphonia`] 0.6.
//!
//! `SymphoniaDecoder` runs on a **worker thread**: it performs blocking file
//! I/O, format probing, and heap allocation, and is explicitly **not**
//! real-time safe. Decoded frames must be handed to a lock-free ring buffer so
//! the RT audio thread never calls into this module.
//!
//! ## Sample normalisation
//!
//! Symphonia's typed [`AudioBuffer`] is internally **planar** — each plane is
//! a contiguous `Vec<S>` for one channel. The decoder uses
//! [`GenericAudioBufferRef::copy_to_slice_planar`] to emit per-channel `f32`
//! slices with automatic sample-format conversion, then concatenates the
//! planes into the flat planar layout required by [`audio_core_bsd::AudioFrame`].
//! No manual de-interleave is needed: symphonia hands us planar data and we
//! preserve that grouping.
//!
//! Integer samples are scaled by symphonia's own `FromSample` impls to a
//! normalised `f32` range; 32-bit float samples pass through. Non-finite
//! samples (`NaN`/`±Inf`) are coerced to `0.0`.
//!
//! ## End-of-stream
//!
//! Symphonia signals end-of-stream via [`FormatReader::next_packet`]
//! returning `Ok(None)`. This is mapped to `Ok(None)` from
//! [`ContainerDecoder::next_frame`]; EOF never panics and is never reported
//! as a decode error.
//!
//! [`symphonia`]: https://crates.io/crates/symphonia
//! [`AudioBuffer`]: symphonia::core::audio::AudioBuffer
//! [`GenericAudioBufferRef::copy_to_slice_planar`]: symphonia::core::audio::GenericAudioBufferRef::copy_to_slice_planar
//! [`FormatReader::next_packet`]: symphonia::core::formats::FormatReader::next_packet

use std::fs::File;
use std::path::{Path, PathBuf};

use audio_core_bsd::AudioFrame;
use symphonia::core::audio::GenericAudioBufferRef;
use symphonia::core::codecs::audio::{
    well_known::CODEC_ID_FLAC, AudioDecoder, AudioDecoderOptions,
};
use symphonia::core::codecs::CodecParameters;
use symphonia::core::errors::Error as SymphoniaError;
use symphonia::core::formats::probe::Hint;
use symphonia::core::formats::{FormatOptions, FormatReader};
use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions};
use symphonia::core::meta::MetadataOptions;
use symphonia::default::{get_codecs, get_probe};

use crate::decoder::{ContainerDecoder, FormatKind, StreamInfo};
use crate::error::{CodecError, Result};

/// A [`symphonia`]-backed decoder for FLAC (primary) and PCM containers.
///
/// Construct with [`SymphoniaDecoder::open`], then drive through the
/// [`ContainerDecoder`] trait. See the [module docs](self) for the
/// worker-thread / planar-layout / end-of-stream contract.
pub struct SymphoniaDecoder {
    /// Path the decoder was constructed against; used to decide whether a
    /// trait `open` call should re-open the source.
    path: PathBuf,
    /// The probed format reader (owns the `MediaSourceStream`).
    format: Box<dyn FormatReader>,
    /// The codec decoder for the selected audio track.
    decoder: Box<dyn AudioDecoder>,
    /// Track id of the selected audio stream.
    track_id: u32,
    /// Cached stream metadata (avoids re-reading `codec_params` each frame).
    sample_rate: u32,
    channels: u16,
    bits_per_sample: u32,
    total_frames: Option<u64>,
    /// sniffed container kind (Flac vs Wav) reported in `StreamInfo`.
    format_kind: FormatKind,
    /// Sticky end-of-stream flag; once true, `next_frame` short-circuits.
    eof: bool,
}

impl SymphoniaDecoder {
    /// Open the container at `path`, probe its format, and instantiate the
    /// matching audio decoder for the first audio track.
    ///
    /// # Errors
    ///
    /// - [`CodecError::Io`] if the file cannot be opened.
    /// - [`CodecError::Format`] if no container or audio track is found.
    /// - [`CodecError::Decode`] if the codec is not registered.
    pub fn open(path: &Path) -> Result<Self> {
        let SymphoniaDecoderState {
            format,
            decoder,
            track_id,
            sample_rate,
            channels,
            bits_per_sample,
            total_frames,
            format_kind,
            eof,
        } = Self::open_inner(path)?;
        Ok(Self {
            path: path.to_path_buf(),
            format,
            decoder,
            track_id,
            sample_rate,
            channels,
            bits_per_sample,
            total_frames,
            format_kind,
            eof,
        })
    }

    /// Shared open logic returning the heavy state without the (re-derivable)
    /// `path` field, so `reopen` can reuse it.
    fn open_inner(path: &Path) -> Result<SymphoniaDecoderState> {
        let file = File::open(path).map_err(|e| CodecError::Io(e.to_string()))?;
        let mss = MediaSourceStream::new(Box::new(file), MediaSourceStreamOptions::default());

        let mut hint = Hint::new();
        if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
            hint.with_extension(ext);
        }

        let probe = get_probe();
        let format = probe
            .probe(
                &hint,
                mss,
                FormatOptions::default(),
                MetadataOptions::default(),
            )
            .map_err(map_symphonia_err)?;

        // Pick the first track that advertises audio codec parameters.
        let tracks = format.tracks();
        let track = tracks
            .iter()
            .find(|t| {
                t.codec_params
                    .as_ref()
                    .is_some_and(CodecParameters::is_audio)
            })
            .ok_or_else(|| CodecError::Format("no audio track found in container".into()))?;

        let params = track
            .codec_params
            .as_ref()
            .and_then(CodecParameters::audio)
            .ok_or_else(|| CodecError::Format("selected track has no audio codec params".into()))?;

        let decoder = get_codecs()
            .make_audio_decoder(params, &AudioDecoderOptions::default())
            .map_err(map_symphonia_err)?;

        let sample_rate = params
            .sample_rate
            .ok_or_else(|| CodecError::Format("container reported no sample rate".into()))?;
        if sample_rate == 0 {
            return Err(CodecError::InvalidSampleRate(0));
        }
        let channel_count = params
            .channels
            .as_ref()
            .map(|c| u16::try_from(c.count()).unwrap_or(0))
            .ok_or_else(|| CodecError::Format("container reported no channels".into()))?;
        if channel_count == 0 {
            return Err(CodecError::InvalidChannelCount(0));
        }
        let bits_per_sample = params.bits_per_sample.unwrap_or(0);
        let format_kind = if params.codec == CODEC_ID_FLAC {
            FormatKind::Flac
        } else {
            // PCM inside a RIFF/WAV container — report the container, not the
            // (lossless) codec, so callers can route by container.
            FormatKind::Wav
        };

        // Copy the track id / frame count out of the borrowed `track` before
        // moving `format` into the state struct below (the borrow would
        // otherwise extend across the move).
        let track_id = track.id;
        let total_frames = track.num_frames;

        Ok(SymphoniaDecoderState {
            format,
            decoder,
            track_id,
            sample_rate,
            channels: channel_count,
            bits_per_sample,
            total_frames,
            format_kind,
            eof: false,
        })
    }

    /// Re-open the source from `path`, replacing all heavy state.
    fn reopen(&mut self, path: &Path) -> Result<()> {
        let inner = Self::open_inner(path)?;
        let SymphoniaDecoderState {
            format,
            decoder,
            track_id,
            sample_rate,
            channels,
            bits_per_sample,
            total_frames,
            format_kind,
            eof,
        } = inner;
        self.format = format;
        self.decoder = decoder;
        self.track_id = track_id;
        self.sample_rate = sample_rate;
        self.channels = channels;
        self.bits_per_sample = bits_per_sample;
        self.total_frames = total_frames;
        self.format_kind = format_kind;
        self.eof = eof;
        self.path = path.to_path_buf();
        Ok(())
    }

    /// Build a [`StreamInfo`] snapshot from the cached metadata.
    fn stream_info(&self) -> StreamInfo {
        StreamInfo {
            format: self.format_kind,
            sample_rate: self.sample_rate,
            channels: self.channels,
            bits_per_sample: self.bits_per_sample,
            total_frames: self.total_frames,
        }
    }

    /// Decode one packet into a planar [`AudioFrame`]. Returns `Ok(None)` at
    /// clean end-of-stream.
    fn decode_packet(&mut self) -> Result<Option<AudioFrame>> {
        if self.eof {
            return Ok(None);
        }

        let packet = match self.format.next_packet() {
            Ok(Some(p)) => p,
            // Symphonia signals EOS via Ok(None); never an error.
            Ok(None) => {
                self.eof = true;
                return Ok(None);
            }
            Err(e) => return Err(map_symphonia_err(e)),
        };

        // Only decode packets belonging to our selected audio track.
        if packet.track_id != self.track_id {
            return self.decode_packet();
        }

        let decoded = self.decoder.decode(&packet).map_err(map_symphonia_err)?;
        Ok(Some(Self::buffer_to_frame(
            &decoded,
            self.channels,
            self.sample_rate,
        )))
    }

    /// Convert a symphonia decoded buffer (already planar internally) into a
    /// flat planar [`AudioFrame`].
    fn buffer_to_frame(
        decoded: &GenericAudioBufferRef<'_>,
        channels: u16,
        sample_rate: u32,
    ) -> AudioFrame {
        let chan_us = usize::from(channels);
        let frames = decoded.frames();
        if frames == 0 {
            return AudioFrame::new(channels, sample_rate);
        }

        // The buffer exposes one plane per channel; copy each into its own
        // f32 slice, then concatenate into the flat planar layout.
        let mut samples: Vec<f32> = vec![0.0; chan_us * frames];
        // Borrow the whole buffer once, then split `samples` into per-channel
        // mutable slices for the bulk copy.
        {
            // `chunks_mut` yields `chan_us` slices each of length `frames`.
            let mut planes: Vec<&mut [f32]> = samples
                .chunks_mut(frames)
                .take(decoded.num_planes())
                .collect();
            decoded.copy_to_slice_planar::<f32, &mut [f32]>(&mut planes);
        }
        // Coerce any non-finite sample to 0.0 (defensive; symphonia's
        // conversion should already be finite for the supported codecs).
        for s in &mut samples {
            if !s.is_finite() {
                *s = 0.0;
            }
        }
        AudioFrame::from_planar(channels, sample_rate, samples)
    }
}

/// Internal helper: the heavy decoder state returned by `open_inner`, split
/// out so the public struct can be assembled from `(path, state)`.
struct SymphoniaDecoderState {
    format: Box<dyn FormatReader>,
    decoder: Box<dyn AudioDecoder>,
    track_id: u32,
    sample_rate: u32,
    channels: u16,
    bits_per_sample: u32,
    total_frames: Option<u64>,
    format_kind: FormatKind,
    eof: bool,
}

impl ContainerDecoder for SymphoniaDecoder {
    fn open(&mut self, path: &Path) -> Result<StreamInfo> {
        if path != self.path {
            self.reopen(path)?;
        }
        Ok(self.stream_info())
    }

    fn next_frame(&mut self) -> Result<Option<AudioFrame>> {
        self.decode_packet()
    }
}

/// Map a [`symphonia`] error into the crate's [`CodecError`].
///
/// `IoError` is surfaced as [`CodecError::Io`]; every other variant (decode,
/// seek, unsupported, limit, reset) is surfaced as [`CodecError::Decode`] so
/// callers see a single, stable error surface regardless of the backend.
fn map_symphonia_err(err: SymphoniaError) -> CodecError {
    match err {
        SymphoniaError::IoError(e) => CodecError::Io(e.to_string()),
        other => CodecError::Decode(other.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Opening a non-existent file surfaces [`CodecError::Io`] — never a panic.
    #[test]
    fn missing_file_yields_io_error_not_panic() {
        let mut bogus = std::path::PathBuf::from("/this/path/does/not/exist.flac");
        bogus.set_extension("flac");
        let res = SymphoniaDecoder::open(&bogus);
        let err = res.err().expect("expected an error");
        assert!(matches!(err, CodecError::Io(_)), "got {err:?}");
    }

    /// Opening a file that exists but is not a valid container surfaces
    /// [`CodecError::Format`] or [`CodecError::Io`] — never a panic. This is
    /// the graceful-degradation gate for the FLAC path when no FLAC fixture is
    /// available.
    #[test]
    fn malformed_file_yields_graceful_error_not_panic() {
        let mut path = std::env::temp_dir();
        path.push(format!(
            "audio_codec_bsd_symphonia_malformed_{}.bin",
            std::process::id()
        ));
        // Write bytes that are neither a valid FLAC nor a valid RIFF/WAVE.
        std::fs::write(&path, b"not a real audio container at all").expect("write temp");
        let res = SymphoniaDecoder::open(&path);
        let _ = std::fs::remove_file(&path);
        // The gate is "no panic": symphonia surfaces an unrecognised container
        // variously as Format/Decode/Io depending on how far probing got, so
        // accept any graceful CodecError variant.
        let err = res.err().expect("expected a graceful error");
        assert!(
            matches!(
                err,
                CodecError::Format(_) | CodecError::Io(_) | CodecError::Decode(_)
            ),
            "expected a graceful error variant, got {err:?}"
        );
    }

    /// If a valid `.flac` fixture is found at the path named by the
    /// `AUDIO_CODEC_FLAC_FIXTURE` env var, decode it end-to-end and assert:
    /// (a) the reported format is `Flac`, (b) every decoded sample is finite
    /// and in `[-1.0, 1.0]`, and (c) the planar length invariant holds.
    ///
    /// This test is **guarded by fixture availability**: there is no FLAC
    /// encoder in the dependency set (symphonia is decode-only, hound writes
    /// WAV only), so a committed binary fixture is the only way to exercise
    /// the real FLAC path. Without one the test self-skips so the suite stays
    /// green on hosts lacking a fixture — see the impl-notes for the rationale
    /// and how to opt in.
    #[test]
    fn flac_fixture_decode_when_provided() {
        let path = if let Some(p) = std::env::var_os("AUDIO_CODEC_FLAC_FIXTURE") {
            std::path::PathBuf::from(p)
        } else {
            eprintln!(
                "[skip] AUDIO_CODEC_FLAC_FIXTURE not set; no FLAC encoder is \
                 available to synthesise one. Skipping the FLAC round-trip test."
            );
            return;
        };
        if !path.exists() {
            eprintln!(
                "[skip] AUDIO_CODEC_FLAC_FIXTURE={path:?} does not exist on disk; \
                 skipping the FLAC round-trip test."
            );
            return;
        }

        let mut dec = SymphoniaDecoder::open(&path).expect("open fixture");
        let info = dec.open(&path).expect("trait open");
        assert_eq!(info.format, FormatKind::Flac, "expected FLAC container");
        assert!(info.sample_rate > 0);
        assert!(info.channels >= 1);

        let mut got_frames = 0usize;
        while let Some(frame) = dec.next_frame().expect("decode frame") {
            assert_eq!(frame.channels, info.channels);
            // Planar length invariant: samples.len() == channels * num_frames.
            assert_eq!(
                frame.samples.len(),
                usize::from(frame.channels) * frame.num_frames()
            );
            // Every sample must be finite and in [-1, 1].
            for &s in &frame.samples {
                assert!(s.is_finite(), "non-finite sample {s}");
                assert!((-1.0..=1.0).contains(&s), "sample {s} out of [-1,1]");
            }
            got_frames += 1;
        }
        assert!(got_frames > 0, "decoded zero frames from a valid fixture");
    }

    // ---- Stereo de-interleave via the symphonia path ----------------------
    //
    // The helpers below are the symphonia-path analogue of the WAV/hound
    // fixture helpers in `wav.rs`. They write a hand-built stereo WAV with
    // hound, then route it through `SymphoniaDecoder` so the
    // probe → packet → `buffer_to_frame` → `copy_to_slice_planar` pipeline —
    // a structurally different de-interleave than hound's interleaved-sample
    // loop — is exercised end-to-end.

    /// Exact-enough float comparison (uses `<`, never `==`, to stay
    /// `clippy::float_cmp`-clean). Matches the tolerance used by `wav.rs`.
    fn approx_eq(a: f32, b: f32) -> bool {
        (a - b).abs() < 1e-4
    }

    /// Scale factor for 16-bit integer PCM: `1 / 2^15`.
    const SCALE_16BIT: f32 = 1.0 / 32_768.0;

    /// Write `interleaved` 16-bit samples to a temp PCM WAV file and return
    /// its path. Uses native `i16` values so no `cast_*` pedantic lint fires.
    fn write_symphonia_wav_fixture(
        channels: u16,
        sample_rate: u32,
        interleaved: &[i16],
    ) -> PathBuf {
        use hound::{SampleFormat, WavSpec, WavWriter};
        let spec = WavSpec {
            channels,
            sample_rate,
            bits_per_sample: 16,
            sample_format: SampleFormat::Int,
        };
        let mut path = std::env::temp_dir();
        path.push(format!(
            "audio_codec_bsd_symphonia_stereo_{}_{}.wav",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_nanos()),
        ));
        let mut writer = WavWriter::create(&path, spec).expect("create wav fixture");
        for &v in interleaved {
            writer.write_sample(v).expect("write sample");
        }
        writer.finalize().expect("finalize wav fixture");
        path
    }

    /// **Symphonia-path stereo gate:** routes a hand-built 2-channel WAV
    /// through `SymphoniaDecoder` (NOT `WavDecoder`/hound), exercising the
    /// packet/buffer API whose de-interleave is structurally distinct from
    /// hound's interleaved-sample loop. Asserts that:
    ///
    /// - `StreamInfo` reports `FormatKind::Wav` and `channels == 2`.
    /// - `channel_slice(0)` and `channel_slice(1)` recover their *independent*
    ///   references within tolerance (proving correct planar grouping).
    /// - The two channels *differ* (catches an interleaved-as-planar bug that
    ///   a byte-count check alone would miss).
    ///
    /// This is the running counterpart to the fixture-gated `flac_*` test: no
    /// external FLAC encoder is needed because symphonia's `wav` + `pcm`
    /// features decode the hound-synthesised RIFF/WAVE in-process.
    #[test]
    fn stereo_wav_deinterleave_via_symphonia() {
        const FRAMES: usize = 8;
        // Channel 0: ascending ramp; Channel 1: a constant plateau. The two
        // patterns are deliberately distinct so an interleaved-as-planar bug
        // would scramble both.
        let want_ch0: [i16; FRAMES] = [-3500, -2500, -1500, -500, 500, 1500, 2500, 3500];
        let want_ch1: [i16; FRAMES] = [16_000; FRAMES];

        // Interleave and write a 16-bit PCM stereo WAV.
        let mut interleaved: Vec<i16> = Vec::with_capacity(FRAMES * 2);
        for i in 0..FRAMES {
            interleaved.push(want_ch0[i]);
            interleaved.push(want_ch1[i]);
        }
        let path = write_symphonia_wav_fixture(2, 48_000, &interleaved);

        // Open via the symphonia path: probe → track → PCM decoder.
        let mut dec = SymphoniaDecoder::open(&path).expect("symphonia open");
        let info = dec.open(&path).expect("trait open");
        // Symphonia reports PCM-in-RIFF as the Wav container (non-FLAC codec).
        assert_eq!(info.format, FormatKind::Wav, "expected Wav container");
        assert_eq!(info.channels, 2, "expected stereo");
        assert_eq!(info.sample_rate, 48_000);

        // Drain every packet, collecting per-channel planar samples. Symphonia
        // may split a small file across packets, so accumulate across frames.
        let mut got_ch0: Vec<f32> = Vec::new();
        let mut got_ch1: Vec<f32> = Vec::new();
        while let Some(frame) = dec.next_frame().expect("decode frame") {
            assert_eq!(frame.channels, 2, "every frame must be stereo");
            got_ch0.extend_from_slice(frame.channel_slice(0));
            got_ch1.extend_from_slice(frame.channel_slice(1));
        }
        assert!(!got_ch0.is_empty(), "decoded zero ch0 samples");

        // (b) The two channels MUST differ — catches interleaved-as-planar.
        assert_ne!(
            got_ch0.as_slice(),
            got_ch1.as_slice(),
            "channels identical: de-interleave failed"
        );

        // (a) Each channel recovers its independent reference within tolerance.
        assert_eq!(got_ch0.len(), FRAMES, "ch0 sample count");
        assert_eq!(got_ch1.len(), FRAMES, "ch1 sample count");
        for (i, &want) in want_ch0.iter().enumerate() {
            let expected = f32::from(want) * SCALE_16BIT;
            assert!(
                approx_eq(got_ch0[i], expected),
                "ch0[{i}] = {}, expected {expected}",
                got_ch0[i]
            );
        }
        for (i, &want) in want_ch1.iter().enumerate() {
            let expected = f32::from(want) * SCALE_16BIT;
            assert!(
                approx_eq(got_ch1[i], expected),
                "ch1[{i}] = {}, expected {expected}",
                got_ch1[i]
            );
        }

        let _ = std::fs::remove_file(&path);
    }
}