diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index c07920a..a5eebb9 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -223,13 +223,11 @@ impl Player { ) .child(transport_glyph(playing)), ) - .child( - div().flex_none().w(px(TIME_W)).child(format!( - "{} / {}", - timecode(position, self.fps), - timecode(self.duration, self.fps) - )), - ), + .child(div().flex_none().w(px(TIME_W)).child(format!( + "{} / {}", + timecode(position, self.fps), + timecode(self.duration, self.fps) + ))), ) // Read-only: no cursor, no hover, no listener -- a clip slice turns // this into a scrubber, today it only reports. diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs index 3d41c11..b13b7fd 100644 --- a/crates/engine-audio/src/lib.rs +++ b/crates/engine-audio/src/lib.rs @@ -91,6 +91,19 @@ impl Ring { } } +/// The consumer half of a flush: drops everything queued, then pops as usual. +/// Doing it here rather than in `ao_flush` keeps the ring single-consumer -- +/// only the RT thread ever moves `read` -- and means a flush asked for while +/// paused (no callbacks running) still lands before the next pop, so the stale +/// samples can never be heard. +fn consume(flush: &AtomicBool, ring: &Ring, dst: &mut [u8], want: usize) -> usize { + if flush.swap(false, Ordering::Acquire) { + ring.read + .store(ring.write.load(Ordering::Acquire), Ordering::Release); + } + ring.pop(dst, want) +} + /// Everything the RT thread and the caller's thread both touch. struct Shared { ring: Ring, @@ -100,6 +113,8 @@ struct Shared { ready: AtomicBool, /// Stream died (daemon gone, node removed); every later write fails. dead: AtomicBool, + /// Asked for by `ao_flush`, honoured by the next process callback. + flush: AtomicBool, underruns: AtomicU64, } @@ -178,7 +193,7 @@ fn run( // the pause and a future seek all have to wait out. let frames = (slice.len() / stride).min(QUANTUM as usize); let want = frames * channels; - let got = shared.ring.pop(slice, want); + let got = consume(&shared.flush, &shared.ring, slice, want); if got < want { // Underrun: silence rather than stale samples, and // the clock below keeps running -- the device plays @@ -323,6 +338,7 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { position: AtomicI64::new(-1), ready: AtomicBool::new(false), dead: AtomicBool::new(false), + flush: AtomicBool::new(false), underruns: AtomicU64::new(0), }); let (ready_tx, ready_rx) = mpsc::channel(); @@ -414,6 +430,28 @@ pub unsafe extern "C" fn ao_set_active(session: *mut c_void, active: u32) -> i32 .unwrap_or(-1) } +/// Drops every queued sample, so playback resumes from whatever is written +/// next: what a seek needs. Takes effect on the next process callback (or the +/// first one after a resume), and leaves the played position alone -- the +/// device keeps counting, the caller re-bases against it. +/// 0 on success, negative on failure. +/// +/// # Safety +/// `session` must come from [`ao_open`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_flush(session: *mut c_void) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &*(session as *const Session) }; + session.shared.flush.store(true, Ordering::Release); + 0 + })) + .unwrap_or(-1) +} + /// Stops playback and releases the session. Safe to call with null. /// /// # Safety @@ -430,7 +468,7 @@ pub unsafe extern "C" fn ao_close(session: *mut c_void) { #[cfg(test)] mod tests { - use super::Ring; + use super::{AtomicBool, Ordering, Ring, consume}; #[test] fn ring_wraps_fills_and_starves() { @@ -452,4 +490,28 @@ mod tests { // Empty ring starves instead of replaying stale samples. assert_eq!(ring.pop(&mut out, 4), 0); } + + #[test] + fn flush_drops_queued_samples() { + let ring = Ring::new(4); + let flush = AtomicBool::new(false); + let mut out = [0u8; 16]; + + // No flush pending: an ordinary pop. + assert_eq!(ring.push(&[1.0, 2.0]), 2); + assert_eq!(consume(&flush, &ring, &mut out, 2), 2); + + // Flushed: the queued samples are gone, so the callback gets nothing + // and fills silence, and the flag is one-shot. + assert_eq!(ring.push(&[3.0, 4.0]), 2); + flush.store(true, Ordering::Release); + assert_eq!(consume(&flush, &ring, &mut out, 2), 0); + assert!(!flush.load(Ordering::Acquire)); + + // Ring is empty, not corrupt: the next write plays as usual. + assert_eq!(ring.push(&[5.0, 6.0, 7.0, 8.0]), 4); + assert_eq!(consume(&flush, &ring, &mut out, 4), 4); + assert_eq!(&out[..4], &5.0f32.to_le_bytes()); + assert_eq!(&out[12..16], &8.0f32.to_le_bytes()); + } } diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index da84896..163b73e 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -49,6 +49,8 @@ struct Session { pending: Vec, timestamp: u64, flushed: bool, + /// Pictures still to be decoded and thrown away to land on a seek target. + skip: u32, /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame, /// which is exactly why the pointers are only valid until the next call. out: Vec, @@ -148,12 +150,23 @@ impl Session { pending: Vec::new(), timestamp: 0, flushed: false, + skip: 0, out: Vec::new(), luma: 0, chroma: 0, }) } + /// As [`Session::open`], but positioned so the first picture handed out is + /// sample `target_sample` (1-based): decode restarts at the sync sample at + /// or before it and the pictures in between are dropped unread. + fn open_at(path: &Path, target_sample: u32) -> Option { + let mut session = Self::open(path)?; + let sync = session.demuxer.seek_to_sync_at_or_before(target_sample); + session.skip = target_sample.saturating_sub(sync); + Some(session) + } + /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF. fn pump(&mut self) -> Result { let mut stalls = 0u32; @@ -175,6 +188,12 @@ impl Session { } } if let Some(handle) = self.ready.pop_front() { + // Seek discards: dropping the handle skips the `vaGetImage` + // read-back (~1.2 ms/picture) and frees its pool buffer. + if self.skip > 0 { + self.skip -= 1; + continue; + } self.emit(handle); return Ok(true); } @@ -283,13 +302,15 @@ impl Session { } } -/// Opens `path` for hardware decode. Returns null on any failure at all: no -/// libva runtime, no render node, unsupported profile, unreadable file. +/// Opens `path` for hardware decode, positioned so the first +/// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean +/// the start of the stream). Returns null on any failure at all: no libva +/// runtime, no render node, unsupported profile, unreadable file. /// /// # Safety /// `path` must be a valid NUL-terminated C string. #[unsafe(no_mangle)] -pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void { +pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> *mut c_void { catch_unwind(AssertUnwindSafe(|| { if path.is_null() { return std::ptr::null_mut(); @@ -299,7 +320,7 @@ pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void { let Ok(path) = path.to_str() else { return std::ptr::null_mut(); }; - match Session::open(Path::new(path)) { + match Session::open_at(Path::new(path), target_sample) { Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, None => std::ptr::null_mut(), } @@ -310,7 +331,7 @@ pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void { /// Fills `out` with stream metadata. 0 on success, negative on failure. /// /// # Safety -/// `session` must come from [`vh_open`] and `out` must be writable. +/// `session` must come from [`vh_open_at`] and `out` must be writable. #[unsafe(no_mangle)] pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 { catch_unwind(AssertUnwindSafe(|| { @@ -334,7 +355,7 @@ pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 /// stream, negative on error. Plane pointers stay valid until the next call. /// /// # Safety -/// `session` must come from [`vh_open`] and `out` must be writable. +/// `session` must come from [`vh_open_at`] and `out` must be writable. #[unsafe(no_mangle)] pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 { catch_unwind(AssertUnwindSafe(|| { @@ -362,12 +383,12 @@ pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) /// Releases a session. Safe to call with null. /// /// # Safety -/// `session` must come from [`vh_open`] and must not be used afterwards. +/// `session` must come from [`vh_open_at`] and must not be used afterwards. #[unsafe(no_mangle)] pub unsafe extern "C" fn vh_close(session: *mut c_void) { let _ = catch_unwind(AssertUnwindSafe(|| { if !session.is_null() { - // SAFETY: pointer came from `Box::into_raw` in `vh_open`. + // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`. drop(unsafe { Box::from_raw(session as *mut Session) }); } })); diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs index 024697f..056f2c0 100644 --- a/crates/engine/src/ao.rs +++ b/crates/engine/src/ao.rs @@ -18,6 +18,7 @@ struct Plugin { write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize, position: unsafe extern "C" fn(*mut c_void) -> i64, set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, + flush: unsafe extern "C" fn(*mut c_void) -> i32, close: unsafe extern "C" fn(*mut c_void), // Never dropped (lives in a static), so the fn pointers above stay valid. _lib: Library, @@ -54,6 +55,9 @@ fn load() -> Option { write: *lib.get(b"ao_write\0").ok()?, position: *lib.get(b"ao_position\0").ok()?, set_active: *lib.get(b"ao_set_active\0").ok()?, + // Required, so a plugin predating seek is rejected whole + // and we play muted rather than half-working. + flush: *lib.get(b"ao_flush\0").ok()?, close: *lib.get(b"ao_close\0").ok()?, _lib: lib, }) @@ -118,6 +122,13 @@ impl AoSession { // SAFETY: `handle` came from `ao_open` and is still open. unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 } } + + /// Drops everything still queued, so the next samples written play right + /// away -- what a seek needs. The played position keeps counting. + pub fn flush(&self) -> bool { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { (self.plugin.flush)(self.handle) == 0 } + } } impl Drop for AoSession { diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index a4f633e..b61fd1d 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -23,6 +23,10 @@ const DEFAULT_PRIMING: u64 = 1024; /// An edit list entry that only shifts the timeline, carrying no media. const EMPTY_EDIT: u64 = u32::MAX as u64; +/// Packets decoded and thrown away ahead of a seek target: one for the MDCT +/// overlap-add that reconstructs the target packet, one to warm the decoder. +const PRE_ROLL: u32 = 2; + #[derive(Debug, Clone, Copy, PartialEq)] pub struct AudioMeta { pub sample_rate: u32, @@ -48,6 +52,16 @@ impl AudioSession { /// audio, which is a valid session; `Err` is a real failure. pub fn open( path: impl AsRef, + ) -> crate::Result)>> { + Self::open_at(path, 0.0) + } + + /// Like [`open`](Self::open) but the first chunk starts at `start_secs` on + /// the audible timeline; `start_sample` stays absolute from audible zero, so + /// the output is the tail of a full run. Past the end yields no chunks. + pub fn open_at( + path: impl AsRef, + start_secs: f64, ) -> crate::Result)>> { let file = File::open(path.as_ref())?; let size = file.metadata()?.len(); @@ -70,14 +84,20 @@ impl AudioSession { let channels: u16 = match track.channel_config()? { ChannelConfig::Mono => 1, ChannelConfig::Stereo => 2, - other => return Err(format!("unsupported channel layout: {other:?} (max stereo)").into()), + other => { + return Err(format!("unsupported channel layout: {other:?} (max stereo)").into()); + } }; let track_id = track.track_id(); let sample_rate = track.sample_freq_index()?.freq(); let priming = priming_samples(track, sample_rate); - let total_samples = scale(track.trak.mdia.mdhd.duration, sample_rate, track.timescale()) - .map(|d| d.saturating_sub(priming)); + let total_samples = scale( + track.trak.mdia.mdhd.duration, + sample_rate, + track.timescale(), + ) + .map(|d| d.saturating_sub(priming)); let mut params = AudioCodecParameters::new(); params @@ -86,6 +106,28 @@ impl AudioSession { .with_extra_data(audio_specific_config(track)?); let decoder = AacDecoder::try_new(¶ms, &AudioDecoderOptions::default())?; + // Where to land, in media samples (priming included, so it is directly + // comparable to decoded position), and which packet holds it. + let media_target = (start_secs * f64::from(sample_rate)) as u64 + priming; + let target_ts = unscale(media_target, sample_rate, track.timescale()); + // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous + // packet to cancel aliasing, plus one more to warm the decoder up. Their + // output is discarded below, so this only costs decode time. + let (start_id, start_ts) = packet_at( + track + .trak + .mdia + .minf + .stbl + .stts + .entries + .iter() + .map(|e| (e.sample_count, e.sample_delta)), + target_ts, + PRE_ROLL, + ); + let start_pos = scale(start_ts, sample_rate, track.timescale()).unwrap_or(0); + let sample_count = reader.sample_count(track_id)?; let meta = AudioMeta { sample_rate, @@ -96,17 +138,22 @@ impl AudioSession { // this bound is ~0.75 s of lookahead — enough to ride out decode jitter // without making a pause take a second to bite. let (tx, rx) = sync_channel(32); - thread::Builder::new().name("audio-decode".into()).spawn(move || { - run(Worker { - reader, - decoder, - track_id, - sample_count, - channels: channels as usize, - priming, - tx, - }) - })?; + thread::Builder::new() + .name("audio-decode".into()) + .spawn(move || { + run(Worker { + reader, + decoder, + track_id, + sample_count, + channels: channels as usize, + priming, + start_id, + start_pos, + media_target, + tx, + }) + })?; Ok(Some((meta, rx))) } } @@ -161,6 +208,56 @@ fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option { (timescale != 0).then(|| value * u64::from(sample_rate) / timescale) } +/// Inverse of [`scale`]: samples-per-channel back into the track timescale. +fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 { + match sample_rate { + 0 => 0, + rate => samples * u64::from(timescale) / u64::from(rate), + } +} + +/// The 1-based packet holding media time `target_ts`, walked back by `pre_roll` +/// packets, plus that packet's own start time. Inverse of the mp4 crate's +/// private `sample_time` walk over stts (`track.rs:475`); its `SttsEntry` is +/// unnameable outside the crate, hence the `(sample_count, sample_delta)` pairs. +/// +/// ponytail: the walk-back is clamped to the start of the containing stts entry +/// rather than crossing into the previous one, so a target within `pre_roll` +/// packets of an entry boundary gets less pre-roll. AAC packets are uniformly +/// 1024 frames (one entry per track), so this cannot fire here; upgrade path is +/// carrying the previous entry's delta through the walk. +fn packet_at( + entries: impl IntoIterator, + target_ts: u64, + pre_roll: u32, +) -> (u32, u64) { + let mut first_id = 1u32; + let mut elapsed = 0u64; + let mut last = (1u32, 0u64); + for (count, delta) in entries { + let span = u64::from(count) * u64::from(delta); + let index = if target_ts < elapsed + span && delta != 0 { + ((target_ts - elapsed) / u64::from(delta)) as u32 + } else { + // Past this entry: remember its last packet in case the target runs + // past the end of the track entirely. + last = ( + first_id + count.saturating_sub(1), + elapsed + span.saturating_sub(u64::from(delta)), + ); + first_id += count; + elapsed += span; + continue; + }; + let index = index - index.min(pre_roll); + return ( + first_id + index, + elapsed + u64::from(index) * u64::from(delta), + ); + } + last +} + struct Worker { reader: Mp4Reader>, decoder: AacDecoder, @@ -168,15 +265,21 @@ struct Worker { sample_count: u32, channels: usize, priming: u64, + /// First packet to feed the decoder, 1-based; includes the pre-roll. + start_id: u32, + /// Media position of `start_id`'s first frame, in samples-per-channel. + start_pos: u64, + /// Media position of the first frame to emit. Everything decoded before it + /// is pre-roll, priming, or seek overshoot, and gets dropped. + media_target: u64, tx: SyncSender, } fn run(mut w: Worker) { let mut interleaved = Vec::new(); - let mut to_skip = w.priming; - let mut emitted = 0u64; + let mut pos = w.start_pos; - for id in 1..=w.sample_count { + for id in w.start_id..=w.sample_count { let sample = match w.reader.read_sample(w.track_id, id) { Ok(Some(sample)) => sample, Ok(None) => break, @@ -199,22 +302,24 @@ fn run(mut w: Worker) { } }; buf.copy_to_vec_interleaved::(&mut interleaved); + let next = pos + (interleaved.len() / w.channels) as u64; - // Priming frames are encoder ramp-up, not audio: drop them so the first - // sample the caller sees is the first audible one. - if to_skip > 0 { - let drop = to_skip.min((interleaved.len() / w.channels) as u64); - interleaved.drain(..drop as usize * w.channels); - to_skip -= drop; - if interleaved.is_empty() { - continue; - } + // Everything before the target is encoder priming and/or decoder + // pre-roll, not audio the caller asked for: drop it, splitting the + // packet that straddles the target. + if next <= w.media_target { + pos = next; + continue; + } + if pos < w.media_target { + interleaved.drain(..(w.media_target - pos) as usize * w.channels); + pos = w.media_target; } let chunk = AudioChunk { - start_sample: emitted, + start_sample: pos - w.priming, samples: std::mem::take(&mut interleaved), }; - emitted += (chunk.samples.len() / w.channels) as u64; + pos = next; if w.tx.send(chunk).is_err() { break; // consumer went away } @@ -223,6 +328,47 @@ fn run(mut w: Worker) { #[cfg(test)] mod tests { + use super::{PRE_ROLL, packet_at}; + + /// A real AAC track: one stts entry, N packets of 1024. + fn aac(count: u32) -> impl IntoIterator { + [(count, 1024)] + } + + #[test] + fn packet_at_walks_back_by_the_pre_roll() { + // Packet 1 covers [0, 1024); the target at 2 s is packet 87 (89088..). + assert_eq!(packet_at(aac(200), 88_200, 0), (87, 88_064)); + assert_eq!(packet_at(aac(200), 88_200, PRE_ROLL), (85, 86_016)); + // Exactly on a packet boundary is the start of that packet, not the end + // of the previous one. + assert_eq!(packet_at(aac(200), 2048, 0), (3, 2048)); + } + + #[test] + fn packet_at_clamps_both_ends() { + // Head: no room for the walk-back, and packet ids are 1-based. + assert_eq!(packet_at(aac(200), 0, PRE_ROLL), (1, 0)); + assert_eq!(packet_at(aac(200), 1500, PRE_ROLL), (1, 0)); + // Past the end: the last packet, so the worker decodes ~nothing. + assert_eq!(packet_at(aac(200), 10_000_000, PRE_ROLL), (200, 203_776)); + // Degenerate boxes must not panic or wrap. + assert_eq!(packet_at([], 5000, PRE_ROLL), (1, 0)); + assert_eq!(packet_at([(4u32, 0u32)], 5000, PRE_ROLL), (4, 0)); + } + + #[test] + fn packet_at_crosses_stts_entries() { + // 10 packets of 1024 then 10 of 512, so the second entry starts at 10240 + // with packet 11. + let entries = [(10u32, 1024u32), (10, 512)]; + assert_eq!(packet_at(entries, 12_500, 0), (15, 12_288)); + assert_eq!(packet_at(entries, 12_500, PRE_ROLL), (13, 11_264)); + // The ponytail clamp: on the first packet of the second entry the + // walk-back stops there instead of stepping into the first entry. + assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240)); + } + #[test] fn asc_round_trips_aac_lc_44100_stereo() { // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo). diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 45d4b55..2b81cf1 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -2,6 +2,8 @@ //! thread (the UI thread) never blocks on decode and memory stays capped. use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::thread; @@ -28,19 +30,33 @@ impl DecodeSession { /// yields frames as the worker decodes them. The worker stops when the /// receiver is dropped, at end of stream, or on the first decode error. pub fn open(path: impl AsRef) -> crate::Result<(VideoMeta, Receiver)> { + let (meta, rx, _cancel) = Self::open_at(path, 0)?; + Ok((meta, rx)) + } + + /// As [`DecodeSession::open`], but the first frame delivered is + /// `start_frame` (0-based display index; [`Frame::index`] stays absolute). + /// Setting the returned flag stops the worker at its next access unit, + /// which is how a caller abandons a session it no longer wants to drain. + pub fn open_at( + path: impl AsRef, + start_frame: u32, + ) -> crate::Result<(VideoMeta, Receiver, Arc)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the // decoder run ahead of the display without limit. let (tx, rx) = sync_channel(2); + let cancel = Arc::new(AtomicBool::new(false)); + let worker_cancel = Arc::clone(&cancel); thread::Builder::new() .name("decode".into()) .spawn(move || { // The plugin has to be opened on the thread that uses it: its // VA-API state is not `Send`-safe across a later hand-off. - if let Some(hw) = open_hw(&path) { + if let Some(hw) = open_hw(&path, start_frame) { eprintln!("decode backend: hardware (VA-API plugin)"); - if run_hw(hw, &tx) { + if run_hw(hw, &tx, start_frame, &worker_cancel) { return; } // A driver that opens but cannot decode a single frame is @@ -48,26 +64,38 @@ impl DecodeSession { eprintln!("hardware decode failed before any frame, falling back to software"); } eprintln!("decode backend: software (rusty_h264)"); - run(demuxer, tx) + run(demuxer, tx, start_frame, &worker_cancel) })?; - Ok((meta, rx)) + Ok((meta, rx, cancel)) } } /// `None` when the software path must be used: forced by `VE_SW=1`, or the /// plugin is absent/broken/unable to open this particular file. -fn open_hw(path: &PathBuf) -> Option { +fn open_hw(path: &PathBuf, start_frame: u32) -> Option { if std::env::var_os("VE_SW").is_some_and(|v| v == "1") { return None; } - HwSession::open(path) + HwSession::open_at(path, start_frame) } /// Returns whether the session was handled; `false` only when hardware decode /// failed without emitting a single frame, so software can still take over. -fn run_hw(mut hw: HwSession, tx: &SyncSender) -> bool { - let mut index = 0u32; +/// +/// The plugin already positioned itself at `start_frame`, so indices are +/// counted from there (a stream whose very first sample is not a sync sample +/// cannot be decoded from its start at all, and is not accounted for). +fn run_hw( + mut hw: HwSession, + tx: &SyncSender, + start_frame: u32, + cancel: &AtomicBool, +) -> bool { + let mut index = start_frame; loop { + if cancel.load(Ordering::Relaxed) { + return true; + } match hw.next_frame() { Ok(Some((y, u, v, width, height))) => { let frame = Frame { @@ -83,7 +111,7 @@ fn run_hw(mut hw: HwSession, tx: &SyncSender) -> bool { } Ok(None) => return true, Err(e) => { - if index == 0 { + if index == start_frame { return false; } eprintln!("hardware decode error at frame {index}: {e}"); @@ -93,13 +121,20 @@ fn run_hw(mut hw: HwSession, tx: &SyncSender) -> bool { } } -fn run(mut demuxer: Demuxer, tx: SyncSender) { +fn run(mut demuxer: Demuxer, tx: SyncSender, start_frame: u32, cancel: &AtomicBool) { let mut decoder = Decoder::new(); - let mut index = 0u32; + // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at + // a sync sample, so pictures between it and `start_frame` are decoded (the + // target frame references them) but never converted or sent. + let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1)); + let mut index = sync - 1; // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames); // reordering streams need POC-sorted output before display. loop { + if cancel.load(Ordering::Relaxed) { + break; + } let au = match demuxer.next_access_unit() { Ok(Some(au)) => au, Ok(None) => break, @@ -116,6 +151,10 @@ fn run(mut demuxer: Demuxer, tx: SyncSender) { break; } }; + if index < start_frame { + index += 1; + continue; + } let frame = Frame { index, width: yuv.width as u32, diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index d1d2c5f..1d22864 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -22,6 +22,9 @@ pub struct Demuxer { sample_count: u32, /// Annex-B SPS+PPS, re-injected ahead of every sync sample. parameter_sets: Vec, + /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box + /// at all, i.e. every sample is a sync sample. + sync_samples: Vec, next_sample: u32, } @@ -49,6 +52,15 @@ impl Demuxer { parameter_sets.extend_from_slice(track.sequence_parameter_set()?); parameter_sets.extend_from_slice(&START_CODE); parameter_sets.extend_from_slice(track.picture_parameter_set()?); + let sync_samples = track + .trak + .mdia + .minf + .stbl + .stss + .as_ref() + .map(|stss| stss.entries.clone()) + .unwrap_or_default(); let sample_count = reader.sample_count(track_id)?; Ok(( @@ -61,6 +73,7 @@ impl Demuxer { track_id, sample_count, parameter_sets, + sync_samples, next_sample: 1, // sample ids are 1-based }, )) @@ -84,6 +97,29 @@ impl Demuxer { append_annex_b(&sample.bytes, &mut au)?; Ok(Some(au)) } + + /// Rewinds/forwards the read cursor to the latest sync sample at or before + /// `sample_id` (1-based), which is the earliest point a decoder can start + /// from and still reach `sample_id`. Returns the sample it landed on. + pub fn seek_to_sync_at_or_before(&mut self, sample_id: u32) -> u32 { + let target = sample_id.clamp(1, self.sample_count.max(1)); + let chosen = sync_at_or_before(&self.sync_samples, target); + self.next_sample = chosen; + chosen + } +} + +/// Largest entry of the ascending sync table that is `<= sample_id`. An empty +/// table means every sample is a sync sample. When `sample_id` sits before the +/// first sync sample there is nothing decodable earlier, so that one wins. +fn sync_at_or_before(syncs: &[u32], sample_id: u32) -> u32 { + if syncs.is_empty() { + return sample_id; + } + match syncs.partition_point(|&s| s <= sample_id) { + 0 => syncs[0], + i => syncs[i - 1], + } } /// avcC length-prefixed NALs -> Annex-B. Assumes a 4-byte length prefix, which @@ -123,6 +159,15 @@ mod tests { assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]); } + #[test] + fn sync_lookup() { + assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs"); + assert_eq!(sync_at_or_before(&[1, 31, 61], 31), 31, "exact hit"); + assert_eq!(sync_at_or_before(&[1, 31, 61], 45), 31, "between syncs"); + assert_eq!(sync_at_or_before(&[5, 31], 2), 5, "before the first sync"); + assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last"); + } + #[test] fn rejects_misparse() { assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err()); diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 7a737f0..1d100e8 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -53,7 +53,7 @@ impl Default for VhFrame { } struct Plugin { - open: unsafe extern "C" fn(*const c_char) -> *mut c_void, + open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void, meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32, next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32, close: unsafe extern "C" fn(*mut c_void), @@ -88,7 +88,7 @@ fn load() -> Option { let plugin = unsafe { (|| { Some(Plugin { - open: *lib.get(b"vh_open\0").ok()?, + open_at: *lib.get(b"vh_open_at\0").ok()?, meta: *lib.get(b"vh_meta\0").ok()?, next_frame: *lib.get(b"vh_next_frame\0").ok()?, close: *lib.get(b"vh_close\0").ok()?, @@ -113,10 +113,19 @@ impl HwSession { /// Probes the plugin against this very file: success means the driver, /// the render node and the stream's profile are all usable. pub fn open(path: &Path) -> Option { + Self::open_at(path, 0) + } + + /// As [`HwSession::open`], but the first [`HwSession::next_frame`] returns + /// display index `start_frame`; earlier pictures are decoded and dropped + /// inside the plugin, without the read-back copy. + pub fn open_at(path: &Path, start_frame: u32) -> Option { let plugin = plugin()?; let c_path = CString::new(path.as_os_str().as_encoded_bytes()).ok()?; + // Sample ids are 1-based, frame indices 0-based. + let target_sample = start_frame.saturating_add(1); // SAFETY: `c_path` is a valid NUL-terminated string alive for the call. - let handle = unsafe { (plugin.open)(c_path.as_ptr()) }; + let handle = unsafe { (plugin.open_at)(c_path.as_ptr(), target_sample) }; if handle.is_null() { return None; } @@ -125,7 +134,7 @@ impl HwSession { pub fn meta(&self) -> Option { let mut meta = VhMeta::default(); - // SAFETY: `handle` came from `vh_open` and is still open. + // SAFETY: `handle` came from `vh_open_at` and is still open. if unsafe { (self.plugin.meta)(self.handle, &mut meta) } < 0 { return None; } @@ -170,7 +179,7 @@ impl HwSession { impl Drop for HwSession { fn drop(&mut self) { - // SAFETY: `handle` came from `vh_open` and is closed exactly once. + // SAFETY: `handle` came from `vh_open_at` and is closed exactly once. unsafe { (self.plugin.close)(self.handle) } } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8e1561a..8b43931 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,9 +11,9 @@ pub mod playback; pub use audio::{AudioChunk, AudioMeta, AudioSession}; pub use clock::PlaybackClock; -pub use playback::PlaybackSession; pub use decode::{DecodeSession, Frame}; pub use demux::VideoMeta; +pub use playback::PlaybackSession; /// Boxed error; the engine has few failure modes and every one of them is fatal /// to the session, so a message is all a caller can act on. diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 17878bd..9e2a10d 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -159,7 +159,8 @@ impl PlaybackSession { // no jump, and this branch cannot be reached again. self.clock.switch_to_wall(); } else { - self.clock.set_audio_position(position as u64, audio.sample_rate); + self.clock + .set_audio_position(position as u64, audio.sample_rate); } } } diff --git a/crates/engine/tests/ao_output.rs b/crates/engine/tests/ao_output.rs index d8673b3..04b1c4f 100644 --- a/crates/engine/tests/ao_output.rs +++ b/crates/engine/tests/ao_output.rs @@ -82,7 +82,10 @@ fn plays_and_tracks_position() { assert!(ao.set_active(true), "resume rejected"); std::thread::sleep(Duration::from_millis(200)); let resumed = ao.position().expect("position went unknown"); - assert!(resumed > paused, "clock did not resume: {paused} -> {resumed}"); + assert!( + resumed > paused, + "clock did not resume: {paused} -> {resumed}" + ); } /// No reachable daemon must fail the open cleanly and quickly, never hang. diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs index bcdeae1..e5f1e54 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -48,7 +48,11 @@ fn decodes_av_mp4_audio() { // d. no gaps, no overlaps. assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start"); assert!(!chunk.samples.is_empty(), "empty chunk {chunks}"); - assert_eq!(chunk.samples.len() % 2, 0, "partial frame in chunk {chunks}"); + assert_eq!( + chunk.samples.len() % 2, + 0, + "partial frame in chunk {chunks}" + ); next_sample += (chunk.samples.len() / 2) as u64; left.extend(chunk.samples.iter().step_by(2)); right.extend(chunk.samples[1..].iter().step_by(2)); @@ -81,9 +85,15 @@ fn decodes_av_mp4_audio() { // Priming trimmed: the sine starts at a rising zero crossing, and audio is // present immediately rather than after a silent or garbage run-in. - assert!(left[0].abs() < 0.05, "first sample {} not near zero", left[0]); + assert!( + left[0].abs() < 0.05, + "first sample {} not near zero", + left[0] + ); assert!(left[1] > 0.0, "first sine quarter is not rising"); - let head_peak = left[..FRAME as usize].iter().fold(0f32, |m, s| m.max(s.abs())); + let head_peak = left[..FRAME as usize] + .iter() + .fold(0f32, |m, s| m.max(s.abs())); assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}"); eprintln!( diff --git a/crates/engine/tests/audio_seek.rs b/crates/engine/tests/audio_seek.rs new file mode 100644 index 0000000..69605a2 --- /dev/null +++ b/crates/engine/tests/audio_seek.rs @@ -0,0 +1,111 @@ +//! `AudioSession::open_at` must produce exactly the tail of a full run: same +//! samples, same absolute `start_sample` numbering, no gaps at the splice. + +use std::path::PathBuf; + +use engine::audio::{AudioChunk, AudioSession}; + +const RATE: u32 = 44100; +const CHANNELS: usize = 2; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Drains a session into one flat interleaved buffer, checking as it goes that +/// chunks are contiguous and that the first one lands on `want_start`. +fn drain(start_secs: f64, want_start: u64) -> Vec { + let (meta, rx) = AudioSession::open_at(asset("test_av.mp4"), start_secs) + .expect("open") + .expect("test_av.mp4 has an audio track"); + assert_eq!((meta.sample_rate, meta.channels as usize), (RATE, CHANNELS)); + + let mut samples = Vec::new(); + let mut next = want_start; + for ( + i, + AudioChunk { + start_sample, + samples: s, + }, + ) in rx.into_iter().enumerate() + { + assert_eq!(start_sample, next, "chunk {i} start at {start_secs}s"); + assert!(!s.is_empty(), "empty chunk {i} at {start_secs}s"); + next += (s.len() / CHANNELS) as u64; + samples.extend(s); + } + samples +} + +/// Largest per-sample difference, and where it is. +fn max_diff(a: &[f32], b: &[f32]) -> (f32, usize) { + a.iter() + .zip(b) + .enumerate() + .map(|(i, (x, y))| ((x - y).abs(), i)) + .fold((0.0, 0), |m, d| if d.0 > m.0 { d } else { m }) +} + +#[test] +fn open_at_zero_matches_open() { + let (mut full, mut at_zero) = (Vec::new(), Vec::new()); + for chunk in AudioSession::open(asset("test_av.mp4")).unwrap().unwrap().1 { + full.extend(chunk.samples); + } + for chunk in AudioSession::open_at(asset("test_av.mp4"), 0.0) + .unwrap() + .unwrap() + .1 + { + at_zero.extend(chunk.samples); + } + assert_eq!(full.len(), at_zero.len()); + assert_eq!(full, at_zero, "open() must be open_at(0.0)"); +} + +#[test] +fn open_at_two_seconds_is_the_tail_of_a_full_run() { + let full = drain(0.0, 0); + let target = 2 * RATE as u64; + let tail = drain(2.0, target); + + let want = &full[target as usize * CHANNELS..]; + assert_eq!(tail.len(), want.len(), "seeked run is a different length"); + if tail == want { + eprintln!("bit-exact: {} samples", tail.len()); + return; + } + // Not bit-exact, and it never will be: perceptual noise substitution draws + // from an LCG seeded once per decoder (symphonia-codec-aac cpe.rs:32,44), so + // a run that skipped 86 packets draws different noise in PNS bands forever. + // The MDCT overlap the pre-roll exists for *is* exact — the first packets + // after the splice match sample for sample. + let (diff, at) = max_diff(&tail, want); + eprintln!("max abs diff {diff:e} at sample {at} of {}", tail.len()); + assert!(diff < 1e-3, "max abs diff {diff} at sample {at}"); +} + +#[test] +fn open_at_mid_first_packet_is_exact() { + // 500 samples in: inside packet 1, before any pre-roll exists to walk back + // to, and it forces the drain-inside-a-chunk trim path. + let full = drain(0.0, 0); + let start = 500u64; + let tail = drain(start as f64 / RATE as f64, start); + let want = &full[start as usize * CHANNELS..]; + assert_eq!(tail.len(), want.len()); + assert_eq!(tail, want, "no decoder state to diverge from at packet 1"); +} + +#[test] +fn open_at_past_duration_ends_clean() { + let tail = drain(60.0, 60 * RATE as u64); + assert!( + tail.is_empty(), + "{} samples past the end of a 5 s file", + tail.len() + ); +} diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index 1a3d697..adfeb90 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -63,7 +63,10 @@ fn decode_all_hw(name: &str) -> (usize, Vec) { #[ignore = "needs libengine_hw.so and a VA-API driver"] fn rejects_unopenable_files() { assert!(HwSession::open(Path::new("/definitely/not/here.mp4")).is_none()); - assert!(HwSession::open(Path::new("/etc/hostname")).is_none(), "not an mp4"); + assert!( + HwSession::open(Path::new("/etc/hostname")).is_none(), + "not an mp4" + ); } #[test] @@ -82,6 +85,44 @@ fn hardware_decodes_high_profile() { assert_eq!(count, 150); } +/// Seeking may only change *when* a picture arrives, never the picture: both +/// backends must land on bytes identical to a linear decode of the same index. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn seek_matches_linear() { + const TARGET: u32 = 60; + let path = asset("test_baseline.mp4"); + + // Software side first, pinned like the test above. SAFETY: --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + let (_, rx) = DecodeSession::open(&path).expect("software open"); + let linear = rx + .into_iter() + .find(|f| f.index == TARGET) + .expect("software frame 60") + .bgra; + + let start = Instant::now(); + let (_, rx, _cancel) = DecodeSession::open_at(&path, TARGET).expect("software open_at"); + let seeked = rx.into_iter().next().expect("no frame after software seek"); + eprintln!("software seek to {TARGET} took {:?}", start.elapsed()); + assert_eq!(seeked.index, TARGET, "first frame after seek is the target"); + assert_eq!(seeked.bgra, linear, "software seek != software linear"); + + let start = Instant::now(); + let mut hw = HwSession::open_at(&path, TARGET).expect("no plugin/driver available"); + let (y, u, v, w, h) = hw + .next_frame() + .expect("hardware decode") + .expect("no frame after hardware seek"); + eprintln!("hardware seek to {TARGET} took {:?}", start.elapsed()); + assert_eq!( + i420_to_bgra(y, u, v, w as usize, h as usize), + linear, + "hardware seek != software linear" + ); +} + /// H.264 8-bit decode is bit-exact by conformance, so the two backends must /// agree. A mismatch means a driver deviation and is reported, not swallowed. #[test]