forge
Explore
Log in

Don't you dare go Hollow

A seek into a Matroska lands on the second it asked for

Browse files at this commit

702501a34bc5831b6617121b2a055358faacb2ddAhmet Kaan GümüşParent: 699950a
  • fix
    • a seek into a Matroska lands on the second it asked for
Show full message
🐛 fix(audio): a seek into a Matroska lands on the second it asked for

A film played 1.47 s further in than the timeline said after a scrub to
600 s, 3.39 s after one to 610 s -- sound against picture, the oldest
complaint in this project, and the Matroska half of the mp4 fps truncation
that was fixed once and never swept.

One symphonia mkv seek does not land where it is asked to. It goes through
the cue table and stops at the first frame at or *past* the cue's cluster:
asking for 599.83 s on a 2h+ AV1/Opus 5.1 mkv landed the
reader at 601.487 s, asking for 609.83 s at 613.407 s, and on the new 30 s
fixture asking for 25 s lands
at 29.987 s. Samples that far behind a reader cannot be reached by any
window rule downstream, so `emit` had nothing to trim and the film simply
played from the landing while the clock counted from the request.

So the landing is read back and an overshoot is asked again from far enough
before it to swallow the overshoot, and every attempt gets a *new reader* --
symphonia's mkv seek is reliable exactly once per reader: it hands out the
frames it had already queued (they arrive carrying the old block's
timestamp) and its element iterator does not recover, so a second seek on
one reader landed back at the file's first cluster, 0.094 s, whatever it was
asked for. That is a *clip* of a film, and at HEAD the second clip of a
two-clip timeline came out with no audio at all. Opening again costs 2 ms on
a 5 GB film.

Seeking to the beginning is now not seeking: that seek is how the first
167 ms of the same film went missing at open, and 2.35 s more of it at 27 s,
where the iterator left inside a cue's cluster ran on into the wrong one.

Two smaller things the trimming needed to be right at all. A packet's own
timestamp cannot carry the decode position: the frames of one laced block
all share the block's, so the position accumulates from the decoder's count
between blocks, which is what both mp4 readers here already do. And the
pre-skip comes off a landing timestamp, because an Opus track's blocks are
timestamped for the audible stream while the decoder hands its samples back
with the pre-skip still in front of them -- 6.5 ms, measured.

Measured against an ffmpeg decode of the same window, envelope correlation,
real files. A 2h+ AV1/Opus 5.1 mkv at
600/610/1200/5400/6000 s: +1.474/+3.393/+0.094/+0.073/+0.094 s before, ≤1 ms
after. An HEVC/AAC 5.1 mkv at 610 and 1200 s: +2.054/+1.856 before, 0.000
after. An H.264/AAC mkv and an AC-3 mp4 were already exact and stay exact --
the mp4 tables never had this to get wrong. A/V skew after a seek on the AV1
mkv: -0.007 s at 600 s, -0.005 s at 5400 s. The video path was measured at
the same four positions and lands on the requested frame.
crates/engine/examples/seek_dump.rsadded+52 -0
@@ -0,0 +1,52 @@
1+//! Where a seek actually lands, in *content*: seeks a file to `start` and
2+//! writes the next `dur` seconds of the mixer's own samples as raw f32, for
3+//! correlating against an ffmpeg decode of the same window.
4+//!
5+//! `cargo run --release -p engine --example seek_dump -- <file> <start_secs> <dur_secs> <out.f32>`
6+//!
7+//! Its reason to exist is the same as `probe_fps`'s: the files this has to be
8+//! measured on are films, too big to keep as fixtures, and "the sound is out of
9+//! step after a scrub" is a number -- the offset between what came out here and
10+//! what ffmpeg decodes at the same second -- long before it is an opinion.
11+
12+use std::io::Write;
13+
14+fn main() {
15+ let mut args = std::env::args().skip(1);
16+ let path = args
17+ .next()
18+ .expect("usage: seek_dump <file> <start> <dur> <out.f32>");
19+ let start: f64 = args.next().expect("missing start").parse().expect("start");
20+ let dur: f64 = args
21+ .next()
22+ .expect("missing duration")
23+ .parse()
24+ .expect("duration");
25+ let out = args.next().expect("missing output path");
26+
27+ let (meta, rx) = engine::AudioSession::open_at(&path, start)
28+ .expect("open")
29+ .expect("no audio track");
30+ eprintln!("{} Hz, {} ch", meta.sample_rate, meta.channels);
31+ let want = (dur * f64::from(meta.sample_rate)) as usize * usize::from(meta.channels);
32+ let mut samples: Vec<f32> = Vec::with_capacity(want);
33+ for chunk in rx {
34+ if samples.is_empty() {
35+ eprintln!("first chunk at sample {}", chunk.start_sample);
36+ }
37+ samples.extend(chunk.samples);
38+ if samples.len() >= want {
39+ break;
40+ }
41+ }
42+ samples.truncate(want);
43+ let mut w = std::io::BufWriter::new(std::fs::File::create(&out).expect("create"));
44+ for s in &samples {
45+ w.write_all(&s.to_le_bytes()).expect("write");
46+ }
47+ w.flush().expect("flush");
48+ eprintln!(
49+ "wrote {} frames to {out}",
50+ samples.len() / usize::from(meta.channels)
51+ );
52+}
crates/engine/src/audio.rsmodified+108 -29
@@ -1358,6 +1358,9 @@ impl Track {
1358 /// out carry their own timestamps.1358 /// out carry their own timestamps.
1359 struct SymTrack {1359 struct SymTrack {
1360 reader: Box<dyn FormatReader>,1360 reader: Box<dyn FormatReader>,
1361+ /// The file the reader reads, kept because a seek builds a *new* one
1362+ /// ([`SymTrack::seek_to`]).
1363+ path: PathBuf,
1361 track_id: u32,1364 track_id: u32,
1362 sample_rate: u32,1365 sample_rate: u32,
1363 /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track,1366 /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track,
@@ -1411,19 +1414,7 @@ impl SymTrack {
1411 }1414 }
1412 1415
1413 fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {1416 fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> {
1414- let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());1417+ let reader = sym_reader(path)?;
1415- // The extension is a hint, not a decision: the probe reads the magic and
1416- // is free to disagree, which is what makes a mislabelled file work.
1417- let mut hint = Hint::new();
1418- if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
1419- hint.with_extension(ext);
1420- }
1421- let reader = symphonia::default::get_probe().probe(
1422- &hint,
1423- mss,
1424- FormatOptions::default(),
1425- MetadataOptions::default(),
1426- )?;
1427 let track = match number {1418 let track = match number {
1428 Some(number) => reader1419 Some(number) => reader
1429 .tracks()1420 .tracks()
@@ -1469,6 +1460,7 @@ impl SymTrack {
1469 };1460 };
1470 Ok(Some(Self {1461 Ok(Some(Self {
1471 reader,1462 reader,
1463+ path: path.to_path_buf(),
1472 track_id,1464 track_id,
1473 sample_rate,1465 sample_rate,
1474 // 5.1 arrives as a stereo source, whatever it was stored as; every1466 // 5.1 arrives as a stereo source, whatever it was stored as; every
@@ -1533,13 +1525,106 @@ impl SymTrack {
1533 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)1525 ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
1534 }1526 }
1535 1527
1536- /// A packet timestamp in the track's time base, as samples per channel.1528+ /// A packet timestamp in the track's time base, as a media position: the
1529+ /// scale [`media`](Self::media) hands out, so a landing compares directly
1530+ /// against a segment's target.
1531+ ///
1532+ /// The priming comes *off* it because a Matroska Opus track's blocks are
1533+ /// timestamped for the audible stream while the decoder hands its samples
1534+ /// back with the pre-skip still in front of them. Measured against ffmpeg's
1535+ /// decode of the same second of a real 5.1 Opus remux: without this term a seeked
1536+ /// Opus track came out 6.5 ms -- one pre-skip, 312 samples -- ahead of it,
1537+ /// with it, on the same sample.
1537 fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 {1538 fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 {
1538 let secs = self.time_base.calc_time_saturating(ts).as_secs_f64();1539 let secs = self.time_base.calc_time_saturating(ts).as_secs_f64();
1539- (secs.max(0.0) * f64::from(self.sample_rate)) as u641540+ ((secs.max(0.0) * f64::from(self.sample_rate)) as u64).saturating_sub(self.priming)
1541+ }
1542+
1543+ /// Puts the reader **at or before** `media_target`, [`SYM_PRE_ROLL`] ahead
1544+ /// of it where the container allows, so that everything the caller did not
1545+ /// ask for is decoder warm-up that [`emit`] drops.
1546+ ///
1547+ /// At or before is the whole point, and it is not what one seek gives. A
1548+ /// Matroska seek lands on the first frame whose timestamp is at or past the
1549+ /// one asked for, and its cue table can put that a whole cluster further on
1550+ /// still: measured on a real 5.1 Opus remux, asking for 599.83 s (600 s less the
1551+ /// pre-roll) landed at 601.487 s and asking for 609.83 s at 613.407 s.
1552+ /// Samples that far *behind* the reader can never be emitted, and the film
1553+ /// played from there while the timeline said 600 s -- 1.5 s of sound
1554+ /// against picture, which is the seek desync this exists to kill. So the
1555+ /// landing is read back, and an overshoot is asked again from far enough
1556+ /// before it to swallow the overshoot.
1557+ ///
1558+ /// Each attempt gets a **new reader**, because symphonia's mkv seek is
1559+ /// reliable exactly once per reader: it neither clears the frames it has
1560+ /// already queued (they come out ahead of the new position, carrying the
1561+ /// old block's timestamp) nor recovers its element iterator, and a second
1562+ /// seek measured on the same file landed the reader back at the first
1563+ /// cluster, 0.094 s, whatever it was asked for. Opening again costs 2 ms on
1564+ /// a 5 GB film, which is what a seek is allowed to cost.
1565+ fn seek_to(&mut self, media_target: u64) {
1566+ let rate = f64::from(self.sample_rate.max(1));
1567+ let mut back = SYM_PRE_ROLL;
1568+ // Enough for any overshoot a cue table can hold: each attempt asks from
1569+ // strictly further back than the last, and the seek to 0 is the floor.
1570+ for _ in 0..8 {
1571+ let from = media_target.saturating_sub(back);
1572+ match sym_reader(&self.path) {
1573+ Ok(reader) => self.reader = reader,
1574+ // Whatever the file did, the reader in hand still reads: fall
1575+ // back to seeking that one, exactly as before this loop existed.
1576+ Err(e) => eprintln!("audio reopen failed: {e}"),
1577+ }
1578+ // Asking for the beginning is asking for nothing: a fresh reader is
1579+ // already there, and *seeking* there is how the first 167 ms of
1580+ // the remux went missing -- the cue table's first point put the
1581+ // reader past them and no window rule can reach back.
1582+ if from == 0 {
1583+ return;
1584+ }
1585+ let secs = from as f64 / rate;
1586+ let Some(time) = Time::try_from_secs_f64(secs) else {
1587+ return;
1588+ };
1589+ let to = SeekTo::Time {
1590+ time,
1591+ track_id: Some(self.track_id),
1592+ };
1593+ // A failed seek is not fatal: it leaves the reader where it was, and
1594+ // the window rules still only emit what the segment asked for.
1595+ let landed = match self.reader.seek(SeekMode::Accurate, to) {
1596+ Ok(landed) => self.samples_at(landed.actual_ts),
1597+ Err(e) => {
1598+ eprintln!("audio seek to {secs:.3}s failed: {e}");
1599+ return;
1600+ }
1601+ };
1602+ if landed <= media_target {
1603+ return;
1604+ }
1605+ back += (landed - media_target) + SYM_PRE_ROLL;
1606+ }
1540 }1607 }
1541 }1608 }
1542 1609
1610+/// One symphonia reader over `path`, which is both how a track is opened and
1611+/// how it is seeked ([`SymTrack::seek_to`]).
1612+fn sym_reader(path: &Path) -> crate::Result<Box<dyn FormatReader>> {
1613+ let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default());
1614+ // The extension is a hint, not a decision: the probe reads the magic and
1615+ // is free to disagree, which is what makes a mislabelled file work.
1616+ let mut hint = Hint::new();
1617+ if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
1618+ hint.with_extension(ext);
1619+ }
1620+ Ok(symphonia::default::get_probe().probe(
1621+ &hint,
1622+ mss,
1623+ FormatOptions::default(),
1624+ MetadataOptions::default(),
1625+ )?)
1626+}
1627+
1543 /// One packet in, interleaved f32 out — whichever library did the decoding, and1628 /// One packet in, interleaved f32 out — whichever library did the decoding, and
1544 /// already folded to the layout [`SymTrack::channels`] promised. The flag is1629 /// already folded to the layout [`SymTrack::channels`] promised. The flag is
1545 /// that fold: `true` for a 5.1 track, and there is nothing else it can be.1630 /// that fold: `true` for a 5.1 track, and there is nothing else it can be.
@@ -2975,20 +3060,13 @@ fn run_sym(
2975 return true;3060 return true;
2976 }3061 }
2977 };3062 };
2978- let rate = f64::from(track.sample_rate.max(1));3063+ track.seek_to(seg.media_target);
2979- let from = seg.media_target.saturating_sub(SYM_PRE_ROLL) as f64 / rate;
2980- if let Some(time) = Time::try_from_secs_f64(from) {
2981- let to = SeekTo::Time {
2982- time,
2983- track_id: Some(track.track_id),
2984- };
2985- // A failed seek is not fatal: it leaves the reader where it was, and
2986- // the window rules below still only emit what the segment asked for.
2987- if let Err(e) = track.reader.seek(SeekMode::Accurate, to) {
2988- eprintln!("audio seek to {from:.3}s failed: {e}");
2989- }
2990- }
2991 let mut interleaved = Vec::new();3064 let mut interleaved = Vec::new();
3065+ // Media position of the next frame to decode: the landing for the first
3066+ // packet, and the decoder's own count from there on. A packet's timestamp
3067+ // cannot carry it, because the frames of one laced block all share the
3068+ // block's -- accumulating is what both mp4 readers here already do.
3069+ let mut at: Option<u64> = None;
2992 loop {3070 loop {
2993 let packet = match track.reader.next_packet() {3071 let packet = match track.reader.next_packet() {
2994 Ok(Some(packet)) => packet,3072 Ok(Some(packet)) => packet,
@@ -3001,7 +3079,7 @@ fn run_sym(
3001 if packet.track_id != track.track_id {3079 if packet.track_id != track.track_id {
3002 continue; // another track of the same container3080 continue; // another track of the same container
3003 }3081 }
3004- let pos = track.samples_at(packet.pts);3082+ let pos = *at.get_or_insert_with(|| track.samples_at(packet.pts));
3005 if pos >= seg.media_end {3083 if pos >= seg.media_end {
3006 return true; // segment done, on to the next one3084 return true; // segment done, on to the next one
3007 }3085 }
@@ -3010,6 +3088,7 @@ fn run_sym(
3010 return true;3088 return true;
3011 }3089 }
3012 let next = pos + (interleaved.len() / channels) as u64;3090 let next = pos + (interleaved.len() / channels) as u64;
3091+ at = Some(next);
3013 // Reborrowed per packet: the filter memory has to carry across the3092 // Reborrowed per packet: the filter memory has to carry across the
3014 // packet boundary, so this is one `EqState` for the whole segment.3093 // packet boundary, so this is one `EqState` for the whole segment.
3015 if !emit(3094 if !emit(
crates/engine/tests/audio_seek.rsmodified+70 -0
@@ -109,3 +109,73 @@ fn open_at_past_duration_ends_clean() {
109 tail.len()109 tail.len()
110 );110 );
111 }111 }
112+
113+/// The seek lands on the second it was asked for, in *content*, ten and twenty
114+/// seconds into a file that has a cue table.
115+///
116+/// That is not what one symphonia seek gives on a Matroska file: it goes
117+/// through the cues and lands on the first frame at or past the *cluster* the
118+/// cue names, which on this fixture is up to 4.99 s later than the request
119+/// (asking 25.0 s landed the reader at 29.987 s) and on a 5.1 Opus film was
120+/// 1.47 s at 600 s and 3.39 s at 610 s. Nothing downstream can recover samples
121+/// the reader is already past, so the film simply played from there while the
122+/// timeline said otherwise -- sound against picture, after every scrub.
123+///
124+/// The chirp is what makes that measurable without a reference decode: 200 Hz
125+/// rising 160 Hz a second, so the frequency of a quarter second of audio names
126+/// the second of the file it was cut from.
127+#[test]
128+fn a_seek_into_a_cued_matroska_lands_on_its_own_second() {
129+ for start in [5.0, 12.5, 25.0] {
130+ let (meta, rx) = AudioSession::open_at(asset("test_seek_chirp.mkv"), start)
131+ .expect("open")
132+ .expect("test_seek_chirp.mkv has an audio track");
133+ let at = chirp_second(&meta, rx.into_iter().flat_map(|c| c.samples));
134+ assert!(
135+ (at - start).abs() < 0.1,
136+ "asked {start}s of the chirp, heard {at:.3}s"
137+ );
138+ }
139+}
140+
141+/// ...and the *second* segment of one session lands too. Two clips of one file
142+/// is two seeks on one reader, which is where symphonia's mkv reader gives up
143+/// altogether: it hands out the frames left over from the first landing and
144+/// then reads on from wherever its iterator ended up -- measured on a film as
145+/// the second seek playing the *first cluster* of it, 0.094 s in, whatever it
146+/// was asked for.
147+#[test]
148+fn the_second_segment_of_a_session_lands_too() {
149+ let (meta, rx) =
150+ AudioSession::open_segments(asset("test_seek_chirp.mkv"), &[(5.0, 6.0), (22.5, 23.5)])
151+ .expect("open")
152+ .expect("test_seek_chirp.mkv has an audio track");
153+ let channels = usize::from(meta.channels);
154+ let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
155+ let second = meta.sample_rate as usize * channels;
156+ assert_eq!(samples.len(), 2 * second, "two one-second segments");
157+ for (want, cut) in [(5.0, &samples[..second]), (22.5, &samples[second..])] {
158+ let at = chirp_second(&meta, cut.iter().copied());
159+ assert!(
160+ (at - want).abs() < 0.1,
161+ "segment from {want}s of the chirp came out as {at:.3}s"
162+ );
163+ }
164+}
165+
166+/// Where in `test_seek_chirp.mkv` a stream of samples was cut from, by the
167+/// frequency of its first quarter second: the chirp starts at 200 Hz and rises
168+/// 160 Hz a second, and zero crossings date it without a reference decode.
169+fn chirp_second(meta: &engine::audio::AudioMeta, samples: impl Iterator<Item = f32>) -> f64 {
170+ const WINDOW: f64 = 0.25;
171+ let channels = usize::from(meta.channels);
172+ let want = (WINDOW * f64::from(meta.sample_rate)) as usize * channels;
173+ let first: Vec<f32> = samples.take(want).step_by(channels).collect();
174+ assert_eq!(first.len(), want / channels, "short of a window to date");
175+ let crossings = first
176+ .windows(2)
177+ .filter(|p| (p[0] < 0.0) != (p[1] < 0.0))
178+ .count();
179+ // The window's *midpoint* is what its mean frequency dates.
180+ (crossings as f64 / 2.0 / WINDOW - 200.0) / 160.0 - WINDOW / 2.0
181+}
scripts/gen_fixtures.shmodified+12 -0
@@ -463,4 +463,16 @@ ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \
463 -f lavfi -i "sine=frequency=880:duration=3" \463 -f lavfi -i "sine=frequency=880:duration=3" \
464 -filter_complex "$tone" -map "[a]" -ar 48000 -c:a pcm_s16le \464 -filter_complex "$tone" -map "[a]" -ar 48000 -c:a pcm_s16le \
465 assets/test_tone_48k.wav465 assets/test_tone_48k.wav
466+# A file long enough to have a *cue table*, whose audio says where in it you
467+# are: a 30 s chirp from 200 Hz rising 160 Hz a second, so the frequency of any
468+# quarter second of it names the second it came from. That is what makes a seek
469+# landing measurable without a reference decode (`tests/audio_seek.rs`), and the
470+# length is the point -- symphonia's Matroska seek goes through the cues, and on
471+# a two-second fixture there are none to go wrong. Opus in an mkv because that
472+# is the film the desync was measured on, keyframes every five seconds because
473+# that is what writes a cue point per cluster.
474+ffmpeg -y -f lavfi -i "testsrc2=size=320x180:rate=24:duration=30" \
475+ -f lavfi -i "aevalsrc=sin(2*PI*(200*t+80*t*t)):s=48000:d=30" \
476+ -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p -g 120 \
477+ -c:a libopus -b:a 128k assets/test_seek_chirp.mkv
466 echo "fixtures written to assets/"478 echo "fixtures written to assets/"