Media: footage audio at another sample rate no longer stutters (#274)

AAC audio in an MP4/MOV whose sample rate differs from the mix rate
(a 44.1 kHz clip in the 48 kHz preview or export, or the reverse)
stuttered and sounded low-pitched in previews and in exported movies.

Cause: FilmCraft's MP4 reader, asked for audio at a rate other than
the file's, applied the edit list's priming offset (1024 samples for
AAC) twice when it resampled: each read started about 1024 source
samples early and extrapolated a ramp over its first ~940 samples
(peaks near 100 against a 0.5 tone). Export and the preview mix ask
for audio a frame or a device buffer at a time, so the ramp repeated
dozens of times a second. Same-rate reads take FilmCraft's copy path
and were exact. FilmCraft fixed this upstream in 5bf2203, 87 commits
past the pinned revision.

Fix: MediaPool reads footage audio at the source's own rate and
resamples it itself (linear, by absolute sample position, so a range
comes out the same however it is split into reads), for every
container.

Test: resampled_audio_read_in_frame_pieces_matches_ffmpeg (44.1 kHz
AAC read at 48 kHz and 48 kHz at 44.1 kHz in 29.97 fps frame pieces,
against ffmpeg's decode: max error 44 before, 0.002 after) and
movies_carry_resampled_footage_audio (a 29.97 fps comp with 44.1 kHz
AAC footage exported to MP4/AAC and MOV/PCM, decoded by ffmpeg: max
error 8.7 before, 0.03 / 0.002 after).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatastic
2026-10-08 22:16:35 +07:00
co-authored by Claude Opus 5.5
parent 929a9c0f01
commit ec892ef145
3 changed files with 170 additions and 23 deletions
+60 -3
View File
@@ -53,6 +53,11 @@ fn settings() -> RenderSettings {
}
fn run(p: &Project, cid: ItemId, footage: &dyn FootageSource, om: &OutputModule, path: &Path) -> effectcraft_export::Report {
run_frames(p, cid, footage, om, path, FRAMES)
}
/// [`run`] for a comp of `frames` frames.
fn run_frames(p: &Project, cid: ItemId, footage: &dyn FootageSource, om: &OutputModule, path: &Path, frames: u64) -> effectcraft_export::Report {
let s = settings();
let path = path.to_string_lossy().to_string();
let job = Job {
@@ -77,10 +82,10 @@ fn run(p: &Project, cid: ItemId, footage: &dyn FootageSource, om: &OutputModule,
true
})
.expect("export");
assert_eq!(last.done, FRAMES);
assert_eq!(last.total, FRAMES);
assert_eq!(last.done, frames);
assert_eq!(last.total, frames);
assert!(calls >= 2);
assert_eq!(r.frames, FRAMES);
assert_eq!(r.frames, frames);
r
}
@@ -400,6 +405,58 @@ fn movies_carry_audio() {
}
}
/// `src`'s audio decoded by ffmpeg as interleaved stereo `f32` at 48 kHz (external oracle).
fn ffmpeg_audio(src: &Path) -> Vec<f32> {
let out = Command::new("ffmpeg")
.args(["-hide_banner", "-loglevel", "error", "-i"])
.arg(src)
.args(["-f", "f32le", "-ac", "2", "-ar", "48000", "-"])
.output()
.expect("ffmpeg");
assert!(out.status.success(), "ffmpeg failed to decode {}", src.display());
out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect()
}
/// Movies of a 29.97 fps comp whose footage has AAC audio at 44.1 kHz sound like the footage
/// (both decoded by ffmpeg): reading footage audio at another rate ramped from a wrong position
/// at the start of every batch of frames, so exports stuttered (#274).
#[test]
fn movies_carry_resampled_footage_audio() {
let d = out_dir("audio-44k");
let clip = d.join("clip.mp4");
let made = Command::new("ffmpeg")
.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=64x48:rate=30000/1001:duration=3", "-f", "lavfi", "-i"])
.args(["aevalsrc=0.5*sin(2*PI*440*t)|0.5*sin(2*PI*(200+400*t/3)*t):s=44100:d=3", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest"])
.arg(&clip)
.status()
.is_ok_and(|s| s.success());
if !made {
eprintln!("ffmpeg not found: skipping");
return;
}
let fps = FrameRate::new(30000, 1001);
let mut p = Project::default();
let mut comp = Comp::new(W, H, fps, fps.tick_of(60));
let fid = p.add_item("clip.mp4", Label::SeaFoam, None, ItemKind::Footage(effectcraft_media::probe(&clip).expect("probe clip")));
let l = build::layer(&mut p, &comp, "clip", LayerSource::Footage { item: fid }, (64, 48), None);
comp.layers.push(l);
let cid = p.add_item("Comp 1", Label::Sandstone, None, ItemKind::Comp(comp.into()));
let want = ffmpeg_audio(&clip);
let pool = MediaPool::new();
// AAC is lossy; PCM differs from ffmpeg's resampler by little more than 16-bit rounding.
for (fmt, name, tol) in [(OutputFormat::H264, "a.mp4", 0.06), (OutputFormat::ProRes, "a.mov", 0.01)] {
let path = d.join(name);
assert!(run_frames(&p, cid, &pool, &OutputModule::for_format(fmt), &path, 60).audio);
let got = ffmpeg_audio(&path);
// 60 frames at 29.97 fps: 96 096 samples at 48 kHz.
assert!((got.len() as i64 / 2 - 96_096).abs() < 1024, "{name}: {} samples", got.len() / 2);
// (Up to the last AAC frames, where the cut to silence smears back into the sound.)
let worst = got.iter().zip(&want).take(94_000 * 2).map(|(g, w)| (g - w).abs()).fold(0.0f32, f32::max);
eprintln!("{name}: max error {worst:.4}");
assert!(worst < tol, "{name}: max error {worst} against the footage");
}
}
#[test]
fn webm_vp9_opus_roundtrip() {
let d = out_dir("webm");