Seek primitives — video open_at, ao_flush, audio open_at
Browse files at this commit96ae36578d67885b35b4a947ae44774d68834c7aParent: 1c1f5e0- feat
- seek primitives — video open_at, ao_flush, audio open_at
14 changed files +565 -68
- crates/app/src/main.rs +5 -7
- crates/engine-audio/src/lib.rs +64 -2
- crates/engine-hw/src/lib.rs +29 -8
- crates/engine/src/ao.rs +11 -0
- crates/engine/src/audio.rs +174 -28
- crates/engine/src/decode.rs +50 -11
- crates/engine/src/demux.rs +45 -0
- crates/engine/src/hw.rs +14 -5
- crates/engine/src/lib.rs +1 -1
- crates/engine/src/playback.rs +2 -1
- crates/engine/tests/ao_output.rs +4 -1
- crates/engine/tests/audio_decode.rs +13 -3
- crates/engine/tests/audio_seek.rs +111 -0
- crates/engine/tests/hw_decode.rs +42 -1
crates/app/src/main.rsmodified+5 -7
| @@ -223,13 +223,11 @@ impl Player { | ||
| 223 | 223 | ) |
| 224 | 224 | .child(transport_glyph(playing)), |
| 225 | 225 | ) |
| 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 | + ))), | |
| 233 | 231 | ) |
| 234 | 232 | // Read-only: no cursor, no hover, no listener -- a clip slice turns |
| 235 | 233 | // this into a scrubber, today it only reports. |
crates/engine-audio/src/lib.rsmodified+64 -2
| @@ -91,6 +91,19 @@ impl Ring { | ||
| 91 | 91 | } |
| 92 | 92 | } |
| 93 | 93 | |
| 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 | + | |
| 94 | 107 | /// Everything the RT thread and the caller's thread both touch. |
| 95 | 108 | struct Shared { |
| 96 | 109 | ring: Ring, |
| @@ -100,6 +113,8 @@ struct Shared { | ||
| 100 | 113 | ready: AtomicBool, |
| 101 | 114 | /// Stream died (daemon gone, node removed); every later write fails. |
| 102 | 115 | dead: AtomicBool, |
| 116 | + /// Asked for by `ao_flush`, honoured by the next process callback. | |
| 117 | + flush: AtomicBool, | |
| 103 | 118 | underruns: AtomicU64, |
| 104 | 119 | } |
| 105 | 120 | |
| @@ -178,7 +193,7 @@ fn run( | ||
| 178 | 193 | // the pause and a future seek all have to wait out. |
| 179 | 194 | let frames = (slice.len() / stride).min(QUANTUM as usize); |
| 180 | 195 | let want = frames * channels; |
| 181 | - let got = shared.ring.pop(slice, want); | |
| 196 | + let got = consume(&shared.flush, &shared.ring, slice, want); | |
| 182 | 197 | if got < want { |
| 183 | 198 | // Underrun: silence rather than stale samples, and |
| 184 | 199 | // 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 { | ||
| 323 | 338 | position: AtomicI64::new(-1), |
| 324 | 339 | ready: AtomicBool::new(false), |
| 325 | 340 | dead: AtomicBool::new(false), |
| 341 | + flush: AtomicBool::new(false), | |
| 326 | 342 | underruns: AtomicU64::new(0), |
| 327 | 343 | }); |
| 328 | 344 | 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 | ||
| 414 | 430 | .unwrap_or(-1) |
| 415 | 431 | } |
| 416 | 432 | |
| 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 | + | |
| 417 | 455 | /// Stops playback and releases the session. Safe to call with null. |
| 418 | 456 | /// |
| 419 | 457 | /// # Safety |
| @@ -430,7 +468,7 @@ pub unsafe extern "C" fn ao_close(session: *mut c_void) { | ||
| 430 | 468 | |
| 431 | 469 | #[cfg(test)] |
| 432 | 470 | mod tests { |
| 433 | - use super::Ring; | |
| 471 | + use super::{AtomicBool, Ordering, Ring, consume}; | |
| 434 | 472 | |
| 435 | 473 | #[test] |
| 436 | 474 | fn ring_wraps_fills_and_starves() { |
| @@ -452,4 +490,28 @@ mod tests { | ||
| 452 | 490 | // Empty ring starves instead of replaying stale samples. |
| 453 | 491 | assert_eq!(ring.pop(&mut out, 4), 0); |
| 454 | 492 | } |
| 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 | + } | |
| 455 | 517 | } |
crates/engine-hw/src/lib.rsmodified+29 -8
| @@ -49,6 +49,8 @@ struct Session { | ||
| 49 | 49 | pending: Vec<u8>, |
| 50 | 50 | timestamp: u64, |
| 51 | 51 | flushed: bool, |
| 52 | + /// Pictures still to be decoded and thrown away to land on a seek target. | |
| 53 | + skip: u32, | |
| 52 | 54 | /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame, |
| 53 | 55 | /// which is exactly why the pointers are only valid until the next call. |
| 54 | 56 | out: Vec<u8>, |
| @@ -148,12 +150,23 @@ impl Session { | ||
| 148 | 150 | pending: Vec::new(), |
| 149 | 151 | timestamp: 0, |
| 150 | 152 | flushed: false, |
| 153 | + skip: 0, | |
| 151 | 154 | out: Vec::new(), |
| 152 | 155 | luma: 0, |
| 153 | 156 | chroma: 0, |
| 154 | 157 | }) |
| 155 | 158 | } |
| 156 | 159 | |
| 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 | + | |
| 157 | 170 | /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF. |
| 158 | 171 | fn pump(&mut self) -> Result<bool, String> { |
| 159 | 172 | let mut stalls = 0u32; |
| @@ -175,6 +188,12 @@ impl Session { | ||
| 175 | 188 | } |
| 176 | 189 | } |
| 177 | 190 | 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 | + } | |
| 178 | 197 | self.emit(handle); |
| 179 | 198 | return Ok(true); |
| 180 | 199 | } |
| @@ -283,13 +302,15 @@ impl Session { | ||
| 283 | 302 | } |
| 284 | 303 | } |
| 285 | 304 | |
| 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. | |
| 288 | 309 | /// |
| 289 | 310 | /// # Safety |
| 290 | 311 | /// `path` must be a valid NUL-terminated C string. |
| 291 | 312 | #[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 { | |
| 293 | 314 | catch_unwind(AssertUnwindSafe(|| { |
| 294 | 315 | if path.is_null() { |
| 295 | 316 | return std::ptr::null_mut(); |
| @@ -299,7 +320,7 @@ pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void { | ||
| 299 | 320 | let Ok(path) = path.to_str() else { |
| 300 | 321 | return std::ptr::null_mut(); |
| 301 | 322 | }; |
| 302 | - match Session::open(Path::new(path)) { | |
| 323 | + match Session::open_at(Path::new(path), target_sample) { | |
| 303 | 324 | Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, |
| 304 | 325 | None => std::ptr::null_mut(), |
| 305 | 326 | } |
| @@ -310,7 +331,7 @@ pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void { | ||
| 310 | 331 | /// Fills `out` with stream metadata. 0 on success, negative on failure. |
| 311 | 332 | /// |
| 312 | 333 | /// # 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. | |
| 314 | 335 | #[unsafe(no_mangle)] |
| 315 | 336 | pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 { |
| 316 | 337 | catch_unwind(AssertUnwindSafe(|| { |
| @@ -334,7 +355,7 @@ pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 | ||
| 334 | 355 | /// stream, negative on error. Plane pointers stay valid until the next call. |
| 335 | 356 | /// |
| 336 | 357 | /// # 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. | |
| 338 | 359 | #[unsafe(no_mangle)] |
| 339 | 360 | pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 { |
| 340 | 361 | catch_unwind(AssertUnwindSafe(|| { |
| @@ -362,12 +383,12 @@ pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) | ||
| 362 | 383 | /// Releases a session. Safe to call with null. |
| 363 | 384 | /// |
| 364 | 385 | /// # 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. | |
| 366 | 387 | #[unsafe(no_mangle)] |
| 367 | 388 | pub unsafe extern "C" fn vh_close(session: *mut c_void) { |
| 368 | 389 | let _ = catch_unwind(AssertUnwindSafe(|| { |
| 369 | 390 | 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`. | |
| 371 | 392 | drop(unsafe { Box::from_raw(session as *mut Session) }); |
| 372 | 393 | } |
| 373 | 394 | })); |
crates/engine/src/ao.rsmodified+11 -0
| @@ -18,6 +18,7 @@ struct Plugin { | ||
| 18 | 18 | write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize, |
| 19 | 19 | position: unsafe extern "C" fn(*mut c_void) -> i64, |
| 20 | 20 | set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, |
| 21 | + flush: unsafe extern "C" fn(*mut c_void) -> i32, | |
| 21 | 22 | close: unsafe extern "C" fn(*mut c_void), |
| 22 | 23 | // Never dropped (lives in a static), so the fn pointers above stay valid. |
| 23 | 24 | _lib: Library, |
| @@ -54,6 +55,9 @@ fn load() -> Option<Plugin> { | ||
| 54 | 55 | write: *lib.get(b"ao_write\0").ok()?, |
| 55 | 56 | position: *lib.get(b"ao_position\0").ok()?, |
| 56 | 57 | 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()?, | |
| 57 | 61 | close: *lib.get(b"ao_close\0").ok()?, |
| 58 | 62 | _lib: lib, |
| 59 | 63 | }) |
| @@ -118,6 +122,13 @@ impl AoSession { | ||
| 118 | 122 | // SAFETY: `handle` came from `ao_open` and is still open. |
| 119 | 123 | unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 } |
| 120 | 124 | } |
| 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 | + } | |
| 121 | 132 | } |
| 122 | 133 | |
| 123 | 134 | impl Drop for AoSession { |
crates/engine/src/audio.rsmodified+174 -28
| @@ -23,6 +23,10 @@ const DEFAULT_PRIMING: u64 = 1024; | ||
| 23 | 23 | /// An edit list entry that only shifts the timeline, carrying no media. |
| 24 | 24 | const EMPTY_EDIT: u64 = u32::MAX as u64; |
| 25 | 25 | |
| 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 | + | |
| 26 | 30 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 27 | 31 | pub struct AudioMeta { |
| 28 | 32 | pub sample_rate: u32, |
| @@ -48,6 +52,16 @@ impl AudioSession { | ||
| 48 | 52 | /// audio, which is a valid session; `Err` is a real failure. |
| 49 | 53 | pub fn open( |
| 50 | 54 | 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, | |
| 51 | 65 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 52 | 66 | let file = File::open(path.as_ref())?; |
| 53 | 67 | let size = file.metadata()?.len(); |
| @@ -70,14 +84,20 @@ impl AudioSession { | ||
| 70 | 84 | let channels: u16 = match track.channel_config()? { |
| 71 | 85 | ChannelConfig::Mono => 1, |
| 72 | 86 | 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 | + } | |
| 74 | 90 | }; |
| 75 | 91 | |
| 76 | 92 | let track_id = track.track_id(); |
| 77 | 93 | let sample_rate = track.sample_freq_index()?.freq(); |
| 78 | 94 | 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)); | |
| 81 | 101 | |
| 82 | 102 | let mut params = AudioCodecParameters::new(); |
| 83 | 103 | params |
| @@ -86,6 +106,28 @@ impl AudioSession { | ||
| 86 | 106 | .with_extra_data(audio_specific_config(track)?); |
| 87 | 107 | let decoder = AacDecoder::try_new(¶ms, &AudioDecoderOptions::default())?; |
| 88 | 108 | |
| 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 | + | |
| 89 | 131 | let sample_count = reader.sample_count(track_id)?; |
| 90 | 132 | let meta = AudioMeta { |
| 91 | 133 | sample_rate, |
| @@ -96,17 +138,22 @@ impl AudioSession { | ||
| 96 | 138 | // this bound is ~0.75 s of lookahead — enough to ride out decode jitter |
| 97 | 139 | // without making a pause take a second to bite. |
| 98 | 140 | 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 | + })?; | |
| 110 | 157 | Ok(Some((meta, rx))) |
| 111 | 158 | } |
| 112 | 159 | } |
| @@ -161,6 +208,56 @@ fn scale(value: u64, sample_rate: u32, timescale: u32) -> Option<u64> { | ||
| 161 | 208 | (timescale != 0).then(|| value * u64::from(sample_rate) / timescale) |
| 162 | 209 | } |
| 163 | 210 | |
| 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 | + | |
| 164 | 261 | struct Worker { |
| 165 | 262 | reader: Mp4Reader<BufReader<File>>, |
| 166 | 263 | decoder: AacDecoder, |
| @@ -168,15 +265,21 @@ struct Worker { | ||
| 168 | 265 | sample_count: u32, |
| 169 | 266 | channels: usize, |
| 170 | 267 | 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, | |
| 171 | 275 | tx: SyncSender<AudioChunk>, |
| 172 | 276 | } |
| 173 | 277 | |
| 174 | 278 | fn run(mut w: Worker) { |
| 175 | 279 | let mut interleaved = Vec::new(); |
| 176 | - let mut to_skip = w.priming; | |
| 177 | - let mut emitted = 0u64; | |
| 280 | + let mut pos = w.start_pos; | |
| 178 | 281 | |
| 179 | - for id in 1..=w.sample_count { | |
| 282 | + for id in w.start_id..=w.sample_count { | |
| 180 | 283 | let sample = match w.reader.read_sample(w.track_id, id) { |
| 181 | 284 | Ok(Some(sample)) => sample, |
| 182 | 285 | Ok(None) => break, |
| @@ -199,22 +302,24 @@ fn run(mut w: Worker) { | ||
| 199 | 302 | } |
| 200 | 303 | }; |
| 201 | 304 | buf.copy_to_vec_interleaved::<f32>(&mut interleaved); |
| 305 | + let next = pos + (interleaved.len() / w.channels) as u64; | |
| 202 | 306 | |
| 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; | |
| 212 | 317 | } |
| 213 | 318 | let chunk = AudioChunk { |
| 214 | - start_sample: emitted, | |
| 319 | + start_sample: pos - w.priming, | |
| 215 | 320 | samples: std::mem::take(&mut interleaved), |
| 216 | 321 | }; |
| 217 | - emitted += (chunk.samples.len() / w.channels) as u64; | |
| 322 | + pos = next; | |
| 218 | 323 | if w.tx.send(chunk).is_err() { |
| 219 | 324 | break; // consumer went away |
| 220 | 325 | } |
| @@ -223,6 +328,47 @@ fn run(mut w: Worker) { | ||
| 223 | 328 | |
| 224 | 329 | #[cfg(test)] |
| 225 | 330 | 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 | + | |
| 226 | 372 | #[test] |
| 227 | 373 | fn asc_round_trips_aac_lc_44100_stereo() { |
| 228 | 374 | // profile 2 (LC), freq_index 4 (44100), chan_conf 2 (stereo). |
crates/engine/src/decode.rsmodified+50 -11
| @@ -2,6 +2,8 @@ | ||
| 2 | 2 | //! thread (the UI thread) never blocks on decode and memory stays capped. |
| 3 | 3 | |
| 4 | 4 | use std::path::{Path, PathBuf}; |
| 5 | +use std::sync::Arc; | |
| 6 | +use std::sync::atomic::{AtomicBool, Ordering}; | |
| 5 | 7 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; |
| 6 | 8 | use std::thread; |
| 7 | 9 | |
| @@ -28,19 +30,33 @@ impl DecodeSession { | ||
| 28 | 30 | /// yields frames as the worker decodes them. The worker stops when the |
| 29 | 31 | /// receiver is dropped, at end of stream, or on the first decode error. |
| 30 | 32 | 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>)> { | |
| 31 | 45 | let path = path.as_ref().to_path_buf(); |
| 32 | 46 | let (meta, demuxer) = Demuxer::open(&path)?; |
| 33 | 47 | // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the |
| 34 | 48 | // decoder run ahead of the display without limit. |
| 35 | 49 | let (tx, rx) = sync_channel(2); |
| 50 | + let cancel = Arc::new(AtomicBool::new(false)); | |
| 51 | + let worker_cancel = Arc::clone(&cancel); | |
| 36 | 52 | thread::Builder::new() |
| 37 | 53 | .name("decode".into()) |
| 38 | 54 | .spawn(move || { |
| 39 | 55 | // The plugin has to be opened on the thread that uses it: its |
| 40 | 56 | // 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) { | |
| 42 | 58 | eprintln!("decode backend: hardware (VA-API plugin)"); |
| 43 | - if run_hw(hw, &tx) { | |
| 59 | + if run_hw(hw, &tx, start_frame, &worker_cancel) { | |
| 44 | 60 | return; |
| 45 | 61 | } |
| 46 | 62 | // A driver that opens but cannot decode a single frame is |
| @@ -48,26 +64,38 @@ impl DecodeSession { | ||
| 48 | 64 | eprintln!("hardware decode failed before any frame, falling back to software"); |
| 49 | 65 | } |
| 50 | 66 | eprintln!("decode backend: software (rusty_h264)"); |
| 51 | - run(demuxer, tx) | |
| 67 | + run(demuxer, tx, start_frame, &worker_cancel) | |
| 52 | 68 | })?; |
| 53 | - Ok((meta, rx)) | |
| 69 | + Ok((meta, rx, cancel)) | |
| 54 | 70 | } |
| 55 | 71 | } |
| 56 | 72 | |
| 57 | 73 | /// `None` when the software path must be used: forced by `VE_SW=1`, or the |
| 58 | 74 | /// 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> { | |
| 60 | 76 | if std::env::var_os("VE_SW").is_some_and(|v| v == "1") { |
| 61 | 77 | return None; |
| 62 | 78 | } |
| 63 | - HwSession::open(path) | |
| 79 | + HwSession::open_at(path, start_frame) | |
| 64 | 80 | } |
| 65 | 81 | |
| 66 | 82 | /// Returns whether the session was handled; `false` only when hardware decode |
| 67 | 83 | /// 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; | |
| 70 | 95 | loop { |
| 96 | + if cancel.load(Ordering::Relaxed) { | |
| 97 | + return true; | |
| 98 | + } | |
| 71 | 99 | match hw.next_frame() { |
| 72 | 100 | Ok(Some((y, u, v, width, height))) => { |
| 73 | 101 | let frame = Frame { |
| @@ -83,7 +111,7 @@ fn run_hw(mut hw: HwSession, tx: &SyncSender<Frame>) -> bool { | ||
| 83 | 111 | } |
| 84 | 112 | Ok(None) => return true, |
| 85 | 113 | Err(e) => { |
| 86 | - if index == 0 { | |
| 114 | + if index == start_frame { | |
| 87 | 115 | return false; |
| 88 | 116 | } |
| 89 | 117 | eprintln!("hardware decode error at frame {index}: {e}"); |
| @@ -93,13 +121,20 @@ fn run_hw(mut hw: HwSession, tx: &SyncSender<Frame>) -> bool { | ||
| 93 | 121 | } |
| 94 | 122 | } |
| 95 | 123 | |
| 96 | -fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>) { | |
| 124 | +fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>, start_frame: u32, cancel: &AtomicBool) { | |
| 97 | 125 | 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; | |
| 99 | 131 | |
| 100 | 132 | // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames); |
| 101 | 133 | // reordering streams need POC-sorted output before display. |
| 102 | 134 | loop { |
| 135 | + if cancel.load(Ordering::Relaxed) { | |
| 136 | + break; | |
| 137 | + } | |
| 103 | 138 | let au = match demuxer.next_access_unit() { |
| 104 | 139 | Ok(Some(au)) => au, |
| 105 | 140 | Ok(None) => break, |
| @@ -116,6 +151,10 @@ fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>) { | ||
| 116 | 151 | break; |
| 117 | 152 | } |
| 118 | 153 | }; |
| 154 | + if index < start_frame { | |
| 155 | + index += 1; | |
| 156 | + continue; | |
| 157 | + } | |
| 119 | 158 | let frame = Frame { |
| 120 | 159 | index, |
| 121 | 160 | width: yuv.width as u32, |
crates/engine/src/demux.rsmodified+45 -0
| @@ -22,6 +22,9 @@ pub struct Demuxer { | ||
| 22 | 22 | sample_count: u32, |
| 23 | 23 | /// Annex-B SPS+PPS, re-injected ahead of every sync sample. |
| 24 | 24 | 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>, | |
| 25 | 28 | next_sample: u32, |
| 26 | 29 | } |
| 27 | 30 | |
| @@ -49,6 +52,15 @@ impl Demuxer { | ||
| 49 | 52 | parameter_sets.extend_from_slice(track.sequence_parameter_set()?); |
| 50 | 53 | parameter_sets.extend_from_slice(&START_CODE); |
| 51 | 54 | 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(); | |
| 52 | 64 | |
| 53 | 65 | let sample_count = reader.sample_count(track_id)?; |
| 54 | 66 | Ok(( |
| @@ -61,6 +73,7 @@ impl Demuxer { | ||
| 61 | 73 | track_id, |
| 62 | 74 | sample_count, |
| 63 | 75 | parameter_sets, |
| 76 | + sync_samples, | |
| 64 | 77 | next_sample: 1, // sample ids are 1-based |
| 65 | 78 | }, |
| 66 | 79 | )) |
| @@ -84,6 +97,29 @@ impl Demuxer { | ||
| 84 | 97 | append_annex_b(&sample.bytes, &mut au)?; |
| 85 | 98 | Ok(Some(au)) |
| 86 | 99 | } |
| 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 | + } | |
| 87 | 123 | } |
| 88 | 124 | |
| 89 | 125 | /// avcC length-prefixed NALs -> Annex-B. Assumes a 4-byte length prefix, which |
| @@ -123,6 +159,15 @@ mod tests { | ||
| 123 | 159 | assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]); |
| 124 | 160 | } |
| 125 | 161 | |
| 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 | + | |
| 126 | 171 | #[test] |
| 127 | 172 | fn rejects_misparse() { |
| 128 | 173 | 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 { | ||
| 53 | 53 | } |
| 54 | 54 | |
| 55 | 55 | 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, | |
| 57 | 57 | meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32, |
| 58 | 58 | next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32, |
| 59 | 59 | close: unsafe extern "C" fn(*mut c_void), |
| @@ -88,7 +88,7 @@ fn load() -> Option<Plugin> { | ||
| 88 | 88 | let plugin = unsafe { |
| 89 | 89 | (|| { |
| 90 | 90 | Some(Plugin { |
| 91 | - open: *lib.get(b"vh_open\0").ok()?, | |
| 91 | + open_at: *lib.get(b"vh_open_at\0").ok()?, | |
| 92 | 92 | meta: *lib.get(b"vh_meta\0").ok()?, |
| 93 | 93 | next_frame: *lib.get(b"vh_next_frame\0").ok()?, |
| 94 | 94 | close: *lib.get(b"vh_close\0").ok()?, |
| @@ -113,10 +113,19 @@ impl HwSession { | ||
| 113 | 113 | /// Probes the plugin against this very file: success means the driver, |
| 114 | 114 | /// the render node and the stream's profile are all usable. |
| 115 | 115 | 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> { | |
| 116 | 123 | let plugin = plugin()?; |
| 117 | 124 | 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); | |
| 118 | 127 | // 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) }; | |
| 120 | 129 | if handle.is_null() { |
| 121 | 130 | return None; |
| 122 | 131 | } |
| @@ -125,7 +134,7 @@ impl HwSession { | ||
| 125 | 134 | |
| 126 | 135 | pub fn meta(&self) -> Option<VhMeta> { |
| 127 | 136 | 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. | |
| 129 | 138 | if unsafe { (self.plugin.meta)(self.handle, &mut meta) } < 0 { |
| 130 | 139 | return None; |
| 131 | 140 | } |
| @@ -170,7 +179,7 @@ impl HwSession { | ||
| 170 | 179 | |
| 171 | 180 | impl Drop for HwSession { |
| 172 | 181 | 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. | |
| 174 | 183 | unsafe { (self.plugin.close)(self.handle) } |
| 175 | 184 | } |
| 176 | 185 | } |
crates/engine/src/lib.rsmodified+1 -1
| @@ -11,9 +11,9 @@ pub mod playback; | ||
| 11 | 11 | |
| 12 | 12 | pub use audio::{AudioChunk, AudioMeta, AudioSession}; |
| 13 | 13 | pub use clock::PlaybackClock; |
| 14 | -pub use playback::PlaybackSession; | |
| 15 | 14 | pub use decode::{DecodeSession, Frame}; |
| 16 | 15 | pub use demux::VideoMeta; |
| 16 | +pub use playback::PlaybackSession; | |
| 17 | 17 | |
| 18 | 18 | /// Boxed error; the engine has few failure modes and every one of them is fatal |
| 19 | 19 | /// 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 { | ||
| 159 | 159 | // no jump, and this branch cannot be reached again. |
| 160 | 160 | self.clock.switch_to_wall(); |
| 161 | 161 | } 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); | |
| 163 | 164 | } |
| 164 | 165 | } |
| 165 | 166 | } |
crates/engine/tests/ao_output.rsmodified+4 -1
| @@ -82,7 +82,10 @@ fn plays_and_tracks_position() { | ||
| 82 | 82 | assert!(ao.set_active(true), "resume rejected"); |
| 83 | 83 | std::thread::sleep(Duration::from_millis(200)); |
| 84 | 84 | 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 | + ); | |
| 86 | 89 | } |
| 87 | 90 | |
| 88 | 91 | /// 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() { | ||
| 48 | 48 | // d. no gaps, no overlaps. |
| 49 | 49 | assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start"); |
| 50 | 50 | 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 | + ); | |
| 52 | 56 | next_sample += (chunk.samples.len() / 2) as u64; |
| 53 | 57 | left.extend(chunk.samples.iter().step_by(2)); |
| 54 | 58 | right.extend(chunk.samples[1..].iter().step_by(2)); |
| @@ -81,9 +85,15 @@ fn decodes_av_mp4_audio() { | ||
| 81 | 85 | |
| 82 | 86 | // Priming trimmed: the sine starts at a rising zero crossing, and audio is |
| 83 | 87 | // 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 | + ); | |
| 85 | 93 | 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())); | |
| 87 | 97 | assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}"); |
| 88 | 98 | |
| 89 | 99 | 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>) { | ||
| 63 | 63 | #[ignore = "needs libengine_hw.so and a VA-API driver"] |
| 64 | 64 | fn rejects_unopenable_files() { |
| 65 | 65 | 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 | + ); | |
| 67 | 70 | } |
| 68 | 71 | |
| 69 | 72 | #[test] |
| @@ -82,6 +85,44 @@ fn hardware_decodes_high_profile() { | ||
| 82 | 85 | assert_eq!(count, 150); |
| 83 | 86 | } |
| 84 | 87 | |
| 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 | + | |
| 85 | 126 | /// H.264 8-bit decode is bit-exact by conformance, so the two backends must |
| 86 | 127 | /// agree. A mismatch means a driver deviation and is reported, not swallowed. |
| 87 | 128 | #[test] |