Audio: a FLAC opens once and off the UI thread; conforming is bounded (#408)
The freeze and quit during a FLAC preview did not reproduce on current main (Windows 11): a 4-minute stereo and a 10-minute 24-bit 6-channel 96 kHz FLAC played through a RAM preview with a real-time audio pull, after trimming and zooming, with no stall, no growing queue and memory bounded by the RAM preview budget; 150 cpal output start/stop cycles ran clean. Three defects in that path were found and fixed: - FilmCraft decodes FLAC, MP3, Ogg and AIFF files whole when they are opened (8 s and 1.4 GB for the 10-minute 6-channel file). MediaPool opened a file outside its lock, so every caller asking before the first open finished decoded the whole file too: a preview's frame workers, audio feeder, conform and waveform threads at once (8 reads at once: 8 decodes). Each path now opens once; the others wait for it. - AudioPlayback::start mixed its first 50 ms on the calling (UI) thread, so the first read of such a file froze the UI for the whole decode (audio-only previews start the sound right away). All mixing is on the feeder thread now; the device plays silence until the first block arrives, and the clock (frames actually played) waits for it. - Conforming (Settings > Disk > Conformed Audio Folder, on by default) held the whole conformed track in memory before writing it, sized by the footage duration from the file's header: a header claiming a month of audio aborted the app on a failed 995 GB allocation. The conformed file is now written a chunk at a time, and footage longer than 24 hours is read from its decoder instead of conformed. Tests: media concurrent_first_reads_open_a_file_once (8 threads: 8 opens before, 1 now; PoolStats::opened), pool a_header_claiming_a_month_of_audio_is_not_conformed (aborted before), ui-egui audio starting_audio_does_not_wait_for_slow_footage (start took the footage's 2 s before), conformed_flac_audio_reads_back_like_the_ decoder, and the robustness test flac_audio_of_any_shape_reads_in_ device_blocks (2 minutes of 24-bit 6-channel 96 kHz, mono 8 kHz, 11.025 kHz, 192 kHz and 8-channel FLAC read in 1024-frame blocks at 48 kHz through and past the end: level, silence after the end, opened once). FLAC fixtures come from ffmpeg (skipped without it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
98a6a3a041
commit
09a5dc357a
@@ -545,3 +545,109 @@ fn exr_still_is_linear_float() {
|
||||
let b = img.data[1];
|
||||
assert!(b[3] == 0.5 && b[0] > 0.85 && b[0] < 1.0, "{b:?}");
|
||||
}
|
||||
|
||||
/// A FLAC of `secs` seconds at `rate` Hz with `channels` channels of a 440 Hz sine (first two:
|
||||
/// −24 dBFS RMS, the rest quieter), samples of `fmt` (`s16`, or `s32` with 24 significant bits).
|
||||
fn sine_flac(secs: u32, rate: u32, channels: u32, fmt: &str) -> Option<PathBuf> {
|
||||
let name = format!("sine_{secs}s_{rate}_{channels}ch_{fmt}.flac");
|
||||
let src = format!("sine=frequency=440:sample_rate={rate}:duration={secs}");
|
||||
let pan = format!("pan={channels}c|{}", (0..channels).map(|c| format!("c{c}={}*c0", if c < 2 { "1" } else { "0.5" })).collect::<Vec<_>>().join("|"));
|
||||
let mut args = vec!["-f", "lavfi", "-i", &src, "-af", &pan, "-sample_fmt", fmt];
|
||||
if fmt == "s32" {
|
||||
args.extend(["-bits_per_raw_sample", "24"]);
|
||||
}
|
||||
args.extend(["-c:a", "flac"]);
|
||||
ffmpeg_fixture(&name, &args)
|
||||
}
|
||||
|
||||
/// #408 robustness: FLAC footage of any rate, depth and channel count reads correctly as the
|
||||
/// preview feeder reads it, one device block at a time at the mix rate, through its end and past
|
||||
/// it: two minutes of 24-bit, 6-channel, 96 kHz audio, and mono 8 kHz, 11.025 kHz, 192 kHz and
|
||||
/// 8-channel files.
|
||||
#[test]
|
||||
fn flac_audio_of_any_shape_reads_in_device_blocks() {
|
||||
for (secs, rate, channels, fmt) in [(120, 96_000, 6, "s32"), (5, 8_000, 1, "s16"), (5, 11_025, 2, "s16"), (5, 192_000, 2, "s32"), (5, 48_000, 8, "s16")] {
|
||||
let Some(p) = sine_flac(secs, rate, channels, fmt) else { return };
|
||||
let f = probe(&p).expect("probe");
|
||||
assert!(f.has_audio && f.kind == FootageKind::Audio, "{}", p.display());
|
||||
assert!((f.duration.seconds() - f64::from(secs)).abs() < 0.01, "{}: {}", p.display(), f.duration.seconds());
|
||||
let pool = MediaPool::new();
|
||||
let mix = 48_000i64;
|
||||
let total = f.duration.to_units_floor(mix);
|
||||
let (mut at, mut sum, mut n, mut worst) = (0i64, 0.0f64, 0usize, std::time::Duration::ZERO);
|
||||
let t0 = Instant::now();
|
||||
while at < total + 4096 {
|
||||
let t = Instant::now();
|
||||
let s = pool.audio_samples(&f, Tick::from_units(at, mix), 1024, 48_000);
|
||||
if at > 0 {
|
||||
worst = worst.max(t.elapsed());
|
||||
}
|
||||
assert_eq!(s.len(), 2048);
|
||||
assert!(s.iter().all(|v| v.is_finite() && v.abs() <= 1.0), "{} at {at}", p.display());
|
||||
if at + 1024 <= total {
|
||||
sum += s.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>();
|
||||
n += s.len();
|
||||
} else if at >= total {
|
||||
assert!(s.iter().all(|v| *v == 0.0), "{}: silence past the end", p.display());
|
||||
}
|
||||
at += 1024;
|
||||
}
|
||||
// ffmpeg's sine source has an amplitude of 1/8, on both channels (mono is duplicated).
|
||||
let rms = (sum / n.max(1) as f64).sqrt();
|
||||
assert!((rms - 0.125 / 2f64.sqrt()).abs() < 0.003, "{}: rms {rms}", p.display());
|
||||
eprintln!("{}: read {secs} s in {:?}, slowest block after the first {worst:?}", p.display(), t0.elapsed());
|
||||
assert_eq!(pool.stats().opened, 1, "opened once, not per block");
|
||||
}
|
||||
}
|
||||
|
||||
/// #408: the first reads of a FLAC from many threads at once (a preview's frame workers, audio
|
||||
/// feeder, conform and waveform threads) decode it once: each decoded the whole file, so memory
|
||||
/// and time grew with the number of threads.
|
||||
#[test]
|
||||
fn concurrent_first_reads_open_a_file_once() {
|
||||
let Some(p) = sine_flac(60, 44_100, 2, "s16") else { return };
|
||||
let f = probe(&p).expect("probe");
|
||||
let pool = MediaPool::new();
|
||||
let start = Arc::new(std::sync::Barrier::new(8));
|
||||
let reads: Vec<_> = (0..8)
|
||||
.map(|_| {
|
||||
let (pool, f, start) = (pool.clone(), f.clone(), start.clone());
|
||||
std::thread::spawn(move || {
|
||||
start.wait();
|
||||
pool.audio_samples(&f, Tick(TICKS_PER_SECOND), 1024, 48_000)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let reads: Vec<Vec<f32>> = reads.into_iter().map(|t| t.join().expect("read")).collect();
|
||||
assert_eq!(pool.stats().opened, 1, "the file was opened once");
|
||||
assert!(reads.iter().all(|r| *r == reads[0]) && reads[0].iter().any(|v| *v != 0.0));
|
||||
}
|
||||
|
||||
/// Settings ▸ Disk ▸ Conformed Audio Folder: a FLAC's conformed file, written a chunk at a time,
|
||||
/// reads back exactly as the decoder reads.
|
||||
#[test]
|
||||
fn conformed_flac_audio_reads_back_like_the_decoder() {
|
||||
let Some(p) = sine_flac(5, 44_100, 2, "s16") else { return };
|
||||
let f = probe(&p).expect("probe");
|
||||
let folder = fixtures().join(format!("conformed-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
let pool = MediaPool::new();
|
||||
let at = Tick::from_seconds_f64(2.5);
|
||||
let decoded = pool.audio_samples(&f, at, 4800, 48_000);
|
||||
pool.set_conform_folder(Some(folder.clone()));
|
||||
let file = pool.conformed_path(&p.to_string_lossy(), 48_000).expect("a conformed path");
|
||||
pool.audio_samples(&f, at, 4800, 48_000);
|
||||
let t0 = Instant::now();
|
||||
while !file.exists() {
|
||||
assert!(t0.elapsed().as_secs() < 60, "the conformed file was never written");
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
// (Renamed into place once complete.) Raw interleaved stereo f32 at 48 kHz.
|
||||
let bytes = std::fs::read(&file).expect("conformed file");
|
||||
assert_eq!(bytes.len(), 5 * 48_000 * 8);
|
||||
let s0 = at.to_units_floor(48_000) as usize * 8;
|
||||
let conformed: Vec<f32> = bytes[s0..s0 + 4800 * 8].as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
|
||||
assert_eq!(conformed, decoded);
|
||||
assert_eq!(pool.audio_samples(&f, at, 4800, 48_000), decoded);
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user