audiofp 0.3.7

Pure-Rust audio fingerprinting and identification: Wang, Panako, Haitsma–Kalker, ONNX neural embedder, AudioSeal watermark, and streaming variants. no_std + alloc capable, bytemuck-friendly hash types.
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
//! One-shot audio file decoding via Symphonia.

use std::fs::File;
use std::path::Path;

use symphonia::core::audio::{Audio, AudioBuffer, GenericAudioBufferRef};
use symphonia::core::codecs::audio::AudioDecoderOptions;
use symphonia::core::errors::Error as SymphoniaError;
use symphonia::core::formats::probe::Hint;
use symphonia::core::formats::{FormatOptions, FormatReader, TrackType};
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;

use crate::dsp::resample::SincResampler;
use crate::error::IoError;
use crate::{AfpError, Result};

/// Decode an audio file into a mono `f32` buffer at the file's native
/// sample rate.
///
/// Multi-channel files are downmixed to mono by averaging channels per
/// frame. The returned tuple is `(samples, sample_rate_hz)`.
///
/// # Supported formats
///
/// MP3, FLAC, WAV, OGG-Vorbis, AAC-in-MP4, raw PCM — whatever Symphonia's
/// default registries provide with the features enabled in
/// `audiofp`'s `Cargo.toml`. The decoder probes magic bytes too, so
/// extension-less files still work as long as they're a recognised format.
///
/// # Errors
///
/// - [`AfpError::Io`] if the file is missing, the format isn't recognised,
///   or a stream-fatal decode error happens. Recoverable per-packet failures
///   inside Symphonia are silently skipped so a single corrupt block
///   doesn't kill the whole-file decode.
///
/// # Example
///
/// ```no_run
/// use audiofp::io::decode_to_mono;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let (samples, sr) = decode_to_mono("song.flac")?;
/// println!("{} samples at {sr} Hz", samples.len());
/// # Ok(()) }
/// ```
pub fn decode_to_mono<P: AsRef<Path>>(path: P) -> Result<(Vec<f32>, u32)> {
    let path = path.as_ref();
    let file = File::open(path).map_err(|e| AfpError::io_with_path(path, e))?;
    let mss = MediaSourceStream::new(Box::new(file), Default::default());

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

    decode_inner(mss, &hint)
}

/// Decode an audio file and resample it to `target_sr` Hz mono `f32`.
///
/// Pass-through (no resample) when the file already matches `target_sr`.
/// Otherwise resamples via [`SincResampler`] at default quality
/// (32-tap Kaiser, β = 8.6). Equivalent to calling [`decode_to_mono`]
/// then [`SincResampler::process`] yourself, but in one step.
///
/// # Errors
///
/// Surfaces every error [`decode_to_mono`] can return; resampling itself
/// cannot fail with the built-in [`SincResampler`].
///
/// # Example
///
/// ```no_run
/// use audiofp::io::decode_to_mono_at;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Get audio ready for Wang in one line:
/// let samples = decode_to_mono_at("song.mp3", 8_000)?;
/// # Ok(()) }
/// ```
pub fn decode_to_mono_at<P: AsRef<Path>>(path: P, target_sr: u32) -> Result<Vec<f32>> {
    if target_sr == 0 {
        return Err(AfpError::Config("target sample rate must be > 0".into()));
    }
    let (samples, sr) = decode_to_mono(path)?;
    if sr == target_sr {
        Ok(samples)
    } else {
        let r = SincResampler::new(sr, target_sr);
        Ok(r.process(&samples))
    }
}

fn decode_inner(mss: MediaSourceStream, hint: &Hint) -> Result<(Vec<f32>, u32)> {
    let mut format: Box<dyn FormatReader> = symphonia::default::get_probe()
        .probe(
            hint,
            mss,
            FormatOptions::default(),
            MetadataOptions::default(),
        )
        .map_err(|e| {
            AfpError::Io(IoError::without_path(std::io::Error::other(format!(
                "probe: {e}"
            ))))
        })?;

    let track = format
        .default_track(TrackType::Audio)
        .ok_or_else(|| {
            AfpError::Io(IoError::without_path(std::io::Error::other(
                "no audio track",
            )))
        })?
        .clone();
    let track_id = track.id;

    let audio_params = match track.codec_params.as_ref() {
        Some(symphonia::core::codecs::CodecParameters::Audio(params)) => params,
        _ => {
            return Err(AfpError::Io(IoError::without_path(std::io::Error::other(
                "no audio codec params",
            ))));
        }
    };

    let sample_rate = audio_params.sample_rate.ok_or_else(|| {
        AfpError::Io(IoError::without_path(std::io::Error::other(
            "missing sample rate",
        )))
    })?;

    let codecs = symphonia::default::get_codecs();
    let decoder_factory = codecs
        .get_audio_decoder(audio_params.codec)
        .ok_or_else(|| {
            AfpError::Io(IoError::without_path(std::io::Error::other(
                "unsupported codec",
            )))
        })?;
    let mut decoder = (decoder_factory.factory)(audio_params, &AudioDecoderOptions::default())
        .map_err(|e| {
            AfpError::Io(IoError::without_path(std::io::Error::other(format!(
                "make decoder: {e}"
            ))))
        })?;

    let mut samples: Vec<f32> = Vec::new();
    let mut convert_buf: Option<AudioBuffer<f32>> = None;

    loop {
        let packet = match format.next_packet() {
            Ok(Some(p)) => p,
            Ok(None) => break,
            Err(SymphoniaError::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                break;
            }
            Err(SymphoniaError::ResetRequired) => continue,
            Err(e) => {
                return Err(AfpError::Io(IoError::without_path(std::io::Error::other(
                    format!("next_packet: {e}"),
                ))));
            }
        };
        if packet.track_id != track_id {
            continue;
        }

        let decoded: GenericAudioBufferRef = match decoder.decode(&packet) {
            Ok(d) => d,
            // Recoverable per-packet failures: skip and keep going.
            Err(SymphoniaError::IoError(_)) | Err(SymphoniaError::DecodeError(_)) => {
                continue;
            }
            Err(e) => {
                return Err(AfpError::Io(IoError::without_path(std::io::Error::other(
                    format!("decode: {e}"),
                ))));
            }
        };

        // Lazily allocate the f32 conversion buffer once the first packet
        // tells us the channel layout / capacity. Reallocate if a later
        // packet decodes to more frames than the current buffer can hold
        // (the first packet's capacity is not guaranteed to bound the rest).
        let needed_cap = decoded.frames().max(decoded.capacity());
        let needs_buf = match &convert_buf {
            None => true,
            Some(buf) => needed_cap > buf.capacity(),
        };
        if needs_buf {
            let spec = decoded.spec().clone();
            convert_buf = Some(AudioBuffer::<f32>::new(spec, needed_cap));
        }
        let buf = convert_buf.as_mut().unwrap();

        // In symphonia 0.6, copy_to requires the destination to have the
        // same frame count as the source. Set it before copying.
        buf.resize_uninit(decoded.frames());
        decoded.copy_to::<f32, _>(buf);

        let n_frames = buf.frames();
        let n_chans = buf.spec().channels().count();

        if n_chans == 1 {
            samples.extend_from_slice(&buf.plane(0).unwrap()[..n_frames]);
        } else {
            samples.reserve(n_frames);
            for i in 0..n_frames {
                let mut sum = 0.0_f32;
                for c in 0..n_chans {
                    sum += buf.plane(c).unwrap()[i];
                }
                samples.push(sum / n_chans as f32);
            }
        }
    }

    Ok((samples, sample_rate))
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::f32::consts::PI;
    use std::io::Write;

    fn write_test_wav(channels: u16, sr: u32, len: usize) -> std::path::PathBuf {
        // Counter ensures each test gets a unique path so parallel runs
        // don't clobber each other.
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        let path = std::env::temp_dir().join(format!(
            "audiofp-decoder-test-{}-{}-{}-{}-{}.wav",
            std::process::id(),
            channels,
            sr,
            len,
            n,
        ));
        let spec = hound::WavSpec {
            channels,
            sample_rate: sr,
            bits_per_sample: 16,
            sample_format: hound::SampleFormat::Int,
        };
        let mut writer = hound::WavWriter::create(&path, spec).unwrap();
        let amp = (i16::MAX as f32) * 0.5;
        for i in 0..len {
            // 440 Hz tone on every channel (mono on every channel for
            // multichannel files = identical channels, downmix is identity).
            let s = libm::sinf(2.0 * PI * 440.0 * i as f32 / sr as f32) * amp;
            for _c in 0..channels {
                writer.write_sample(s as i16).unwrap();
            }
        }
        writer.finalize().unwrap();
        path
    }

    #[test]
    fn open_missing_file_returns_io_error() {
        let res = decode_to_mono("/nonexistent/path/that/does/not/exist.wav");
        match res {
            Err(AfpError::Io(_)) => {}
            other => panic!("expected Io error, got {other:?}"),
        }
    }

    #[test]
    fn round_trip_mono_wav() {
        let path = write_test_wav(1, 8_000, 8_000);
        let result = decode_to_mono(&path);
        std::fs::remove_file(&path).ok();
        let (samples, sr) = result.unwrap();
        assert_eq!(sr, 8_000);
        assert_eq!(samples.len(), 8_000);

        // Spot-check a sample mid-buffer.
        let expected = libm::sinf(2.0 * PI * 440.0 * 100.0 / 8_000.0) * 0.5;
        // 16-bit truncation introduces ~3e-5 error; allow a generous bound.
        assert!(
            (samples[100] - expected).abs() < 0.01,
            "sample[100] = {}, expected ≈ {expected}",
            samples[100]
        );
    }

    #[test]
    fn stereo_wav_downmixes_to_mono() {
        // Both channels are identical so downmix should be the same signal.
        let path = write_test_wav(2, 16_000, 16_000);
        let result = decode_to_mono(&path);
        std::fs::remove_file(&path).ok();
        let (samples, sr) = result.unwrap();
        assert_eq!(sr, 16_000);
        assert_eq!(samples.len(), 16_000);

        let expected = libm::sinf(2.0 * PI * 440.0 * 200.0 / 16_000.0) * 0.5;
        assert!((samples[200] - expected).abs() < 0.01);
    }

    #[test]
    fn decode_to_mono_at_resamples() {
        let path = write_test_wav(1, 16_000, 16_000); // 1 sec @ 16 kHz
        let result = decode_to_mono_at(&path, 8_000);
        std::fs::remove_file(&path).ok();
        let samples = result.unwrap();
        // 16k → 8k means roughly half as many samples.
        assert!(
            (samples.len() as i64 - 8_000).abs() < 16,
            "resampled len = {}",
            samples.len()
        );
    }

    #[test]
    fn decode_to_mono_at_passthrough_when_rates_match() {
        let path = write_test_wav(1, 8_000, 4_000);
        let result = decode_to_mono_at(&path, 8_000);
        std::fs::remove_file(&path).ok();
        let samples = result.unwrap();
        assert_eq!(samples.len(), 4_000);
    }

    #[test]
    fn unknown_extension_still_decodes() {
        // Symphonia probes magic bytes too, so an extensionless file still
        // works as long as it's a recognised format.
        let path = write_test_wav(1, 8_000, 4_000);
        let renamed = path.with_extension("");
        std::fs::rename(&path, &renamed).unwrap();

        let result = decode_to_mono(&renamed);
        std::fs::remove_file(&renamed).ok();

        // Use of ? syntax via match: succeed or report.
        let (samples, sr) = match result {
            Ok(v) => v,
            Err(e) => panic!("decode without extension failed: {e}"),
        };
        assert_eq!(sr, 8_000);
        assert_eq!(samples.len(), 4_000);
    }

    /// Ensure the public APIs don't hold onto the file handle past
    /// successful decode (otherwise removing the file would fail on
    /// Windows; on Unix it would leak a descriptor).
    #[test]
    fn temp_file_can_be_deleted_after_decode() {
        let path = write_test_wav(1, 8_000, 1_000);
        decode_to_mono(&path).unwrap();
        // Should not error out.
        std::fs::remove_file(&path).unwrap();
    }

    /// Dummy `Write` ensures the unused-import pruner doesn't strip
    /// `std::io::Write` if a future test needs in-memory writers.
    #[allow(dead_code)]
    fn _writer_witness<W: Write>(_w: W) {}

    fn write_test_wav_float(channels: u16, sr: u32, len: usize) -> std::path::PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        let path = std::env::temp_dir().join(format!(
            "audiofp-decoder-float-{}-{}-{}-{}.wav",
            std::process::id(),
            channels,
            sr,
            n,
        ));
        let spec = hound::WavSpec {
            channels,
            sample_rate: sr,
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
        };
        let mut writer = hound::WavWriter::create(&path, spec).unwrap();
        for i in 0..len {
            let s = libm::sinf(2.0 * PI * 440.0 * i as f32 / sr as f32) * 0.5;
            for _c in 0..channels {
                writer.write_sample(s).unwrap();
            }
        }
        writer.finalize().unwrap();
        path
    }

    #[test]
    fn float_wav_decodes_with_higher_precision() {
        let path = write_test_wav_float(1, 16_000, 4_000);
        let result = decode_to_mono(&path);
        std::fs::remove_file(&path).ok();
        let (samples, sr) = result.unwrap();
        assert_eq!(sr, 16_000);
        assert_eq!(samples.len(), 4_000);
        // 32-bit float should give near-exact reconstruction.
        let expected = libm::sinf(2.0 * PI * 440.0 * 100.0 / 16_000.0) * 0.5;
        assert!(
            (samples[100] - expected).abs() < 1e-6,
            "sample[100] = {}, expected {expected}",
            samples[100]
        );
    }

    #[test]
    fn high_sample_rate_preserved() {
        let path = write_test_wav(1, 48_000, 4_800);
        let result = decode_to_mono(&path);
        std::fs::remove_file(&path).ok();
        let (samples, sr) = result.unwrap();
        assert_eq!(sr, 48_000);
        assert_eq!(samples.len(), 4_800);
    }

    #[test]
    fn decode_to_mono_at_handles_upsample() {
        let path = write_test_wav(1, 8_000, 4_000);
        let result = decode_to_mono_at(&path, 16_000);
        std::fs::remove_file(&path).ok();
        let samples = result.unwrap();
        // 8k → 16k should give roughly 2× samples.
        assert!(
            (samples.len() as i64 - 8_000).abs() < 16,
            "upsampled len = {}",
            samples.len()
        );
    }
}