Merge branch 'worktree-agent-ab6fdf12423ce2e46'
Browse files at this commit7 changed files +1020 -184
- crates/app/src/player/library.rs +9 -2
- crates/engine-hw/src/lib.rs +69 -0
- crates/engine/src/decode.rs +566 -151
- crates/engine/src/hw.rs +27 -0
- crates/engine/src/playback.rs +136 -31
- crates/engine/src/scale.rs +39 -0
- crates/engine/tests/playback.rs +174 -0
crates/app/src/player/library.rsmodified+9 -2
| @@ -475,8 +475,13 @@ impl Player { | |||
| 475 | place: bool, | 475 | place: bool, |
| 476 | ) -> String { | 476 | ) -> String { |
| 477 | match opened { | 477 | match opened { |
| 478 | - Ok((session, subs)) => { | 478 | + Ok((mut session, subs)) => { |
| 479 | self.fps = session.meta().frame_rate; | 479 | self.fps = session.meta().frame_rate; |
| 480 | + // This window *is* the real-time viewer: a picture already past | ||
| 481 | + // the clock is one `pump` takes off the channel and throws away, | ||
| 482 | + // so the worker stops paying for it instead | ||
| 483 | + // ([`PlaybackSession::drop_late_pictures`]). | ||
| 484 | + session.drop_late_pictures(true); | ||
| 480 | // Read before the session moves: a file that plays silent says | 485 | // Read before the session moves: a file that plays silent says |
| 481 | // so here or nowhere. | 486 | // so here or nowhere. |
| 482 | let silent = audio_notice(&session); | 487 | let silent = audio_notice(&session); |
| @@ -737,8 +742,10 @@ impl Player { | |||
| 737 | return; | 742 | return; |
| 738 | } | 743 | } |
| 739 | let text = match opened { | 744 | let text = match opened { |
| 740 | - Ok(session) => { | 745 | + Ok(mut session) => { |
| 741 | self.fps = session.meta().frame_rate; | 746 | self.fps = session.meta().frame_rate; |
| 747 | + // As at the file door above: the window watches in real time. | ||
| 748 | + session.drop_late_pictures(true); | ||
| 742 | let silent = audio_notice(&session); | 749 | let silent = audio_notice(&session); |
| 743 | // A project is named after itself but still exports beside its | 750 | // A project is named after itself but still exports beside its |
| 744 | // media: that is the only place an export has ever landed. | 751 | // media: that is the only place an export has ever landed. |
crates/engine-hw/src/lib.rsmodified+69 -0
| @@ -308,6 +308,49 @@ impl Session { | |||
| 308 | Some(session) | 308 | Some(session) |
| 309 | } | 309 | } |
| 310 | 310 | ||
| 311 | + /// Repositions an **open** session, exactly as [`Session::open_at`] positions | ||
| 312 | + /// a new one: the next [`Session::pump`] hands back sample `target_sample`. | ||
| 313 | + /// | ||
| 314 | + /// This is what a seek costs when the session is kept: a demuxer seek and a | ||
| 315 | + /// decoder flush, and *not* the VA-API initialisation (~90 ms measured), the | ||
| 316 | + /// render node probe, the container parse and the surface pool that opening | ||
| 317 | + /// one again pays for. | ||
| 318 | + /// | ||
| 319 | + /// The flush is the whole of the decoder's reset: cros-codecs finishes what | ||
| 320 | + /// is in flight and goes to `Reset`, from where it resumes on the next | ||
| 321 | + /// parameter set or key frame -- and every sync sample this demuxer hands | ||
| 322 | + /// out carries the parameter sets in front of it (`demux`'s `is_sync` | ||
| 323 | + /// re-injection), which is exactly where a seek lands. The pictures the | ||
| 324 | + /// flush makes ready are dropped with `ready`: they belong to where the | ||
| 325 | + /// session *was*. | ||
| 326 | + fn seek_to(&mut self, target_sample: u32) -> Result<(), String> { | ||
| 327 | + self.decoder.get().flush().map_err(|e| e.to_string())?; | ||
| 328 | + // Drain what the flush completed, dropping every handle: each one holds | ||
| 329 | + // a pool buffer out of circulation, and none of them is ours to show. | ||
| 330 | + while let Some(event) = self.decoder.get().next_event() { | ||
| 331 | + if let DecoderEvent::FormatChanged = event { | ||
| 332 | + let info = self | ||
| 333 | + .decoder | ||
| 334 | + .get() | ||
| 335 | + .stream_info() | ||
| 336 | + .ok_or("format changed without stream info")? | ||
| 337 | + .clone(); | ||
| 338 | + self.pool.resize(&info); | ||
| 339 | + } | ||
| 340 | + } | ||
| 341 | + self.ready.clear(); | ||
| 342 | + self.pending.clear(); | ||
| 343 | + self.flushed = false; | ||
| 344 | + // The same arithmetic `open_at` does, for the same reason. | ||
| 345 | + let target_frame = target_sample.saturating_sub(1); | ||
| 346 | + let first = self.demuxer.seek_to_sync_at_or_before(target_frame); | ||
| 347 | + self.skip = (i64::from(target_frame) - first).max(0) as u32; | ||
| 348 | + // ...and the same open-GOP window: a session positioned anywhere but the | ||
| 349 | + // start may meet leading pictures that reference what it never decoded. | ||
| 350 | + self.leading = if target_frame > 0 { 0 } else { LEADING_LIMIT }; | ||
| 351 | + Ok(()) | ||
| 352 | + } | ||
| 353 | + | ||
| 311 | /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF. | 354 | /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF. |
| 312 | fn pump(&mut self) -> Result<bool, String> { | 355 | fn pump(&mut self) -> Result<bool, String> { |
| 313 | let mut stalls = 0u32; | 356 | let mut stalls = 0u32; |
| @@ -599,6 +642,32 @@ pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) | |||
| 599 | .unwrap_or(-1) | 642 | .unwrap_or(-1) |
| 600 | } | 643 | } |
| 601 | 644 | ||
| 645 | +/// Repositions an open session so the next [`vh_next_frame`] returns sample | ||
| 646 | +/// `target_sample` (1-based, as [`vh_open_at`]). 0 on success, negative on | ||
| 647 | +/// failure -- and a caller that gets one closes the session and opens another, | ||
| 648 | +/// which is what it did for every seek before this symbol existed. | ||
| 649 | +/// | ||
| 650 | +/// # Safety | ||
| 651 | +/// `session` must come from [`vh_open_at`] and still be open. | ||
| 652 | +#[unsafe(no_mangle)] | ||
| 653 | +pub unsafe extern "C" fn vh_seek(session: *mut c_void, target_sample: u32) -> i32 { | ||
| 654 | + catch_unwind(AssertUnwindSafe(|| { | ||
| 655 | + if session.is_null() { | ||
| 656 | + return -1; | ||
| 657 | + } | ||
| 658 | + // SAFETY: caller-guaranteed live session. | ||
| 659 | + let session = unsafe { &mut *(session as *mut Session) }; | ||
| 660 | + match session.seek_to(target_sample) { | ||
| 661 | + Ok(()) => 0, | ||
| 662 | + Err(e) => { | ||
| 663 | + eprintln!("engine_hw: seek failed: {e}"); | ||
| 664 | + -2 | ||
| 665 | + } | ||
| 666 | + } | ||
| 667 | + })) | ||
| 668 | + .unwrap_or(-1) | ||
| 669 | +} | ||
| 670 | + | ||
| 602 | /// Releases a session. Safe to call with null. | 671 | /// Releases a session. Safe to call with null. |
| 603 | /// | 672 | /// |
| 604 | /// # Safety | 673 | /// # Safety |
crates/engine/src/decode.rsmodified+566 -151
| @@ -3,8 +3,8 @@ | |||
| 3 | 3 | ||
| 4 | use std::path::{Path, PathBuf}; | 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::sync::Arc; | 5 | use std::sync::Arc; |
| 6 | -use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; | 6 | +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; |
| 7 | -use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; | 7 | +use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; |
| 8 | use std::thread; | 8 | use std::thread; |
| 9 | 9 | ||
| 10 | use rusty_h264::Decoder; | 10 | use rusty_h264::Decoder; |
| @@ -136,15 +136,171 @@ pub(crate) struct Worker { | |||
| 136 | /// `None` once detached, and for a range with nothing to decode: either way | 136 | /// `None` once detached, and for a range with nothing to decode: either way |
| 137 | /// there is no thread left to wait for. | 137 | /// there is no thread left to wait for. |
| 138 | handle: Option<thread::JoinHandle<()>>, | 138 | handle: Option<thread::JoinHandle<()>>, |
| 139 | + /// How a *later* span reaches this same thread ([`Worker::reseek`]), for the | ||
| 140 | + /// workers that decode a file: the still, the gap and a detached worker have | ||
| 141 | + /// no such door and are the one-span threads they always were. | ||
| 142 | + reuse: Option<Reuse>, | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// The door a persistent decode worker is steered through: the file it has open, | ||
| 146 | +/// the channel its next span arrives on, and the generation counter that tells | ||
| 147 | +/// the span it is decoding *now* that nobody is waiting for it any more. | ||
| 148 | +/// | ||
| 149 | +/// The point of all three is that a seek onto the same file costs a demuxer | ||
| 150 | +/// seek and a decoder flush ([`crate::hw::HwSession::seek`]) rather than a | ||
| 151 | +/// thread, a container parse and a VA-API initialisation (98 ms measured). | ||
| 152 | +struct Reuse { | ||
| 153 | + path: PathBuf, | ||
| 154 | + spans: std::sync::mpsc::Sender<SpanCmd>, | ||
| 155 | + /// Bumped by every reseek and by [`Worker::abandon`]; the decode loop stops | ||
| 156 | + /// the moment it no longer matches the span it was handed. | ||
| 157 | + generation: Arc<AtomicU64>, | ||
| 158 | + /// The worker's decoder, published once and read across every span it | ||
| 159 | + /// decodes -- so a reseek onto a file already open says "hardware" from the | ||
| 160 | + /// first repaint instead of going back through `opening`. | ||
| 161 | + backend: BackendCell, | ||
| 162 | + /// Where the caller's playhead stands, in this file's own frames | ||
| 163 | + /// ([`Worker::playhead`]): the worker converts and sends nothing behind it. | ||
| 164 | + /// Rewritten to the target by every reseek, so it can never carry one span's | ||
| 165 | + /// position into the next. | ||
| 166 | + floor: Arc<AtomicU32>, | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/// One span asked of a persistent worker: the range in the file's own frames, | ||
| 170 | +/// everything a picture is graded, placed and mapped by, and the channel the | ||
| 171 | +/// pictures go down. Carries its generation, so a command already superseded on | ||
| 172 | +/// its way through the queue is dropped rather than decoded. | ||
| 173 | +struct SpanCmd { | ||
| 174 | + generation: u64, | ||
| 175 | + start: u32, | ||
| 176 | + end: u32, | ||
| 177 | + color: ColorParams, | ||
| 178 | + canvas: Composer, | ||
| 179 | + tone: tonemap::Preset, | ||
| 180 | + tx: SyncSender<Frame>, | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// What stops a decode loop: the worker's terminal flag (the thread itself is | ||
| 184 | +/// going away) and the generation of the span it was handed (only *this* span is | ||
| 185 | +/// going away). One check, so every loop treats them alike. | ||
| 186 | +/// | ||
| 187 | +/// ...and where the playhead has reached ([`Abort::late`]), which is the same | ||
| 188 | +/// question one picture at a time: a frame due before it is a frame nobody can | ||
| 189 | +/// be shown any more. | ||
| 190 | +struct Abort<'a> { | ||
| 191 | + cancel: &'a AtomicBool, | ||
| 192 | + generation: &'a AtomicU64, | ||
| 193 | + mine: u64, | ||
| 194 | + floor: &'a AtomicU32, | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +impl Abort<'_> { | ||
| 198 | + fn hit(&self) -> bool { | ||
| 199 | + self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + /// Whether the picture at source frame `index` is already past due: the | ||
| 203 | + /// caller's playhead has gone by it, so converting it (a full BGRA pass over | ||
| 204 | + /// 8 MB at 1080p) and queueing it would only push a picture nobody sees in | ||
| 205 | + /// front of the one they are waiting for. | ||
| 206 | + /// | ||
| 207 | + /// It is still *decoded* -- the pictures after it reference it -- and the | ||
| 208 | + /// floor only ever moves with the playhead the session publishes, so a | ||
| 209 | + /// paused session (and every seek, which republishes its own target) drops | ||
| 210 | + /// nothing at all. | ||
| 211 | + fn late(&self, index: u32) -> bool { | ||
| 212 | + self.floor.load(Ordering::Relaxed) > index | ||
| 213 | + } | ||
| 139 | } | 214 | } |
| 140 | 215 | ||
| 141 | impl Worker { | 216 | impl Worker { |
| 142 | - /// Stops the worker at its next check without waiting. Callers that replace | 217 | + /// Stops the worker *and its thread* at their next check, without waiting. |
| 143 | - /// a worker should do this first and drop the receiver second: a worker | 218 | + /// Callers that replace a worker should do this first and drop the receiver |
| 144 | - /// parked in `send` only wakes on the disconnect, so the join below would | 219 | + /// second: a worker parked in `send` only wakes on the disconnect, so the |
| 145 | - /// otherwise wait for a consumer that is never coming. | 220 | + /// join below would otherwise wait for a consumer that is never coming. |
| 146 | - pub(crate) fn cancel(&self) { | 221 | + /// |
| 222 | + /// The command channel goes with it, which is what wakes a persistent worker | ||
| 223 | + /// parked between spans -- without that it would sit in `recv` forever and a | ||
| 224 | + /// retired worker would never be reaped (nor joined at exit in any bounded | ||
| 225 | + /// time, which is the Mesa `atexit` hazard this whole type exists for). | ||
| 226 | + pub(crate) fn cancel(&mut self) { | ||
| 147 | self.cancel.store(true, Ordering::Release); | 227 | self.cancel.store(true, Ordering::Release); |
| 228 | + self.reuse = None; | ||
| 229 | + } | ||
| 230 | + | ||
| 231 | + /// Stops the span the worker is decoding, keeping the *thread* -- and with | ||
| 232 | + /// it the open file and the open decoder -- for the span that follows. What | ||
| 233 | + /// a seek does, since the next thing it says is [`Worker::reseek`]. | ||
| 234 | + /// | ||
| 235 | + /// Falls back to [`cancel`](Self::cancel) for a worker with nothing to | ||
| 236 | + /// reuse (a still, a gap, a detached one), where the two mean the same | ||
| 237 | + /// thing: this worker has no next span. | ||
| 238 | + pub(crate) fn abandon(&mut self) { | ||
| 239 | + match &self.reuse { | ||
| 240 | + Some(reuse) => { | ||
| 241 | + reuse.generation.fetch_add(1, Ordering::Release); | ||
| 242 | + } | ||
| 243 | + None => self.cancel(), | ||
| 244 | + } | ||
| 245 | + } | ||
| 246 | + | ||
| 247 | + /// Tells the worker where the caller's playhead stands, in the file's own | ||
| 248 | + /// frames: it converts and queues nothing behind that, because a picture | ||
| 249 | + /// whose moment has passed cannot be shown and would only delay the one that | ||
| 250 | + /// can (see [`Abort::late`]). A worker with no reuse door -- a still, a gap | ||
| 251 | + /// -- has nothing to tell, and this costs it nothing to say. | ||
| 252 | + pub(crate) fn playhead(&self, source_frame: u32) { | ||
| 253 | + if let Some(reuse) = &self.reuse { | ||
| 254 | + reuse.floor.store(source_frame, Ordering::Relaxed); | ||
| 255 | + } | ||
| 256 | + } | ||
| 257 | + | ||
| 258 | + /// Points this worker at another range of the file it already has open, | ||
| 259 | + /// handing back the channel the new span's pictures arrive on and the cell | ||
| 260 | + /// that says what is decoding them. `None` when this worker cannot take the | ||
| 261 | + /// job -- another file, no reuse door, or a thread that has already returned | ||
| 262 | + /// -- and the caller then opens a worker of its own, exactly as it always | ||
| 263 | + /// did. | ||
| 264 | + /// | ||
| 265 | + /// The pictures of the *old* span are left in their own channel, which the | ||
| 266 | + /// caller drops: that disconnect is what wakes this worker if it is parked | ||
| 267 | + /// in `send`, and only then does it reach the command below. So the order at | ||
| 268 | + /// the call site is unchanged -- install the new receiver, and the old | ||
| 269 | + /// worker finds out by losing its consumer. | ||
| 270 | + pub(crate) fn reseek( | ||
| 271 | + &mut self, | ||
| 272 | + path: &Path, | ||
| 273 | + start: u32, | ||
| 274 | + end: u32, | ||
| 275 | + color: ColorParams, | ||
| 276 | + canvas: Composer, | ||
| 277 | + tone: tonemap::Preset, | ||
| 278 | + ) -> Option<(Receiver<Frame>, BackendCell)> { | ||
| 279 | + let reuse = self.reuse.as_ref()?; | ||
| 280 | + if reuse.path != path || self.is_finished() { | ||
| 281 | + return None; | ||
| 282 | + } | ||
| 283 | + let (tx, rx) = sync_channel(canvas.queue_depth()); | ||
| 284 | + // The new span's own playhead, before its first picture is decoded: a | ||
| 285 | + // floor left over from where the timeline *was* would drop every | ||
| 286 | + // picture of a seek that went backwards. | ||
| 287 | + reuse.floor.store(start, Ordering::Relaxed); | ||
| 288 | + // Bumped before the command is queued, so the span running now stops at | ||
| 289 | + // its next picture whatever order the two threads are scheduled in. | ||
| 290 | + let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1; | ||
| 291 | + reuse | ||
| 292 | + .spans | ||
| 293 | + .send(SpanCmd { | ||
| 294 | + generation, | ||
| 295 | + start, | ||
| 296 | + end, | ||
| 297 | + color, | ||
| 298 | + canvas, | ||
| 299 | + tone, | ||
| 300 | + tx, | ||
| 301 | + }) | ||
| 302 | + .ok()?; | ||
| 303 | + Some((rx, reuse.backend.clone())) | ||
| 148 | } | 304 | } |
| 149 | 305 | ||
| 150 | /// Whether the thread has already returned, i.e. dropping this would not | 306 | /// Whether the thread has already returned, i.e. dropping this would not |
| @@ -158,8 +314,14 @@ impl Worker { | |||
| 158 | 314 | ||
| 159 | /// Lets the worker run on unwatched -- what the public API does, since it | 315 | /// Lets the worker run on unwatched -- what the public API does, since it |
| 160 | /// hands out the flag alone. | 316 | /// hands out the flag alone. |
| 317 | + /// | ||
| 318 | + /// The reuse door goes with the handle: nothing can steer a worker nobody | ||
| 319 | + /// holds, and dropping the command channel is what makes such a thread end | ||
| 320 | + /// at its span rather than park waiting for a next one it can never be | ||
| 321 | + /// given -- with a VA-API session open, into Mesa's `atexit`. | ||
| 161 | fn detach(mut self) -> Arc<AtomicBool> { | 322 | fn detach(mut self) -> Arc<AtomicBool> { |
| 162 | self.handle = None; | 323 | self.handle = None; |
| 324 | + self.reuse = None; | ||
| 163 | Arc::clone(&self.cancel) | 325 | Arc::clone(&self.cancel) |
| 164 | } | 326 | } |
| 165 | } | 327 | } |
| @@ -167,6 +329,8 @@ impl Worker { | |||
| 167 | impl Drop for Worker { | 329 | impl Drop for Worker { |
| 168 | fn drop(&mut self) { | 330 | fn drop(&mut self) { |
| 169 | if let Some(handle) = self.handle.take() { | 331 | if let Some(handle) = self.handle.take() { |
| 332 | + // `cancel` drops the command channel too, so a worker parked between | ||
| 333 | + // spans wakes on the disconnect and this join is bounded. | ||
| 170 | self.cancel(); | 334 | self.cancel(); |
| 171 | let _ = handle.join(); | 335 | let _ = handle.join(); |
| 172 | } | 336 | } |
| @@ -258,6 +422,7 @@ impl DecodeSession { | |||
| 258 | worker: Worker { | 422 | worker: Worker { |
| 259 | cancel, | 423 | cancel, |
| 260 | handle: None, | 424 | handle: None, |
| 425 | + reuse: None, | ||
| 261 | }, | 426 | }, |
| 262 | backend: BackendCell::new(Backend::Gap), | 427 | backend: BackendCell::new(Backend::Gap), |
| 263 | }; | 428 | }; |
| @@ -287,7 +452,11 @@ impl DecodeSession { | |||
| 287 | .ok(); | 452 | .ok(); |
| 288 | FrameStream { | 453 | FrameStream { |
| 289 | frames: rx, | 454 | frames: rx, |
| 290 | - worker: Worker { cancel, handle }, | 455 | + worker: Worker { |
| 456 | + cancel, | ||
| 457 | + handle, | ||
| 458 | + reuse: None, | ||
| 459 | + }, | ||
| 291 | backend: BackendCell::new(Backend::Gap), | 460 | backend: BackendCell::new(Backend::Gap), |
| 292 | } | 461 | } |
| 293 | } | 462 | } |
| @@ -317,6 +486,7 @@ impl DecodeSession { | |||
| 317 | worker: Worker { | 486 | worker: Worker { |
| 318 | cancel, | 487 | cancel, |
| 319 | handle: None, | 488 | handle: None, |
| 489 | + reuse: None, | ||
| 320 | }, | 490 | }, |
| 321 | backend: BackendCell::new(Backend::Still), | 491 | backend: BackendCell::new(Backend::Still), |
| 322 | }); | 492 | }); |
| @@ -369,7 +539,11 @@ impl DecodeSession { | |||
| 369 | .ok(); | 539 | .ok(); |
| 370 | Ok(FrameStream { | 540 | Ok(FrameStream { |
| 371 | frames: rx, | 541 | frames: rx, |
| 372 | - worker: Worker { cancel, handle }, | 542 | + worker: Worker { |
| 543 | + cancel, | ||
| 544 | + handle, | ||
| 545 | + reuse: None, | ||
| 546 | + }, | ||
| 373 | backend: BackendCell::new(Backend::Still), | 547 | backend: BackendCell::new(Backend::Still), |
| 374 | }) | 548 | }) |
| 375 | } | 549 | } |
| @@ -414,57 +588,34 @@ impl DecodeSession { | |||
| 414 | hw_decodes(&path, start_frame, meta.codec)?; | 588 | hw_decodes(&path, start_frame, meta.codec)?; |
| 415 | } | 589 | } |
| 416 | let end_frame = end_frame.min(meta.frame_count); | 590 | let end_frame = end_frame.min(meta.frame_count); |
| 417 | - // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the | ||
| 418 | - // decoder run ahead of the display without limit. | ||
| 419 | - let (tx, rx) = sync_channel(2); | ||
| 420 | - let cancel = Arc::new(AtomicBool::new(false)); | ||
| 421 | - // Written by the worker below the moment it knows, so a caller reading | ||
| 422 | - // it sees what opened rather than what was hoped for. | ||
| 423 | - let backend = BackendCell::default(); | ||
| 424 | if end_frame <= start_frame { | 591 | if end_frame <= start_frame { |
| 425 | - // Nothing to decode: dropping `tx` here closes the channel cleanly, | 592 | + // Nothing to decode: a disconnected receiver and no thread at all, |
| 426 | // so the caller sees an immediate end of stream rather than an error. | 593 | // so the caller sees an immediate end of stream rather than an error. |
| 594 | + let (_, rx) = sync_channel(1); | ||
| 427 | return Ok(( | 595 | return Ok(( |
| 428 | meta, | 596 | meta, |
| 429 | FrameStream { | 597 | FrameStream { |
| 430 | frames: rx, | 598 | frames: rx, |
| 431 | worker: Worker { | 599 | worker: Worker { |
| 432 | - cancel, | 600 | + cancel: Arc::new(AtomicBool::new(false)), |
| 433 | handle: None, | 601 | handle: None, |
| 602 | + reuse: None, | ||
| 434 | }, | 603 | }, |
| 435 | - backend, | 604 | + backend: BackendCell::default(), |
| 436 | }, | 605 | }, |
| 437 | )); | 606 | )); |
| 438 | } | 607 | } |
| 439 | - let worker_cancel = Arc::clone(&cancel); | ||
| 440 | - let worker_backend = backend.clone(); | ||
| 441 | - let handle = thread::Builder::new() | ||
| 442 | - .name("decode".into()) | ||
| 443 | - .spawn(move || { | ||
| 444 | - decode_span( | ||
| 445 | - &path, | ||
| 446 | - demuxer, | ||
| 447 | - meta, | ||
| 448 | - start_frame, | ||
| 449 | - end_frame, | ||
| 450 | - color, | ||
| 451 | - canvas, | ||
| 452 | - tone, | ||
| 453 | - tx, | ||
| 454 | - &worker_cancel, | ||
| 455 | - &worker_backend, | ||
| 456 | - ) | ||
| 457 | - })?; | ||
| 458 | Ok(( | 608 | Ok(( |
| 459 | meta, | 609 | meta, |
| 460 | - FrameStream { | 610 | + span_worker( |
| 461 | - frames: rx, | 611 | + path, |
| 462 | - worker: Worker { | 612 | + Some(Source::demuxed(demuxer, meta)), |
| 463 | - cancel, | 613 | + start_frame, |
| 464 | - handle: Some(handle), | 614 | + end_frame, |
| 465 | - }, | 615 | + color, |
| 466 | - backend, | 616 | + canvas, |
| 467 | - }, | 617 | + tone, |
| 618 | + ), | ||
| 468 | )) | 619 | )) |
| 469 | } | 620 | } |
| 470 | 621 | ||
| @@ -488,120 +639,312 @@ impl DecodeSession { | |||
| 488 | canvas: Composer, | 639 | canvas: Composer, |
| 489 | tone: tonemap::Preset, | 640 | tone: tonemap::Preset, |
| 490 | ) -> FrameStream { | 641 | ) -> FrameStream { |
| 491 | - let path = path.as_ref().to_path_buf(); | 642 | + span_worker( |
| 492 | - let (tx, rx) = sync_channel(2); | 643 | + path.as_ref().to_path_buf(), |
| 493 | - let cancel = Arc::new(AtomicBool::new(false)); | 644 | + None, |
| 494 | - let backend = BackendCell::default(); | 645 | + start_frame, |
| 495 | - let worker_cancel = Arc::clone(&cancel); | 646 | + end_frame, |
| 496 | - let worker_backend = backend.clone(); | 647 | + color, |
| 497 | - let handle = thread::Builder::new() | 648 | + canvas, |
| 498 | - .name("decode".into()) | 649 | + tone, |
| 499 | - .spawn(move || { | 650 | + ) |
| 500 | - // Cancelled before this thread was even scheduled: do not open | ||
| 501 | - // the file at all. A scrub abandons workers by the dozen and | ||
| 502 | - // this is where all but the last of them stop. | ||
| 503 | - if worker_cancel.load(Ordering::Relaxed) { | ||
| 504 | - return; | ||
| 505 | - } | ||
| 506 | - let (meta, demuxer) = match Demuxer::open(&path) { | ||
| 507 | - Ok(opened) => opened, | ||
| 508 | - Err(e) => { | ||
| 509 | - eprintln!("video open failed: {e}"); | ||
| 510 | - // Dropping `tx` disconnects the receiver, which is the | ||
| 511 | - // session's "walk on to the next span". | ||
| 512 | - worker_backend.set(Backend::Gap); | ||
| 513 | - return; | ||
| 514 | - } | ||
| 515 | - }; | ||
| 516 | - decode_span( | ||
| 517 | - &path, | ||
| 518 | - demuxer, | ||
| 519 | - meta, | ||
| 520 | - start_frame, | ||
| 521 | - // The clamp the sync opener does with the metadata it read | ||
| 522 | - // on the caller's thread; here the metadata arrives first. | ||
| 523 | - end_frame.min(meta.frame_count), | ||
| 524 | - color, | ||
| 525 | - canvas, | ||
| 526 | - tone, | ||
| 527 | - tx, | ||
| 528 | - &worker_cancel, | ||
| 529 | - &worker_backend, | ||
| 530 | - ) | ||
| 531 | - }) | ||
| 532 | - .ok(); | ||
| 533 | - FrameStream { | ||
| 534 | - frames: rx, | ||
| 535 | - worker: Worker { cancel, handle }, | ||
| 536 | - backend, | ||
| 537 | - } | ||
| 538 | } | 651 | } |
| 539 | } | 652 | } |
| 540 | 653 | ||
| 541 | -/// One worker thread's whole job, on that thread: pick the decoder, decode | 654 | +/// Spawns a decode worker over `path` and gives it its first span. The thread |
| 542 | -/// `[start_frame, end_frame)`, send the pictures. Both openers end here -- the | 655 | +/// **outlives that span**: it parks on its command channel afterwards, so the |
| 543 | -/// sync one, which demuxed on the caller's thread, and the deferred one, which | 656 | +/// next seek onto the same file reaches it through [`Worker::reseek`] and costs |
| 544 | -/// demuxed on this one -- so there is exactly one description of what a decode | 657 | +/// a demuxer seek and a decoder flush instead of a thread, a container parse and |
| 545 | -/// worker does, whoever opened the file. | 658 | +/// a VA-API initialisation (98 ms measured worst case). |
| 659 | +/// | ||
| 660 | +/// `opened` is the file when the caller already read it (the sync opener, which | ||
| 661 | +/// demuxes on the caller's thread to have metadata to return); `None` is the | ||
| 662 | +/// deferred one, where the worker opens it and nothing here touches the disk. | ||
| 546 | #[allow(clippy::too_many_arguments)] | 663 | #[allow(clippy::too_many_arguments)] |
| 547 | -fn decode_span( | 664 | +fn span_worker( |
| 548 | - path: &PathBuf, | 665 | + path: PathBuf, |
| 549 | - demuxer: Demuxer, | 666 | + opened: Option<Source>, |
| 550 | - meta: VideoMeta, | ||
| 551 | start_frame: u32, | 667 | start_frame: u32, |
| 552 | end_frame: u32, | 668 | end_frame: u32, |
| 553 | color: ColorParams, | 669 | color: ColorParams, |
| 554 | canvas: Composer, | 670 | canvas: Composer, |
| 555 | tone: tonemap::Preset, | 671 | tone: tonemap::Preset, |
| 556 | - tx: SyncSender<Frame>, | 672 | +) -> FrameStream { |
| 557 | - cancel: &AtomicBool, | 673 | + // The depth is the size of the pictures this worker will *emit*, which for a |
| 674 | + // pass-through canvas is the stream's own -- and the sync opener has already | ||
| 675 | + // read that on the caller's thread. Asking the canvas alone is how the file | ||
| 676 | + // door came up with 2: every session opens pass-through (a freshly opened | ||
| 677 | + // file *is* the project resolution), so a whole file would play at the | ||
| 678 | + // decode-ahead this engine had before there was one, until the first seek | ||
| 679 | + // built a real canvas. | ||
| 680 | + let depth = match (&opened, canvas.places_nothing()) { | ||
| 681 | + (Some(source), true) => crate::scale::queue_depth(source.meta.width, source.meta.height), | ||
| 682 | + _ => canvas.queue_depth(), | ||
| 683 | + }; | ||
| 684 | + let (tx, rx) = sync_channel(depth); | ||
| 685 | + let cancel = Arc::new(AtomicBool::new(false)); | ||
| 686 | + // Written by the worker the moment it knows, so a caller reading it sees | ||
| 687 | + // what opened rather than what was hoped for -- and kept across the spans | ||
| 688 | + // that follow, since they are decoded by that very decoder. | ||
| 689 | + let backend = BackendCell::default(); | ||
| 690 | + let generation = Arc::new(AtomicU64::new(0)); | ||
| 691 | + // The playhead starts where the span does: nothing is behind it yet. | ||
| 692 | + let floor = Arc::new(AtomicU32::new(start_frame)); | ||
| 693 | + let (spans, commands) = std::sync::mpsc::channel(); | ||
| 694 | + let first = SpanCmd { | ||
| 695 | + generation: 0, | ||
| 696 | + start: start_frame, | ||
| 697 | + end: end_frame, | ||
| 698 | + color, | ||
| 699 | + canvas, | ||
| 700 | + tone, | ||
| 701 | + tx, | ||
| 702 | + }; | ||
| 703 | + let worker_cancel = Arc::clone(&cancel); | ||
| 704 | + let worker_backend = backend.clone(); | ||
| 705 | + let worker_generation = Arc::clone(&generation); | ||
| 706 | + let worker_floor = Arc::clone(&floor); | ||
| 707 | + let worker_path = path.clone(); | ||
| 708 | + let handle = thread::Builder::new() | ||
| 709 | + .name("decode".into()) | ||
| 710 | + .spawn(move || { | ||
| 711 | + let mut source = opened; | ||
| 712 | + let mut cmd = first; | ||
| 713 | + loop { | ||
| 714 | + let abort = Abort { | ||
| 715 | + cancel: &worker_cancel, | ||
| 716 | + generation: &worker_generation, | ||
| 717 | + mine: cmd.generation, | ||
| 718 | + floor: &worker_floor, | ||
| 719 | + }; | ||
| 720 | + // Superseded (or cancelled) before this thread was even | ||
| 721 | + // scheduled: do not open the file, and do not enter VA-API | ||
| 722 | + // initialisation, which is the one stretch a cancel cannot | ||
| 723 | + // interrupt. A scrub abandons spans by the dozen and this is | ||
| 724 | + // where all but the last of them stop. | ||
| 725 | + if !abort.hit() { | ||
| 726 | + run_span(&worker_path, &mut source, cmd, &abort, &worker_backend); | ||
| 727 | + } | ||
| 728 | + // Parked between spans. A seek and a clip boundary arrive in | ||
| 729 | + // milliseconds and find the decoder still open, which is the | ||
| 730 | + // whole point of this thread -- but a session nobody comes back | ||
| 731 | + // to (the timeline played out, the window was left alone) must | ||
| 732 | + // not sit on the driver: it would hold a live libva thread into | ||
| 733 | + // whatever exit path the process takes, which is the SIGSEGV in | ||
| 734 | + // Mesa's `atexit` the retired pool exists to prevent, and | ||
| 735 | + // holding it *while idle* would widen that from "quit during a | ||
| 736 | + // decode" to "quit any time after opening a file". | ||
| 737 | + // | ||
| 738 | + // So the wait is in two halves: the fast one keeps everything, | ||
| 739 | + // and past [`IDLE`] the hardware session is closed. The demuxer | ||
| 740 | + // stays -- it is a file handle and an index, not driver state, | ||
| 741 | + // and rebuilding it is what costs seconds on a big Matroska -- | ||
| 742 | + // so the reseek after a long pause pays one VA-API init and | ||
| 743 | + // nothing else. | ||
| 744 | + match commands.recv_timeout(IDLE) { | ||
| 745 | + Ok(next) => cmd = next, | ||
| 746 | + Err(RecvTimeoutError::Timeout) => { | ||
| 747 | + if let Some(source) = &mut source | ||
| 748 | + && source.hw.take().is_some() | ||
| 749 | + { | ||
| 750 | + eprintln!("decode worker idle: hardware session closed"); | ||
| 751 | + } | ||
| 752 | + // The session dropped the command channel: this worker | ||
| 753 | + // is retired (or was detached), so the file goes now. | ||
| 754 | + match commands.recv() { | ||
| 755 | + Ok(next) => cmd = next, | ||
| 756 | + Err(_) => return, | ||
| 757 | + } | ||
| 758 | + } | ||
| 759 | + Err(RecvTimeoutError::Disconnected) => return, | ||
| 760 | + } | ||
| 761 | + } | ||
| 762 | + }) | ||
| 763 | + .ok(); | ||
| 764 | + FrameStream { | ||
| 765 | + frames: rx, | ||
| 766 | + worker: Worker { | ||
| 767 | + cancel, | ||
| 768 | + handle, | ||
| 769 | + reuse: Some(Reuse { | ||
| 770 | + path, | ||
| 771 | + spans, | ||
| 772 | + generation, | ||
| 773 | + backend: backend.clone(), | ||
| 774 | + floor, | ||
| 775 | + }), | ||
| 776 | + }, | ||
| 777 | + backend, | ||
| 778 | + } | ||
| 779 | +} | ||
| 780 | + | ||
| 781 | +/// How long a parked worker keeps its hardware session before closing it. Long | ||
| 782 | +/// enough that a seek, a scrub step and a clip boundary all find the decoder | ||
| 783 | +/// where they left it; short enough that a session left alone is not holding | ||
| 784 | +/// libva when the process exits. | ||
| 785 | +const IDLE: std::time::Duration = std::time::Duration::from_secs(2); | ||
| 786 | + | ||
| 787 | +/// How many pictures in a row a worker may drop for being late before it hands | ||
| 788 | +/// one over regardless. The policy needs a floor of its own: a machine that | ||
| 789 | +/// cannot decode a file in real time is late on *every* picture, and dropping | ||
| 790 | +/// every picture is a black screen rather than a stutter -- so the slowest seat | ||
| 791 | +/// still gets one in nine, which is roughly what it could paint before (the | ||
| 792 | +/// front-end restarted the decoder once every two seconds to the same effect, | ||
| 793 | +/// and paid a VA-API init for each restart). | ||
| 794 | +const LATE_RUN: u32 = 8; | ||
| 795 | + | ||
| 796 | +/// What a decode worker keeps **between** the spans it is asked for: the | ||
| 797 | +/// container it read, what the stream says about itself, and the hardware | ||
| 798 | +/// session -- the three things a seek used to throw away and buy again. | ||
| 799 | +struct Source { | ||
| 800 | + meta: VideoMeta, | ||
| 801 | + /// What the film says its brightest picture is ([`Demuxer::light`]): the | ||
| 802 | + /// tone map's assumed peak on the reference rendition, so a 1759 cd/m^2 | ||
| 803 | + /// grade is converted at 1759 rather than at the 1000 a file that declared | ||
| 804 | + /// nothing is assumed at. A property of the stream, read once with it. | ||
| 805 | + peak: Option<f32>, | ||
| 806 | + demuxer: Demuxer, | ||
| 807 | + /// The plugin's session, opened on this thread (its VA-API state is not | ||
| 808 | + /// `Send`-safe across a hand-off) and *kept*. `None` for software: forced by | ||
| 809 | + /// `VE_SW`, refused by the plugin, or handed back by a session that opened | ||
| 810 | + /// and then decoded nothing. | ||
| 811 | + hw: Option<HwSession>, | ||
| 812 | +} | ||
| 813 | + | ||
| 814 | +impl Source { | ||
| 815 | + /// The file as the sync opener already read it. | ||
| 816 | + fn demuxed(demuxer: Demuxer, meta: VideoMeta) -> Self { | ||
| 817 | + Self { | ||
| 818 | + meta, | ||
| 819 | + peak: demuxer.light().peak(), | ||
| 820 | + demuxer, | ||
| 821 | + hw: None, | ||
| 822 | + } | ||
| 823 | + } | ||
| 824 | + | ||
| 825 | + /// ...and as the deferred opener reads it, on the worker. `None` is a file | ||
| 826 | + /// that would not open: the caller drops the sender, and the disconnected | ||
| 827 | + /// receiver is the session's "walk on to the next span". | ||
| 828 | + fn open(path: &Path) -> Option<Self> { | ||
| 829 | + match Demuxer::open(path) { | ||
| 830 | + Ok((meta, demuxer)) => Some(Self::demuxed(demuxer, meta)), | ||
| 831 | + Err(e) => { | ||
| 832 | + eprintln!("video open failed: {e}"); | ||
| 833 | + None | ||
| 834 | + } | ||
| 835 | + } | ||
| 836 | + } | ||
| 837 | + | ||
| 838 | + /// Puts the hardware decoder at `start`, keeping the session open where the | ||
| 839 | + /// plugin can reposition it. `None` when there is no hardware here at all; | ||
| 840 | + /// otherwise whether the session was **reused** -- which is what lets the | ||
| 841 | + /// caller tell a driver that cannot decode this stream from one that merely | ||
| 842 | + /// did not follow a reseek. | ||
| 843 | + fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> { | ||
| 844 | + if let Some(hw) = &mut self.hw { | ||
| 845 | + if hw.seek(start) { | ||
| 846 | + eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})"); | ||
| 847 | + return Some(true); | ||
| 848 | + } | ||
| 849 | + // A plugin too old to reposition, or a decoder that would not | ||
| 850 | + // flush: closed and opened again, which is what every seek did. | ||
| 851 | + self.hw = None; | ||
| 852 | + } | ||
| 853 | + self.hw = open_hw(path, start); | ||
| 854 | + self.hw.as_ref().map(|_| { | ||
| 855 | + eprintln!("decode backend: hardware (VA-API plugin)"); | ||
| 856 | + false | ||
| 857 | + }) | ||
| 858 | + } | ||
| 859 | +} | ||
| 860 | + | ||
| 861 | +/// One span on a worker's thread: position the decoder, decode | ||
| 862 | +/// `[start, end)`, send the pictures. Every opener ends here -- the sync one, | ||
| 863 | +/// which demuxed on the caller's thread, the deferred one, which demuxes on | ||
| 864 | +/// this one, and every reseek after them -- so there is exactly one description | ||
| 865 | +/// of what a decode worker does. | ||
| 866 | +fn run_span( | ||
| 867 | + path: &Path, | ||
| 868 | + source: &mut Option<Source>, | ||
| 869 | + cmd: SpanCmd, | ||
| 870 | + abort: &Abort, | ||
| 558 | backend: &BackendCell, | 871 | backend: &BackendCell, |
| 559 | ) { | 872 | ) { |
| 873 | + let SpanCmd { | ||
| 874 | + start, | ||
| 875 | + end, | ||
| 876 | + color, | ||
| 877 | + canvas, | ||
| 878 | + tone, | ||
| 879 | + tx, | ||
| 880 | + .. | ||
| 881 | + } = cmd; | ||
| 882 | + let opened = match source { | ||
| 883 | + Some(opened) => opened, | ||
| 884 | + None => { | ||
| 885 | + let Some(fresh) = Source::open(path) else { | ||
| 886 | + backend.set(Backend::Gap); | ||
| 887 | + return; | ||
| 888 | + }; | ||
| 889 | + source.insert(fresh) | ||
| 890 | + } | ||
| 891 | + }; | ||
| 892 | + // The clamp the sync opener does with the metadata it read on the caller's | ||
| 893 | + // thread; here the metadata arrives first. | ||
| 894 | + let end = end.min(opened.meta.frame_count); | ||
| 560 | // An empty range decodes nothing and must send nothing: `run_hw` counts a | 895 | // An empty range decodes nothing and must send nothing: `run_hw` counts a |
| 561 | // frame *out* before it compares, so without this a zero-length span would | 896 | // frame *out* before it compares, so without this a zero-length span would |
| 562 | - // emit one picture. The sync opener never even spawns for this case. | 897 | + // emit one picture. |
| 563 | - if end_frame <= start_frame { | 898 | + if end <= start { |
| 564 | return; | 899 | return; |
| 565 | } | 900 | } |
| 566 | - // Cancelled before this thread was even scheduled -- do not enter VA-API | 901 | + // The stream's own colour and peak brightness: properties of the stream, so |
| 567 | - // initialisation at all, because that is the one stretch a cancel cannot | 902 | + // neither can change while one range decodes -- but the grade, the canvas |
| 568 | - // interrupt (~65-90 ms of driver setup that would then have to be torn | 903 | + // and the rendition are the *span's*, so this is built per span. |
| 569 | - // down again). | 904 | + let mut render = Render::new(color, opened.meta.color, canvas, tone, opened.peak); |
| 570 | - if cancel.load(Ordering::Relaxed) { | 905 | + if let Some(reused) = opened.position_hw(path, start) { |
| 571 | - return; | 906 | + // Cancelled during the init (or the seek): leave without decoding. |
| 572 | - } | 907 | + if abort.hit() { |
| 573 | - // The stream's own colour, and with it what the film says its brightest | ||
| 574 | - // picture is ([`Demuxer::light`]): the tone map's assumed peak on the | ||
| 575 | - // reference rendition, so a 1759 cd/m^2 grade is converted at 1759 rather | ||
| 576 | - // than at the 1000 a file that declared nothing is assumed at. Both are | ||
| 577 | - // properties of the stream, so neither can change while one range decodes. | ||
| 578 | - let mut render = Render::new(color, meta.color, canvas, tone, demuxer.light().peak()); | ||
| 579 | - // The plugin has to be opened on the thread that uses it: its VA-API state | ||
| 580 | - // is not `Send`-safe across a later hand-off. | ||
| 581 | - if let Some(hw) = open_hw(path, start_frame) { | ||
| 582 | - // Cancelled *during* init: close the session (dropping `hw` does it) | ||
| 583 | - // and leave without decoding anything. | ||
| 584 | - if cancel.load(Ordering::Relaxed) { | ||
| 585 | return; | 908 | return; |
| 586 | } | 909 | } |
| 587 | - eprintln!("decode backend: hardware (VA-API plugin)"); | ||
| 588 | backend.set(Backend::Hardware); | 910 | backend.set(Backend::Hardware); |
| 589 | - if run_hw(hw, &tx, start_frame, end_frame, &mut render, cancel) { | 911 | + let mut decoded = run_hw( |
| 912 | + opened.hw.as_mut().expect("positioned above"), | ||
| 913 | + &tx, | ||
| 914 | + start, | ||
| 915 | + end, | ||
| 916 | + &mut render, | ||
| 917 | + abort, | ||
| 918 | + ); | ||
| 919 | + // A *reused* session that produced nothing may simply be one this | ||
| 920 | + // reseek left where the driver would not follow; a session opened fresh | ||
| 921 | + // at the same frame is the honest second question, and only its silence | ||
| 922 | + // is a software fallback. Without this a single unfollowed seek would | ||
| 923 | + // collapse the rest of the file to software. | ||
| 924 | + if !decoded && reused { | ||
| 925 | + eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}"); | ||
| 926 | + opened.hw = open_hw(path, start); | ||
| 927 | + if let Some(hw) = opened.hw.as_mut() { | ||
| 928 | + decoded = run_hw(hw, &tx, start, end, &mut render, abort); | ||
| 929 | + } | ||
| 930 | + } | ||
| 931 | + if decoded { | ||
| 590 | return; | 932 | return; |
| 591 | } | 933 | } |
| 592 | // A driver that opens but cannot decode a single frame is still a | 934 | // A driver that opens but cannot decode a single frame is still a |
| 593 | // fallback case, not a dead session. | 935 | // fallback case, not a dead session. |
| 936 | + opened.hw = None; | ||
| 594 | eprintln!("hardware decode failed before any frame, falling back to software"); | 937 | eprintln!("hardware decode failed before any frame, falling back to software"); |
| 595 | } | 938 | } |
| 596 | // ...except where there is nothing to fall back to. Feeding HEVC or VP9 | 939 | // ...except where there is nothing to fall back to. Feeding HEVC or VP9 |
| 597 | // bytes to `rusty_h264` would be garbage, not a fallback. | 940 | // bytes to `rusty_h264` would be garbage, not a fallback. |
| 598 | - if meta.codec != Codec::H264 { | 941 | + if opened.meta.codec != Codec::H264 { |
| 599 | - eprintln!("{}", meta.codec.needs_plugin()); | 942 | + eprintln!("{}", opened.meta.codec.needs_plugin()); |
| 600 | return; | 943 | return; |
| 601 | } | 944 | } |
| 602 | eprintln!("decode backend: software (rusty_h264)"); | 945 | eprintln!("decode backend: software (rusty_h264)"); |
| 603 | backend.set(Backend::Software); | 946 | backend.set(Backend::Software); |
| 604 | - run(demuxer, tx, start_frame, end_frame, &mut render, cancel) | 947 | + run(&mut opened.demuxer, &tx, start, end, &mut render, abort) |
| 605 | } | 948 | } |
| 606 | 949 | ||
| 607 | /// One clip's pictures on their way to the renderer: graded, placed on the | 950 | /// One clip's pictures on their way to the renderer: graded, placed on the |
| @@ -856,7 +1199,7 @@ fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Ve | |||
| 856 | 1199 | ||
| 857 | /// `None` when the software path must be used: forced by `VE_SW=1`, or the | 1200 | /// `None` when the software path must be used: forced by `VE_SW=1`, or the |
| 858 | /// plugin is absent/broken/unable to open this particular file. | 1201 | /// plugin is absent/broken/unable to open this particular file. |
| 859 | -fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> { | 1202 | +fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> { |
| 860 | if std::env::var_os("VE_SW").is_some_and(|v| v == "1") { | 1203 | if std::env::var_os("VE_SW").is_some_and(|v| v == "1") { |
| 861 | return None; | 1204 | return None; |
| 862 | } | 1205 | } |
| @@ -893,24 +1236,33 @@ fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), Stri | |||
| 893 | /// counted from there (a stream whose very first sample is not a sync sample | 1236 | /// counted from there (a stream whose very first sample is not a sync sample |
| 894 | /// cannot be decoded from its start at all, and is not accounted for). | 1237 | /// cannot be decoded from its start at all, and is not accounted for). |
| 895 | fn run_hw( | 1238 | fn run_hw( |
| 896 | - mut hw: HwSession, | 1239 | + hw: &mut HwSession, |
| 897 | tx: &SyncSender<Frame>, | 1240 | tx: &SyncSender<Frame>, |
| 898 | start_frame: u32, | 1241 | start_frame: u32, |
| 899 | end_frame: u32, | 1242 | end_frame: u32, |
| 900 | render: &mut Render, | 1243 | render: &mut Render, |
| 901 | - cancel: &AtomicBool, | 1244 | + abort: &Abort, |
| 902 | ) -> bool { | 1245 | ) -> bool { |
| 903 | let mut index = start_frame; | 1246 | let mut index = start_frame; |
| 1247 | + // Pictures dropped for being late since the last one handed over; see | ||
| 1248 | + // [`LATE_RUN`]. | ||
| 1249 | + let mut skipped = 0; | ||
| 904 | loop { | 1250 | loop { |
| 905 | - if cancel.load(Ordering::Relaxed) { | 1251 | + if abort.hit() { |
| 906 | return true; | 1252 | return true; |
| 907 | } | 1253 | } |
| 908 | match hw.next_frame() { | 1254 | match hw.next_frame() { |
| 909 | Ok(Some((y, u, v, width, height))) => { | 1255 | Ok(Some((y, u, v, width, height))) => { |
| 910 | - let frame = render.frame(index, y, u, v, width, height); | 1256 | + let due = index; |
| 911 | index += 1; | 1257 | index += 1; |
| 912 | - if tx.send(frame).is_err() { | 1258 | + if abort.late(due) && skipped < LATE_RUN { |
| 913 | - return true; // consumer went away | 1259 | + skipped += 1; |
| 1260 | + } else { | ||
| 1261 | + skipped = 0; | ||
| 1262 | + let frame = render.frame(due, y, u, v, width, height); | ||
| 1263 | + if tx.send(frame).is_err() { | ||
| 1264 | + return true; // consumer went away | ||
| 1265 | + } | ||
| 914 | } | 1266 | } |
| 915 | if index >= end_frame { | 1267 | if index >= end_frame { |
| 916 | return true; // end of the requested range | 1268 | return true; // end of the requested range |
| @@ -1022,6 +1374,59 @@ mod tests { | |||
| 1022 | ); | 1374 | ); |
| 1023 | } | 1375 | } |
| 1024 | 1376 | ||
| 1377 | + /// The late-picture policy, at the one place it is decided. A worker told | ||
| 1378 | + /// the playhead is already at frame 20 must not spend a conversion and a | ||
| 1379 | + /// queue slot on the twenty pictures behind it -- they can never be shown -- | ||
| 1380 | + /// and it must not go silent either, which is what [`LATE_RUN`] bounds: a | ||
| 1381 | + /// machine that cannot decode in real time is late on every picture, and one | ||
| 1382 | + /// in nine still reaches the screen. | ||
| 1383 | + /// | ||
| 1384 | + /// Deterministic on purpose: the floor is set by hand rather than by a clock | ||
| 1385 | + /// that would have to outrun a debug-build decoder to prove anything. | ||
| 1386 | + #[test] | ||
| 1387 | + fn a_worker_skips_the_pictures_the_playhead_has_gone_past() { | ||
| 1388 | + let take = |floor: u32| { | ||
| 1389 | + let stream = DecodeSession::open_worker_deferred( | ||
| 1390 | + asset("test_baseline.mp4"), | ||
| 1391 | + 0, | ||
| 1392 | + u32::MAX, | ||
| 1393 | + ColorParams::default(), | ||
| 1394 | + Composer::passthrough(), | ||
| 1395 | + tonemap::Preset::default(), | ||
| 1396 | + ); | ||
| 1397 | + stream.worker.playhead(floor); | ||
| 1398 | + let mut indices = Vec::new(); | ||
| 1399 | + while indices.len() < 4 { | ||
| 1400 | + let frame = stream | ||
| 1401 | + .frames | ||
| 1402 | + .recv_timeout(Duration::from_secs(10)) | ||
| 1403 | + .expect("a picture"); | ||
| 1404 | + indices.push(frame.index); | ||
| 1405 | + } | ||
| 1406 | + indices | ||
| 1407 | + }; | ||
| 1408 | + | ||
| 1409 | + // Nobody has moved: every picture of the range is owed, in order. | ||
| 1410 | + assert_eq!(take(0), vec![0, 1, 2, 3]); | ||
| 1411 | + | ||
| 1412 | + // The playhead is at 20, so the pictures before it are decoded (the ones | ||
| 1413 | + // after reference them) and dropped unconverted -- all but the one in | ||
| 1414 | + // nine [`LATE_RUN`] lets through, so the caller never goes blind. | ||
| 1415 | + let caught_up = take(20); | ||
| 1416 | + assert!( | ||
| 1417 | + caught_up[0] > 0 && caught_up.windows(2).any(|w| w[1] > w[0] + 1), | ||
| 1418 | + "nothing was skipped: {caught_up:?}" | ||
| 1419 | + ); | ||
| 1420 | + assert!( | ||
| 1421 | + caught_up.iter().any(|&i| i >= 20), | ||
| 1422 | + "the playhead was never reached: {caught_up:?}" | ||
| 1423 | + ); | ||
| 1424 | + assert!( | ||
| 1425 | + caught_up.len() >= 4, | ||
| 1426 | + "the worker went silent instead of dropping down to one in nine" | ||
| 1427 | + ); | ||
| 1428 | + } | ||
| 1429 | + | ||
| 1025 | /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait. | 1430 | /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait. |
| 1026 | /// The channel is bounded, so such a worker is parked in `send` within a | 1431 | /// The channel is bounded, so such a worker is parked in `send` within a |
| 1027 | /// few frames, and the only thing that can wake it is its receiver going | 1432 | /// few frames, and the only thing that can wake it is its receiver going |
| @@ -1060,24 +1465,28 @@ mod tests { | |||
| 1060 | } | 1465 | } |
| 1061 | 1466 | ||
| 1062 | fn run( | 1467 | fn run( |
| 1063 | - mut demuxer: Demuxer, | 1468 | + demuxer: &mut Demuxer, |
| 1064 | - tx: SyncSender<Frame>, | 1469 | + tx: &SyncSender<Frame>, |
| 1065 | start_frame: u32, | 1470 | start_frame: u32, |
| 1066 | end_frame: u32, | 1471 | end_frame: u32, |
| 1067 | render: &mut Render, | 1472 | render: &mut Render, |
| 1068 | - cancel: &AtomicBool, | 1473 | + abort: &Abort, |
| 1069 | ) { | 1474 | ) { |
| 1475 | + // A decoder per span, and cheap: it is a parameter-set map and a picture | ||
| 1476 | + // buffer, while the *demuxer* -- whose index cost seconds to build -- is the | ||
| 1477 | + // one this worker keeps. | ||
| 1070 | let mut decoder = Decoder::new(); | 1478 | let mut decoder = Decoder::new(); |
| 1071 | // Decoding has to restart at a sync sample, so pictures between it and | 1479 | // Decoding has to restart at a sync sample, so pictures between it and |
| 1072 | // `start_frame` are decoded (the target frame references them) but never | 1480 | // `start_frame` are decoded (the target frame references them) but never |
| 1073 | // converted or sent. Signed, because the landing sync sample can sit inside | 1481 | // converted or sent. Signed, because the landing sync sample can sit inside |
| 1074 | // what the file's edit list trims, i.e. *before* frame 0. | 1482 | // what the file's edit list trims, i.e. *before* frame 0. |
| 1075 | let mut index = demuxer.seek_to_sync_at_or_before(start_frame); | 1483 | let mut index = demuxer.seek_to_sync_at_or_before(start_frame); |
| 1484 | + let mut skipped = 0; | ||
| 1076 | 1485 | ||
| 1077 | // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames); | 1486 | // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames); |
| 1078 | // reordering streams need POC-sorted output before display. | 1487 | // reordering streams need POC-sorted output before display. |
| 1079 | loop { | 1488 | loop { |
| 1080 | - if cancel.load(Ordering::Relaxed) { | 1489 | + if abort.hit() { |
| 1081 | break; | 1490 | break; |
| 1082 | } | 1491 | } |
| 1083 | let au = match demuxer.next_access_unit() { | 1492 | let au = match demuxer.next_access_unit() { |
| @@ -1100,17 +1509,23 @@ fn run( | |||
| 1100 | index += 1; | 1509 | index += 1; |
| 1101 | continue; | 1510 | continue; |
| 1102 | } | 1511 | } |
| 1103 | - let frame = render.frame( | 1512 | + let due = index as u32; |
| 1104 | - index as u32, | ||
| 1105 | - &yuv.y, | ||
| 1106 | - &yuv.u, | ||
| 1107 | - &yuv.v, | ||
| 1108 | - yuv.width as u32, | ||
| 1109 | - yuv.height as u32, | ||
| 1110 | - ); | ||
| 1111 | index += 1; | 1513 | index += 1; |
| 1112 | - if tx.send(frame).is_err() { | 1514 | + if abort.late(due) && skipped < LATE_RUN { |
| 1113 | - break; // consumer went away | 1515 | + skipped += 1; |
| 1516 | + } else { | ||
| 1517 | + skipped = 0; | ||
| 1518 | + let frame = render.frame( | ||
| 1519 | + due, | ||
| 1520 | + &yuv.y, | ||
| 1521 | + &yuv.u, | ||
| 1522 | + &yuv.v, | ||
| 1523 | + yuv.width as u32, | ||
| 1524 | + yuv.height as u32, | ||
| 1525 | + ); | ||
| 1526 | + if tx.send(frame).is_err() { | ||
| 1527 | + break; // consumer went away | ||
| 1528 | + } | ||
| 1114 | } | 1529 | } |
| 1115 | if index >= i64::from(end_frame) { | 1530 | if index >= i64::from(end_frame) { |
| 1116 | break; // end of the requested range | 1531 | break; // end of the requested range |
crates/engine/src/hw.rsmodified+27 -0
| @@ -95,6 +95,11 @@ struct Plugin { | |||
| 95 | /// missing: a plugin built before it exports the four above and not this, | 95 | /// missing: a plugin built before it exports the four above and not this, |
| 96 | /// which costs a front-end the listing and never a decode. | 96 | /// which costs a front-end the listing and never a decode. |
| 97 | caps: Option<unsafe extern "C" fn(*mut VhCaps) -> i32>, | 97 | caps: Option<unsafe extern "C" fn(*mut VhCaps) -> i32>, |
| 98 | + /// Repositioning an open session, and optional for the reason `caps` is: a | ||
| 99 | + /// plugin built before it decodes exactly as it did, and a caller that | ||
| 100 | + /// cannot reposition closes the session and opens another -- which is what | ||
| 101 | + /// every seek did before this symbol existed. | ||
| 102 | + seek: Option<unsafe extern "C" fn(*mut c_void, u32) -> i32>, | ||
| 98 | // Never dropped (lives in a static), so the fn pointers above stay valid. | 103 | // Never dropped (lives in a static), so the fn pointers above stay valid. |
| 99 | _lib: Library, | 104 | _lib: Library, |
| 100 | } | 105 | } |
| @@ -131,6 +136,7 @@ fn load() -> Option<Plugin> { | |||
| 131 | next_frame: *lib.get(b"vh_next_frame\0").ok()?, | 136 | next_frame: *lib.get(b"vh_next_frame\0").ok()?, |
| 132 | close: *lib.get(b"vh_close\0").ok()?, | 137 | close: *lib.get(b"vh_close\0").ok()?, |
| 133 | caps: lib.get(b"vh_caps\0").ok().map(|s| *s), | 138 | caps: lib.get(b"vh_caps\0").ok().map(|s| *s), |
| 139 | + seek: lib.get(b"vh_seek\0").ok().map(|s| *s), | ||
| 134 | _lib: lib, | 140 | _lib: lib, |
| 135 | }) | 141 | }) |
| 136 | })() | 142 | })() |
| @@ -194,6 +200,27 @@ impl HwSession { | |||
| 194 | Some(Self { plugin, handle }) | 200 | Some(Self { plugin, handle }) |
| 195 | } | 201 | } |
| 196 | 202 | ||
| 203 | + /// Repositions this very session so the next [`HwSession::next_frame`] | ||
| 204 | + /// returns display index `start_frame` -- the same landing | ||
| 205 | + /// [`HwSession::open_at`] gives, without the VA-API initialisation (~90 ms), | ||
| 206 | + /// the render node probe and the container parse that opening one again | ||
| 207 | + /// costs. What lets a decode worker outlive the seeks its caller makes. | ||
| 208 | + /// | ||
| 209 | + /// `false` when the plugin cannot do it -- too old to export the symbol, or | ||
| 210 | + /// a decoder that would not flush -- and the caller then opens a new session | ||
| 211 | + /// exactly as it always did. The session is left untouched either way, so a | ||
| 212 | + /// `false` is never a half-moved decoder. | ||
| 213 | + pub fn seek(&mut self, start_frame: u32) -> bool { | ||
| 214 | + let Some(seek) = self.plugin.seek else { | ||
| 215 | + return false; | ||
| 216 | + }; | ||
| 217 | + // Sample ids are 1-based, frame indices 0-based -- as in `open_at`. | ||
| 218 | + let target_sample = start_frame.saturating_add(1); | ||
| 219 | + // SAFETY: `handle` came from `vh_open_at` and is still open; the plugin | ||
| 220 | + // writes nothing through it and the call cannot unwind (it catches). | ||
| 221 | + unsafe { seek(self.handle, target_sample) == 0 } | ||
| 222 | + } | ||
| 223 | + | ||
| 197 | pub fn meta(&self) -> Option<VhMeta> { | 224 | pub fn meta(&self) -> Option<VhMeta> { |
| 198 | let mut meta = VhMeta::default(); | 225 | let mut meta = VhMeta::default(); |
| 199 | // SAFETY: `handle` came from `vh_open_at` and is still open. | 226 | // SAFETY: `handle` came from `vh_open_at` and is still open. |
crates/engine/src/playback.rsmodified+136 -31
| @@ -374,6 +374,10 @@ pub struct PlaybackSession { | |||
| 374 | /// of a restart is never counted as timeline time. See | 374 | /// of a restart is never counted as timeline time. See |
| 375 | /// [`Audio::content_at`]. | 375 | /// [`Audio::content_at`]. |
| 376 | priming: bool, | 376 | priming: bool, |
| 377 | + /// Whether the decode worker may drop a picture whose moment has already | ||
| 378 | + /// passed ([`Self::drop_late_pictures`]). Off unless a caller says it is | ||
| 379 | + /// watching this in real time. | ||
| 380 | + drop_late: bool, | ||
| 377 | } | 381 | } |
| 378 | 382 | ||
| 379 | /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the | 383 | /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the |
| @@ -488,6 +492,7 @@ impl PlaybackSession { | |||
| 488 | eos: false, | 492 | eos: false, |
| 489 | mix: None, | 493 | mix: None, |
| 490 | priming: false, | 494 | priming: false, |
| 495 | + drop_late: false, | ||
| 491 | }) | 496 | }) |
| 492 | } | 497 | } |
| 493 | 498 | ||
| @@ -600,6 +605,7 @@ impl PlaybackSession { | |||
| 600 | eos: false, | 605 | eos: false, |
| 601 | mix: None, | 606 | mix: None, |
| 602 | priming: false, | 607 | priming: false, |
| 608 | + drop_late: false, | ||
| 603 | }) | 609 | }) |
| 604 | } | 610 | } |
| 605 | 611 | ||
| @@ -676,6 +682,7 @@ impl PlaybackSession { | |||
| 676 | eos: false, | 682 | eos: false, |
| 677 | mix: None, | 683 | mix: None, |
| 678 | priming: false, | 684 | priming: false, |
| 685 | + drop_late: false, | ||
| 679 | }) | 686 | }) |
| 680 | } | 687 | } |
| 681 | 688 | ||
| @@ -969,6 +976,7 @@ impl PlaybackSession { | |||
| 969 | eos: false, | 976 | eos: false, |
| 970 | mix: None, | 977 | mix: None, |
| 971 | priming: false, | 978 | priming: false, |
| 979 | + drop_late: false, | ||
| 972 | }; | 980 | }; |
| 973 | // The scaffolding above opened source 0 from its first frame and the | 981 | // The scaffolding above opened source 0 from its first frame and the |
| 974 | // whole of its audio; this puts both onto the clip the playhead is | 982 | // whole of its audio; this puts both onto the clip the playhead is |
| @@ -1237,6 +1245,7 @@ impl PlaybackSession { | |||
| 1237 | /// big film, seconds off a cold cache). End of stream is | 1245 | /// big film, seconds off a cold cache). End of stream is |
| 1238 | /// [`PlaybackSession::is_eos`]. | 1246 | /// [`PlaybackSession::is_eos`]. |
| 1239 | pub fn try_frame(&mut self) -> Option<Frame> { | 1247 | pub fn try_frame(&mut self) -> Option<Frame> { |
| 1248 | + self.publish_playhead(); | ||
| 1240 | loop { | 1249 | loop { |
| 1241 | match self.frames.try_recv() { | 1250 | match self.frames.try_recv() { |
| 1242 | Ok(mut frame) => { | 1251 | Ok(mut frame) => { |
| @@ -1292,6 +1301,32 @@ impl PlaybackSession { | |||
| 1292 | self.eos | 1301 | self.eos |
| 1293 | } | 1302 | } |
| 1294 | 1303 | ||
| 1304 | + /// Tells the decode worker which frame of its *file* the clock has reached, | ||
| 1305 | + /// so the pictures it is holding that are already behind the playhead are | ||
| 1306 | + /// dropped where they are cheap to drop -- before the conversion and before | ||
| 1307 | + /// the queue -- instead of being converted, queued and thrown away by the | ||
| 1308 | + /// caller one repaint later. The whole of the late-frame policy: a decoder | ||
| 1309 | + /// that has fallen behind catches up by not painting what nobody can see, | ||
| 1310 | + /// rather than by being restarted every two seconds (`Player::pump`). | ||
| 1311 | + /// | ||
| 1312 | + /// The stamp is the exact inverse of the one [`try_frame`](Self::try_frame) | ||
| 1313 | + /// puts on a decoded frame: timeline frame -> the clip's own frames | ||
| 1314 | + /// ([`Span::speed`]) -> the file's ([`Rate`]). A gap and the emptied | ||
| 1315 | + /// timeline have no file to be inside of, and publish nothing. | ||
| 1316 | + fn publish_playhead(&self) { | ||
| 1317 | + if !self.drop_late { | ||
| 1318 | + return; | ||
| 1319 | + } | ||
| 1320 | + let Some(span) = self.span else { return }; | ||
| 1321 | + let Some((_, in_frame)) = span.from else { | ||
| 1322 | + return; | ||
| 1323 | + }; | ||
| 1324 | + let now = secs_to_frame(self.clock.now(), self.meta.frame_rate); | ||
| 1325 | + let offset = now.saturating_sub(span.start).min(span.len); | ||
| 1326 | + self.worker | ||
| 1327 | + .playhead(self.span_rate.source_at(in_frame + span.speed.source_at(offset))); | ||
| 1328 | + } | ||
| 1329 | + | ||
| 1295 | /// Installs `replacement` as the decode worker, parking the outgoing one in | 1330 | /// Installs `replacement` as the decode worker, parking the outgoing one in |
| 1296 | /// [`retired`](Self::retired) rather than joining it here, and reaping the | 1331 | /// [`retired`](Self::retired) rather than joining it here, and reaping the |
| 1297 | /// parked ones that have already returned. | 1332 | /// parked ones that have already returned. |
| @@ -1301,9 +1336,20 @@ impl PlaybackSession { | |||
| 1301 | /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's | 1336 | /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's |
| 1302 | /// worker on this seek and the list stays a handful long. Nothing waits. | 1337 | /// worker on this seek and the list stays a handful long. Nothing waits. |
| 1303 | fn retire(&mut self, replacement: Worker) { | 1338 | fn retire(&mut self, replacement: Worker) { |
| 1339 | + // A *replacement*, which is now the narrow case: a seek onto the file | ||
| 1340 | + // the worker already has open steers it instead ([`Worker::reseek`]) | ||
| 1341 | + // and never comes here, so this count is the picture restarts that | ||
| 1342 | + // really cost a thread and a decoder open -- which is what makes it | ||
| 1343 | + // worth counting. | ||
| 1304 | self.restarts += 1; | 1344 | self.restarts += 1; |
| 1305 | - self.retired | 1345 | + let mut outgoing = std::mem::replace(&mut self.worker, replacement); |
| 1306 | - .push(std::mem::replace(&mut self.worker, replacement)); | 1346 | + // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is |
| 1347 | + // being replaced rather than steered, so its thread has to end -- and | ||
| 1348 | + // the cancel is what drops its command channel, without which a worker | ||
| 1349 | + // parked between spans would sit in `recv` forever, never reaped here | ||
| 1350 | + // and never joined in any bounded time at exit. | ||
| 1351 | + outgoing.cancel(); | ||
| 1352 | + self.retired.push(outgoing); | ||
| 1307 | self.retired.retain(|w| !w.is_finished()); | 1353 | self.retired.retain(|w| !w.is_finished()); |
| 1308 | } | 1354 | } |
| 1309 | 1355 | ||
| @@ -1357,9 +1403,11 @@ impl PlaybackSession { | |||
| 1357 | let Some(span) = self.project.composite_span_at(next) else { | 1403 | let Some(span) = self.project.composite_span_at(next) else { |
| 1358 | return false; | 1404 | return false; |
| 1359 | }; | 1405 | }; |
| 1360 | - // We only get here on a disconnect, so the old worker has already | 1406 | + // We only get here on a disconnect, so the old span is already done; |
| 1361 | - // returned; cancel anyway, so `retire` treats every path alike. | 1407 | + // abandon anyway, so `start_span` treats every path alike -- and the |
| 1362 | - self.worker.cancel(); | 1408 | + // *worker* is kept, because the next clip is very often the same file |
| 1409 | + // (a split cuts one clip in two) and it already has it open. | ||
| 1410 | + self.worker.abandon(); | ||
| 1363 | self.start_span(Some(span)); | 1411 | self.start_span(Some(span)); |
| 1364 | true | 1412 | true |
| 1365 | } | 1413 | } |
| @@ -1419,36 +1467,58 @@ impl PlaybackSession { | |||
| 1419 | start, | 1467 | start, |
| 1420 | from: Some((source, in_frame)), | 1468 | from: Some((source, in_frame)), |
| 1421 | .. | 1469 | .. |
| 1422 | - }) => Ok(DecodeSession::open_worker_deferred( | 1470 | + }) => { |
| 1423 | - &self.project.sources()[source].path, | 1471 | + let path = &self.project.sources()[source].path; |
| 1424 | - // The file's own frames, which is the only place they exist: | 1472 | + // The file's own frames, which is the only place they exist: a |
| 1425 | - // a clip counts the timeline's ([`Rate`]). | 1473 | + // clip counts the timeline's ([`Rate`]). |
| 1426 | - self.span_rate.source_at(in_frame), | 1474 | + let start_frame = self.span_rate.source_at(in_frame); |
| 1427 | // Source frames, which a speed makes more (or fewer) than the | 1475 | // Source frames, which a speed makes more (or fewer) than the |
| 1428 | // timeline frames the span covers -- and which a file shot at | 1476 | // timeline frames the span covers -- and which a file shot at |
| 1429 | // another rate makes fewer (or more) again. One past the last | 1477 | // another rate makes fewer (or more) again. One past the last |
| 1430 | // frame this span shows, not one past its length: at another | 1478 | // frame this span shows, not one past its length: at another |
| 1431 | // rate those are two different frames. | 1479 | // rate those are two different frames. |
| 1432 | - self.span_rate.source_at( | 1480 | + let end_frame = self.span_rate.source_at( |
| 1433 | in_frame + span.expect("matched above").source_len().saturating_sub(1), | 1481 | in_frame + span.expect("matched above").source_len().saturating_sub(1), |
| 1434 | - ) + 1, | 1482 | + ) + 1; |
| 1435 | - self.project | 1483 | + let color = self |
| 1484 | + .project | ||
| 1436 | .composite_color_at(start) | 1485 | .composite_color_at(start) |
| 1437 | .copied() | 1486 | .copied() |
| 1438 | - .unwrap_or_default(), | 1487 | + .unwrap_or_default(); |
| 1439 | // ...and the canvas it is placed on: the project's resolution | 1488 | // ...and the canvas it is placed on: the project's resolution |
| 1440 | // and this clip's own fit policy, constant across the span for | 1489 | // and this clip's own fit policy, constant across the span for |
| 1441 | - // the reason the grade is. | 1490 | + // the reason the grade is. Built where it is handed over rather |
| 1442 | - Composer::new( | 1491 | + // than kept in a local, because a `Composer` owns the scratch |
| 1443 | - self.meta.width, | 1492 | + // buffers it places through -- the value is not copied about. |
| 1444 | - self.meta.height, | 1493 | + let fit = self.project.composite_fit_at(start); |
| 1445 | - self.project.composite_fit_at(start), | 1494 | + let canvas = || Composer::new(self.meta.width, self.meta.height, fit); |
| 1446 | - ), | ||
| 1447 | // ...and the rendition an HDR source among them is mapped to, | 1495 | // ...and the rendition an HDR source among them is mapped to, |
| 1448 | - // the project's own and constant across the span for that reason | 1496 | + // the project's own and constant across the span for that |
| 1449 | - // too. | 1497 | + // reason too. |
| 1450 | - self.project.tone(), | 1498 | + let tone = self.project.tone(); |
| 1451 | - )), | 1499 | + // The worker already decoding this very file takes the new span |
| 1500 | + // itself: no thread, no container parse, no VA-API init -- the | ||
| 1501 | + // whole of what a seek used to cost. It answers `None` for any | ||
| 1502 | + // other file (and for a worker whose thread has ended), and the | ||
| 1503 | + // deferred opener below is then exactly the path it always was. | ||
| 1504 | + if let Some((frames, backend)) = | ||
| 1505 | + self.worker | ||
| 1506 | + .reseek(path, start_frame, end_frame, color, canvas(), tone) | ||
| 1507 | + { | ||
| 1508 | + self.frames = frames; | ||
| 1509 | + self.backend = backend; | ||
| 1510 | + self.span = span; | ||
| 1511 | + return; | ||
| 1512 | + } | ||
| 1513 | + Ok(DecodeSession::open_worker_deferred( | ||
| 1514 | + &self.project.sources()[source].path, | ||
| 1515 | + start_frame, | ||
| 1516 | + end_frame, | ||
| 1517 | + color, | ||
| 1518 | + canvas(), | ||
| 1519 | + tone, | ||
| 1520 | + )) | ||
| 1521 | + } | ||
| 1452 | // A gap: black for as long as it runs. An emptied timeline has no | 1522 | // A gap: black for as long as it runs. An emptied timeline has no |
| 1453 | // span at all and gets one frame of it -- enough to put black on | 1523 | // span at all and gets one frame of it -- enough to put black on |
| 1454 | // screen, and it ends where the timeline does, at once. | 1524 | // screen, and it ends where the timeline does, at once. |
| @@ -1467,8 +1537,9 @@ impl PlaybackSession { | |||
| 1467 | // [`decode_backend`](Self::decode_backend) describing a worker that | 1537 | // [`decode_backend`](Self::decode_backend) describing a worker that |
| 1468 | // is no longer feeding anything). A dead receiver instead, which is | 1538 | // is no longer feeding anything). A dead receiver instead, which is |
| 1469 | // what carries the session on to the next span. The old worker stays | 1539 | // what carries the session on to the next span. The old worker stays |
| 1470 | - // parked in `self.worker` where the caller already cancelled it; the | 1540 | + // parked in `self.worker`, where the caller has already abandoned |
| 1471 | - // next span retires it. | 1541 | + // the span it was decoding ([`Worker::abandon`]) without ending the |
| 1542 | + // thread; the next span reseeks it or retires it. | ||
| 1472 | self.frames = std::sync::mpsc::channel().1; | 1543 | self.frames = std::sync::mpsc::channel().1; |
| 1473 | self.backend = BackendCell::new(Backend::Gap); | 1544 | self.backend = BackendCell::new(Backend::Gap); |
| 1474 | self.span = span; | 1545 | self.span = span; |
| @@ -2584,6 +2655,31 @@ impl PlaybackSession { | |||
| 2584 | Some((tap, audio.sample_rate)) | 2655 | Some((tap, audio.sample_rate)) |
| 2585 | } | 2656 | } |
| 2586 | 2657 | ||
| 2658 | + /// Says that this session is being **watched in real time**, so a picture | ||
| 2659 | + /// whose moment has passed is worth nothing and the decode worker may drop | ||
| 2660 | + /// it where it is cheap to drop -- before the conversion (a full BGRA pass | ||
| 2661 | + /// over 8 MB at 1080p) and before the queue. | ||
| 2662 | + /// | ||
| 2663 | + /// Off by default, and that is the contract every *pull* consumer relies on: | ||
| 2664 | + /// an export, the file-level [`DecodeSession`] API and a test draining as | ||
| 2665 | + /// fast as it can all ask for a range of frames and must be given every one | ||
| 2666 | + /// of them, in order. Only a viewer has a moment for a picture to be past. | ||
| 2667 | + /// | ||
| 2668 | + /// A front-end that turns this on was dropping those very frames itself, one | ||
| 2669 | + /// repaint later (`Player::pump` takes everything due and shows the last): | ||
| 2670 | + /// what changes is where the work stops, and therefore how quickly a decoder | ||
| 2671 | + /// that fell behind catches up. | ||
| 2672 | + /// | ||
| 2673 | + /// It does not replace [`resync_picture`](Self::resync_picture): both | ||
| 2674 | + /// mechanisms are live and this one is the first line. It catches up without | ||
| 2675 | + /// restarting anything, which is why the front-end's resync -- a picture | ||
| 2676 | + /// restart, once per `RESYNC_GAP` -- now fires only where dropping was not | ||
| 2677 | + /// enough (a decoder so far behind that even one picture in nine | ||
| 2678 | + /// ([`crate::decode`]'s `LATE_RUN`) cannot close the gap). | ||
| 2679 | + pub fn drop_late_pictures(&mut self, on: bool) { | ||
| 2680 | + self.drop_late = on; | ||
| 2681 | + } | ||
| 2682 | + | ||
| 2587 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode | 2683 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode |
| 2588 | /// workers are replaced rather than steered: a fresh channel cannot hold a | 2684 | /// workers are replaced rather than steered: a fresh channel cannot hold a |
| 2589 | /// stale frame, and it works just as well after EOF, where the old workers | 2685 | /// stale frame, and it works just as well after EOF, where the old workers |
| @@ -2629,12 +2725,15 @@ impl PlaybackSession { | |||
| 2629 | /// keeps playing out of the same stream, the clock keeps running, and a | 2725 | /// keeps playing out of the same stream, the clock keeps running, and a |
| 2630 | /// grade dragged during playback is therefore silent. | 2726 | /// grade dragged during playback is therefore silent. |
| 2631 | fn start_picture(&mut self, target: u32) { | 2727 | fn start_picture(&mut self, target: u32) { |
| 2632 | - // Cancel first, drop second: the old worker may be parked in `send` on | 2728 | + // Abandon first, drop second: the old worker may be parked in `send` on |
| 2633 | // the bounded channel, where only the disconnect wakes it -- and it | 2729 | // the bounded channel, where only the disconnect wakes it -- and it |
| 2634 | - // then finds the flag already set. It is then parked, not joined; see | 2730 | + // then finds the span already superseded. The *thread* is kept, and |
| 2635 | - // [`retire`](Self::retire), which is what keeps a scrub off the price | 2731 | + // with it the open file and the open decoder, so a seek onto the same |
| 2636 | - // of a VA-API init. | 2732 | + // source costs a demuxer seek and a decoder flush rather than the |
| 2637 | - self.worker.cancel(); | 2733 | + // VA-API init (98 ms) a new worker would pay; a worker that cannot take |
| 2734 | + // the new span is retired by [`retire`](Self::retire) instead, and | ||
| 2735 | + // nothing on this thread joins either way. | ||
| 2736 | + self.worker.abandon(); | ||
| 2638 | // The span runs from `target` to the end of whatever it landed in -- a | 2737 | // The span runs from `target` to the end of whatever it landed in -- a |
| 2639 | // clip, or a gap, which starts a black-frame worker instead. `None` is | 2738 | // clip, or a gap, which starts a black-frame worker instead. `None` is |
| 2640 | // the emptied timeline, black too, and `start_span` says so. | 2739 | // the emptied timeline, black too, and `start_span` says so. |
| @@ -2847,6 +2946,12 @@ impl PlaybackSession { | |||
| 2847 | /// Moves the clock forward; the caller runs this once per rendered frame. | 2946 | /// Moves the clock forward; the caller runs this once per rendered frame. |
| 2848 | /// Costs an atomic load, and once per session a mode switch. | 2947 | /// Costs an atomic load, and once per session a mode switch. |
| 2849 | pub fn tick(&mut self) { | 2948 | pub fn tick(&mut self) { |
| 2949 | + // Before every early return below: where the playhead stands is what the | ||
| 2950 | + // decode worker drops its stale pictures against, and a front-end that | ||
| 2951 | + // repaints without draining (a slow frame, a busy render thread) must | ||
| 2952 | + // still be moving it -- otherwise the queue fills with pictures whose | ||
| 2953 | + // moment passed while nobody was taking them. | ||
| 2954 | + self.publish_playhead(); | ||
| 2850 | let Some(audio) = &self.audio else { | 2955 | let Some(audio) = &self.audio else { |
| 2851 | return; // wall time from the start, nothing to poll | 2956 | return; // wall time from the start, nothing to poll |
| 2852 | }; | 2957 | }; |
crates/engine/src/scale.rsmodified+39 -0
| @@ -345,6 +345,24 @@ pub fn compose_i420( | |||
| 345 | /// lift the black frame around the picture. Callers therefore grade the source | 345 | /// lift the black frame around the picture. Callers therefore grade the source |
| 346 | /// planes and place the result; the bars stay exactly [`black_i420`]. | 346 | /// planes and place the result; the bars stay exactly [`black_i420`]. |
| 347 | /// | 347 | /// |
| 348 | +/// How many `width` x `height` BGRA pictures a decode worker may keep ahead of | ||
| 349 | +/// its consumer: ~96 MB of them, so the queue is a memory budget rather than a | ||
| 350 | +/// frame count -- 16 at 720p (the ceiling), 12 at 1080p, 3 at 3840x2160, 2 at | ||
| 351 | +/// 4096x2160 (the floor), all measured. A worker holds one more than this in its | ||
| 352 | +/// hand, so a burst off a full queue is `queue_depth + 1`. | ||
| 353 | +/// | ||
| 354 | +/// The floor of 2 is the bound this engine ran on everywhere before there was | ||
| 355 | +/// any decode-ahead; the ceiling keeps a small picture from queueing a second of | ||
| 356 | +/// video the consumer would have to walk through after a seek. | ||
| 357 | +pub(crate) fn queue_depth(width: u32, height: u32) -> usize { | ||
| 358 | + const BUDGET: usize = 96 << 20; | ||
| 359 | + let bytes = width as usize * height as usize * 4; | ||
| 360 | + if bytes == 0 { | ||
| 361 | + return 2; | ||
| 362 | + } | ||
| 363 | + (BUDGET / bytes).clamp(2, 16) | ||
| 364 | +} | ||
| 365 | + | ||
| 348 | /// A canvas of the picture's own size is a pass-through: [`place`](Composer::place) | 366 | /// A canvas of the picture's own size is a pass-through: [`place`](Composer::place) |
| 349 | /// hands the caller's own planes straight back, allocates nothing and touches no | 367 | /// hands the caller's own planes straight back, allocates nothing and touches no |
| 350 | /// byte, which is what keeps a project at its media's resolution the byte-for-byte | 368 | /// byte, which is what keeps a project at its media's resolution the byte-for-byte |
| @@ -386,6 +404,27 @@ impl Composer { | |||
| 386 | Self::new(0, 0, FitPolicy::Fit) | 404 | Self::new(0, 0, FitPolicy::Fit) |
| 387 | } | 405 | } |
| 388 | 406 | ||
| 407 | + /// Whether this canvas is the one that places nothing | ||
| 408 | + /// ([`passthrough`](Self::passthrough)) -- asked without a picture in hand, | ||
| 409 | + /// unlike [`is_passthrough`](Self::is_passthrough), because the caller that | ||
| 410 | + /// needs it is sizing a queue before anything has been decoded. | ||
| 411 | + pub(crate) fn places_nothing(&self) -> bool { | ||
| 412 | + self.width == 0 || self.height == 0 | ||
| 413 | + } | ||
| 414 | + | ||
| 415 | + /// How many decoded pictures a worker over this canvas may keep ahead of | ||
| 416 | + /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue | ||
| 417 | + /// than a 1080p one instead of the same number of far bigger frames. | ||
| 418 | + /// | ||
| 419 | + /// A **pass-through** canvas has no size of its own -- the pictures come out | ||
| 420 | + /// at the source's -- so it cannot answer, and the caller that knows the | ||
| 421 | + /// stream asks [`queue_depth`] with those dimensions instead. Answering 2 | ||
| 422 | + /// here would be the pre-decode-ahead bound, which is exactly the bug this | ||
| 423 | + /// pair exists to keep out of the file-open path. | ||
| 424 | + pub(crate) fn queue_depth(&self) -> usize { | ||
| 425 | + queue_depth(self.width, self.height) | ||
| 426 | + } | ||
| 427 | + | ||
| 389 | /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this | 428 | /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this |
| 390 | /// composer would hand it back untouched. What lets a caller keep a fused | 429 | /// composer would hand it back untouched. What lets a caller keep a fused |
| 391 | /// fast path (the graded conversion) for the common case. | 430 | /// fast path (the graded conversion) for the common case. |
crates/engine/tests/playback.rsmodified+174 -0
| @@ -47,6 +47,12 @@ fn pump(session: &mut PlaybackSession, last_index: &mut Option<u32>) { | |||
| 47 | let target = session.now() * session.meta().frame_rate; | 47 | let target = session.now() * session.meta().frame_rate; |
| 48 | while let Some(frame) = session.try_frame() { | 48 | while let Some(frame) = session.try_frame() { |
| 49 | if let Some(previous) = *last_index { | 49 | if let Some(previous) = *last_index { |
| 50 | + // One at a time, in order. Every session here is a *pull* consumer | ||
| 51 | + // -- `open` leaves `drop_late_pictures` off -- and such a caller is | ||
| 52 | + // owed every frame of the range it asked for, which is the contract | ||
| 53 | + // an export and the file-level API rest on. Only a session told it | ||
| 54 | + // is being watched in real time may skip, and the two tests that | ||
| 55 | + // turn that on take their frames through `next_index` instead. | ||
| 50 | assert_eq!( | 56 | assert_eq!( |
| 51 | frame.index, | 57 | frame.index, |
| 52 | previous + 1, | 58 | previous + 1, |
| @@ -1637,3 +1643,171 @@ fn an_emptied_timeline_plays_black_saves_loads_and_undoes() { | |||
| 1637 | assert!((session.timeline_duration() - whole).abs() < 1e-9); | 1643 | assert!((session.timeline_duration() - whole).abs() < 1e-9); |
| 1638 | assert_eq!(session.clip_spans().len(), 1); | 1644 | assert_eq!(session.clip_spans().len(), 1); |
| 1639 | } | 1645 | } |
| 1646 | + | ||
| 1647 | +/// The session half of the late-frame policy: a *watched* session still lands | ||
| 1648 | +/// exactly on the frame a seek asked for. The floor the worker drops against is | ||
| 1649 | +/// the playhead mapped back into the file own frames, and a floor even one | ||
| 1650 | +/// frame ahead of the landing would eat the very picture the seek exists to | ||
| 1651 | +/// show ([`PlaybackSession::drop_late_pictures`]). | ||
| 1652 | +#[test] | ||
| 1653 | +fn a_watched_session_still_lands_on_the_frame_a_seek_asked_for() { | ||
| 1654 | + let mut session = open(asset("test_baseline.mp4")); | ||
| 1655 | + session.drop_late_pictures(true); | ||
| 1656 | + let fps = session.meta().frame_rate; | ||
| 1657 | + session.seek(3.0); | ||
| 1658 | + assert_eq!( | ||
| 1659 | + next_index(&mut session, "seek(3.0) on a watched session"), | ||
| 1660 | + (3.0 * fps) as u32, | ||
| 1661 | + "the landing frame was dropped as late" | ||
| 1662 | + ); | ||
| 1663 | + // ...and again backwards: a floor left where the last span ended would drop | ||
| 1664 | + // every picture of a seek that went back. | ||
| 1665 | + session.seek(1.0); | ||
| 1666 | + assert_eq!( | ||
| 1667 | + next_index(&mut session, "seek(1.0) on a watched session"), | ||
| 1668 | + (1.0 * fps) as u32 | ||
| 1669 | + ); | ||
| 1670 | +} | ||
| 1671 | + | ||
| 1672 | +/// The pixels a *reused* decoder hands back are the pixels a fresh one does. | ||
| 1673 | +/// One session takes three seeks -- forwards, backwards, forwards again -- and | ||
| 1674 | +/// the worker survives all of them (`Worker::reseek`: the file stays open, the | ||
| 1675 | +/// hardware session is repositioned rather than reopened), so a decoder left | ||
| 1676 | +/// holding one span references while another span is asked for would show here | ||
| 1677 | +/// as a smear and nowhere else. The reference is the file-level API, which | ||
| 1678 | +/// opens a decoder of its own per frame. | ||
| 1679 | +#[test] | ||
| 1680 | +fn a_reseek_decodes_the_same_picture_a_fresh_decoder_does() { | ||
| 1681 | + let path = asset("test_baseline.mp4"); | ||
| 1682 | + let mut session = open(&path); | ||
| 1683 | + let fps = session.meta().frame_rate; | ||
| 1684 | + // Small targets on purpose: the fixture's only sync sample is frame 0, so | ||
| 1685 | + // every one of these decodes from the start of the file and a debug-build | ||
| 1686 | + // software decoder is what runs the suite. | ||
| 1687 | + for target in [20u32, 5, 35] { | ||
| 1688 | + session.seek(f64::from(target) / fps); | ||
| 1689 | + let frame = next_frame(&mut session, "a seek onto a worker already open"); | ||
| 1690 | + assert_eq!(frame.index, target, "the seek landed elsewhere"); | ||
| 1691 | + assert!( | ||
| 1692 | + frame.bgra == source_frame(&path, target), | ||
| 1693 | + "frame {target} off the reused decoder is not the picture a fresh one decodes" | ||
| 1694 | + ); | ||
| 1695 | + } | ||
| 1696 | +} | ||
| 1697 | + | ||
| 1698 | +/// What the drop policy must never do: thin a picture the decoder was keeping up | ||
| 1699 | +/// with. `pump`'s own contiguity assert covers every *pull* consumer above; | ||
| 1700 | +/// nothing there bounds what a **watched** session delivers, and a one-in-N | ||
| 1701 | +/// regression inside the worker would pass the whole suite otherwise. | ||
| 1702 | +/// | ||
| 1703 | +/// The fixture is the smallest one here (320x180) so the question can be asked | ||
| 1704 | +/// on a debug build at the file's own rate -- no retime, because a retimed | ||
| 1705 | +/// timeline legitimately shows only every n-th source frame and the sharp half | ||
| 1706 | +/// of this test is that the indices arrive one at a time. A box too slow even | ||
| 1707 | +/// for this says so and stops: thinning the picture there is the policy working | ||
| 1708 | +/// (`LATE_RUN`), not a regression. | ||
| 1709 | +#[test] | ||
| 1710 | +fn a_watched_session_keeps_every_picture_its_decoder_keeps_up_with() { | ||
| 1711 | + let path = asset("test_speed_sync.mp4"); | ||
| 1712 | + | ||
| 1713 | + // What this box decodes, flat out, with nothing dropped: frames per second. | ||
| 1714 | + let mut measure = open(&path); | ||
| 1715 | + let fps = measure.meta().frame_rate; | ||
| 1716 | + measure.play(); | ||
| 1717 | + let mut decoded = 0u32; | ||
| 1718 | + let taken = Instant::now(); | ||
| 1719 | + while taken.elapsed() < Duration::from_millis(500) && !measure.is_eos() { | ||
| 1720 | + measure.tick(); | ||
| 1721 | + while measure.try_frame().is_some() { | ||
| 1722 | + decoded += 1; | ||
| 1723 | + } | ||
| 1724 | + sleep(Duration::from_millis(2)); | ||
| 1725 | + } | ||
| 1726 | + let capable = f64::from(decoded) / taken.elapsed().as_secs_f64(); | ||
| 1727 | + drop(measure); | ||
| 1728 | + eprintln!("this box decodes the fixture at {capable:.1} fps, which plays at {fps:.1}"); | ||
| 1729 | + if capable < fps * 1.2 { | ||
| 1730 | + eprintln!("SKIP: too slow to ask the question at all"); | ||
| 1731 | + return; | ||
| 1732 | + } | ||
| 1733 | + | ||
| 1734 | + // Watched, playing at its own rate, drained like a front-end that keeps up: | ||
| 1735 | + // every picture is due when it arrives and none of them may be dropped. | ||
| 1736 | + let mut session = open(&path); | ||
| 1737 | + session.drop_late_pictures(true); | ||
| 1738 | + session.play(); | ||
| 1739 | + let mut delivered = 0u32; | ||
| 1740 | + let mut last: Option<u32> = None; | ||
| 1741 | + let watched = Instant::now(); | ||
| 1742 | + while watched.elapsed() < Duration::from_millis(500) && !session.is_eos() { | ||
| 1743 | + session.tick(); | ||
| 1744 | + while let Some(frame) = session.try_frame() { | ||
| 1745 | + delivered += 1; | ||
| 1746 | + if let Some(previous) = last { | ||
| 1747 | + assert_eq!( | ||
| 1748 | + frame.index, | ||
| 1749 | + previous + 1, | ||
| 1750 | + "a picture was dropped while the decoder was keeping up" | ||
| 1751 | + ); | ||
| 1752 | + } | ||
| 1753 | + last = Some(frame.index); | ||
| 1754 | + } | ||
| 1755 | + sleep(Duration::from_millis(2)); | ||
| 1756 | + } | ||
| 1757 | + // Frames the clock went over, which is what the timeline owed the screen. | ||
| 1758 | + let passed = session.now() * fps; | ||
| 1759 | + let density = f64::from(delivered) / passed.max(1.0); | ||
| 1760 | + eprintln!("watched: {delivered} delivered over {passed:.1} frames of clock"); | ||
| 1761 | + assert!( | ||
| 1762 | + density >= 0.9, | ||
| 1763 | + "the worker thinned a picture it was keeping up with: {delivered} of \ | ||
| 1764 | + {passed:.1} frames ({density:.2}), decoder measured at {capable:.1} fps" | ||
| 1765 | + ); | ||
| 1766 | +} | ||
| 1767 | + | ||
| 1768 | +/// The decode-ahead a **freshly opened** file gets. Every session opens its first | ||
| 1769 | +/// worker pass-through -- a file just opened *is* the project resolution -- and | ||
| 1770 | +/// asking a pass-through canvas how deep to queue answers 2, the bound this | ||
| 1771 | +/// engine had before there was any decode-ahead: the whole file would then play | ||
| 1772 | +/// at that depth until the first seek built a real canvas. The depth is taken | ||
| 1773 | +/// from the stream instead (`scale::queue_depth`), and this is where that is | ||
| 1774 | +/// visible from outside: a paused session left alone fills its queue, and the | ||
| 1775 | +/// burst that comes off it is the depth plus the picture in the worker's hand. | ||
| 1776 | +/// | ||
| 1777 | +/// 720p fixture: ~96 MB of BGRA is 16 pictures at that size (the ceiling), so | ||
| 1778 | +/// the burst is 17 and the regression it guards against is a burst of 3. | ||
| 1779 | +#[test] | ||
| 1780 | +fn a_freshly_opened_file_queues_more_than_two_pictures() { | ||
| 1781 | + let mut session = open(asset("test_baseline.mp4")); | ||
| 1782 | + // Paused throughout: no seek, no play, nothing that would build a canvas. | ||
| 1783 | + // The best of three attempts, because filling the queue is the decoder's own | ||
| 1784 | + // work and this box shares itself with whatever else is running. | ||
| 1785 | + let mut burst = 0; | ||
| 1786 | + for _ in 0..3 { | ||
| 1787 | + sleep(Duration::from_millis(1500)); | ||
| 1788 | + let mut n = 0; | ||
| 1789 | + while session.try_frame().is_some() { | ||
| 1790 | + n += 1; | ||
| 1791 | + } | ||
| 1792 | + burst = burst.max(n); | ||
| 1793 | + } | ||
| 1794 | + eprintln!("burst off a freshly opened file: {burst} pictures"); | ||
| 1795 | + assert!( | ||
| 1796 | + burst > 8, | ||
| 1797 | + "a freshly opened file queued {burst} pictures: the first worker is \ | ||
| 1798 | + still sizing its queue from a pass-through canvas" | ||
| 1799 | + ); | ||
| 1800 | + | ||
| 1801 | + // ...and the same worker still answers. Four and a half seconds parked is | ||
| 1802 | + // well past the idle mark at which it closes its hardware session | ||
| 1803 | + // (`decode`'s `IDLE`), so this is the seek that has to reopen one lazily -- | ||
| 1804 | + // the one path that would have gone quiet if closing it left the worker | ||
| 1805 | + // holding a decoder it could no longer use. | ||
| 1806 | + let fps = session.meta().frame_rate; | ||
| 1807 | + session.seek(2.0); | ||
| 1808 | + assert_eq!( | ||
| 1809 | + next_index(&mut session, "a seek after the worker went idle"), | ||
| 1810 | + (2.0 * fps) as u32, | ||
| 1811 | + "the worker did not come back from its idle park" | ||
| 1812 | + ); | ||
| 1813 | +} | ||