SPB Git

Repository Public

files.rs 14.7 KB 286 lines rust

1//! ORIX Sonata2//! File: crates/sonata-render/tests/files.rs3//! Description: Audio file round trips, independent decoding with ffmpeg and afinfo when4//! installed, dither statistics, atomic writing and rejection of malformed files.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai8#![allow(clippy::needless_range_loop)] // sample indices are the subject of these assertions910use sonata_render::*;11use std::path::PathBuf;12use std::process::Command;1314fn tmp(name: &str) -> PathBuf {15    let dir = std::env::temp_dir().join(format!("sonata-render-tests-{}", std::process::id()));16    std::fs::create_dir_all(&dir).unwrap();17    dir.join(name)18}1920fn test_audio(rate: u32, frames: usize, channels: usize) -> AudioData {21    let mut s = 42u64;22    AudioData {23        sample_rate: rate,24        channels: (0..channels)25            .map(|c| {26                (0..frames)27                    .map(|i| {28                        s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);29                        let noise = ((s >> 40) as f32 / (1u64 << 23) as f32 - 1.0) * 0.01;30                        0.7 * (i as f32 * (0.02 + 0.013 * c as f32)).sin() + noise31                    })32                    .collect()33            })34            .collect(),35    }36}3738const ALL: [(FileFormat, SampleFormat, &str); 12] = [39    (FileFormat::Wav, SampleFormat::Pcm16, "wav"),40    (FileFormat::Wav, SampleFormat::Pcm24, "wav"),41    (FileFormat::Wav, SampleFormat::Pcm32, "wav"),42    (FileFormat::Wav, SampleFormat::Float32, "wav"),43    (FileFormat::Wav, SampleFormat::Float64, "wav"),44    (FileFormat::Aiff, SampleFormat::Pcm16, "aiff"),45    (FileFormat::Aiff, SampleFormat::Pcm24, "aiff"),46    (FileFormat::Aiff, SampleFormat::Pcm32, "aiff"),47    (FileFormat::Aiff, SampleFormat::Float32, "aifc"),48    (FileFormat::Aiff, SampleFormat::Float64, "aifc"),49    (FileFormat::Flac, SampleFormat::Pcm16, "flac"),50    (FileFormat::Flac, SampleFormat::Pcm24, "flac"),51];5253/// Largest error allowed after a round trip: half an LSB of the integer format (plus float3254/// rounding), exact for float formats.55fn tolerance(s: SampleFormat) -> f32 {56    match s {57        SampleFormat::Pcm16 => 0.5 / 32_768.0 + 1e-7,58        SampleFormat::Pcm24 => 0.5 / 8_388_608.0 + 1e-7,59        SampleFormat::Pcm32 => 1e-7,60        _ => 0.0,61    }62}6364#[test]65fn every_format_round_trips_through_our_reader() {66    for rate in [44_100u32, 48_000, 88_200, 96_000, 176_400, 192_000] {67        for channels in [1usize, 2] {68            let audio = test_audio(rate, 5_003, channels);69            for (format, samples, _) in ALL {70                let (bytes, report) = encode_audio(&audio, &FileSpec::new(format, samples)).unwrap();71                assert_eq!((report.frames, report.clipped_samples, report.non_finite_samples), (5_003, 0, 0));72                let (back, info) = decode_audio(&bytes, &ReadLimits::default()).unwrap();73                assert_eq!((back.sample_rate, back.channels.len(), back.frames()), (rate, channels, 5_003), "{format:?} {samples:?}");74                assert_eq!((info.format, info.bits, info.float), (format, samples.bits(), samples.is_float()));75                let err = audio.channels.iter().zip(&back.channels).flat_map(|(a, b)| a.iter().zip(b).map(|(x, y)| (x - y).abs())).fold(0.0f32, f32::max);76                assert!(err <= tolerance(samples), "{format:?} {samples:?} at {rate} Hz: error {err}");77            }78        }79    }80}8182fn have(tool: &str) -> bool {83    Command::new(tool).arg("-version").output().map(|o| o.status.success()).unwrap_or(false)84        || Command::new("which").arg(tool).output().map(|o| o.status.success()).unwrap_or(false)85}8687/// Every file we write is decoded by ffmpeg (an independent implementation) to 32-bit float PCM88/// and compared with the source. Skipped, with a message, when ffmpeg is not installed.89#[test]90fn ffmpeg_decodes_our_files_to_the_same_samples() {91    if !have("ffmpeg") {92        eprintln!("SKIPPED: ffmpeg is not installed; files were not checked by an independent decoder");93        return;94    }95    for (rate, channels) in [(48_000u32, 2usize), (44_100, 1), (96_000, 2)] {96        let audio = test_audio(rate, 30_011, channels);97        for (format, samples, ext) in ALL {98            let path = tmp(&format!("ff-{rate}-{channels}-{samples:?}.{ext}"));99            let mut spec = FileSpec::new(format, samples);100            spec.overwrite = true;101            write_audio_file(&path, &audio, &spec).unwrap();102            let out = Command::new("ffmpeg").args(["-v", "error", "-i"]).arg(&path).args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]).output().unwrap();103            assert!(out.status.success() && out.stderr.is_empty(), "ffmpeg rejected {}: {}", path.display(), String::from_utf8_lossy(&out.stderr));104            let decoded: Vec<f32> = out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();105            assert_eq!(decoded.len(), 30_011 * channels, "{format:?} {samples:?}: ffmpeg decoded a different length");106            let mut err = 0.0f32;107            for (i, v) in decoded.iter().enumerate() {108                err = err.max((v - audio.channels[i % channels][i / channels]).abs());109            }110            assert!(err <= tolerance(samples), "{format:?} {samples:?} {rate} Hz: ffmpeg differs by {err}");111            let probe =112                Command::new("ffprobe").args(["-v", "error", "-show_entries", "stream=sample_rate,channels", "-of", "csv=p=0"]).arg(&path).output().unwrap();113            assert_eq!(String::from_utf8_lossy(&probe.stdout).trim(), format!("{rate},{channels}"));114            std::fs::remove_file(&path).unwrap();115        }116    }117}118119/// Core Audio (afinfo) must accept the files too, and FLAC streams must pass `flac`-style120/// verification by ffmpeg's strict decoder (MD5 checked by our own decoder in the unit tests).121#[test]122fn core_audio_accepts_our_files() {123    if !have("afinfo") {124        eprintln!("SKIPPED: afinfo is not available");125        return;126    }127    let audio = test_audio(48_000, 9_600, 2);128    for (format, samples, ext) in ALL {129        let path = tmp(&format!("af-{samples:?}.{ext}"));130        let mut spec = FileSpec::new(format, samples);131        spec.overwrite = true;132        write_audio_file(&path, &audio, &spec).unwrap();133        let out = Command::new("afinfo").arg(&path).output().unwrap();134        let text = String::from_utf8_lossy(&out.stdout);135        assert!(out.status.success(), "afinfo rejected {format:?} {samples:?}");136        assert!(text.contains("2 ch") && text.contains("48000 Hz"), "{text}");137        assert!(138            text.contains("audio packets: 9600") || text.contains("9600 valid frames") || text.contains("estimated duration: 0.200"),139            "{format:?} {samples:?}: {text}"140        );141        std::fs::remove_file(&path).unwrap();142    }143}144145#[test]146fn we_read_files_written_by_other_encoders() {147    if !have("ffmpeg") {148        eprintln!("SKIPPED: ffmpeg is not installed");149        return;150    }151    let audio = test_audio(44_100, 22_050, 2);152    let src = tmp("src.wav");153    let mut spec = FileSpec::new(FileFormat::Wav, SampleFormat::Float32);154    spec.overwrite = true;155    write_audio_file(&src, &audio, &spec).unwrap();156    // ffmpeg's FLAC uses LPC subframes and several stereo modes; its AIFF is big-endian PCM; `sowt` is little-endian AIFF-C.157    for (name, args, tol) in [158        ("x16.flac", vec!["-c:a", "flac", "-sample_fmt", "s16"], 0.5 / 32_768.0 + 1e-6),159        ("x24.flac", vec!["-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24", "-compression_level", "8"], 0.5 / 8_388_608.0 + 1e-6),160        ("x.aiff", vec!["-c:a", "pcm_s24be"], 0.5 / 8_388_608.0 + 1e-6),161        ("y.aifc", vec!["-c:a", "pcm_s16le", "-f", "aiff"], 0.5 / 32_768.0 + 1e-6),162        ("u8.wav", vec!["-c:a", "pcm_u8"], 1.0 / 128.0),163        ("x32.wav", vec!["-c:a", "pcm_s32le"], 1e-6),164        ("f64.wav", vec!["-c:a", "pcm_f64le"], 0.0),165    ] {166        let path = tmp(name);167        let out = Command::new("ffmpeg").args(["-v", "error", "-y", "-i"]).arg(&src).args(&args).arg(&path).output().unwrap();168        assert!(out.status.success(), "ffmpeg could not write {name}: {}", String::from_utf8_lossy(&out.stderr));169        let (back, _) = read_audio_file(&path, &ReadLimits::default()).unwrap_or_else(|e| panic!("{name}: {e}"));170        assert_eq!((back.sample_rate, back.channels.len(), back.frames()), (44_100, 2, 22_050), "{name}");171        let err = audio.channels.iter().zip(&back.channels).flat_map(|(a, b)| a.iter().zip(b).map(|(x, y)| (x - y).abs())).fold(0.0f32, f32::max);172        assert!(err <= tol, "{name}: error {err}");173        std::fs::remove_file(&path).unwrap();174    }175    std::fs::remove_file(&src).unwrap();176}177178#[test]179fn integer_conversion_clips_reports_and_scrubs() {180    let audio = AudioData { sample_rate: 48_000, channels: vec![vec![0.0, 1.0, -1.0, 1.5, -2.0, f32::NAN, 0.5, 32_767.0 / 32_768.0]] };181    let (pcm, clipped, bad) = to_pcm(&audio, 16, Dither::None, 0);182    assert_eq!(pcm[0], vec![0, 32_767, -32_768, 32_767, -32_768, 0, 16_384, 32_767]);183    assert_eq!((clipped, bad), (3, 1));184    let (_, report) = encode_audio(&audio, &FileSpec::new(FileFormat::Wav, SampleFormat::Float32)).unwrap();185    assert_eq!((report.clipped_samples, report.non_finite_samples), (0, 1));186    // Float files keep values beyond full scale.187    let (bytes, _) = encode_audio(&audio, &FileSpec::new(FileFormat::Wav, SampleFormat::Float32)).unwrap();188    assert_eq!(decode_audio(&bytes, &ReadLimits::default()).unwrap().0.channels[0][4], -2.0);189}190191#[test]192fn tpdf_dither_statistics_and_determinism() {193    // A constant a quarter LSB above zero: without dither it rounds to 0 and the information is194    // lost; with TPDF dither the mean of the quantised signal recovers it.195    let n = 400_000;196    let level = 0.25 / 32_768.0;197    let audio = AudioData { sample_rate: 48_000, channels: vec![vec![level; n]] };198    let (plain, _, _) = to_pcm(&audio, 16, Dither::None, 1);199    assert!(plain[0].iter().all(|v| *v == 0));200    let (d, _, _) = to_pcm(&audio, 16, Dither::Tpdf, 1);201    let mean = d[0].iter().map(|v| *v as f64).sum::<f64>() / n as f64;202    let var = d[0].iter().map(|v| (*v as f64 - mean).powi(2)).sum::<f64>() / n as f64;203    assert!((mean - 0.25).abs() < 0.005, "dithered mean {mean} LSB, expected 0.25");204    // TPDF makes the total error variance independent of the signal: 1/4 LSB^2 (dither 1/6 + quantiser 1/12).205    assert!((var + (mean - 0.25).powi(2) - 0.25).abs() < 0.01, "variance {var}");206    assert!(d[0].iter().all(|v| (-1..=2).contains(v)));207    // Same seed, same file; another seed, another noise; channels are decorrelated.208    assert_eq!(to_pcm(&audio, 16, Dither::Tpdf, 1).0, d);209    assert_ne!(to_pcm(&audio, 16, Dither::Tpdf, 2).0, d);210    let two = AudioData { sample_rate: 48_000, channels: vec![vec![level; 1000], vec![level; 1000]] };211    let (p, _, _) = to_pcm(&two, 16, Dither::Tpdf, 1);212    assert_ne!(p[0], p[1]);213    // Dither is ignored for float output.214    let mut spec = FileSpec::new(FileFormat::Wav, SampleFormat::Float32);215    let a = encode_audio(&audio, &spec).unwrap().0;216    spec.dither = Dither::Tpdf;217    assert_eq!(encode_audio(&audio, &spec).unwrap().0, a);218}219220#[test]221fn writing_is_atomic_and_never_overwrites_silently() {222    let audio = test_audio(48_000, 100, 2);223    // Its own directory: other tests write (and briefly keep temporary files) in the shared one.224    let dir = tmp("atomic-dir");225    let _ = std::fs::remove_dir_all(&dir);226    std::fs::create_dir_all(&dir).unwrap();227    let path = dir.join("atomic.wav");228    let spec = FileSpec::new(FileFormat::Wav, SampleFormat::Pcm16);229    write_audio_file(&path, &audio, &spec).unwrap();230    let first = std::fs::read(&path).unwrap();231    let err = write_audio_file(&path, &test_audio(48_000, 200, 2), &spec).unwrap_err();232    assert!(err.contains("already exists"), "{err}");233    assert_eq!(std::fs::read(&path).unwrap(), first, "a refused write must leave the file untouched");234    let mut over = spec;235    over.overwrite = true;236    write_audio_file(&path, &test_audio(48_000, 200, 2), &over).unwrap();237    assert_ne!(std::fs::read(&path).unwrap().len(), first.len());238    // No temporary file is left behind, on success or on failure.239    let leftovers =240        |dir: &std::path::Path| std::fs::read_dir(dir).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().ends_with(".tmp")).count();241    assert_eq!(leftovers(path.parent().unwrap()), 0);242    assert!(write_audio_file(&tmp("missing-dir/x.wav"), &audio, &spec).is_err());243    assert!(write_audio_file(path.parent().unwrap(), &audio, &over).is_err());244    assert_eq!(leftovers(path.parent().unwrap()), 0);245    assert!(encode_audio(&audio, &FileSpec::new(FileFormat::Flac, SampleFormat::Float32)).is_err());246    assert_eq!(FileFormat::from_extension(std::path::Path::new("a/b.AIF")), Some(FileFormat::Aiff));247    assert_eq!(FileFormat::from_extension(std::path::Path::new("a/b.mp3")), None);248    std::fs::remove_dir_all(&dir).unwrap();249}250251#[test]252fn malformed_and_oversized_files_are_rejected_without_panicking() {253    let audio = test_audio(48_000, 2_000, 2);254    let limits = ReadLimits::default();255    for (format, samples, _) in ALL {256        let (bytes, _) = encode_audio(&audio, &FileSpec::new(format, samples)).unwrap();257        // Truncations at every position of the header region and a sample of the body.258        for cut in (0..bytes.len().min(120)).chain((120..bytes.len()).step_by(997)) {259            let _ = decode_audio(&bytes[..cut], &limits);260        }261        // Bit flips anywhere must not panic (they may or may not be detected, except in FLAC where CRCs catch them).262        let mut s = 9u64;263        for _ in 0..300 {264            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);265            let mut bad = bytes.clone();266            let at = (s >> 33) as usize % bad.len();267            bad[at] ^= 1 << ((s >> 20) & 7);268            if let Ok((a, _)) = decode_audio(&bad, &limits) {269                assert!(a.channels.iter().all(|c| c.iter().all(|v| v.is_finite())));270            }271        }272        let small = ReadLimits { max_frames: 100, ..limits };273        assert!(decode_audio(&bytes, &small).unwrap_err().contains("limit"), "{format:?}");274        let tiny = ReadLimits { max_file_bytes: 64, ..limits };275        assert!(decode_audio(&bytes, &tiny).is_err());276        let mono_only = ReadLimits { max_channels: 1, ..limits };277        assert!(decode_audio(&bytes, &mono_only).is_err());278    }279    assert!(decode_audio(b"", &limits).is_err());280    assert!(decode_audio(b"RIFF\0\0\0\0WAVE", &limits).unwrap_err().contains("no data chunk"));281    assert!(decode_audio(b"RF64\0\0\0\0WAVE", &limits).unwrap_err().contains("RF64"));282    assert!(decode_audio(b"ID3\x03 not audio at all", &limits).unwrap_err().contains("unrecognised"));283    assert!(read_audio_file(&tmp("does-not-exist.wav"), &limits).is_err());284    assert!(read_audio_file(&std::env::temp_dir(), &limits).unwrap_err().contains("not a regular file"));285}286
Files main
Menu

Theme