forge
Explore
Log in

Don't you dare go Hollow

Seek primitives — video open_at, ao_flush, audio open_at

Browse files at this commit

96ae36578d67885b35b4a947ae44774d68834c7aAhmet Kaan GümüşParent: 1c1f5e0
  • feat
    • seek primitives — video open_at, ao_flush, audio open_at
Show full message
✨ feat(engine): seek primitives — video open_at, ao_flush, audio open_at

Lane 1 of the seek slice; PlaybackSession orchestration comes next.

- demux/decode: stss sync lookup, DecodeSession::open_at decodes from
  the keyframe and discards to the target; Frame.index stays absolute.
  HW plugin ABI: vh_open renamed vh_open_at(path, target) — discards
  skip the vaGetImage readback; measured seek cost 65ms HW / 222ms SW
- engine-audio: ao_flush drains the ring consumer-side in the RT
  callback (one-shot atomic), stale PCM unplayable even when paused;
  played-position atomics untouched so clock math survives
- audio: open_at walks stts, 2-packet AAC pre-roll (MDCT overlap
  reconstructed exactly — verified 0-diff before the first PNS band),
  sample-exact trim; priming skip and seek discard unified. AAC seek
  is deliberately not bit-exact: symphonia's PNS noise LCG state
  depends on packet history; bounded <1e-3 by test instead
crates/app/src/main.rsmodified+5 -7
@@ -223,13 +223,11 @@ impl Player {
223223 )
224224 .child(transport_glyph(playing)),
225225 )
226- .child(
227- div().flex_none().w(px(TIME_W)).child(format!(
228- "{} / {}",
229- timecode(position, self.fps),
230- timecode(self.duration, self.fps)
231- )),
232- ),
226+ .child(div().flex_none().w(px(TIME_W)).child(format!(
227+ "{} / {}",
228+ timecode(position, self.fps),
229+ timecode(self.duration, self.fps)
230+ ))),
233231 )
234232 // Read-only: no cursor, no hover, no listener -- a clip slice turns
235233 // this into a scrubber, today it only reports.
crates/engine-audio/src/lib.rsmodified+64 -2
@@ -91,6 +91,19 @@ impl Ring {
9191 }
9292 }
9393
94+/// The consumer half of a flush: drops everything queued, then pops as usual.
95+/// Doing it here rather than in `ao_flush` keeps the ring single-consumer --
96+/// only the RT thread ever moves `read` -- and means a flush asked for while
97+/// paused (no callbacks running) still lands before the next pop, so the stale
98+/// samples can never be heard.
99+fn consume(flush: &AtomicBool, ring: &Ring, dst: &mut [u8], want: usize) -> usize {
100+ if flush.swap(false, Ordering::Acquire) {
101+ ring.read
102+ .store(ring.write.load(Ordering::Acquire), Ordering::Release);
103+ }
104+ ring.pop(dst, want)
105+}
106+
94107 /// Everything the RT thread and the caller's thread both touch.
95108 struct Shared {
96109 ring: Ring,
@@ -100,6 +113,8 @@ struct Shared {
100113 ready: AtomicBool,
101114 /// Stream died (daemon gone, node removed); every later write fails.
102115 dead: AtomicBool,
116+ /// Asked for by `ao_flush`, honoured by the next process callback.
117+ flush: AtomicBool,
103118 underruns: AtomicU64,
104119 }
105120
@@ -178,7 +193,7 @@ fn run(
178193 // the pause and a future seek all have to wait out.
179194 let frames = (slice.len() / stride).min(QUANTUM as usize);
180195 let want = frames * channels;
181- let got = shared.ring.pop(slice, want);
196+ let got = consume(&shared.flush, &shared.ring, slice, want);
182197 if got < want {
183198 // Underrun: silence rather than stale samples, and
184199 // 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 {
323338 position: AtomicI64::new(-1),
324339 ready: AtomicBool::new(false),
325340 dead: AtomicBool::new(false),
341+ flush: AtomicBool::new(false),
326342 underruns: AtomicU64::new(0),
327343 });
328344 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
414430 .unwrap_or(-1)
415431 }
416432
433+/// Drops every queued sample, so playback resumes from whatever is written
434+/// next: what a seek needs. Takes effect on the next process callback (or the
435+/// first one after a resume), and leaves the played position alone -- the
436+/// device keeps counting, the caller re-bases against it.
437+/// 0 on success, negative on failure.
438+///
439+/// # Safety
440+/// `session` must come from [`ao_open`].
441+#[unsafe(no_mangle)]
442+pub unsafe extern "C" fn ao_flush(session: *mut c_void) -> i32 {
443+ catch_unwind(AssertUnwindSafe(|| {
444+ if session.is_null() {
445+ return -1;
446+ }
447+ // SAFETY: caller-guaranteed live session.
448+ let session = unsafe { &*(session as *const Session) };
449+ session.shared.flush.store(true, Ordering::Release);
450+ 0
451+ }))
452+ .unwrap_or(-1)
453+}
454+
417455 /// Stops playback and releases the session. Safe to call with null.
418456 ///
419457 /// # Safety
@@ -430,7 +468,7 @@ pub unsafe extern "C" fn ao_close(session: *mut c_void) {
430468
431469 #[cfg(test)]
432470 mod tests {
433- use super::Ring;
471+ use super::{AtomicBool, Ordering, Ring, consume};
434472
435473 #[test]
436474 fn ring_wraps_fills_and_starves() {
@@ -452,4 +490,28 @@ mod tests {
452490 // Empty ring starves instead of replaying stale samples.
453491 assert_eq!(ring.pop(&mut out, 4), 0);
454492 }
493+
494+ #[test]
495+ fn flush_drops_queued_samples() {
496+ let ring = Ring::new(4);
497+ let flush = AtomicBool::new(false);
498+ let mut out = [0u8; 16];
499+
500+ // No flush pending: an ordinary pop.
501+ assert_eq!(ring.push(&[1.0, 2.0]), 2);
502+ assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
503+
504+ // Flushed: the queued samples are gone, so the callback gets nothing
505+ // and fills silence, and the flag is one-shot.
506+ assert_eq!(ring.push(&[3.0, 4.0]), 2);
507+ flush.store(true, Ordering::Release);
508+ assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
509+ assert!(!flush.load(Ordering::Acquire));
510+
511+ // Ring is empty, not corrupt: the next write plays as usual.
512+ assert_eq!(ring.push(&[5.0, 6.0, 7.0, 8.0]), 4);
513+ assert_eq!(consume(&flush, &ring, &mut out, 4), 4);
514+ assert_eq!(&out[..4], &5.0f32.to_le_bytes());
515+ assert_eq!(&out[12..16], &8.0f32.to_le_bytes());
516+ }
455517 }
crates/engine-hw/src/lib.rsmodified+29 -8
@@ -49,6 +49,8 @@ struct Session {
4949 pending: Vec<u8>,
5050 timestamp: u64,
5151 flushed: bool,
52+ /// Pictures still to be decoded and thrown away to land on a seek target.
53+ skip: u32,
5254 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
5355 /// which is exactly why the pointers are only valid until the next call.
5456 out: Vec<u8>,
@@ -148,12 +150,23 @@ impl Session {
148150 pending: Vec::new(),
149151 timestamp: 0,
150152 flushed: false,
153+ skip: 0,
151154 out: Vec::new(),
152155 luma: 0,
153156 chroma: 0,
154157 })
155158 }
156159
160+ /// As [`Session::open`], but positioned so the first picture handed out is
161+ /// sample `target_sample` (1-based): decode restarts at the sync sample at
162+ /// or before it and the pictures in between are dropped unread.
163+ fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
164+ let mut session = Self::open(path)?;
165+ let sync = session.demuxer.seek_to_sync_at_or_before(target_sample);
166+ session.skip = target_sample.saturating_sub(sync);
167+ Some(session)
168+ }
169+
157170 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
158171 fn pump(&mut self) -> Result<bool, String> {
159172 let mut stalls = 0u32;
@@ -175,6 +188,12 @@ impl Session {
175188 }
176189 }
177190 if let Some(handle) = self.ready.pop_front() {
191+ // Seek discards: dropping the handle skips the `vaGetImage`
192+ // read-back (~1.2 ms/picture) and frees its pool buffer.
193+ if self.skip > 0 {
194+ self.skip -= 1;
195+ continue;
196+ }
178197 self.emit(handle);
179198 return Ok(true);
180199 }
@@ -283,13 +302,15 @@ impl Session {
283302 }
284303 }
285304
286-/// Opens `path` for hardware decode. Returns null on any failure at all: no
287-/// libva runtime, no render node, unsupported profile, unreadable file.
305+/// Opens `path` for hardware decode, positioned so the first
306+/// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
307+/// the start of the stream). Returns null on any failure at all: no libva
308+/// runtime, no render node, unsupported profile, unreadable file.
288309 ///
289310 /// # Safety
290311 /// `path` must be a valid NUL-terminated C string.
291312 #[unsafe(no_mangle)]
292-pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void {
313+pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> *mut c_void {
293314 catch_unwind(AssertUnwindSafe(|| {
294315 if path.is_null() {
295316 return std::ptr::null_mut();
@@ -299,7 +320,7 @@ pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void {
299320 let Ok(path) = path.to_str() else {
300321 return std::ptr::null_mut();
301322 };
302- match Session::open(Path::new(path)) {
323+ match Session::open_at(Path::new(path), target_sample) {
303324 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
304325 None => std::ptr::null_mut(),
305326 }
@@ -310,7 +331,7 @@ pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void {
310331 /// Fills `out` with stream metadata. 0 on success, negative on failure.
311332 ///
312333 /// # Safety
313-/// `session` must come from [`vh_open`] and `out` must be writable.
334+/// `session` must come from [`vh_open_at`] and `out` must be writable.
314335 #[unsafe(no_mangle)]
315336 pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 {
316337 catch_unwind(AssertUnwindSafe(|| {
@@ -334,7 +355,7 @@ pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32
334355 /// stream, negative on error. Plane pointers stay valid until the next call.
335356 ///
336357 /// # Safety
337-/// `session` must come from [`vh_open`] and `out` must be writable.
358+/// `session` must come from [`vh_open_at`] and `out` must be writable.
338359 #[unsafe(no_mangle)]
339360 pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 {
340361 catch_unwind(AssertUnwindSafe(|| {
@@ -362,12 +383,12 @@ pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame)
362383 /// Releases a session. Safe to call with null.
363384 ///
364385 /// # Safety
365-/// `session` must come from [`vh_open`] and must not be used afterwards.
386+/// `session` must come from [`vh_open_at`] and must not be used afterwards.
366387 #[unsafe(no_mangle)]
367388 pub unsafe extern "C" fn vh_close(session: *mut c_void) {
368389 let _ = catch_unwind(AssertUnwindSafe(|| {
369390 if !session.is_null() {
370- // SAFETY: pointer came from `Box::into_raw` in `vh_open`.
391+ // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.
371392 drop(unsafe { Box::from_raw(session as *mut Session) });
372393 }
373394 }));
crates/engine/src/ao.rsmodified+11 -0
@@ -18,6 +18,7 @@ struct Plugin {
1818 write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize,
1919 position: unsafe extern "C" fn(*mut c_void) -> i64,
2020 set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32,
21+ flush: unsafe extern "C" fn(*mut c_void) -> i32,
2122 close: unsafe extern "C" fn(*mut c_void),
2223 // Never dropped (lives in a static), so the fn pointers above stay valid.
2324 _lib: Library,
@@ -54,6 +55,9 @@ fn load() -> Option<Plugin> {
5455 write: *lib.get(b"ao_write\0").ok()?,
5556 position: *lib.get(b"ao_position\0").ok()?,
5657 set_active: *lib.get(b"ao_set_active\0").ok()?,
58+ // Required, so a plugin predating seek is rejected whole
59+ // and we play muted rather than half-working.
60+ flush: *lib.get(b"ao_flush\0").ok()?,
5761 close: *lib.get(b"ao_close\0").ok()?,
5862 _lib: lib,
5963 })
@@ -118,6 +122,13 @@ impl AoSession {
118122 // SAFETY: `handle` came from `ao_open` and is still open.
119123 unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 }
120124 }
125+
126+ /// Drops everything still queued, so the next samples written play right
127+ /// away -- what a seek needs. The played position keeps counting.
128+ pub fn flush(&self) -> bool {
129+ // SAFETY: `handle` came from `ao_open` and is still open.
130+ unsafe { (self.plugin.flush)(self.handle) == 0 }
131+ }
121132 }
122133
123134 impl Drop for AoSession {
crates/engine/src/audio.rsmodified+174 -28
@@ -23,6 +23,10 @@ const DEFAULT_PRIMING: u64 = 1024;
2323 /// An edit list entry that only shifts the timeline, carrying no media.
2424 const EMPTY_EDIT: u64 = u32::MAX as u64;
2525
26+/// Packets decoded and thrown away ahead of a seek target: one for the MDCT
27+/// overlap-add that reconstructs the target packet, one to warm the decoder.
28+const PRE_ROLL: u32 = 2;
29+
2630 #[derive(Debug, Clone, Copy, PartialEq)]
2731 pub struct AudioMeta {
2832 pub sample_rate: u32,
@@ -48,6 +52,16 @@ impl AudioSession {
4852 /// audio, which is a valid session; `Err` is a real failure.
4953 pub fn open(
5054 path: impl AsRef<Path>,
55+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
56+ Self::open_at(path, 0.0)
57+ }
58+
59+ /// Like [`open`](Self::open) but the first chunk starts at `start_secs` on
60+ /// the audible timeline; `start_sample` stays absolute from audible zero, so
61+ /// the output is the tail of a full run. Past the end yields no chunks.
62+ pub fn open_at(
63+ path: impl AsRef<Path>,
64+ start_secs: f64,
5165 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
5266 let file = File::open(path.as_ref())?;
5367 let size = file.metadata()?.len();
@@ -70,14 +84,20 @@ impl AudioSession {
7084 let channels: u16 = match track.channel_config()? {
7185 ChannelConfig::Mono => 1,
7286 ChannelConfig::Stereo => 2,
73- other => return Err(format!("unsupported channel layout: {other:?} (max stereo)").into()),
87+ other => {
88+ return Err(format!("unsupported channel layout: {other:?} (max stereo)").into());
89+ }
7490 };
7591
7692 let track_id = track.track_id();
7793 let sample_rate = track.sample_freq_index()?.freq();
7894 let priming = priming_samples(track, sample_rate);
79- let total_samples = scale(track.trak.mdia.mdhd.duration, sample_rate, track.timescale())
80- .map(|d| d.saturating_sub(priming));
95+ let total_samples = scale(
96+ track.trak.mdia.mdhd.duration,
97+ sample_rate,
98+ track.timescale(),
99+ )
100+ .map(|d| d.saturating_sub(priming));
81101
82102 let mut params = AudioCodecParameters::new();
83103 params
@@ -86,6 +106,28 @@ impl AudioSession {
86106 .with_extra_data(audio_specific_config(track)?);
87107 let decoder = AacDecoder::try_new(&params, &AudioDecoderOptions::default())?;
88108
109+ // Where to land, in media samples (priming included, so it is directly
110+ // comparable to decoded position), and which packet holds it.
111+ let media_target = (start_secs * f64::from(sample_rate)) as u64 + priming;
112+ let target_ts = unscale(media_target, sample_rate, track.timescale());
113+ // Two packets of pre-roll: AAC-LC's MDCT overlap-add needs the previous
114+ // packet to cancel aliasing, plus one more to warm the decoder up. Their
115+ // output is discarded below, so this only costs decode time.
116+ let (start_id, start_ts) = packet_at(
117+ track
118+ .trak
119+ .mdia
120+ .minf
121+ .stbl
122+ .stts
123+ .entries
124+ .iter()
125+ .map(|e| (e.sample_count, e.sample_delta)),
126+ target_ts,
127+ PRE_ROLL,
128+ );
129+ let start_pos = scale(start_ts, sample_rate, track.timescale()).unwrap_or(0);
130+
89131 let sample_count = reader.sample_count(track_id)?;
90132 let meta = AudioMeta {
91133 sample_rate,
@@ -96,17 +138,22 @@ impl AudioSession {
96138 // this bound is ~0.75 s of lookahead — enough to ride out decode jitter
97139 // without making a pause take a second to bite.
98140 let (tx, rx) = sync_channel(32);
99- thread::Builder::new().name("audio-decode".into()).spawn(move || {
100- run(Worker {
101- reader,
102- decoder,
103- track_id,
104- sample_count,
105- channels: channels as usize,
106- priming,
107- tx,
108- })
109- })?;
141+ thread::Builder::new()
142+ .name("audio-decode".into())
143+ .spawn(move || {
144+ run(Worker {
145+ reader,
146+ decoder,
147+ track_id,
148+ sample_count,
149+ channels: channels as usize,
150+ priming,
151+ start_id,
152+ start_pos,
153+ media_target,
154+ tx,
155+ })
156+ })?;
110157 Ok(Some((meta, rx)))
111158 }
112159 }
@@ -161,6 +208,56 @@ fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option<u64> {
161208 (timescale != 0).then(|| value * u64::from(sample_rate) / timescale)
162209 }
163210
211+/// Inverse of [`scale`]: samples-per-channel back into the track timescale.
212+fn unscale(samples: u64, sample_rate: u32, timescale: u32) -> u64 {
213+ match sample_rate {
214+ 0 => 0,
215+ rate => samples * u64::from(timescale) / u64::from(rate),
216+ }
217+}
218+
219+/// The 1-based packet holding media time `target_ts`, walked back by `pre_roll`
220+/// packets, plus that packet's own start time. Inverse of the mp4 crate's
221+/// private `sample_time` walk over stts (`track.rs:475`); its `SttsEntry` is
222+/// unnameable outside the crate, hence the `(sample_count, sample_delta)` pairs.
223+///
224+/// ponytail: the walk-back is clamped to the start of the containing stts entry
225+/// rather than crossing into the previous one, so a target within `pre_roll`
226+/// packets of an entry boundary gets less pre-roll. AAC packets are uniformly
227+/// 1024 frames (one entry per track), so this cannot fire here; upgrade path is
228+/// carrying the previous entry's delta through the walk.
229+fn packet_at(
230+ entries: impl IntoIterator<Item = (u32, u32)>,
231+ target_ts: u64,
232+ pre_roll: u32,
233+) -> (u32, u64) {
234+ let mut first_id = 1u32;
235+ let mut elapsed = 0u64;
236+ let mut last = (1u32, 0u64);
237+ for (count, delta) in entries {
238+ let span = u64::from(count) * u64::from(delta);
239+ let index = if target_ts < elapsed + span && delta != 0 {
240+ ((target_ts - elapsed) / u64::from(delta)) as u32
241+ } else {
242+ // Past this entry: remember its last packet in case the target runs
243+ // past the end of the track entirely.
244+ last = (
245+ first_id + count.saturating_sub(1),
246+ elapsed + span.saturating_sub(u64::from(delta)),
247+ );
248+ first_id += count;
249+ elapsed += span;
250+ continue;
251+ };
252+ let index = index - index.min(pre_roll);
253+ return (
254+ first_id + index,
255+ elapsed + u64::from(index) * u64::from(delta),
256+ );
257+ }
258+ last
259+}
260+
164261 struct Worker {
165262 reader: Mp4Reader<BufReader<File>>,
166263 decoder: AacDecoder,
@@ -168,15 +265,21 @@ struct Worker {
168265 sample_count: u32,
169266 channels: usize,
170267 priming: u64,
268+ /// First packet to feed the decoder, 1-based; includes the pre-roll.
269+ start_id: u32,
270+ /// Media position of `start_id`'s first frame, in samples-per-channel.
271+ start_pos: u64,
272+ /// Media position of the first frame to emit. Everything decoded before it
273+ /// is pre-roll, priming, or seek overshoot, and gets dropped.
274+ media_target: u64,
171275 tx: SyncSender<AudioChunk>,
172276 }
173277
174278 fn run(mut w: Worker) {
175279 let mut interleaved = Vec::new();
176- let mut to_skip = w.priming;
177- let mut emitted = 0u64;
280+ let mut pos = w.start_pos;
178281
179- for id in 1..=w.sample_count {
282+ for id in w.start_id..=w.sample_count {
180283 let sample = match w.reader.read_sample(w.track_id, id) {
181284 Ok(Some(sample)) => sample,
182285 Ok(None) => break,
@@ -199,22 +302,24 @@ fn run(mut w: Worker) {
199302 }
200303 };
201304 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
305+ let next = pos + (interleaved.len() / w.channels) as u64;
202306
203- // Priming frames are encoder ramp-up, not audio: drop them so the first
204- // sample the caller sees is the first audible one.
205- if to_skip > 0 {
206- let drop = to_skip.min((interleaved.len() / w.channels) as u64);
207- interleaved.drain(..drop as usize * w.channels);
208- to_skip -= drop;
209- if interleaved.is_empty() {
210- continue;
211- }
307+ // Everything before the target is encoder priming and/or decoder
308+ // pre-roll, not audio the caller asked for: drop it, splitting the
309+ // packet that straddles the target.
310+ if next <= w.media_target {
311+ pos = next;
312+ continue;
313+ }
314+ if pos < w.media_target {
315+ interleaved.drain(..(w.media_target - pos) as usize * w.channels);
316+ pos = w.media_target;
212317 }
213318 let chunk = AudioChunk {
214- start_sample: emitted,
319+ start_sample: pos - w.priming,
215320 samples: std::mem::take(&mut interleaved),
216321 };
217- emitted += (chunk.samples.len() / w.channels) as u64;
322+ pos = next;
218323 if w.tx.send(chunk).is_err() {
219324 break; // consumer went away
220325 }
@@ -223,6 +328,47 @@ fn run(mut w: Worker) {
223328
224329 #[cfg(test)]
225330 mod tests {
331+ use super::{PRE_ROLL, packet_at};
332+
333+ /// A real AAC track: one stts entry, N packets of 1024.
334+ fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> {
335+ [(count, 1024)]
336+ }
337+
338+ #[test]
339+ fn packet_at_walks_back_by_the_pre_roll() {
340+ // Packet 1 covers [0, 1024); the target at 2 s is packet 87 (89088..).
341+ assert_eq!(packet_at(aac(200), 88_200, 0), (87, 88_064));
342+ assert_eq!(packet_at(aac(200), 88_200, PRE_ROLL), (85, 86_016));
343+ // Exactly on a packet boundary is the start of that packet, not the end
344+ // of the previous one.
345+ assert_eq!(packet_at(aac(200), 2048, 0), (3, 2048));
346+ }
347+
348+ #[test]
349+ fn packet_at_clamps_both_ends() {
350+ // Head: no room for the walk-back, and packet ids are 1-based.
351+ assert_eq!(packet_at(aac(200), 0, PRE_ROLL), (1, 0));
352+ assert_eq!(packet_at(aac(200), 1500, PRE_ROLL), (1, 0));
353+ // Past the end: the last packet, so the worker decodes ~nothing.
354+ assert_eq!(packet_at(aac(200), 10_000_000, PRE_ROLL), (200, 203_776));
355+ // Degenerate boxes must not panic or wrap.
356+ assert_eq!(packet_at([], 5000, PRE_ROLL), (1, 0));
357+ assert_eq!(packet_at([(4u32, 0u32)], 5000, PRE_ROLL), (4, 0));
358+ }
359+
360+ #[test]
361+ fn packet_at_crosses_stts_entries() {
362+ // 10 packets of 1024 then 10 of 512, so the second entry starts at 10240
363+ // with packet 11.
364+ let entries = [(10u32, 1024u32), (10, 512)];
365+ assert_eq!(packet_at(entries, 12_500, 0), (15, 12_288));
366+ assert_eq!(packet_at(entries, 12_500, PRE_ROLL), (13, 11_264));
367+ // The ponytail clamp: on the first packet of the second entry the
368+ // walk-back stops there instead of stepping into the first entry.
369+ assert_eq!(packet_at(entries, 10_500, PRE_ROLL), (11, 10_240));
370+ }
371+
226372 #[test]
227373 fn asc_round_trips_aac_lc_44100_stereo() {
228374 // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo).
crates/engine/src/decode.rsmodified+50 -11
@@ -2,6 +2,8 @@
22 //! thread (the UI thread) never blocks on decode and memory stays capped.
33
44 use std::path::{Path, PathBuf};
5+use std::sync::Arc;
6+use std::sync::atomic::{AtomicBool, Ordering};
57 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
68 use std::thread;
79
@@ -28,19 +30,33 @@ impl DecodeSession {
2830 /// yields frames as the worker decodes them. The worker stops when the
2931 /// receiver is dropped, at end of stream, or on the first decode error.
3032 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
33+ let (meta, rx, _cancel) = Self::open_at(path, 0)?;
34+ Ok((meta, rx))
35+ }
36+
37+ /// As [`DecodeSession::open`], but the first frame delivered is
38+ /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
39+ /// Setting the returned flag stops the worker at its next access unit,
40+ /// which is how a caller abandons a session it no longer wants to drain.
41+ pub fn open_at(
42+ path: impl AsRef<Path>,
43+ start_frame: u32,
44+ ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
3145 let path = path.as_ref().to_path_buf();
3246 let (meta, demuxer) = Demuxer::open(&path)?;
3347 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
3448 // decoder run ahead of the display without limit.
3549 let (tx, rx) = sync_channel(2);
50+ let cancel = Arc::new(AtomicBool::new(false));
51+ let worker_cancel = Arc::clone(&cancel);
3652 thread::Builder::new()
3753 .name("decode".into())
3854 .spawn(move || {
3955 // The plugin has to be opened on the thread that uses it: its
4056 // VA-API state is not `Send`-safe across a later hand-off.
41- if let Some(hw) = open_hw(&path) {
57+ if let Some(hw) = open_hw(&path, start_frame) {
4258 eprintln!("decode backend: hardware (VA-API plugin)");
43- if run_hw(hw, &tx) {
59+ if run_hw(hw, &tx, start_frame, &worker_cancel) {
4460 return;
4561 }
4662 // A driver that opens but cannot decode a single frame is
@@ -48,26 +64,38 @@ impl DecodeSession {
4864 eprintln!("hardware decode failed before any frame, falling back to software");
4965 }
5066 eprintln!("decode backend: software (rusty_h264)");
51- run(demuxer, tx)
67+ run(demuxer, tx, start_frame, &worker_cancel)
5268 })?;
53- Ok((meta, rx))
69+ Ok((meta, rx, cancel))
5470 }
5571 }
5672
5773 /// `None` when the software path must be used: forced by `VE_SW=1`, or the
5874 /// plugin is absent/broken/unable to open this particular file.
59-fn open_hw(path: &PathBuf) -> Option<HwSession> {
75+fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
6076 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
6177 return None;
6278 }
63- HwSession::open(path)
79+ HwSession::open_at(path, start_frame)
6480 }
6581
6682 /// Returns whether the session was handled; `false` only when hardware decode
6783 /// failed without emitting a single frame, so software can still take over.
68-fn run_hw(mut hw: HwSession, tx: &SyncSender<Frame>) -> bool {
69- let mut index = 0u32;
84+///
85+/// The plugin already positioned itself at `start_frame`, so indices are
86+/// counted from there (a stream whose very first sample is not a sync sample
87+/// cannot be decoded from its start at all, and is not accounted for).
88+fn run_hw(
89+ mut hw: HwSession,
90+ tx: &SyncSender<Frame>,
91+ start_frame: u32,
92+ cancel: &AtomicBool,
93+) -> bool {
94+ let mut index = start_frame;
7095 loop {
96+ if cancel.load(Ordering::Relaxed) {
97+ return true;
98+ }
7199 match hw.next_frame() {
72100 Ok(Some((y, u, v, width, height))) => {
73101 let frame = Frame {
@@ -83,7 +111,7 @@ fn run_hw(mut hw: HwSession, tx: &SyncSender<Frame>) -> bool {
83111 }
84112 Ok(None) => return true,
85113 Err(e) => {
86- if index == 0 {
114+ if index == start_frame {
87115 return false;
88116 }
89117 eprintln!("hardware decode error at frame {index}: {e}");
@@ -93,13 +121,20 @@ fn run_hw(mut hw: HwSession, tx: &SyncSender<Frame>) -> bool {
93121 }
94122 }
95123
96-fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>) {
124+fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>, start_frame: u32, cancel: &AtomicBool) {
97125 let mut decoder = Decoder::new();
98- let mut index = 0u32;
126+ // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at
127+ // a sync sample, so pictures between it and `start_frame` are decoded (the
128+ // target frame references them) but never converted or sent.
129+ let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1));
130+ let mut index = sync - 1;
99131
100132 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
101133 // reordering streams need POC-sorted output before display.
102134 loop {
135+ if cancel.load(Ordering::Relaxed) {
136+ break;
137+ }
103138 let au = match demuxer.next_access_unit() {
104139 Ok(Some(au)) => au,
105140 Ok(None) => break,
@@ -116,6 +151,10 @@ fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>) {
116151 break;
117152 }
118153 };
154+ if index < start_frame {
155+ index += 1;
156+ continue;
157+ }
119158 let frame = Frame {
120159 index,
121160 width: yuv.width as u32,
crates/engine/src/demux.rsmodified+45 -0
@@ -22,6 +22,9 @@ pub struct Demuxer {
2222 sample_count: u32,
2323 /// Annex-B SPS+PPS, re-injected ahead of every sync sample.
2424 parameter_sets: Vec<u8>,
25+ /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
26+ /// at all, i.e. every sample is a sync sample.
27+ sync_samples: Vec<u32>,
2528 next_sample: u32,
2629 }
2730
@@ -49,6 +52,15 @@ impl Demuxer {
4952 parameter_sets.extend_from_slice(track.sequence_parameter_set()?);
5053 parameter_sets.extend_from_slice(&START_CODE);
5154 parameter_sets.extend_from_slice(track.picture_parameter_set()?);
55+ let sync_samples = track
56+ .trak
57+ .mdia
58+ .minf
59+ .stbl
60+ .stss
61+ .as_ref()
62+ .map(|stss| stss.entries.clone())
63+ .unwrap_or_default();
5264
5365 let sample_count = reader.sample_count(track_id)?;
5466 Ok((
@@ -61,6 +73,7 @@ impl Demuxer {
6173 track_id,
6274 sample_count,
6375 parameter_sets,
76+ sync_samples,
6477 next_sample: 1, // sample ids are 1-based
6578 },
6679 ))
@@ -84,6 +97,29 @@ impl Demuxer {
8497 append_annex_b(&sample.bytes, &mut au)?;
8598 Ok(Some(au))
8699 }
100+
101+ /// Rewinds/forwards the read cursor to the latest sync sample at or before
102+ /// `sample_id` (1-based), which is the earliest point a decoder can start
103+ /// from and still reach `sample_id`. Returns the sample it landed on.
104+ pub fn seek_to_sync_at_or_before(&mut self, sample_id: u32) -> u32 {
105+ let target = sample_id.clamp(1, self.sample_count.max(1));
106+ let chosen = sync_at_or_before(&self.sync_samples, target);
107+ self.next_sample = chosen;
108+ chosen
109+ }
110+}
111+
112+/// Largest entry of the ascending sync table that is `<= sample_id`. An empty
113+/// table means every sample is a sync sample. When `sample_id` sits before the
114+/// first sync sample there is nothing decodable earlier, so that one wins.
115+fn sync_at_or_before(syncs: &[u32], sample_id: u32) -> u32 {
116+ if syncs.is_empty() {
117+ return sample_id;
118+ }
119+ match syncs.partition_point(|&s| s <= sample_id) {
120+ 0 => syncs[0],
121+ i => syncs[i - 1],
122+ }
87123 }
88124
89125 /// avcC length-prefixed NALs -> Annex-B. Assumes a 4-byte length prefix, which
@@ -123,6 +159,15 @@ mod tests {
123159 assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]);
124160 }
125161
162+ #[test]
163+ fn sync_lookup() {
164+ assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs");
165+ assert_eq!(sync_at_or_before(&[1, 31, 61], 31), 31, "exact hit");
166+ assert_eq!(sync_at_or_before(&[1, 31, 61], 45), 31, "between syncs");
167+ assert_eq!(sync_at_or_before(&[5, 31], 2), 5, "before the first sync");
168+ assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last");
169+ }
170+
126171 #[test]
127172 fn rejects_misparse() {
128173 assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err());
crates/engine/src/hw.rsmodified+14 -5
@@ -53,7 +53,7 @@ impl Default for VhFrame {
5353 }
5454
5555 struct Plugin {
56- open: unsafe extern "C" fn(*const c_char) -> *mut c_void,
56+ open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,
5757 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,
5858 next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,
5959 close: unsafe extern "C" fn(*mut c_void),
@@ -88,7 +88,7 @@ fn load() -> Option<Plugin> {
8888 let plugin = unsafe {
8989 (|| {
9090 Some(Plugin {
91- open: *lib.get(b"vh_open\0").ok()?,
91+ open_at: *lib.get(b"vh_open_at\0").ok()?,
9292 meta: *lib.get(b"vh_meta\0").ok()?,
9393 next_frame: *lib.get(b"vh_next_frame\0").ok()?,
9494 close: *lib.get(b"vh_close\0").ok()?,
@@ -113,10 +113,19 @@ impl HwSession {
113113 /// Probes the plugin against this very file: success means the driver,
114114 /// the render node and the stream's profile are all usable.
115115 pub fn open(path: &Path) -> Option<Self> {
116+ Self::open_at(path, 0)
117+ }
118+
119+ /// As [`HwSession::open`], but the first [`HwSession::next_frame`] returns
120+ /// display index `start_frame`; earlier pictures are decoded and dropped
121+ /// inside the plugin, without the read-back copy.
122+ pub fn open_at(path: &Path, start_frame: u32) -> Option<Self> {
116123 let plugin = plugin()?;
117124 let c_path = CString::new(path.as_os_str().as_encoded_bytes()).ok()?;
125+ // Sample ids are 1-based, frame indices 0-based.
126+ let target_sample = start_frame.saturating_add(1);
118127 // SAFETY: `c_path` is a valid NUL-terminated string alive for the call.
119- let handle = unsafe { (plugin.open)(c_path.as_ptr()) };
128+ let handle = unsafe { (plugin.open_at)(c_path.as_ptr(), target_sample) };
120129 if handle.is_null() {
121130 return None;
122131 }
@@ -125,7 +134,7 @@ impl HwSession {
125134
126135 pub fn meta(&self) -> Option<VhMeta> {
127136 let mut meta = VhMeta::default();
128- // SAFETY: `handle` came from `vh_open` and is still open.
137+ // SAFETY: `handle` came from `vh_open_at` and is still open.
129138 if unsafe { (self.plugin.meta)(self.handle, &mut meta) } < 0 {
130139 return None;
131140 }
@@ -170,7 +179,7 @@ impl HwSession {
170179
171180 impl Drop for HwSession {
172181 fn drop(&mut self) {
173- // SAFETY: `handle` came from `vh_open` and is closed exactly once.
182+ // SAFETY: `handle` came from `vh_open_at` and is closed exactly once.
174183 unsafe { (self.plugin.close)(self.handle) }
175184 }
176185 }
crates/engine/src/lib.rsmodified+1 -1
@@ -11,9 +11,9 @@ pub mod playback;
1111
1212 pub use audio::{AudioChunk, AudioMeta, AudioSession};
1313 pub use clock::PlaybackClock;
14-pub use playback::PlaybackSession;
1514 pub use decode::{DecodeSession, Frame};
1615 pub use demux::VideoMeta;
16+pub use playback::PlaybackSession;
1717
1818 /// Boxed error; the engine has few failure modes and every one of them is fatal
1919 /// to the session, so a message is all a caller can act on.
crates/engine/src/playback.rsmodified+2 -1
@@ -159,7 +159,8 @@ impl PlaybackSession {
159159 // no jump, and this branch cannot be reached again.
160160 self.clock.switch_to_wall();
161161 } else {
162- self.clock.set_audio_position(position as u64, audio.sample_rate);
162+ self.clock
163+ .set_audio_position(position as u64, audio.sample_rate);
163164 }
164165 }
165166 }
crates/engine/tests/ao_output.rsmodified+4 -1
@@ -82,7 +82,10 @@ fn plays_and_tracks_position() {
8282 assert!(ao.set_active(true), "resume rejected");
8383 std::thread::sleep(Duration::from_millis(200));
8484 let resumed = ao.position().expect("position went unknown");
85- assert!(resumed > paused, "clock did not resume: {paused} -> {resumed}");
85+ assert!(
86+ resumed > paused,
87+ "clock did not resume: {paused} -> {resumed}"
88+ );
8689 }
8790
8891 /// No reachable daemon must fail the open cleanly and quickly, never hang.
crates/engine/tests/audio_decode.rsmodified+13 -3
@@ -48,7 +48,11 @@ fn decodes_av_mp4_audio() {
4848 // d. no gaps, no overlaps.
4949 assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start");
5050 assert!(!chunk.samples.is_empty(), "empty chunk {chunks}");
51- assert_eq!(chunk.samples.len() % 2, 0, "partial frame in chunk {chunks}");
51+ assert_eq!(
52+ chunk.samples.len() % 2,
53+ 0,
54+ "partial frame in chunk {chunks}"
55+ );
5256 next_sample += (chunk.samples.len() / 2) as u64;
5357 left.extend(chunk.samples.iter().step_by(2));
5458 right.extend(chunk.samples[1..].iter().step_by(2));
@@ -81,9 +85,15 @@ fn decodes_av_mp4_audio() {
8185
8286 // Priming trimmed: the sine starts at a rising zero crossing, and audio is
8387 // present immediately rather than after a silent or garbage run-in.
84- assert!(left[0].abs() < 0.05, "first sample {} not near zero", left[0]);
88+ assert!(
89+ left[0].abs() < 0.05,
90+ "first sample {} not near zero",
91+ left[0]
92+ );
8593 assert!(left[1] > 0.0, "first sine quarter is not rising");
86- let head_peak = left[..FRAME as usize].iter().fold(0f32, |m, s| m.max(s.abs()));
94+ let head_peak = left[..FRAME as usize]
95+ .iter()
96+ .fold(0f32, |m, s| m.max(s.abs()));
8797 assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}");
8898
8999 eprintln!(
crates/engine/tests/audio_seek.rsadded+111 -0
@@ -0,0 +1,111 @@
1+//! `AudioSession::open_at` must produce exactly the tail of a full run: same
2+//! samples, same absolute `start_sample` numbering, no gaps at the splice.
3+
4+use std::path::PathBuf;
5+
6+use engine::audio::{AudioChunk, AudioSession};
7+
8+const RATE: u32 = 44100;
9+const CHANNELS: usize = 2;
10+
11+fn asset(name: &str) -> PathBuf {
12+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
13+ .join("../../assets")
14+ .join(name)
15+}
16+
17+/// Drains a session into one flat interleaved buffer, checking as it goes that
18+/// chunks are contiguous and that the first one lands on `want_start`.
19+fn drain(start_secs: f64, want_start: u64) -> Vec<f32> {
20+ let (meta, rx) = AudioSession::open_at(asset("test_av.mp4"), start_secs)
21+ .expect("open")
22+ .expect("test_av.mp4 has an audio track");
23+ assert_eq!((meta.sample_rate, meta.channels as usize), (RATE, CHANNELS));
24+
25+ let mut samples = Vec::new();
26+ let mut next = want_start;
27+ for (
28+ i,
29+ AudioChunk {
30+ start_sample,
31+ samples: s,
32+ },
33+ ) in rx.into_iter().enumerate()
34+ {
35+ assert_eq!(start_sample, next, "chunk {i} start at {start_secs}s");
36+ assert!(!s.is_empty(), "empty chunk {i} at {start_secs}s");
37+ next += (s.len() / CHANNELS) as u64;
38+ samples.extend(s);
39+ }
40+ samples
41+}
42+
43+/// Largest per-sample difference, and where it is.
44+fn max_diff(a: &[f32], b: &[f32]) -> (f32, usize) {
45+ a.iter()
46+ .zip(b)
47+ .enumerate()
48+ .map(|(i, (x, y))| ((x - y).abs(), i))
49+ .fold((0.0, 0), |m, d| if d.0 > m.0 { d } else { m })
50+}
51+
52+#[test]
53+fn open_at_zero_matches_open() {
54+ let (mut full, mut at_zero) = (Vec::new(), Vec::new());
55+ for chunk in AudioSession::open(asset("test_av.mp4")).unwrap().unwrap().1 {
56+ full.extend(chunk.samples);
57+ }
58+ for chunk in AudioSession::open_at(asset("test_av.mp4"), 0.0)
59+ .unwrap()
60+ .unwrap()
61+ .1
62+ {
63+ at_zero.extend(chunk.samples);
64+ }
65+ assert_eq!(full.len(), at_zero.len());
66+ assert_eq!(full, at_zero, "open() must be open_at(0.0)");
67+}
68+
69+#[test]
70+fn open_at_two_seconds_is_the_tail_of_a_full_run() {
71+ let full = drain(0.0, 0);
72+ let target = 2 * RATE as u64;
73+ let tail = drain(2.0, target);
74+
75+ let want = &full[target as usize * CHANNELS..];
76+ assert_eq!(tail.len(), want.len(), "seeked run is a different length");
77+ if tail == want {
78+ eprintln!("bit-exact: {} samples", tail.len());
79+ return;
80+ }
81+ // Not bit-exact, and it never will be: perceptual noise substitution draws
82+ // from an LCG seeded once per decoder (symphonia-codec-aac cpe.rs:32,44), so
83+ // a run that skipped 86 packets draws different noise in PNS bands forever.
84+ // The MDCT overlap the pre-roll exists for *is* exact — the first packets
85+ // after the splice match sample for sample.
86+ let (diff, at) = max_diff(&tail, want);
87+ eprintln!("max abs diff {diff:e} at sample {at} of {}", tail.len());
88+ assert!(diff < 1e-3, "max abs diff {diff} at sample {at}");
89+}
90+
91+#[test]
92+fn open_at_mid_first_packet_is_exact() {
93+ // 500 samples in: inside packet 1, before any pre-roll exists to walk back
94+ // to, and it forces the drain-inside-a-chunk trim path.
95+ let full = drain(0.0, 0);
96+ let start = 500u64;
97+ let tail = drain(start as f64 / RATE as f64, start);
98+ let want = &full[start as usize * CHANNELS..];
99+ assert_eq!(tail.len(), want.len());
100+ assert_eq!(tail, want, "no decoder state to diverge from at packet 1");
101+}
102+
103+#[test]
104+fn open_at_past_duration_ends_clean() {
105+ let tail = drain(60.0, 60 * RATE as u64);
106+ assert!(
107+ tail.is_empty(),
108+ "{} samples past the end of a 5 s file",
109+ tail.len()
110+ );
111+}
crates/engine/tests/hw_decode.rsmodified+42 -1
@@ -63,7 +63,10 @@ fn decode_all_hw(name: &str) -> (usize, Vec<u8>) {
6363 #[ignore = "needs libengine_hw.so and a VA-API driver"]
6464 fn rejects_unopenable_files() {
6565 assert!(HwSession::open(Path::new("/definitely/not/here.mp4")).is_none());
66- assert!(HwSession::open(Path::new("/etc/hostname")).is_none(), "not an mp4");
66+ assert!(
67+ HwSession::open(Path::new("/etc/hostname")).is_none(),
68+ "not an mp4"
69+ );
6770 }
6871
6972 #[test]
@@ -82,6 +85,44 @@ fn hardware_decodes_high_profile() {
8285 assert_eq!(count, 150);
8386 }
8487
88+/// Seeking may only change *when* a picture arrives, never the picture: both
89+/// backends must land on bytes identical to a linear decode of the same index.
90+#[test]
91+#[ignore = "needs libengine_hw.so and a VA-API driver"]
92+fn seek_matches_linear() {
93+ const TARGET: u32 = 60;
94+ let path = asset("test_baseline.mp4");
95+
96+ // Software side first, pinned like the test above. SAFETY: --test-threads=1.
97+ unsafe { std::env::set_var("VE_SW", "1") };
98+ let (_, rx) = DecodeSession::open(&path).expect("software open");
99+ let linear = rx
100+ .into_iter()
101+ .find(|f| f.index == TARGET)
102+ .expect("software frame 60")
103+ .bgra;
104+
105+ let start = Instant::now();
106+ let (_, rx, _cancel) = DecodeSession::open_at(&path, TARGET).expect("software open_at");
107+ let seeked = rx.into_iter().next().expect("no frame after software seek");
108+ eprintln!("software seek to {TARGET} took {:?}", start.elapsed());
109+ assert_eq!(seeked.index, TARGET, "first frame after seek is the target");
110+ assert_eq!(seeked.bgra, linear, "software seek != software linear");
111+
112+ let start = Instant::now();
113+ let mut hw = HwSession::open_at(&path, TARGET).expect("no plugin/driver available");
114+ let (y, u, v, w, h) = hw
115+ .next_frame()
116+ .expect("hardware decode")
117+ .expect("no frame after hardware seek");
118+ eprintln!("hardware seek to {TARGET} took {:?}", start.elapsed());
119+ assert_eq!(
120+ i420_to_bgra(y, u, v, w as usize, h as usize),
121+ linear,
122+ "hardware seek != software linear"
123+ );
124+}
125+
85126 /// H.264 8-bit decode is bit-exact by conformance, so the two backends must
86127 /// agree. A mismatch means a driver deviation and is reported, not swallowed.
87128 #[test]