forge
Explore
Log in

Don't you dare go Hollow

The worker that decoded a span stays for the next one

Browse files at this commit

bbdd4d6d2db19f0017cabb759a21fb9f0c3b5ac3Ahmet Kaan GümüşParent: 267d45b
  • perf
    • the worker that decoded a span stays for the next one
Show full message
⚡ perf(decode): the worker that decoded a span stays for the next one

A seek used to cost a thread, a container parse and a VA-API
initialisation (98 ms measured worst case) before it could decode a
single picture, because every span opened a decoder of its own and threw
it away again. The worker now outlives its span: it parks on a command
channel, and a seek onto the file it already has open reaches it through
Worker::reseek -- a demuxer seek and a decoder flush, 1-4 ms measured
against a 28-37 ms open of the same file warm.

The plugin learns the same trick from the other side: vh_seek
repositions an open session exactly as vh_open_at positions a new one,
and it is an optional symbol, so a plugin built before it still decodes
and its caller simply opens a session per seek as it always did.

Cancelling and abandoning become two different things: a seek abandons
the span (the thread, the file and the decoder stay), a replacement
cancels the worker (the thread ends, and the command channel goes with
it, so nothing parks in recv past the session that owns it and no VA-API
session meets Mesa's atexit).
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 /// # Safety673 /// # Safety
crates/engine/src/decode.rsmodified+393 -137
@@ -3,7 +3,7 @@
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, AtomicU64, Ordering};
7 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};7 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
8 use std::thread;8 use std::thread;
9 9
@@ -136,15 +136,133 @@ pub(crate) struct Worker {
136 /// `None` once detached, and for a range with nothing to decode: either way136 /// `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+}
163+
164+/// One span asked of a persistent worker: the range in the file's own frames,
165+/// everything a picture is graded, placed and mapped by, and the channel the
166+/// pictures go down. Carries its generation, so a command already superseded on
167+/// its way through the queue is dropped rather than decoded.
168+struct SpanCmd {
169+ generation: u64,
170+ start: u32,
171+ end: u32,
172+ color: ColorParams,
173+ canvas: Composer,
174+ tone: tonemap::Preset,
175+ tx: SyncSender<Frame>,
176+}
177+
178+/// What stops a decode loop: the worker's terminal flag (the thread itself is
179+/// going away) and the generation of the span it was handed (only *this* span is
180+/// going away). One check, so every loop treats them alike.
181+struct Abort<'a> {
182+ cancel: &'a AtomicBool,
183+ generation: &'a AtomicU64,
184+ mine: u64,
185+}
186+
187+impl Abort<'_> {
188+ fn hit(&self) -> bool {
189+ self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine
190+ }
139 }191 }
140 192
141 impl Worker {193 impl Worker {
142- /// Stops the worker at its next check without waiting. Callers that replace194+ /// 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 worker195+ /// 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 would196+ /// second: a worker parked in `send` only wakes on the disconnect, so the
145- /// otherwise wait for a consumer that is never coming.197+ /// join below would otherwise wait for a consumer that is never coming.
146- pub(crate) fn cancel(&self) {198+ ///
199+ /// The command channel goes with it, which is what wakes a persistent worker
200+ /// parked between spans -- without that it would sit in `recv` forever and a
201+ /// retired worker would never be reaped (nor joined at exit in any bounded
202+ /// time, which is the Mesa `atexit` hazard this whole type exists for).
203+ pub(crate) fn cancel(&mut self) {
147 self.cancel.store(true, Ordering::Release);204 self.cancel.store(true, Ordering::Release);
205+ self.reuse = None;
206+ }
207+
208+ /// Stops the span the worker is decoding, keeping the *thread* -- and with
209+ /// it the open file and the open decoder -- for the span that follows. What
210+ /// a seek does, since the next thing it says is [`Worker::reseek`].
211+ ///
212+ /// Falls back to [`cancel`](Self::cancel) for a worker with nothing to
213+ /// reuse (a still, a gap, a detached one), where the two mean the same
214+ /// thing: this worker has no next span.
215+ pub(crate) fn abandon(&mut self) {
216+ match &self.reuse {
217+ Some(reuse) => {
218+ reuse.generation.fetch_add(1, Ordering::Release);
219+ }
220+ None => self.cancel(),
221+ }
222+ }
223+
224+ /// Points this worker at another range of the file it already has open,
225+ /// handing back the channel the new span's pictures arrive on and the cell
226+ /// that says what is decoding them. `None` when this worker cannot take the
227+ /// job -- another file, no reuse door, or a thread that has already returned
228+ /// -- and the caller then opens a worker of its own, exactly as it always
229+ /// did.
230+ ///
231+ /// The pictures of the *old* span are left in their own channel, which the
232+ /// caller drops: that disconnect is what wakes this worker if it is parked
233+ /// in `send`, and only then does it reach the command below. So the order at
234+ /// the call site is unchanged -- install the new receiver, and the old
235+ /// worker finds out by losing its consumer.
236+ pub(crate) fn reseek(
237+ &mut self,
238+ path: &Path,
239+ start: u32,
240+ end: u32,
241+ color: ColorParams,
242+ canvas: Composer,
243+ tone: tonemap::Preset,
244+ ) -> Option<(Receiver<Frame>, BackendCell)> {
245+ let reuse = self.reuse.as_ref()?;
246+ if reuse.path != path || self.is_finished() {
247+ return None;
248+ }
249+ let (tx, rx) = sync_channel(QUEUE);
250+ // Bumped before the command is queued, so the span running now stops at
251+ // its next picture whatever order the two threads are scheduled in.
252+ let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1;
253+ reuse
254+ .spans
255+ .send(SpanCmd {
256+ generation,
257+ start,
258+ end,
259+ color,
260+ canvas,
261+ tone,
262+ tx,
263+ })
264+ .ok()?;
265+ Some((rx, reuse.backend.clone()))
148 }266 }
149 267
150 /// Whether the thread has already returned, i.e. dropping this would not268 /// Whether the thread has already returned, i.e. dropping this would not
@@ -158,8 +276,14 @@ impl Worker {
158 276
159 /// Lets the worker run on unwatched -- what the public API does, since it277 /// Lets the worker run on unwatched -- what the public API does, since it
160 /// hands out the flag alone.278 /// hands out the flag alone.
279+ ///
280+ /// The reuse door goes with the handle: nothing can steer a worker nobody
281+ /// holds, and dropping the command channel is what makes such a thread end
282+ /// at its span rather than park waiting for a next one it can never be
283+ /// given -- with a VA-API session open, into Mesa's `atexit`.
161 fn detach(mut self) -> Arc<AtomicBool> {284 fn detach(mut self) -> Arc<AtomicBool> {
162 self.handle = None;285 self.handle = None;
286+ self.reuse = None;
163 Arc::clone(&self.cancel)287 Arc::clone(&self.cancel)
164 }288 }
165 }289 }
@@ -167,6 +291,8 @@ impl Worker {
167 impl Drop for Worker {291 impl Drop for Worker {
168 fn drop(&mut self) {292 fn drop(&mut self) {
169 if let Some(handle) = self.handle.take() {293 if let Some(handle) = self.handle.take() {
294+ // `cancel` drops the command channel too, so a worker parked between
295+ // spans wakes on the disconnect and this join is bounded.
170 self.cancel();296 self.cancel();
171 let _ = handle.join();297 let _ = handle.join();
172 }298 }
@@ -258,6 +384,7 @@ impl DecodeSession {
258 worker: Worker {384 worker: Worker {
259 cancel,385 cancel,
260 handle: None,386 handle: None,
387+ reuse: None,
261 },388 },
262 backend: BackendCell::new(Backend::Gap),389 backend: BackendCell::new(Backend::Gap),
263 };390 };
@@ -287,7 +414,11 @@ impl DecodeSession {
287 .ok();414 .ok();
288 FrameStream {415 FrameStream {
289 frames: rx,416 frames: rx,
290- worker: Worker { cancel, handle },417+ worker: Worker {
418+ cancel,
419+ handle,
420+ reuse: None,
421+ },
291 backend: BackendCell::new(Backend::Gap),422 backend: BackendCell::new(Backend::Gap),
292 }423 }
293 }424 }
@@ -317,6 +448,7 @@ impl DecodeSession {
317 worker: Worker {448 worker: Worker {
318 cancel,449 cancel,
319 handle: None,450 handle: None,
451+ reuse: None,
320 },452 },
321 backend: BackendCell::new(Backend::Still),453 backend: BackendCell::new(Backend::Still),
322 });454 });
@@ -369,7 +501,11 @@ impl DecodeSession {
369 .ok();501 .ok();
370 Ok(FrameStream {502 Ok(FrameStream {
371 frames: rx,503 frames: rx,
372- worker: Worker { cancel, handle },504+ worker: Worker {
505+ cancel,
506+ handle,
507+ reuse: None,
508+ },
373 backend: BackendCell::new(Backend::Still),509 backend: BackendCell::new(Backend::Still),
374 })510 })
375 }511 }
@@ -414,57 +550,34 @@ impl DecodeSession {
414 hw_decodes(&path, start_frame, meta.codec)?;550 hw_decodes(&path, start_frame, meta.codec)?;
415 }551 }
416 let end_frame = end_frame.min(meta.frame_count);552 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 {553 if end_frame <= start_frame {
425- // Nothing to decode: dropping `tx` here closes the channel cleanly,554+ // 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.555 // so the caller sees an immediate end of stream rather than an error.
556+ let (_, rx) = sync_channel(1);
427 return Ok((557 return Ok((
428 meta,558 meta,
429 FrameStream {559 FrameStream {
430 frames: rx,560 frames: rx,
431 worker: Worker {561 worker: Worker {
432- cancel,562+ cancel: Arc::new(AtomicBool::new(false)),
433 handle: None,563 handle: None,
564+ reuse: None,
434 },565 },
435- backend,566+ backend: BackendCell::default(),
436 },567 },
437 ));568 ));
438 }569 }
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((570 Ok((
459 meta,571 meta,
460- FrameStream {572+ span_worker(
461- frames: rx,573+ path,
462- worker: Worker {574+ Some(Source::demuxed(demuxer, meta)),
463- cancel,575+ start_frame,
464- handle: Some(handle),576+ end_frame,
465- },577+ color,
466- backend,578+ canvas,
467- },579+ tone,
580+ ),
468 ))581 ))
469 }582 }
470 583
@@ -488,120 +601,260 @@ impl DecodeSession {
488 canvas: Composer,601 canvas: Composer,
489 tone: tonemap::Preset,602 tone: tonemap::Preset,
490 ) -> FrameStream {603 ) -> FrameStream {
491- let path = path.as_ref().to_path_buf();604+ span_worker(
492- let (tx, rx) = sync_channel(2);605+ path.as_ref().to_path_buf(),
493- let cancel = Arc::new(AtomicBool::new(false));606+ None,
494- let backend = BackendCell::default();607+ start_frame,
495- let worker_cancel = Arc::clone(&cancel);608+ end_frame,
496- let worker_backend = backend.clone();609+ color,
497- let handle = thread::Builder::new()610+ canvas,
498- .name("decode".into())611+ tone,
499- .spawn(move || {612+ )
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 }613 }
539 }614 }
540 615
541-/// One worker thread's whole job, on that thread: pick the decoder, decode616+/// How many decoded pictures a worker may run ahead of its consumer. Small on
542-/// `[start_frame, end_frame)`, send the pictures. Both openers end here -- the617+/// purpose: a 1080p BGRA frame is ~8 MB, so the decoder must not run ahead of
543-/// sync one, which demuxed on the caller's thread, and the deferred one, which618+/// the display without limit.
544-/// demuxed on this one -- so there is exactly one description of what a decode619+const QUEUE: usize = 2;
545-/// worker does, whoever opened the file.620+
621+/// Spawns a decode worker over `path` and gives it its first span. The thread
622+/// **outlives that span**: it parks on its command channel afterwards, so the
623+/// next seek onto the same file reaches it through [`Worker::reseek`] and costs
624+/// a demuxer seek and a decoder flush instead of a thread, a container parse and
625+/// a VA-API initialisation (98 ms measured worst case).
626+///
627+/// `opened` is the file when the caller already read it (the sync opener, which
628+/// demuxes on the caller's thread to have metadata to return); `None` is the
629+/// deferred one, where the worker opens it and nothing here touches the disk.
546 #[allow(clippy::too_many_arguments)]630 #[allow(clippy::too_many_arguments)]
547-fn decode_span(631+fn span_worker(
548- path: &PathBuf,632+ path: PathBuf,
549- demuxer: Demuxer,633+ opened: Option<Source>,
550- meta: VideoMeta,
551 start_frame: u32,634 start_frame: u32,
552 end_frame: u32,635 end_frame: u32,
553 color: ColorParams,636 color: ColorParams,
554 canvas: Composer,637 canvas: Composer,
555 tone: tonemap::Preset,638 tone: tonemap::Preset,
556- tx: SyncSender<Frame>,639+) -> FrameStream {
557- cancel: &AtomicBool,640+ let (tx, rx) = sync_channel(QUEUE);
641+ let cancel = Arc::new(AtomicBool::new(false));
642+ // Written by the worker the moment it knows, so a caller reading it sees
643+ // what opened rather than what was hoped for -- and kept across the spans
644+ // that follow, since they are decoded by that very decoder.
645+ let backend = BackendCell::default();
646+ let generation = Arc::new(AtomicU64::new(0));
647+ let (spans, commands) = std::sync::mpsc::channel();
648+ let first = SpanCmd {
649+ generation: 0,
650+ start: start_frame,
651+ end: end_frame,
652+ color,
653+ canvas,
654+ tone,
655+ tx,
656+ };
657+ let worker_cancel = Arc::clone(&cancel);
658+ let worker_backend = backend.clone();
659+ let worker_generation = Arc::clone(&generation);
660+ let worker_path = path.clone();
661+ let handle = thread::Builder::new()
662+ .name("decode".into())
663+ .spawn(move || {
664+ let mut source = opened;
665+ let mut cmd = first;
666+ loop {
667+ let abort = Abort {
668+ cancel: &worker_cancel,
669+ generation: &worker_generation,
670+ mine: cmd.generation,
671+ };
672+ // Superseded (or cancelled) before this thread was even
673+ // scheduled: do not open the file, and do not enter VA-API
674+ // initialisation, which is the one stretch a cancel cannot
675+ // interrupt. A scrub abandons spans by the dozen and this is
676+ // where all but the last of them stop.
677+ if !abort.hit() {
678+ run_span(&worker_path, &mut source, cmd, &abort, &worker_backend);
679+ }
680+ // The session dropped the command channel: this worker is
681+ // retired (or was detached), so the file, the decoder and the
682+ // VA-API session it holds go now -- before Mesa's `atexit`.
683+ match commands.recv() {
684+ Ok(next) => cmd = next,
685+ Err(_) => return,
686+ }
687+ }
688+ })
689+ .ok();
690+ FrameStream {
691+ frames: rx,
692+ worker: Worker {
693+ cancel,
694+ handle,
695+ reuse: Some(Reuse {
696+ path,
697+ spans,
698+ generation,
699+ backend: backend.clone(),
700+ }),
701+ },
702+ backend,
703+ }
704+}
705+
706+/// What a decode worker keeps **between** the spans it is asked for: the
707+/// container it read, what the stream says about itself, and the hardware
708+/// session -- the three things a seek used to throw away and buy again.
709+struct Source {
710+ meta: VideoMeta,
711+ /// What the film says its brightest picture is ([`Demuxer::light`]): the
712+ /// tone map's assumed peak on the reference rendition, so a 1759 cd/m^2
713+ /// grade is converted at 1759 rather than at the 1000 a file that declared
714+ /// nothing is assumed at. A property of the stream, read once with it.
715+ peak: Option<f32>,
716+ demuxer: Demuxer,
717+ /// The plugin's session, opened on this thread (its VA-API state is not
718+ /// `Send`-safe across a hand-off) and *kept*. `None` for software: forced by
719+ /// `VE_SW`, refused by the plugin, or handed back by a session that opened
720+ /// and then decoded nothing.
721+ hw: Option<HwSession>,
722+}
723+
724+impl Source {
725+ /// The file as the sync opener already read it.
726+ fn demuxed(demuxer: Demuxer, meta: VideoMeta) -> Self {
727+ Self {
728+ meta,
729+ peak: demuxer.light().peak(),
730+ demuxer,
731+ hw: None,
732+ }
733+ }
734+
735+ /// ...and as the deferred opener reads it, on the worker. `None` is a file
736+ /// that would not open: the caller drops the sender, and the disconnected
737+ /// receiver is the session's "walk on to the next span".
738+ fn open(path: &Path) -> Option<Self> {
739+ match Demuxer::open(path) {
740+ Ok((meta, demuxer)) => Some(Self::demuxed(demuxer, meta)),
741+ Err(e) => {
742+ eprintln!("video open failed: {e}");
743+ None
744+ }
745+ }
746+ }
747+
748+ /// Puts the hardware decoder at `start`, keeping the session open where the
749+ /// plugin can reposition it. `None` when there is no hardware here at all;
750+ /// otherwise whether the session was **reused** -- which is what lets the
751+ /// caller tell a driver that cannot decode this stream from one that merely
752+ /// did not follow a reseek.
753+ fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {
754+ if let Some(hw) = &mut self.hw {
755+ if hw.seek(start) {
756+ eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})");
757+ return Some(true);
758+ }
759+ // A plugin too old to reposition, or a decoder that would not
760+ // flush: closed and opened again, which is what every seek did.
761+ self.hw = None;
762+ }
763+ self.hw = open_hw(path, start);
764+ self.hw.as_ref().map(|_| {
765+ eprintln!("decode backend: hardware (VA-API plugin)");
766+ false
767+ })
768+ }
769+}
770+
771+/// One span on a worker's thread: position the decoder, decode
772+/// `[start, end)`, send the pictures. Every opener ends here -- the sync one,
773+/// which demuxed on the caller's thread, the deferred one, which demuxes on
774+/// this one, and every reseek after them -- so there is exactly one description
775+/// of what a decode worker does.
776+fn run_span(
777+ path: &Path,
778+ source: &mut Option<Source>,
779+ cmd: SpanCmd,
780+ abort: &Abort,
558 backend: &BackendCell,781 backend: &BackendCell,
559 ) {782 ) {
783+ let SpanCmd {
784+ start,
785+ end,
786+ color,
787+ canvas,
788+ tone,
789+ tx,
790+ ..
791+ } = cmd;
792+ let opened = match source {
793+ Some(opened) => opened,
794+ None => {
795+ let Some(fresh) = Source::open(path) else {
796+ backend.set(Backend::Gap);
797+ return;
798+ };
799+ source.insert(fresh)
800+ }
801+ };
802+ // The clamp the sync opener does with the metadata it read on the caller's
803+ // thread; here the metadata arrives first.
804+ let end = end.min(opened.meta.frame_count);
560 // An empty range decodes nothing and must send nothing: `run_hw` counts a805 // 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 would806 // 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.807+ // emit one picture.
563- if end_frame <= start_frame {808+ if end <= start {
564 return;809 return;
565 }810 }
566- // Cancelled before this thread was even scheduled -- do not enter VA-API811+ // 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 cannot812+ // 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 torn813+ // and the rendition are the *span's*, so this is built per span.
569- // down again).814+ let mut render = Render::new(color, opened.meta.color, canvas, tone, opened.peak);
570- if cancel.load(Ordering::Relaxed) {815+ if let Some(reused) = opened.position_hw(path, start) {
571- return;816+ // Cancelled during the init (or the seek): leave without decoding.
572- }817+ 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;818 return;
586 }819 }
587- eprintln!("decode backend: hardware (VA-API plugin)");
588 backend.set(Backend::Hardware);820 backend.set(Backend::Hardware);
589- if run_hw(hw, &tx, start_frame, end_frame, &mut render, cancel) {821+ let mut decoded = run_hw(
822+ opened.hw.as_mut().expect("positioned above"),
823+ &tx,
824+ start,
825+ end,
826+ &mut render,
827+ abort,
828+ );
829+ // A *reused* session that produced nothing may simply be one this
830+ // reseek left where the driver would not follow; a session opened fresh
831+ // at the same frame is the honest second question, and only its silence
832+ // is a software fallback. Without this a single unfollowed seek would
833+ // collapse the rest of the file to software.
834+ if !decoded && reused {
835+ eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}");
836+ opened.hw = open_hw(path, start);
837+ if let Some(hw) = opened.hw.as_mut() {
838+ decoded = run_hw(hw, &tx, start, end, &mut render, abort);
839+ }
840+ }
841+ if decoded {
590 return;842 return;
591 }843 }
592 // A driver that opens but cannot decode a single frame is still a844 // A driver that opens but cannot decode a single frame is still a
593 // fallback case, not a dead session.845 // fallback case, not a dead session.
846+ opened.hw = None;
594 eprintln!("hardware decode failed before any frame, falling back to software");847 eprintln!("hardware decode failed before any frame, falling back to software");
595 }848 }
596 // ...except where there is nothing to fall back to. Feeding HEVC or VP9849 // ...except where there is nothing to fall back to. Feeding HEVC or VP9
597 // bytes to `rusty_h264` would be garbage, not a fallback.850 // bytes to `rusty_h264` would be garbage, not a fallback.
598- if meta.codec != Codec::H264 {851+ if opened.meta.codec != Codec::H264 {
599- eprintln!("{}", meta.codec.needs_plugin());852+ eprintln!("{}", opened.meta.codec.needs_plugin());
600 return;853 return;
601 }854 }
602 eprintln!("decode backend: software (rusty_h264)");855 eprintln!("decode backend: software (rusty_h264)");
603 backend.set(Backend::Software);856 backend.set(Backend::Software);
604- run(demuxer, tx, start_frame, end_frame, &mut render, cancel)857+ run(&mut opened.demuxer, &tx, start, end, &mut render, abort)
605 }858 }
606 859
607 /// One clip's pictures on their way to the renderer: graded, placed on the860 /// One clip's pictures on their way to the renderer: graded, placed on the
@@ -856,7 +1109,7 @@ fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Ve
856 1109
857 /// `None` when the software path must be used: forced by `VE_SW=1`, or the1110 /// `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.1111 /// plugin is absent/broken/unable to open this particular file.
859-fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {1112+fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> {
860 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {1113 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
861 return None;1114 return None;
862 }1115 }
@@ -893,16 +1146,16 @@ 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 sample1146 /// 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).1147 /// cannot be decoded from its start at all, and is not accounted for).
895 fn run_hw(1148 fn run_hw(
896- mut hw: HwSession,1149+ hw: &mut HwSession,
897 tx: &SyncSender<Frame>,1150 tx: &SyncSender<Frame>,
898 start_frame: u32,1151 start_frame: u32,
899 end_frame: u32,1152 end_frame: u32,
900 render: &mut Render,1153 render: &mut Render,
901- cancel: &AtomicBool,1154+ abort: &Abort,
902 ) -> bool {1155 ) -> bool {
903 let mut index = start_frame;1156 let mut index = start_frame;
904 loop {1157 loop {
905- if cancel.load(Ordering::Relaxed) {1158+ if abort.hit() {
906 return true;1159 return true;
907 }1160 }
908 match hw.next_frame() {1161 match hw.next_frame() {
@@ -1060,13 +1313,16 @@ mod tests {
1060 }1313 }
1061 1314
1062 fn run(1315 fn run(
1063- mut demuxer: Demuxer,1316+ demuxer: &mut Demuxer,
1064- tx: SyncSender<Frame>,1317+ tx: &SyncSender<Frame>,
1065 start_frame: u32,1318 start_frame: u32,
1066 end_frame: u32,1319 end_frame: u32,
1067 render: &mut Render,1320 render: &mut Render,
1068- cancel: &AtomicBool,1321+ abort: &Abort,
1069 ) {1322 ) {
1323+ // A decoder per span, and cheap: it is a parameter-set map and a picture
1324+ // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
1325+ // one this worker keeps.
1070 let mut decoder = Decoder::new();1326 let mut decoder = Decoder::new();
1071 // Decoding has to restart at a sync sample, so pictures between it and1327 // Decoding has to restart at a sync sample, so pictures between it and
1072 // `start_frame` are decoded (the target frame references them) but never1328 // `start_frame` are decoded (the target frame references them) but never
@@ -1077,7 +1333,7 @@ fn run(
1077 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);1333 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);
1078 // reordering streams need POC-sorted output before display.1334 // reordering streams need POC-sorted output before display.
1079 loop {1335 loop {
1080- if cancel.load(Ordering::Relaxed) {1336+ if abort.hit() {
1081 break;1337 break;
1082 }1338 }
1083 let au = match demuxer.next_access_unit() {1339 let au = match demuxer.next_access_unit() {
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+62 -29
@@ -1230,8 +1230,14 @@ impl PlaybackSession {
1230 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's1230 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
1231 /// worker on this seek and the list stays a handful long. Nothing waits.1231 /// worker on this seek and the list stays a handful long. Nothing waits.
1232 fn retire(&mut self, replacement: Worker) {1232 fn retire(&mut self, replacement: Worker) {
1233- self.retired1233+ let mut outgoing = std::mem::replace(&mut self.worker, replacement);
1234- .push(std::mem::replace(&mut self.worker, replacement));1234+ // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is
1235+ // being replaced rather than steered, so its thread has to end -- and
1236+ // the cancel is what drops its command channel, without which a worker
1237+ // parked between spans would sit in `recv` forever, never reaped here
1238+ // and never joined in any bounded time at exit.
1239+ outgoing.cancel();
1240+ self.retired.push(outgoing);
1235 self.retired.retain(|w| !w.is_finished());1241 self.retired.retain(|w| !w.is_finished());
1236 }1242 }
1237 1243
@@ -1265,9 +1271,11 @@ impl PlaybackSession {
1265 let Some(span) = self.project.composite_span_at(next) else {1271 let Some(span) = self.project.composite_span_at(next) else {
1266 return false;1272 return false;
1267 };1273 };
1268- // We only get here on a disconnect, so the old worker has already1274+ // We only get here on a disconnect, so the old span is already done;
1269- // returned; cancel anyway, so `retire` treats every path alike.1275+ // abandon anyway, so `start_span` treats every path alike -- and the
1270- self.worker.cancel();1276+ // *worker* is kept, because the next clip is very often the same file
1277+ // (a split cuts one clip in two) and it already has it open.
1278+ self.worker.abandon();
1271 self.start_span(Some(span));1279 self.start_span(Some(span));
1272 true1280 true
1273 }1281 }
@@ -1327,36 +1335,58 @@ impl PlaybackSession {
1327 start,1335 start,
1328 from: Some((source, in_frame)),1336 from: Some((source, in_frame)),
1329 ..1337 ..
1330- }) => Ok(DecodeSession::open_worker_deferred(1338+ }) => {
1331- &self.project.sources()[source].path,1339+ let path = &self.project.sources()[source].path;
1332- // The file's own frames, which is the only place they exist:1340+ // The file's own frames, which is the only place they exist: a
1333- // a clip counts the timeline's ([`Rate`]).1341+ // clip counts the timeline's ([`Rate`]).
1334- self.span_rate.source_at(in_frame),1342+ let start_frame = self.span_rate.source_at(in_frame);
1335 // Source frames, which a speed makes more (or fewer) than the1343 // Source frames, which a speed makes more (or fewer) than the
1336 // timeline frames the span covers -- and which a file shot at1344 // timeline frames the span covers -- and which a file shot at
1337 // another rate makes fewer (or more) again. One past the last1345 // another rate makes fewer (or more) again. One past the last
1338 // frame this span shows, not one past its length: at another1346 // frame this span shows, not one past its length: at another
1339 // rate those are two different frames.1347 // rate those are two different frames.
1340- self.span_rate.source_at(1348+ let end_frame = self.span_rate.source_at(
1341 in_frame + span.expect("matched above").source_len().saturating_sub(1),1349 in_frame + span.expect("matched above").source_len().saturating_sub(1),
1342- ) + 1,1350+ ) + 1;
1343- self.project1351+ let color = self
1352+ .project
1344 .composite_color_at(start)1353 .composite_color_at(start)
1345 .copied()1354 .copied()
1346- .unwrap_or_default(),1355+ .unwrap_or_default();
1347 // ...and the canvas it is placed on: the project's resolution1356 // ...and the canvas it is placed on: the project's resolution
1348 // and this clip's own fit policy, constant across the span for1357 // and this clip's own fit policy, constant across the span for
1349- // the reason the grade is.1358+ // the reason the grade is. Built where it is handed over rather
1350- Composer::new(1359+ // than kept in a local, because a `Composer` owns the scratch
1351- self.meta.width,1360+ // buffers it places through -- the value is not copied about.
1352- self.meta.height,1361+ let fit = self.project.composite_fit_at(start);
1353- self.project.composite_fit_at(start),1362+ let canvas = || Composer::new(self.meta.width, self.meta.height, fit);
1354- ),
1355 // ...and the rendition an HDR source among them is mapped to,1363 // ...and the rendition an HDR source among them is mapped to,
1356- // the project's own and constant across the span for that reason1364+ // the project's own and constant across the span for that
1357- // too.1365+ // reason too.
1358- self.project.tone(),1366+ let tone = self.project.tone();
1359- )),1367+ // The worker already decoding this very file takes the new span
1368+ // itself: no thread, no container parse, no VA-API init -- the
1369+ // whole of what a seek used to cost. It answers `None` for any
1370+ // other file (and for a worker whose thread has ended), and the
1371+ // deferred opener below is then exactly the path it always was.
1372+ if let Some((frames, backend)) =
1373+ self.worker
1374+ .reseek(path, start_frame, end_frame, color, canvas(), tone)
1375+ {
1376+ self.frames = frames;
1377+ self.backend = backend;
1378+ self.span = span;
1379+ return;
1380+ }
1381+ Ok(DecodeSession::open_worker_deferred(
1382+ &self.project.sources()[source].path,
1383+ start_frame,
1384+ end_frame,
1385+ color,
1386+ canvas(),
1387+ tone,
1388+ ))
1389+ }
1360 // A gap: black for as long as it runs. An emptied timeline has no1390 // A gap: black for as long as it runs. An emptied timeline has no
1361 // span at all and gets one frame of it -- enough to put black on1391 // span at all and gets one frame of it -- enough to put black on
1362 // screen, and it ends where the timeline does, at once.1392 // screen, and it ends where the timeline does, at once.
@@ -2488,12 +2518,15 @@ impl PlaybackSession {
2488 /// keeps playing out of the same stream, the clock keeps running, and a2518 /// keeps playing out of the same stream, the clock keeps running, and a
2489 /// grade dragged during playback is therefore silent.2519 /// grade dragged during playback is therefore silent.
2490 fn start_picture(&mut self, target: u32) {2520 fn start_picture(&mut self, target: u32) {
2491- // Cancel first, drop second: the old worker may be parked in `send` on2521+ // Abandon first, drop second: the old worker may be parked in `send` on
2492 // the bounded channel, where only the disconnect wakes it -- and it2522 // the bounded channel, where only the disconnect wakes it -- and it
2493- // then finds the flag already set. It is then parked, not joined; see2523+ // then finds the span already superseded. The *thread* is kept, and
2494- // [`retire`](Self::retire), which is what keeps a scrub off the price2524+ // with it the open file and the open decoder, so a seek onto the same
2495- // of a VA-API init.2525+ // source costs a demuxer seek and a decoder flush rather than the
2496- self.worker.cancel();2526+ // VA-API init (98 ms) a new worker would pay; a worker that cannot take
2527+ // the new span is retired by [`retire`](Self::retire) instead, and
2528+ // nothing on this thread joins either way.
2529+ self.worker.abandon();
2497 // The span runs from `target` to the end of whatever it landed in -- a2530 // The span runs from `target` to the end of whatever it landed in -- a
2498 // clip, or a gap, which starts a black-frame worker instead. `None` is2531 // clip, or a gap, which starts a black-frame worker instead. `None` is
2499 // the emptied timeline, black too, and `start_span` says so.2532 // the emptied timeline, black too, and `start_span` says so.