Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

#236: audio in MKV and OBS-remuxed MP4 plays without crackling

ippsecd51945c80792
diff --git a/crates/codecs/src/audio.rs b/crates/codecs/src/audio.rs
index 4942f6a6c..3287cc06e 100644
--- a/crates/codecs/src/audio.rs
+++ b/crates/codecs/src/audio.rs
@@ -87,7 +87,7 @@ impl PacketDecoder {
/// (HE-AAC, see [`aac_output_rate`]) the decoded core is upsampled to it.
pub fn aac(asc: &[u8], sample_rate: u32) -> Result<Self> {
if let Ok(dec) = filmcraft_aac::Decoder::new(asc) {
- let up = (dec.sample_rate().checked_mul(2) == Some(sample_rate)).then(|| Box::new(Upsample2x::new(dec.channels())));
+ let up = upsamples_core(dec.sample_rate(), sample_rate).then(|| Box::new(Upsample2x::new(dec.channels())));
return Ok(Self { inner: Inner::Aac { dec: Box::new(dec), asc: asc.to_vec(), up }, channels: 0 });
}
Self::new(CODEC_TYPE_AAC, sample_rate, Some(asc.to_vec()))
@@ -244,6 +244,77 @@ pub fn aac_output_rate<'a>(asc: &[u8], first_units: impl IntoIterator<Item = &'a
Some(core)
}
+/// Whether [`PacketDecoder::aac`] upsamples a decoded AAC core at `core` Hz to `rate` (HE-AAC).
+fn upsamples_core(core: u32, rate: u32) -> bool {
+ core.checked_mul(2) == Some(rate)
+}
+
+/// A codec whose packets all decode to the same number of samples (see [`fixed_packet_samples`]).
+#[derive(Clone, Copy, Debug)]
+pub enum FixedFrames<'a> {
+ /// AAC with this AudioSpecificConfig.
+ Aac(&'a [u8]),
+ /// MPEG-1/2 audio, layer I, II or III.
+ MpegAudio,
+ /// AC-3 (and E-AC-3).
+ Ac3,
+}
+
+/// Samples each packet decodes to at the stream's output `rate`, for codecs where that is the same
+/// for every packet: AAC 1024 (2048 when [`PacketDecoder::aac`] upsamples an HE-AAC core); MPEG
+/// audio and AC-3 from the frame header of `first`, the stream's first packet. `None` when it is
+/// not known: an AAC configuration our decoder does not read, a header that does not parse, or a
+/// header whose rate is not `rate`.
+pub fn fixed_packet_samples(codec: FixedFrames, first: &[u8], rate: u32) -> Option<i64> {
+ let mpegts = match codec {
+ FixedFrames::Aac(asc) => {
+ let core = filmcraft_aac::Decoder::new(asc).ok()?.sample_rate();
+ return Some(if upsamples_core(core, rate) { 2048 } else { 1024 });
+ }
+ FixedFrames::MpegAudio => filmcraft_mpegts::Codec::MpegAudio,
+ FixedFrames::Ac3 => filmcraft_mpegts::Codec::Ac3,
+ };
+ let f = filmcraft_mpegts::frame_info(&mpegts, first)?;
+ (f.sample_rate == rate && f.samples > 0).then_some(f.samples as i64)
+}
+
+/// Where the container puts one audio packet, for [`contiguous_starts`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct PacketTime {
+ /// Its timestamp, in output samples.
+ pub stamp: i64,
+ /// Whether `stamp` is the packet's own. A Matroska frame after the first in a laced block
+ /// without a duration repeats the block's timestamp.
+ pub stamped: bool,
+ /// Samples it decodes to, when known.
+ pub samples: Option<i64>,
+}
+
+/// Packet start positions in output samples: each packet starts where the previous one ends,
+/// unless its own timestamp is more than `tolerance` samples from there (a real gap or overlap in
+/// the recording) or the previous packet's length is unknown; then it starts at its timestamp.
+///
+/// Container timestamps are coarser than a sample. Matroska stores milliseconds, and a remux to MP4
+/// (OBS's) turns that rounding into uneven sample durations: a 1024-sample AAC frame at 48 kHz lasts
+/// 21.33 ms, so frames are stamped at 0, 1008, 2064, 3072… Placing each decoded packet at its
+/// stamp overwrote the end of one packet and left a hole of silence after another, a click every
+/// few packets: crackling throughout playback and export (#236).
+pub fn contiguous_starts(packets: impl IntoIterator<Item = PacketTime>, tolerance: i64) -> Vec<i64> {
+ let tolerance = tolerance.max(0).unsigned_abs();
+ let mut next: Option<i64> = None;
+ packets
+ .into_iter()
+ .map(|p| {
+ let start = match next {
+ Some(n) if !p.stamped || n.abs_diff(p.stamp) <= tolerance => n,
+ _ => p.stamp,
+ };
+ next = p.samples.and_then(|k| start.checked_add(k));
+ start
+ })
+ .collect()
+}
+
/// Taps on each side of the interpolation point in [`Upsample2x`].
const UPSAMPLE_HALF: usize = 12;
@@ -739,3 +810,82 @@ mod he_aac_tests {
}
}
}
+
+#[cfg(test)]
+mod packet_time_tests {
+ use super::*;
+
+ /// 1024-sample frames at 48 kHz stamped to the nearest millisecond, then back in samples.
+ fn ms_stamps(count: i64) -> Vec<i64> {
+ (0..count).map(|k| (k * 1024 * 1000 + 24_000) / 48_000 * 48).collect()
+ }
+
+ fn timed(stamps: &[i64], samples: Option<i64>) -> Vec<PacketTime> {
+ stamps.iter().map(|&stamp| PacketTime { stamp, stamped: true, samples }).collect()
+ }
+
+ #[test]
+ fn rounded_stamps_give_back_to_back_packets() {
+ let stamps = ms_stamps(200);
+ assert_eq!(&stamps[..4], [0, 1008, 2064, 3072]);
+ let starts = contiguous_starts(timed(&stamps, Some(1024)), 512);
+ assert_eq!(starts, (0..200).map(|k| k * 1024).collect::<Vec<_>>());
+ }
+
+ #[test]
+ fn real_gaps_and_overlaps_resynchronise() {
+ // a 100 ms gap after packet 3, then a packet stamped 600 samples early
+ let mut stamps: Vec<i64> = (0..8).map(|k| k * 1024).collect();
+ for s in &mut stamps[4..] {
+ *s += 4800;
+ }
+ stamps[7] -= 600;
+ let starts = contiguous_starts(timed(&stamps, Some(1024)), 512);
+ assert_eq!(starts, [0, 1024, 2048, 3072, 8896, 9920, 10944, 11368]);
+ // within the tolerance: runs on
+ stamps[7] += 200;
+ assert_eq!(contiguous_starts(timed(&stamps, Some(1024)), 512)[7], 11968);
+ }
+
+ #[test]
+ fn unstamped_packets_follow_on_and_unknown_lengths_resynchronise() {
+ // a laced block of three frames that repeat its timestamp
+ let packets = [0, 1024, 1024, 1024, 4096].map(|stamp| PacketTime { stamp, stamped: true, samples: Some(1024) });
+ let mut laced = packets;
+ laced[2].stamped = false;
+ laced[3].stamped = false;
+ assert_eq!(contiguous_starts(laced, 512), [0, 1024, 2048, 3072, 4096]);
+ // a packet whose length is unknown: the next one starts at its own stamp
+ let mut unknown = timed(&[0, 1024, 2100, 3124], Some(1024));
+ unknown[1].samples = None;
+ assert_eq!(contiguous_starts(unknown, 512), [0, 1024, 2100, 3124]);
+ }
+
+ #[test]
+ fn hostile_values_stay_finite() {
+ let packets = [
+ PacketTime { stamp: i64::MAX, stamped: true, samples: Some(i64::MAX) },
+ PacketTime { stamp: i64::MIN, stamped: false, samples: Some(-5) },
+ PacketTime { stamp: 0, stamped: true, samples: Some(i64::MIN) },
+ PacketTime { stamp: 7, stamped: true, samples: None },
+ ];
+ assert_eq!(contiguous_starts(packets, i64::MIN).len(), 4);
+ assert_eq!(contiguous_starts(packets, i64::MAX).len(), 4);
+ assert!(contiguous_starts([], 512).is_empty());
+ }
+
+ #[test]
+ fn fixed_frame_lengths() {
+ // AAC-LC 48 kHz stereo; HE-AAC (24 kHz core) played at 48 kHz is upsampled
+ assert_eq!(fixed_packet_samples(FixedFrames::Aac(&[0x11, 0x90]), &[], 48_000), Some(1024));
+ assert_eq!(fixed_packet_samples(FixedFrames::Aac(&[0x13, 0x10]), &[], 48_000), Some(2048));
+ assert_eq!(fixed_packet_samples(FixedFrames::Aac(&[]), &[], 48_000), None);
+ // MPEG-1 layer III 44.1 kHz, 128 kbps; MPEG-2 layer III 22.05 kHz
+ assert_eq!(fixed_packet_samples(FixedFrames::MpegAudio, &[0xFF, 0xFB, 0x90, 0x44], 44_100), Some(1152));
+ assert_eq!(fixed_packet_samples(FixedFrames::MpegAudio, &[0xFF, 0xF3, 0x90, 0x44], 22_050), Some(576));
+ // the header's rate must be the stream's
+ assert_eq!(fixed_packet_samples(FixedFrames::MpegAudio, &[0xFF, 0xFB, 0x90, 0x44], 48_000), None);
+ assert_eq!(fixed_packet_samples(FixedFrames::MpegAudio, &[0xFF], 44_100), None);
+ assert_eq!(fixed_packet_samples(FixedFrames::Ac3, &[0x0B, 0x77], 48_000), None);
+ }
+}
diff --git a/crates/codecs/src/audio_timing_tests.rs b/crates/codecs/src/audio_timing_tests.rs
new file mode 100644
index 000000000..40e43a2d8
--- /dev/null
+++ b/crates/codecs/src/audio_timing_tests.rs
@@ -0,0 +1,178 @@
+//! Audio packets placed by container timestamps (#236).
+//!
+//! An AAC access unit decodes to 1024 samples, 21.33 ms at 48 kHz. Matroska stores timestamps in
+//! whole milliseconds, and OBS's remux to MP4 carries that rounding into sample durations of 1008,
+//! 1008, 1056… Placing each decoded packet at its own timestamp overwrote the end of one packet and
+//! left a hole of silence after another: playback and export crackled throughout. The streams here
+//! are AAC from our own encoder muxed with such timestamps; read back block by block, as playback
+//! reads them, they must be exactly the access units decoded back to back.
+
+use std::io::Cursor;
+use std::sync::Arc;
+
+use filmcraft_isobmff::{Brand, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
+use filmcraft_matroska::{LacingMode, MkvWriter, MuxOptions, TrackKind, TrackSpec};
+use filmcraft_media::MediaSource;
+
+use crate::audio::PacketDecoder;
+use crate::{MkvSource, Mp4Source};
+
+/// A second of a stereo tone (440 Hz left, 660 Hz right) encoded with our AAC encoder: the
+/// AudioSpecificConfig and the access units.
+fn aac(rate: u32) -> (Vec<u8>, Vec<Vec<u8>>) {
+ let tone = |hz: f32| (0..rate as usize).map(|i| 0.5 * (std::f32::consts::TAU * hz * i as f32 / rate as f32).sin()).collect::<Vec<f32>>();
+ let (l, r) = (tone(440.0), tone(660.0));
+ let mut enc = filmcraft_aac::Encoder::new(filmcraft_aac::EncoderConfig::cbr(rate, 2, 160_000)).unwrap();
+ let mut units = enc.encode(&[&l, &r]);
+ units.extend(enc.flush());
+ (enc.audio_specific_config(), units)
+}
+
+/// The access units decoded back to back.
+fn continuous(asc: &[u8], rate: u32, units: &[Vec<u8>]) -> Vec<Vec<f32>> {
+ let mut dec = PacketDecoder::aac(asc, rate).unwrap();
+ let mut out = vec![Vec::new(), Vec::new()];
+ for u in units {
+ for (o, c) in out.iter_mut().zip(dec.decode(u, 0).unwrap()) {
+ o.extend(c);
+ }
+ }
+ out
+}
+
+/// Access unit `k`'s start to the nearest millisecond, as muxers stamp it.
+fn stamp_ms(rate: u32, k: usize) -> i64 {
+ (k as i64 * 1024 * 2000 + rate as i64) / (2 * rate as i64)
+}
+
+/// Matroska (1 ms timestamps), with the units after `gap` delayed by `gap_ms` (a real gap).
+fn mkv(asc: &[u8], rate: u32, units: &[Vec<u8>], lacing: LacingMode, gap: usize, gap_ms: i64) -> Arc<[u8]> {
+ let mut spec = TrackSpec::new(TrackKind::Audio, "A_AAC");
+ spec.codec_private = asc.to_vec();
+ spec.audio = Some((rate as f64, 2, None));
+ let opts = MuxOptions { lacing, ..MuxOptions::default() };
+ assert_eq!(opts.timestamp_scale, 1_000_000, "1 ms timestamps");
+ let mut w = MkvWriter::new(Cursor::new(Vec::new()), vec![spec], opts).unwrap();
+ for (k, u) in units.iter().enumerate() {
+ let ms = stamp_ms(rate, k) + if k >= gap { gap_ms } else { 0 };
+ w.write_frame(0, ms * 1_000_000, true, u, None).unwrap();
+ }
+ w.finish().unwrap().into_inner().into()
+}
+
+/// MP4 as OBS remuxes Matroska: each millisecond timestamp rescaled to the sample rate, the
+/// differences written as sample durations.
+fn mp4_remuxed(asc: &[u8], rate: u32, units: &[Vec<u8>]) -> Arc<[u8]> {
+ let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
+ let t = w.add_track(TrackConfig::new(SampleEntry::aac(asc.to_vec(), 2, rate), rate)).unwrap();
+ let at = |k: usize| (stamp_ms(rate, k) * rate as i64 + 500) / 1000;
+ for (k, u) in units.iter().enumerate() {
+ let duration = (at(k + 1) - at(k)) as u32;
+ w.write_sample(t, WriteSample { data: u, duration, composition_offset: 0, is_sync: true }).unwrap();
+ }
+ w.finish().unwrap().into_inner().into()
+}
+
+/// `frames` samples per channel read in 512-sample blocks at `rate`, as playback reads them.
+fn played(src: &dyn MediaSource, rate: u32, frames: usize) -> Vec<Vec<f32>> {
+ let mut out = vec![Vec::new(), Vec::new()];
+ let mut pos = 0;
+ while pos < frames {
+ let n = 512.min(frames - pos);
+ let b = src.audio(pos as i64, n, rate).unwrap();
+ for (o, c) in out.iter_mut().zip(&b.channels) {
+ o.extend_from_slice(c);
+ }
+ pos += n;
+ }
+ out
+}
+
+/// Samples of `got` that differ from `want[k - shift]` (silence where that is out of range), and
+/// the first few.
+fn mismatches(got: &[Vec<f32>], want: &[Vec<f32>], shift: usize) -> (usize, Vec<(usize, usize)>) {
+ let mut bad = Vec::new();
+ for (c, (g, w)) in got.iter().zip(want).enumerate() {
+ for (k, x) in g.iter().enumerate() {
+ let expect = k.checked_sub(shift).and_then(|j| w.get(j)).copied().unwrap_or(0.0);
+ if x.to_bits() != expect.to_bits() {
+ bad.push((c, k));
+ }
+ }
+ }
+ (bad.len(), bad.into_iter().take(4).collect())
+}
+
+/// Runs of two or more exact zeros inside the signal: holes left between packets.
+fn holes(got: &[Vec<f32>]) -> usize {
+ got.iter().map(|c| c.windows(2).filter(|w| w[0] == 0.0 && w[1] == 0.0).count()).sum()
+}
+
+#[test]
+fn matroska_millisecond_stamps_play_back_to_back() {
+ for rate in [48_000, 44_100] {
+ let (asc, units) = aac(rate);
+ let want = continuous(&asc, rate, &units);
+ let frames = units.len().saturating_sub(1) * 1024;
+ for lacing in [LacingMode::None, LacingMode::Xiph] {
+ let bytes = mkv(&asc, rate, &units, lacing, usize::MAX, 0);
+ let src = MkvSource::open("tone.mkv", bytes.clone()).unwrap();
+ let got = played(&src, rate, frames);
+ let (n, first) = mismatches(&got, &want, 0);
+ assert_eq!(n, 0, "{rate} Hz, {lacing:?}: {n} samples differ from the continuous decode, first (channel, sample) {first:?}");
+ // random access (a fresh source, so a cold decoder primed with the packet before) gives
+ // the same samples
+ let src = MkvSource::open("tone.mkv", bytes).unwrap();
+ for start in [30_011usize, 7_000] {
+ let got = src.audio(start as i64, 4_800, rate).unwrap().channels;
+ let at: Vec<Vec<f32>> = want.iter().map(|c| c[start..start + 4_800].to_vec()).collect();
+ assert_eq!(mismatches(&got, &at, 0).0, 0, "{rate} Hz, {lacing:?}: seek to {start}");
+ }
+ }
+ }
+}
+
+#[test]
+fn obs_remuxed_mp4_plays_back_to_back() {
+ for rate in [48_000, 44_100] {
+ let (asc, units) = aac(rate);
+ let want = continuous(&asc, rate, &units);
+ let bytes = mp4_remuxed(&asc, rate, &units);
+ let src = Mp4Source::open("tone.mp4", bytes).unwrap();
+ let got = played(&src, rate, units.len().saturating_sub(1) * 1024);
+ let (n, first) = mismatches(&got, &want, 0);
+ assert_eq!(n, 0, "{rate} Hz: {n} samples differ from the continuous decode, first (channel, sample) {first:?}");
+ }
+}
+
+#[test]
+fn a_real_gap_stays_where_the_timestamps_put_it() {
+ let rate = 48_000;
+ let (asc, units) = aac(rate);
+ let want = continuous(&asc, rate, &units);
+ // 100 ms of the recording missing before unit 20: it plays as silence, and the units after it
+ // keep their timestamps (to the millisecond)
+ let src = MkvSource::open("gap.mkv", mkv(&asc, rate, &units, LacingMode::None, 20, 100)).unwrap();
+ let shift = ((stamp_ms(rate, 20) + 100) * 48 - 20 * 1024) as usize;
+ assert!((4_700..4_900).contains(&shift), "{shift}");
+ let got = played(&src, rate, units.len().saturating_sub(1) * 1024 + shift);
+ let before: Vec<Vec<f32>> = got.iter().map(|c| c[..20 * 1024].to_vec()).collect();
+ assert_eq!(mismatches(&before, &want, 0).0, 0);
+ assert!(got.iter().all(|c| c[20 * 1024..20 * 1024 + shift].iter().all(|x| *x == 0.0)), "the gap is silent");
+ let after: Vec<Vec<f32>> = got.iter().map(|c| c[20 * 1024 + shift..].to_vec()).collect();
+ let rest: Vec<Vec<f32>> = want.iter().map(|c| c[20 * 1024..].to_vec()).collect();
+ let (n, first) = mismatches(&after, &rest, 0);
+ assert_eq!(n, 0, "{n} samples after the gap differ, first {first:?}");
+}
+
+#[test]
+fn playing_at_another_rate_leaves_no_holes() {
+ // a 44.1 kHz recording in a 48 kHz sequence (export's default rate)
+ let (asc, units) = aac(44_100);
+ let src = MkvSource::open("tone.mkv", mkv(&asc, 44_100, &units, LacingMode::None, usize::MAX, 0)).unwrap();
+ let frames = (units.len().saturating_sub(2) * 1024) * 48_000 / 44_100;
+ let got = played(&src, 48_000, frames);
+ // skip the encoder's priming (the first frame decodes to near-silence)
+ let tail: Vec<Vec<f32>> = got.iter().map(|c| c[2048..].to_vec()).collect();
+ assert_eq!(holes(&tail), 0);
+}
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index a14f74d3d..fb405cd74 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -173,6 +173,8 @@ pub fn open_bytes(name: &str, bytes: Arc<[u8]>) -> std::result::Result<filmcraft
filmcraft_media::open_bytes(name, bytes, &openers())
}
+#[cfg(test)]
+mod audio_timing_tests;
#[cfg(test)]
mod rounded_pts_tests;
#[cfg(test)]
diff --git a/crates/codecs/src/mkv.rs b/crates/codecs/src/mkv.rs
index ee23eede1..e1fa14824 100644
--- a/crates/codecs/src/mkv.rs
+++ b/crates/codecs/src/mkv.rs
@@ -8,6 +8,9 @@
//! subtracts `CodecDelay` from timestamps, so the pre-skip samples land before zero and are never
//! read; random access decodes `SeekPreRoll` (at least [`crate::audio::OPUS_PRE_ROLL`]) of preceding
//! packets before the target. Packet starts are accumulated from TOC durations (see [`opus_starts`]).
+//!
+//! AAC, MPEG audio and AC-3 packets each decode to a fixed number of samples, which millisecond
+//! timestamps can't express: their packets run on from one another (see [`audio_starts`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@@ -51,35 +54,71 @@ pub struct MkvSource {
audio_preroll: i64,
}
+/// Audio packet start positions in source sample frames.
+///
+/// Block timestamps are quantised to `TimestampScale` (usually 1 ms), so they are only accurate to a
+/// tick: a 1024-sample AAC frame at 48 kHz lasts 21.33 ms. Packets that all decode to the same
+/// length (AAC, MPEG audio, AC-3) therefore run on from one another, resynchronising to the
+/// timestamp only across gaps of more than half a packet (and more than two ticks); see
+/// [`crate::audio::contiguous_starts`]. Opus packets: [`opus_starts`]. Other codecs start at their
+/// timestamps.
+fn audio_starts(file: &MkvFile, bytes: &crate::Src, ti: usize, rate: i64) -> Vec<i64> {
+ use crate::audio::{FixedFrames, PacketTime, contiguous_starts, fixed_packet_samples};
+ let Some(t) = file.tracks.get(ti) else { return Vec::new() };
+ if let Some(h) = opus_head(&t.codec) {
+ return opus_starts(file, bytes, ti, &h, rate);
+ }
+ let (n, d) = tb(t);
+ let at = |pts: i64| (pts as i128 * n as i128 * rate as i128 / d as i128) as i64;
+ let first = || file.read_sample(bytes, ti, 0).unwrap_or_default();
+ let out_rate = u32::try_from(rate).unwrap_or(0);
+ let frame = match &t.codec {
+ Codec::Aac { asc } => fixed_packet_samples(FixedFrames::Aac(asc), &[], out_rate),
+ Codec::Mp3 | Codec::Mp2 => fixed_packet_samples(FixedFrames::MpegAudio, &first(), out_rate),
+ Codec::Ac3 => fixed_packet_samples(FixedFrames::Ac3, &first(), out_rate),
+ _ => None,
+ };
+ let Some(frame) = frame else {
+ return t.samples.iter().map(|s| at(s.pts)).collect();
+ };
+ let packets = t.samples.iter().map(|s| PacketTime { stamp: at(s.pts), stamped: own_stamp(s), samples: Some(frame) });
+ contiguous_starts(packets, (frame / 2).max(stamp_tolerance(t, rate)))
+}
+
/// Sample-exact Opus packet start positions (48 kHz frames, pre-skip removed).
///
-/// Block timestamps are quantised to `TimestampScale` (usually 1 ms) and the demuxer subtracts a
-/// rounded `CodecDelay`, so they are only accurate to a tick. Starts are therefore accumulated from
-/// each packet's TOC duration, resynchronising to the timestamp only across real gaps (more than
-/// two ticks off). Pre-skip is the exact `CodecDelay` (or the header's pre-skip when it is absent).
+/// The demuxer also subtracts a rounded `CodecDelay` from the timestamps. Starts are accumulated
+/// from each packet's TOC duration, resynchronising to the timestamp only across real gaps (more
+/// than two ticks off). Pre-skip is the exact `CodecDelay` (or the header's pre-skip when it is
+/// absent).
fn opus_starts(file: &MkvFile, bytes: &crate::Src, ti: usize, head: &filmcraft_opus::OpusHead, rate: i64) -> Vec<i64> {
- let t = &file.tracks[ti];
+ let Some(t) = file.tracks.get(ti) else { return Vec::new() };
let (n, d) = tb(t);
let scale_ns = (n as i128 * 1_000_000_000 / d as i128).max(1);
let delay_ns = t.codec_delay_ns as i128;
// The demuxer's rounding of CodecDelay to ticks (half away from zero), undone here.
let delay_ticks = ((delay_ns + scale_ns / 2) / scale_ns) as i64;
let skip = if t.codec_delay_ns > 0 { (delay_ns * rate as i128 / 1_000_000_000) as i64 } else { head.pre_skip as i64 };
- let at = |pts: i64| ((pts + delay_ticks) as i128 * n as i128 * rate as i128 / d as i128) as i64 - skip;
- let tolerance = (2 * scale_ns * rate as i128 / 1_000_000_000) as i64 + 1;
- let mut starts = Vec::with_capacity(t.samples.len());
- let mut next: Option<i64> = None;
- for (i, s) in t.samples.iter().enumerate() {
- let stamped = at(s.pts);
- let start = match next {
- Some(p) if (p - stamped).abs() <= tolerance => p,
- _ => stamped,
- };
- starts.push(start);
- let dur = file.read_sample(bytes, ti, i).ok().and_then(|p| crate::audio::opus_packet_samples(&p));
- next = dur.map(|k| start + k as i64);
- }
- starts
+ let at = |pts: i64| ((pts.saturating_add(delay_ticks) as i128 * n as i128 * rate as i128 / d as i128) as i64).saturating_sub(skip);
+ let packets = t.samples.iter().enumerate().map(|(i, s)| crate::audio::PacketTime {
+ stamp: at(s.pts),
+ stamped: own_stamp(s),
+ samples: file.read_sample(bytes, ti, i).ok().and_then(|p| crate::audio::opus_packet_samples(&p)).map(|k| k as i64),
+ });
+ crate::audio::contiguous_starts(packets, stamp_tolerance(t, rate))
+}
+
+/// Two timestamp ticks in sample frames at `rate`, plus one: how far a packet's Matroska timestamp
+/// can be from its exact start.
+fn stamp_tolerance(t: &filmcraft_matroska::Track, rate: i64) -> i64 {
+ let (n, d) = tb(t);
+ i64::try_from(2 * n as i128 * rate as i128 / d as i128).unwrap_or(i64::MAX).saturating_add(1)
+}
+
+/// Whether a sample's timestamp is its own: frames after the first in a laced block without a
+/// duration repeat the block's timestamp.
+fn own_stamp(s: &filmcraft_matroska::Sample) -> bool {
+ s.lace == 0 || s.duration > 0
}
/// The parsed `OpusHead` of an `A_OPUS` track.
@@ -311,18 +350,7 @@ impl MkvSource {
start_timecode: None,
file_size: Some(bytes.0.len()),
};
- let audio_starts = atrack
- .map(|i| {
- let t = &file.tracks[i];
- let rate = info.audio.as_ref().map_or(48_000, |a| a.sample_rate) as i64;
- let (n, d) = tb(t);
- let at = |pts: i64| (pts as i128 * n as i128 * rate as i128 / d as i128) as i64;
- match opus_head(&t.codec) {
- Some(h) => opus_starts(&file, &bytes, i, &h, rate),
- None => t.samples.iter().map(|s| at(s.pts)).collect(),
- }
- })
- .unwrap_or_default();
+ let audio_starts = atrack.map(|i| audio_starts(&file, &bytes, i, info.audio.as_ref().map_or(48_000, |a| a.sample_rate) as i64)).unwrap_or_default();
let audio_preroll = atrack
.map(|i| {
let t = &file.tracks[i];
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index 2fedf3be1..2cdcad31f 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -37,11 +37,11 @@ pub struct Mp4Source {
atrack: Option<usize>,
video: GopCache,
audio: Mutex<AudioState>,
- /// Cumulative sample start frames for the audio track (for packet lookup).
+ /// Audio packet start positions in source sample frames (see [`audio_starts`]).
audio_starts: Vec<i64>,
/// Presentation offset of the audio track in its timescale (edit list, or Opus pre-skip).
audio_offset: i64,
- /// Decoder pre-roll after a seek, in audio track timescale units (0: prime with one packet).
+ /// Decoder pre-roll after a seek, in source sample frames (0: prime with one packet).
audio_preroll: i64,
}
@@ -49,6 +49,40 @@ pub fn sniff(b: &[u8]) -> bool {
b.len() >= 12 && matches!(&b[4..8], b"ftyp" | b"moov" | b"mdat" | b"wide" | b"free" | b"skip")
}
+/// Audio packet start positions in source sample frames at `rate`: the running total of the sample
+/// durations, except that packets which all decode to the same length (AAC, MPEG audio, AC-3) run
+/// on from one another, resynchronising to the total only across gaps of more than half a packet.
+/// A remux from Matroska (OBS's) carries the millisecond rounding of its timestamps into the
+/// durations: 1008, 1008, 1056… for 1024-sample AAC frames at 48 kHz (see
+/// [`crate::audio::contiguous_starts`]).
+fn audio_starts(file: &Mp4File, bytes: &crate::Src, ti: usize, rate: u32) -> Vec<i64> {
+ use crate::audio::{FixedFrames, PacketTime, contiguous_starts, fixed_packet_samples};
+ let Some(t) = file.tracks.get(ti) else { return Vec::new() };
+ let ts = i128::from(t.timescale.max(1));
+ let mut total = 0i128;
+ let stamps: Vec<i64> = t
+ .samples
+ .iter()
+ .map(|s| {
+ let at = total * i128::from(rate) / ts;
+ total += i128::from(s.duration);
+ i64::try_from(at).unwrap_or(i64::MAX)
+ })
+ .collect();
+ let first = || file.read_sample(bytes, ti, 0).unwrap_or_default();
+ let frame = match t.entries.first().map(|e| &e.codec) {
+ Some(CodecConfig::Aac(a)) => fixed_packet_samples(FixedFrames::Aac(&a.asc), &[], rate),
+ Some(CodecConfig::Mp3) => fixed_packet_samples(FixedFrames::MpegAudio, &first(), rate),
+ Some(CodecConfig::Ac3 { .. }) => fixed_packet_samples(FixedFrames::Ac3, &first(), rate),
+ _ => None,
+ };
+ let Some(frame) = frame else { return stamps };
+ // samples per track timescale unit, rounded up: how coarse the running total is
+ let unit = i64::try_from((i128::from(rate) + ts - 1) / ts).unwrap_or(i64::MAX);
+ let packets = stamps.iter().map(|&stamp| PacketTime { stamp, stamped: true, samples: Some(frame) });
+ contiguous_starts(packets, (frame / 2).max(unit.saturating_mul(2).saturating_add(1)))
+}
+
/// HDR static metadata from the sample entry's `mdcv` / `clli` boxes (0 = unknown).
fn hdr_metadata(md: Option<&filmcraft_isobmff::MasteringDisplay>, cll: Option<(u16, u16)>) -> Option<filmcraft_color::HdrMetadata> {
if md.is_none() && cll.is_none() {
@@ -240,20 +274,8 @@ impl Mp4Source {
start_timecode,
file_size: Some(bytes.0.len()),
};
- let audio_starts = atrack
- .map(|i| {
- let t = &file.tracks[i];
- let mut acc = 0i64;
- t.samples
- .iter()
- .map(|s| {
- let st = acc;
- acc += s.duration as i64;
- st
- })
- .collect()
- })
- .unwrap_or_default();
+ let audio_rate = info.audio.as_ref().map_or(48_000, |a| a.sample_rate);
+ let audio_starts = atrack.map(|i| audio_starts(&file, &bytes, i, audio_rate)).unwrap_or_default();
let (audio_offset, audio_preroll) = atrack
.map(|i| {
let t = &file.tracks[i];
@@ -261,7 +283,8 @@ impl Mp4Source {
match &t.entries[0].codec {
CodecConfig::Opus(o) => {
let off = if t.edit_offset != 0 { t.edit_offset } else { -(o.pre_skip as i64) * ts / 48_000 };
- (off, (crate::audio::OPUS_PRE_ROLL as u64 * ts as u64).div_ceil(48_000) as i64)
+ // (Opus plays at 48 kHz: the pre-roll is in its sample frames)
+ (off, crate::audio::OPUS_PRE_ROLL as i64)
}
_ => (t.edit_offset, 0),
}
@@ -393,14 +416,12 @@ impl MediaSource for Mp4Source {
let offset = i128::from(self.audio_offset) * i128::from(src_rate) / i128::from(track.timescale.max(1));
let s0 = i64::try_from(i128::from(p0) - offset).unwrap_or(if offset > 0 { i64::MIN } else { i64::MAX });
let need = (frames as f64 * ratio).ceil() as i64 + 2;
- // Samples-per-unit: the track timescale is usually the sample rate for audio.
- let unit = src_rate as f64 / track.timescale.max(1) as f64;
let mut src: Vec<Vec<f32>> = vec![vec![0.0; need.max(0) as usize]; ch];
let mut st = self.audio.lock().unwrap_or_else(|e| e.into_inner());
- let first = self.audio_starts.partition_point(|&x| (x as f64 * unit) as i64 <= s0.max(0)).saturating_sub(1);
+ let first = self.audio_starts.partition_point(|&x| x <= s0.max(0)).saturating_sub(1);
let mut i = first;
while i < track.samples.len() {
- let pk_start = (self.audio_starts[i] as f64 * unit) as i64;
+ let pk_start = self.audio_starts[i];
if pk_start >= s0.saturating_add(need) {
break;
}
diff --git a/crates/codecs/tests/matroska_audio_oracle.rs b/crates/codecs/tests/matroska_audio_oracle.rs
new file mode 100644
index 000000000..c1726fd8c
--- /dev/null
+++ b/crates/codecs/tests/matroska_audio_oracle.rs
@@ -0,0 +1,50 @@
+//! Matroska audio made by ffmpeg, against ffmpeg's decode (#236). ffmpeg stamps blocks to the
+//! millisecond, so at 44.1 kHz AAC (1024-sample), MP3 (1152) and AC-3 (1536) packets are each
+//! stamped up to half a millisecond off their exact start. Read back block by block, as playback
+//! reads it, a tone must stay as smooth as ffmpeg's decode of it: no holes or overlaps between
+//! packets.
+
+mod common;
+
+use common::*;
+
+/// Largest |second difference| of `x` from `from` on: a click shows up as a spike.
+fn roughness(x: &[f32], from: usize) -> f32 {
+ x.windows(3).skip(from).map(|w| (w[0] - 2.0 * w[1] + w[2]).abs()).fold(0.0, f32::max)
+}
+
+#[test]
+fn matroska_audio_plays_without_holes() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ let cases: [(&str, u32, &[&str]); 5] = [
+ ("tone_aac_48k.mkv", 48_000, &["-c:a", "aac", "-b:a", "160k"]),
+ ("tone_aac_44k.mkv", 44_100, &["-c:a", "aac", "-b:a", "160k"]),
+ ("tone_mp3_44k.mkv", 44_100, &["-c:a", "libmp3lame", "-b:a", "192k"]),
+ ("tone_mp2_44k.mkv", 44_100, &["-c:a", "mp2", "-b:a", "192k"]),
+ ("tone_ac3_44k.mkv", 44_100, &["-c:a", "ac3", "-b:a", "192k"]),
+ ];
+ for (name, rate, codec) in cases {
+ let input = format!("sine=frequency=440:sample_rate={rate}:duration=3");
+ let args: Vec<&str> = ["-f", "lavfi", "-i", input.as_str(), "-af", "volume=4"].iter().copied().chain(codec.iter().copied()).collect();
+ let Some(path) = fixture(&ff, name, &args) else {
+ eprintln!("SKIPPED ({name}): this ffmpeg can't encode it");
+ continue;
+ };
+ let src = filmcraft_codecs::open_bytes(name, bytes(&path)).unwrap();
+ assert_eq!(src.info().audio.as_ref().map(|a| a.sample_rate), Some(rate), "{name}");
+ let frames = rate as usize * 29 / 10;
+ let mut ours = Vec::with_capacity(frames);
+ while ours.len() < frames {
+ let n = 512.min(frames - ours.len());
+ ours.extend_from_slice(&src.audio(ours.len() as i64, n, rate).unwrap().channels[0]);
+ }
+ let theirs = ffmpeg_audio_f32(&ff, &path, &[]);
+ // past the codecs' start-up (priming, MP3's first frame)
+ let skip = rate as usize / 10;
+ let (r_ours, r_theirs) = (roughness(&ours, skip), roughness(&theirs[..theirs.len().min(frames)], skip));
+ let peak = ours.iter().skip(skip).fold(0f32, |m, x| m.max(x.abs()));
+ println!("{name}: peak {peak:.3}, max |second difference| ours {r_ours:.5}, ffmpeg {r_theirs:.5}");
+ assert!(peak > 0.4, "{name}: the tone is missing (peak {peak})");
+ assert!(r_ours < 2.0 * r_theirs + 0.005, "{name}: clicks between packets (|Δ²| {r_ours} vs ffmpeg's {r_theirs})");
+ }
+}