diff --git a/crates/engine/examples/seek_dump.rs b/crates/engine/examples/seek_dump.rs new file mode 100644 index 0000000..90bf8ab --- /dev/null +++ b/crates/engine/examples/seek_dump.rs @@ -0,0 +1,52 @@ +//! Where a seek actually lands, in *content*: seeks a file to `start` and +//! writes the next `dur` seconds of the mixer's own samples as raw f32, for +//! correlating against an ffmpeg decode of the same window. +//! +//! `cargo run --release -p engine --example seek_dump -- ` +//! +//! Its reason to exist is the same as `probe_fps`'s: the files this has to be +//! measured on are films, too big to keep as fixtures, and "the sound is out of +//! step after a scrub" is a number -- the offset between what came out here and +//! what ffmpeg decodes at the same second -- long before it is an opinion. + +use std::io::Write; + +fn main() { + let mut args = std::env::args().skip(1); + let path = args + .next() + .expect("usage: seek_dump "); + let start: f64 = args.next().expect("missing start").parse().expect("start"); + let dur: f64 = args + .next() + .expect("missing duration") + .parse() + .expect("duration"); + let out = args.next().expect("missing output path"); + + let (meta, rx) = engine::AudioSession::open_at(&path, start) + .expect("open") + .expect("no audio track"); + eprintln!("{} Hz, {} ch", meta.sample_rate, meta.channels); + let want = (dur * f64::from(meta.sample_rate)) as usize * usize::from(meta.channels); + let mut samples: Vec = Vec::with_capacity(want); + for chunk in rx { + if samples.is_empty() { + eprintln!("first chunk at sample {}", chunk.start_sample); + } + samples.extend(chunk.samples); + if samples.len() >= want { + break; + } + } + samples.truncate(want); + let mut w = std::io::BufWriter::new(std::fs::File::create(&out).expect("create")); + for s in &samples { + w.write_all(&s.to_le_bytes()).expect("write"); + } + w.flush().expect("flush"); + eprintln!( + "wrote {} frames to {out}", + samples.len() / usize::from(meta.channels) + ); +} diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 0d62b93..7d2f435 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -1358,6 +1358,9 @@ impl Track { /// out carry their own timestamps. struct SymTrack { reader: Box, + /// The file the reader reads, kept because a seek builds a *new* one + /// ([`SymTrack::seek_to`]). + path: PathBuf, track_id: u32, sample_rate: u32, /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track, @@ -1411,19 +1414,7 @@ impl SymTrack { } fn open_inner(path: &Path, number: Option) -> crate::Result> { - let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); - // The extension is a hint, not a decision: the probe reads the magic and - // is free to disagree, which is what makes a mislabelled file work. - let mut hint = Hint::new(); - if let Some(ext) = path.extension().and_then(|e| e.to_str()) { - hint.with_extension(ext); - } - let reader = symphonia::default::get_probe().probe( - &hint, - mss, - FormatOptions::default(), - MetadataOptions::default(), - )?; + let reader = sym_reader(path)?; let track = match number { Some(number) => reader .tracks() @@ -1469,6 +1460,7 @@ impl SymTrack { }; Ok(Some(Self { reader, + path: path.to_path_buf(), track_id, sample_rate, // 5.1 arrives as a stereo source, whatever it was stored as; every @@ -1533,13 +1525,106 @@ impl SymTrack { ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming) } - /// A packet timestamp in the track's time base, as samples per channel. + /// A packet timestamp in the track's time base, as a media position: the + /// scale [`media`](Self::media) hands out, so a landing compares directly + /// against a segment's target. + /// + /// The priming comes *off* it because a Matroska 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. Measured against ffmpeg's + /// decode of the same second of a real 5.1 Opus remux: without this term a seeked + /// Opus track came out 6.5 ms -- one pre-skip, 312 samples -- ahead of it, + /// with it, on the same sample. fn samples_at(&self, ts: symphonia_core::units::Timestamp) -> u64 { let secs = self.time_base.calc_time_saturating(ts).as_secs_f64(); - (secs.max(0.0) * f64::from(self.sample_rate)) as u64 + ((secs.max(0.0) * f64::from(self.sample_rate)) as u64).saturating_sub(self.priming) + } + + /// Puts the reader **at or before** `media_target`, [`SYM_PRE_ROLL`] ahead + /// of it where the container allows, so that everything the caller did not + /// ask for is decoder warm-up that [`emit`] drops. + /// + /// At or before is the whole point, and it is not what one seek gives. A + /// Matroska seek lands on the first frame whose timestamp is at or past the + /// one asked for, and its cue table can put that a whole cluster further on + /// still: measured on a real 5.1 Opus remux, asking for 599.83 s (600 s less the + /// pre-roll) landed at 601.487 s and asking for 609.83 s at 613.407 s. + /// Samples that far *behind* the reader can never be emitted, and the film + /// played from there while the timeline said 600 s -- 1.5 s of sound + /// against picture, which is the seek desync this exists to kill. So the + /// landing is read back, and an overshoot is asked again from far enough + /// before it to swallow the overshoot. + /// + /// Each attempt gets a **new reader**, because symphonia's mkv seek is + /// reliable exactly once per reader: it neither clears the frames it has + /// already queued (they come out ahead of the new position, carrying the + /// old block's timestamp) nor recovers its element iterator, and a second + /// seek measured on the same file landed the reader back at the first + /// cluster, 0.094 s, whatever it was asked for. Opening again costs 2 ms on + /// a 5 GB film, which is what a seek is allowed to cost. + fn seek_to(&mut self, media_target: u64) { + let rate = f64::from(self.sample_rate.max(1)); + let mut back = SYM_PRE_ROLL; + // Enough for any overshoot a cue table can hold: each attempt asks from + // strictly further back than the last, and the seek to 0 is the floor. + for _ in 0..8 { + let from = media_target.saturating_sub(back); + match sym_reader(&self.path) { + Ok(reader) => self.reader = reader, + // Whatever the file did, the reader in hand still reads: fall + // back to seeking that one, exactly as before this loop existed. + Err(e) => eprintln!("audio reopen failed: {e}"), + } + // Asking for the beginning is asking for nothing: a fresh reader is + // already there, and *seeking* there is how the first 167 ms of + // the remux went missing -- the cue table's first point put the + // reader past them and no window rule can reach back. + if from == 0 { + return; + } + let secs = from as f64 / rate; + let Some(time) = Time::try_from_secs_f64(secs) else { + return; + }; + let to = SeekTo::Time { + time, + track_id: Some(self.track_id), + }; + // A failed seek is not fatal: it leaves the reader where it was, and + // the window rules still only emit what the segment asked for. + let landed = match self.reader.seek(SeekMode::Accurate, to) { + Ok(landed) => self.samples_at(landed.actual_ts), + Err(e) => { + eprintln!("audio seek to {secs:.3}s failed: {e}"); + return; + } + }; + if landed <= media_target { + return; + } + back += (landed - media_target) + SYM_PRE_ROLL; + } } } +/// One symphonia reader over `path`, which is both how a track is opened and +/// how it is seeked ([`SymTrack::seek_to`]). +fn sym_reader(path: &Path) -> crate::Result> { + let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); + // The extension is a hint, not a decision: the probe reads the magic and + // is free to disagree, which is what makes a mislabelled file work. + let mut hint = Hint::new(); + if let Some(ext) = path.extension().and_then(|e| e.to_str()) { + hint.with_extension(ext); + } + Ok(symphonia::default::get_probe().probe( + &hint, + mss, + FormatOptions::default(), + MetadataOptions::default(), + )?) +} + /// One packet in, interleaved f32 out — whichever library did the decoding, and /// already folded to the layout [`SymTrack::channels`] promised. The flag is /// that fold: `true` for a 5.1 track, and there is nothing else it can be. @@ -2975,20 +3060,13 @@ fn run_sym( return true; } }; - let rate = f64::from(track.sample_rate.max(1)); - let from = seg.media_target.saturating_sub(SYM_PRE_ROLL) as f64 / rate; - if let Some(time) = Time::try_from_secs_f64(from) { - let to = SeekTo::Time { - time, - track_id: Some(track.track_id), - }; - // A failed seek is not fatal: it leaves the reader where it was, and - // the window rules below still only emit what the segment asked for. - if let Err(e) = track.reader.seek(SeekMode::Accurate, to) { - eprintln!("audio seek to {from:.3}s failed: {e}"); - } - } + track.seek_to(seg.media_target); let mut interleaved = Vec::new(); + // Media position of the next frame to decode: the landing for the first + // packet, and the decoder's own count from there on. A packet's timestamp + // cannot carry it, because the frames of one laced block all share the + // block's -- accumulating is what both mp4 readers here already do. + let mut at: Option = None; loop { let packet = match track.reader.next_packet() { Ok(Some(packet)) => packet, @@ -3001,7 +3079,7 @@ fn run_sym( if packet.track_id != track.track_id { continue; // another track of the same container } - let pos = track.samples_at(packet.pts); + let pos = *at.get_or_insert_with(|| track.samples_at(packet.pts)); if pos >= seg.media_end { return true; // segment done, on to the next one } @@ -3010,6 +3088,7 @@ fn run_sym( return true; } let next = pos + (interleaved.len() / channels) as u64; + at = Some(next); // Reborrowed per packet: the filter memory has to carry across the // packet boundary, so this is one `EqState` for the whole segment. if !emit( diff --git a/crates/engine/tests/audio_seek.rs b/crates/engine/tests/audio_seek.rs index 69605a2..b15b54e 100644 --- a/crates/engine/tests/audio_seek.rs +++ b/crates/engine/tests/audio_seek.rs @@ -109,3 +109,73 @@ fn open_at_past_duration_ends_clean() { tail.len() ); } + +/// The seek lands on the second it was asked for, in *content*, ten and twenty +/// seconds into a file that has a cue table. +/// +/// That is not what one symphonia seek gives on a Matroska file: it goes +/// through the cues and lands on the first frame at or past the *cluster* the +/// cue names, which on this fixture is up to 4.99 s later than the request +/// (asking 25.0 s landed the reader at 29.987 s) and on a 5.1 Opus film was +/// 1.47 s at 600 s and 3.39 s at 610 s. Nothing downstream can recover samples +/// the reader is already past, so the film simply played from there while the +/// timeline said otherwise -- sound against picture, after every scrub. +/// +/// The chirp is what makes that measurable without a reference decode: 200 Hz +/// rising 160 Hz a second, so the frequency of a quarter second of audio names +/// the second of the file it was cut from. +#[test] +fn a_seek_into_a_cued_matroska_lands_on_its_own_second() { + for start in [5.0, 12.5, 25.0] { + let (meta, rx) = AudioSession::open_at(asset("test_seek_chirp.mkv"), start) + .expect("open") + .expect("test_seek_chirp.mkv has an audio track"); + let at = chirp_second(&meta, rx.into_iter().flat_map(|c| c.samples)); + assert!( + (at - start).abs() < 0.1, + "asked {start}s of the chirp, heard {at:.3}s" + ); + } +} + +/// ...and the *second* segment of one session lands too. Two clips of one file +/// is two seeks on one reader, which is where symphonia's mkv reader gives up +/// altogether: it hands out the frames left over from the first landing and +/// then reads on from wherever its iterator ended up -- measured on a film as +/// the second seek playing the *first cluster* of it, 0.094 s in, whatever it +/// was asked for. +#[test] +fn the_second_segment_of_a_session_lands_too() { + let (meta, rx) = + AudioSession::open_segments(asset("test_seek_chirp.mkv"), &[(5.0, 6.0), (22.5, 23.5)]) + .expect("open") + .expect("test_seek_chirp.mkv has an audio track"); + let channels = usize::from(meta.channels); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let second = meta.sample_rate as usize * channels; + assert_eq!(samples.len(), 2 * second, "two one-second segments"); + for (want, cut) in [(5.0, &samples[..second]), (22.5, &samples[second..])] { + let at = chirp_second(&meta, cut.iter().copied()); + assert!( + (at - want).abs() < 0.1, + "segment from {want}s of the chirp came out as {at:.3}s" + ); + } +} + +/// Where in `test_seek_chirp.mkv` a stream of samples was cut from, by the +/// frequency of its first quarter second: the chirp starts at 200 Hz and rises +/// 160 Hz a second, and zero crossings date it without a reference decode. +fn chirp_second(meta: &engine::audio::AudioMeta, samples: impl Iterator) -> f64 { + const WINDOW: f64 = 0.25; + let channels = usize::from(meta.channels); + let want = (WINDOW * f64::from(meta.sample_rate)) as usize * channels; + let first: Vec = samples.take(want).step_by(channels).collect(); + assert_eq!(first.len(), want / channels, "short of a window to date"); + let crossings = first + .windows(2) + .filter(|p| (p[0] < 0.0) != (p[1] < 0.0)) + .count(); + // The window's *midpoint* is what its mean frequency dates. + (crossings as f64 / 2.0 / WINDOW - 200.0) / 160.0 - WINDOW / 2.0 +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 5505f37..c6a4fc0 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -463,4 +463,16 @@ ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \ -f lavfi -i "sine=frequency=880:duration=3" \ -filter_complex "$tone" -map "[a]" -ar 48000 -c:a pcm_s16le \ assets/test_tone_48k.wav +# A file long enough to have a *cue table*, whose audio says where in it you +# are: a 30 s chirp from 200 Hz rising 160 Hz a second, so the frequency of any +# quarter second of it names the second it came from. That is what makes a seek +# landing measurable without a reference decode (`tests/audio_seek.rs`), and the +# length is the point -- symphonia's Matroska seek goes through the cues, and on +# a two-second fixture there are none to go wrong. Opus in an mkv because that +# is the film the desync was measured on, keyframes every five seconds because +# that is what writes a cue point per cluster. +ffmpeg -y -f lavfi -i "testsrc2=size=320x180:rate=24:duration=30" \ + -f lavfi -i "aevalsrc=sin(2*PI*(200*t+80*t*t)):s=48000:d=30" \ + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p -g 120 \ + -c:a libopus -b:a 128k assets/test_seek_chirp.mkv echo "fixtures written to assets/"