forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB99d87d4Tahinli3 months ago508 commits

decode.rs1534 lines, 61.4 KiBHistoryRawDownload
1//! Background decode worker. Frames leave over a bounded channel so the caller's
2//! thread (the UI thread) never blocks on decode and memory stays capped.
3
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
7use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
8use std::thread;
9
10use rusty_h264::Decoder;
11
12use crate::color::ColorParams;
13use crate::colorspace::{ColorDescription, Matrix, Transfer};
14use crate::convert::{i420_to_bgra, i420_to_bgra_with};
15use crate::demux::{Codec, Demuxer, VideoMeta};
16use crate::hw::HwSession;
17use crate::scale::Composer;
18use crate::tonemap::{self, ToneMapper};
19
20/// One decoded picture, ready to hand to a renderer.
21pub struct Frame {
22 /// Position in decode order, starting at 0.
23 pub index: u32,
24 pub width: u32,
25 pub height: u32,
26 /// BGRA8, straight alpha, tightly packed.
27 pub bgra: Vec<u8>,
28}
29
30/// Which decoder a source is really running on. Read-only introspection: it
31/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose --
32/// a hardware session that opened and then failed before its first picture
33/// falls back to software and this says so, because it is written where the
34/// fallback happens rather than where it was hoped for.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Backend {
37 /// The worker has not reached its decoder yet: the plugin's VA-API init is
38 /// ~90 ms, and this is what a caller reads in that window.
39 #[default]
40 Opening,
41 /// The VA-API plugin (`libengine_hw.so`).
42 Hardware,
43 /// `rusty_h264`, in this process.
44 Software,
45 /// A still image: one `image` decode, no stream and no decoder to pick.
46 Still,
47 /// A gap: black frames, nothing decoded at all.
48 Gap,
49}
50
51impl Backend {
52 /// Short enough for a library row and a transport line.
53 pub fn label(self) -> &'static str {
54 match self {
55 Self::Opening => "opening",
56 Self::Hardware => "HW",
57 Self::Software => "SW",
58 Self::Still => "still",
59 Self::Gap => "gap",
60 }
61 }
62
63 fn code(self) -> u8 {
64 match self {
65 Self::Opening => 0,
66 Self::Hardware => 1,
67 Self::Software => 2,
68 Self::Still => 3,
69 Self::Gap => 4,
70 }
71 }
72
73 fn from_code(code: u8) -> Self {
74 match code {
75 1 => Self::Hardware,
76 2 => Self::Software,
77 3 => Self::Still,
78 4 => Self::Gap,
79 _ => Self::Opening,
80 }
81 }
82}
83
84/// Where a worker publishes the decoder it opened, for whoever holds the other
85/// end of its channel. One atomic byte, written once at open (and once more if
86/// hardware hands the range back to software), read whenever a caller repaints
87/// -- never per frame on either side.
88#[derive(Clone, Default)]
89pub struct BackendCell(Arc<AtomicU8>);
90
91impl BackendCell {
92 pub(crate) fn new(backend: Backend) -> Self {
93 Self(Arc::new(AtomicU8::new(backend.code())))
94 }
95
96 fn set(&self, backend: Backend) {
97 self.0.store(backend.code(), Ordering::Relaxed);
98 }
99
100 pub fn get(&self) -> Backend {
101 Backend::from_code(self.0.load(Ordering::Relaxed))
102 }
103}
104
105/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`]
106/// decides it: the same `VE_SW` pin and the same plugin probe against this very
107/// file. What lets a front-end name the decoder *before* anything plays.
108///
109/// The codec is `None` for a still image, which has no coded stream. A stream
110/// no decoder here can take is an `Err` naming the plugin, exactly as opening
111/// it would be -- the same refusal, one VA-API init earlier.
112///
113/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per
114/// file, off a render thread, and keep the answer.
115pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
116 if crate::is_image(path) {
117 return Ok((None, Backend::Still));
118 }
119 let path = path.to_path_buf();
120 let (meta, _demuxer) = Demuxer::open(&path)?;
121 match hw_decodes(&path, 0, meta.codec) {
122 Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)),
123 Err(e) if meta.codec != Codec::H264 => return Err(e.into()),
124 Err(_) => {}
125 }
126 Ok((Some(meta.codec), Backend::Software))
127}
128
129/// A running decode worker: the flag that stops it, and the handle to wait on.
130///
131/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
132/// outlives the process otherwise, and Mesa's `atexit` handlers free the state
133/// it is still reading -- a SIGSEGV at exit, long after the last test passed.
134pub(crate) struct Worker {
135 cancel: Arc<AtomicBool>,
136 /// `None` once detached, and for a range with nothing to decode: either way
137 /// there is no thread left to wait for.
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).
152struct 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.
173struct 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.
190struct Abort<'a> {
191 cancel: &'a AtomicBool,
192 generation: &'a AtomicU64,
193 mine: u64,
194 floor: &'a AtomicU32,
195}
196
197impl 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 }
214}
215
216impl Worker {
217 /// Stops the worker *and its thread* at their next check, without waiting.
218 /// Callers that replace a worker should do this first and drop the receiver
219 /// second: a worker parked in `send` only wakes on the disconnect, so the
220 /// join below would otherwise wait for a consumer that is never coming.
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) {
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()))
304 }
305
306 /// Whether the thread has already returned, i.e. dropping this would not
307 /// wait. `true` for a worker that never had a thread. What lets a caller
308 /// park cancelled workers and reap them without ever blocking.
309 pub(crate) fn is_finished(&self) -> bool {
310 self.handle
311 .as_ref()
312 .is_none_or(thread::JoinHandle::is_finished)
313 }
314
315 /// Lets the worker run on unwatched -- what the public API does, since it
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`.
322 fn detach(mut self) -> Arc<AtomicBool> {
323 self.handle = None;
324 self.reuse = None;
325 Arc::clone(&self.cancel)
326 }
327}
328
329impl Drop for Worker {
330 fn drop(&mut self) {
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.
334 self.cancel();
335 let _ = handle.join();
336 }
337 }
338}
339
340/// A running worker and the frames it is sending, handed out as one value
341/// because they must be *dropped* as one, in this order: the receiver
342/// disconnects first, which is the only thing that wakes a worker parked in a
343/// full `send`, and the join inside [`Worker::drop`] runs second.
344///
345/// Rust drops fields in declaration order, so this struct *is* that rule, and
346/// it holds wherever the value goes: an early return out of a half-built
347/// session, an unwind, a caller not written yet. Two separate locals do not
348/// hold it -- they drop in reverse order of declaration, so the worker there
349/// joins a thread nobody will ever drain, which is a hang and not a slow path.
350pub(crate) struct FrameStream {
351 pub(crate) frames: Receiver<Frame>,
352 pub(crate) worker: Worker,
353 /// What this stream's pictures are being decoded by. Dropped last and read
354 /// by the caller, so it outlives nothing and blocks nothing.
355 pub(crate) backend: BackendCell,
356}
357
358pub struct DecodeSession;
359
360impl DecodeSession {
361 /// Opens `path`, returning stream metadata immediately and a receiver that
362 /// yields frames as the worker decodes them. The worker stops when the
363 /// receiver is dropped, at end of stream, or on the first decode error.
364 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
365 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
366 Ok((meta, rx))
367 }
368
369 /// As [`DecodeSession::open`], but the first frame delivered is
370 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
371 /// Setting the returned flag stops the worker at its next access unit,
372 /// which is how a caller abandons a session it no longer wants to drain.
373 pub fn open_at(
374 path: impl AsRef<Path>,
375 start_frame: u32,
376 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
377 // `u32::MAX` is clamped to the stream's frame count below, so this is
378 // "to the end of the file".
379 Self::open_range(path, start_frame, u32::MAX)
380 }
381
382 /// As [`DecodeSession::open_at`], but the worker also stops on its own
383 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
384 /// absolute source frames, which is what a clip of a longer file needs.
385 /// `end_frame` is capped at the stream's frame count, and an empty range
386 /// yields a receiver that is simply already disconnected.
387 pub fn open_range(
388 path: impl AsRef<Path>,
389 start_frame: u32,
390 end_frame: u32,
391 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
392 // Ungraded: the public API opens a *file*, and a colour grade belongs to
393 // a clip of a timeline. `PlaybackSession` is what has one to pass.
394 let (meta, stream) = Self::open_worker(
395 path,
396 start_frame,
397 end_frame,
398 ColorParams::default(),
399 // No project, no canvas: the file-level API hands back the
400 // pictures the file holds, at the size it holds them.
401 Composer::passthrough(),
402 // ...and no project means no picked rendition either: an HDR file
403 // opened through this door is mapped the published way.
404 tonemap::Preset::default(),
405 )?;
406 // The public API hands out the flag alone, so the worker is detached and
407 // the receiver goes to the caller: nothing here joins anything.
408 Ok((meta, stream.frames, stream.worker.detach()))
409 }
410
411 /// A worker that decodes nothing and emits `len` black frames, indexed from
412 /// zero -- what a *gap* in the video lane looks like. It goes down the same
413 /// channel as decoded frames, so a gap costs the caller no branch at all
414 /// beyond choosing this opener: same bounded channel, same backpressure,
415 /// same cancel, same retire path.
416 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
417 let (tx, rx) = sync_channel(2);
418 let cancel = Arc::new(AtomicBool::new(false));
419 if len == 0 {
420 return FrameStream {
421 frames: rx,
422 worker: Worker {
423 cancel,
424 handle: None,
425 reuse: None,
426 },
427 backend: BackendCell::new(Backend::Gap),
428 };
429 }
430 let worker_cancel = Arc::clone(&cancel);
431 // One buffer, cloned per frame: opaque black is a constant, and the
432 // clone is a memcpy against a decode this replaces entirely.
433 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
434 let handle = thread::Builder::new()
435 .name("black".into())
436 .spawn(move || {
437 for index in 0..len {
438 if worker_cancel.load(Ordering::Relaxed) {
439 return;
440 }
441 let frame = Frame {
442 index,
443 width,
444 height,
445 bgra: black.clone(),
446 };
447 if tx.send(frame).is_err() {
448 return; // caller moved on
449 }
450 }
451 })
452 .ok();
453 FrameStream {
454 frames: rx,
455 worker: Worker {
456 cancel,
457 handle,
458 reuse: None,
459 },
460 backend: BackendCell::new(Backend::Gap),
461 }
462 }
463
464 /// A worker for a still image ([`crate::is_image`]): the file is decoded
465 /// *once* and the same picture goes down the channel `len` times, indexed
466 /// from `start_frame` exactly as a decoder's pictures are -- so a placed
467 /// image is a clip like any other to everything downstream (`try_frame`
468 /// rewrites those indices, `next_clip` walks off the end of the range).
469 ///
470 /// Graded and placed on the canvas once too, before the repeat: a still is
471 /// the same pixels every frame, so the whole cost of one is one conversion
472 /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays.
473 pub(crate) fn open_still(
474 path: &Path,
475 start_frame: u32,
476 len: u32,
477 color: ColorParams,
478 canvas: Composer,
479 ) -> crate::Result<FrameStream> {
480 let still = Still::open(path)?;
481 let (tx, rx) = sync_channel(2);
482 let cancel = Arc::new(AtomicBool::new(false));
483 if len == 0 {
484 return Ok(FrameStream {
485 frames: rx,
486 worker: Worker {
487 cancel,
488 handle: None,
489 reuse: None,
490 },
491 backend: BackendCell::new(Backend::Still),
492 });
493 }
494 // The one conversion, on this thread: it is a few milliseconds and the
495 // error it could raise has already been raised by `Still::open`.
496 // BT.601 limited, because that is what `rgb_to_i420` above wrote these
497 // planes in: a still round-trips through the pair, not through the
498 // colour of whatever file is on the timeline beside it.
499 // No preset argument, and none wanted: a still is decoded into BT.601
500 // SDR planes, so the tone map is not built at all whichever rendition
501 // the project is watching.
502 let first = Render::new(
503 color,
504 ColorDescription::default(),
505 canvas,
506 tonemap::Preset::default(),
507 // ...and no declared peak either, for the same reason: there is no
508 // tone map on this path to hand one to.
509 None,
510 )
511 .frame(
512 start_frame,
513 &still.y,
514 &still.u,
515 &still.v,
516 still.width,
517 still.height,
518 );
519 let worker_cancel = Arc::clone(&cancel);
520 let handle = thread::Builder::new()
521 .name("still".into())
522 .spawn(move || {
523 let (width, height, bgra) = (first.width, first.height, first.bgra);
524 for index in 0..len {
525 if worker_cancel.load(Ordering::Relaxed) {
526 return;
527 }
528 let frame = Frame {
529 index: start_frame + index,
530 width,
531 height,
532 bgra: bgra.clone(),
533 };
534 if tx.send(frame).is_err() {
535 return; // caller moved on
536 }
537 }
538 })
539 .ok();
540 Ok(FrameStream {
541 frames: rx,
542 worker: Worker {
543 cancel,
544 handle,
545 reuse: None,
546 },
547 backend: BackendCell::new(Backend::Still),
548 })
549 }
550
551 /// As [`DecodeSession::open_range`], but the caller gets the whole
552 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
553 /// `color` -- the clip's own setting, folded into the conversion the frames
554 /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
555 /// than read per frame because a worker *is* one clip's range: a grade
556 /// changed while this one runs reaches the picture when the session reseeks
557 /// onto the new one, which every edit does.
558 ///
559 /// In-process only: a caller that outlives its workers has to be able to
560 /// join them at exit.
561 ///
562 /// `canvas` is the project's own resolution and this clip's fit policy: the
563 /// frames come out at *that* size, whatever the file's is. A
564 /// [`Composer::passthrough`] (or one already the source's size) leaves every
565 /// picture exactly as it was decoded.
566 ///
567 /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured
568 /// here for the reason the grade is: it is constant across one span, and a
569 /// preset picked while this worker runs reaches the picture when the session
570 /// reseeks onto the new one. An SDR source ignores it entirely.
571 pub(crate) fn open_worker(
572 path: impl AsRef<Path>,
573 start_frame: u32,
574 end_frame: u32,
575 color: ColorParams,
576 canvas: Composer,
577 tone: tonemap::Preset,
578 ) -> crate::Result<(VideoMeta, FrameStream)> {
579 let path = path.as_ref().to_path_buf();
580 let (meta, demuxer) = Demuxer::open(&path)?;
581 // No software HEVC or VP9 decoder exists, so such a file the plugin will
582 // not take is refused *here*, where the caller still has somewhere to
583 // show it -- a worker that opened and then produced nothing is a black
584 // screen with no explanation. The probe session is opened, made to
585 // decode one picture and dropped: it costs one extra VA-API init
586 // (~90 ms) plus that frame, and only off the H.264 path.
587 if meta.codec != Codec::H264 {
588 hw_decodes(&path, start_frame, meta.codec)?;
589 }
590 let end_frame = end_frame.min(meta.frame_count);
591 if end_frame <= start_frame {
592 // Nothing to decode: a disconnected receiver and no thread at all,
593 // so the caller sees an immediate end of stream rather than an error.
594 let (_, rx) = sync_channel(1);
595 return Ok((
596 meta,
597 FrameStream {
598 frames: rx,
599 worker: Worker {
600 cancel: Arc::new(AtomicBool::new(false)),
601 handle: None,
602 reuse: None,
603 },
604 backend: BackendCell::default(),
605 },
606 ));
607 }
608 Ok((
609 meta,
610 span_worker(
611 path,
612 Some(Source::demuxed(demuxer, meta)),
613 start_frame,
614 end_frame,
615 color,
616 canvas,
617 tone,
618 ),
619 ))
620 }
621
622 /// As [`open_worker`](Self::open_worker), but the *file* is opened on the
623 /// worker too: nothing here touches the disk, so the caller pays a thread
624 /// spawn and not a demux -- 550-750 ms warm on a 25 GB film, seconds cold,
625 /// which is what a seek or a clip boundary used to cost the UI thread.
626 ///
627 /// The price is that there is no [`VideoMeta`] to return and no synchronous
628 /// refusal either: a file that will not open, and a codec no decoder here
629 /// takes (the plugin probe is skipped -- the worker's own refusal below
630 /// covers it), simply drop the sender. The disconnected receiver is what
631 /// carries a session on to the next span, which is exactly what a failed
632 /// open did on this path before. Callers that must *tell* the user why --
633 /// an import at the door -- keep the sync opener.
634 pub(crate) fn open_worker_deferred(
635 path: impl AsRef<Path>,
636 start_frame: u32,
637 end_frame: u32,
638 color: ColorParams,
639 canvas: Composer,
640 tone: tonemap::Preset,
641 ) -> FrameStream {
642 span_worker(
643 path.as_ref().to_path_buf(),
644 None,
645 start_frame,
646 end_frame,
647 color,
648 canvas,
649 tone,
650 )
651 }
652}
653
654/// Spawns a decode worker over `path` and gives it its first span. The thread
655/// **outlives that span**: it parks on its command channel afterwards, so the
656/// next seek onto the same file reaches it through [`Worker::reseek`] and costs
657/// a demuxer seek and a decoder flush instead of a thread, a container parse and
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.
663#[allow(clippy::too_many_arguments)]
664fn span_worker(
665 path: PathBuf,
666 opened: Option<Source>,
667 start_frame: u32,
668 end_frame: u32,
669 color: ColorParams,
670 canvas: Composer,
671 tone: tonemap::Preset,
672) -> FrameStream {
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.
785const 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).
794const 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.
799struct 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
814impl 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.
866fn run_span(
867 path: &Path,
868 source: &mut Option<Source>,
869 cmd: SpanCmd,
870 abort: &Abort,
871 backend: &BackendCell,
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);
895 // An empty range decodes nothing and must send nothing: `run_hw` counts a
896 // frame *out* before it compares, so without this a zero-length span would
897 // emit one picture.
898 if end <= start {
899 return;
900 }
901 // The stream's own colour and peak brightness: properties of the stream, so
902 // neither can change while one range decodes -- but the grade, the canvas
903 // and the rendition are the *span's*, so this is built per span.
904 let mut render = Render::new(color, opened.meta.color, canvas, tone, opened.peak);
905 if let Some(reused) = opened.position_hw(path, start) {
906 // Cancelled during the init (or the seek): leave without decoding.
907 if abort.hit() {
908 return;
909 }
910 backend.set(Backend::Hardware);
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 {
932 return;
933 }
934 // A driver that opens but cannot decode a single frame is still a
935 // fallback case, not a dead session.
936 opened.hw = None;
937 eprintln!("hardware decode failed before any frame, falling back to software");
938 }
939 // ...except where there is nothing to fall back to. Feeding HEVC or VP9
940 // bytes to `rusty_h264` would be garbage, not a fallback.
941 if opened.meta.codec != Codec::H264 {
942 eprintln!("{}", opened.meta.codec.needs_plugin());
943 return;
944 }
945 eprintln!("decode backend: software (rusty_h264)");
946 backend.set(Backend::Software);
947 run(&mut opened.demuxer, &tx, start, end, &mut render, abort)
948}
949
950/// One clip's pictures on their way to the renderer: graded, placed on the
951/// project canvas, converted. Both decode loops go through it, so hardware and
952/// software cannot show two different pictures.
953///
954/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
955/// applied at the resolution it was shot at, and the letterbox bars around it
956/// are not the clip -- a brightness grade must not lift them off black.
957///
958/// A project at the media's own resolution never reaches any of that: it takes
959/// the fused graded conversion, the one path this engine had before there was a
960/// project resolution, byte for byte and allocation for allocation.
961struct Render {
962 color: ColorParams,
963 /// What the source's samples mean -- the stream's own matrix and range,
964 /// which is what the conversion below is done in rather than the BT.601 it
965 /// used to assume of every file.
966 desc: ColorDescription,
967 canvas: Composer,
968 /// This stream's HDR-to-SDR map, built once here because building it is
969 /// float work over 9 537 grid nodes and the transfer is a property of the
970 /// stream. `None` for an SDR stream, which is what keeps that path exactly
971 /// the one it was.
972 tone: Option<ToneMapper>,
973 /// The working copy of the source planes, refilled per frame and kept
974 /// across the worker's whole range. Empty unless the clip needs one: it is
975 /// tone-mapped in place, graded in place, or both.
976 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
977}
978
979/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's
980/// output contract ([`crate::tonemap`]), and no longer the HDR space the file
981/// declared.
982const TONE_MAPPED: ColorDescription = ColorDescription {
983 matrix: Matrix::Bt709,
984 transfer: Transfer::Sdr,
985 full_range: false,
986};
987
988impl Render {
989 /// `peak` is what the file declared about its own brightness
990 /// ([`Demuxer::light`]), which only an HDR stream has and only the
991 /// reference rendition reads (see [`tonemap::Preset`]).
992 fn new(
993 color: ColorParams,
994 desc: ColorDescription,
995 canvas: Composer,
996 preset: tonemap::Preset,
997 peak: Option<f32>,
998 ) -> Self {
999 Self {
1000 color,
1001 desc,
1002 canvas,
1003 // corner-cut: the ceiling is that the map reads limited-range codes
1004 // (`tonemap`'s input contract), so a full-range PQ file -- which
1005 // no encoder writes and no camera produces -- is mapped as if it
1006 // were limited and comes out slightly crushed. The upgrade is a
1007 // range argument to `ToneMapper::new`.
1008 tone: match desc.transfer {
1009 Transfer::Sdr => None,
1010 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)),
1011 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
1012 },
1013 graded: (Vec::new(), Vec::new(), Vec::new()),
1014 }
1015 }
1016
1017 fn frame(
1018 &mut self,
1019 index: u32,
1020 y: &[u8],
1021 u: &[u8],
1022 v: &[u8],
1023 width: u32,
1024 height: u32,
1025 ) -> Frame {
1026 let passthrough = self.canvas.is_passthrough(width, height);
1027 // Everything that has to happen to the samples before the canvas sees
1028 // them, on one copy: the tone map (HDR streams only) and, unless the
1029 // conversion below can fuse it, the grade. An SDR stream that is either
1030 // ungraded or passing through takes neither and never allocates.
1031 //
1032 // The grade lands *after* the map on purpose: it is a look on the
1033 // picture a viewer is shown, so its brightness and saturation mean what
1034 // they say in the SDR the tone map just produced, not in the 10-stop
1035 // HDR the file was in.
1036 let (y, u, v, desc) = if self.tone.is_some() || (!passthrough && !self.color.is_identity())
1037 {
1038 let (gy, gu, gv) = &mut self.graded;
1039 gy.clear();
1040 gy.extend_from_slice(y);
1041 gu.clear();
1042 gu.extend_from_slice(u);
1043 gv.clear();
1044 gv.extend_from_slice(v);
1045 if let Some(tone) = &self.tone {
1046 tone.map(gy, gu, gv, width as usize, height as usize);
1047 }
1048 if !passthrough && !self.color.is_identity() {
1049 crate::color::apply_yuv(&self.color, gy, gu, gv);
1050 }
1051 let desc = if self.tone.is_some() {
1052 TONE_MAPPED
1053 } else {
1054 self.desc
1055 };
1056 (&gy[..], &gu[..], &gv[..], desc)
1057 } else {
1058 (y, u, v, self.desc)
1059 };
1060 if passthrough {
1061 return Frame {
1062 index,
1063 width,
1064 height,
1065 bgra: i420_to_bgra_with(
1066 &desc,
1067 &self.color,
1068 y,
1069 u,
1070 v,
1071 width as usize,
1072 height as usize,
1073 ),
1074 };
1075 }
1076 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
1077 Frame {
1078 index,
1079 width,
1080 height,
1081 // Ungraded on purpose: the grade is already in the pixels above and
1082 // the canvas around them must stay the black it was filled with.
1083 bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize),
1084 }
1085 }
1086}
1087
1088/// One still image, decoded to tightly packed I420 -- the shape every other
1089/// source arrives in, so a placed image goes through the same grade, the same
1090/// canvas and the same conversion as a decoded picture and there is no second
1091/// pixel path to keep in step.
1092///
1093/// Held whole rather than streamed: an image *is* one picture, and the file is
1094/// read once per span that plays it.
1095pub(crate) struct Still {
1096 pub(crate) y: Vec<u8>,
1097 pub(crate) u: Vec<u8>,
1098 pub(crate) v: Vec<u8>,
1099 pub(crate) width: u32,
1100 pub(crate) height: u32,
1101}
1102
1103impl Still {
1104 /// Decodes `path`. Refused by name for a picture that is not one
1105 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
1106 /// file are both held to cannot be walked around by a 30000-pixel-wide PNG.
1107 ///
1108 /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a
1109 /// transparent PNG arrives fully opaque over its own colours rather than
1110 /// over the clip beneath it. I420 has nowhere to carry it and this engine
1111 /// composes one picture per frame (topmost lane wins), so there is nothing
1112 /// for a blend to blend with.
1113 ///
1114 /// corner-cut: the ceiling is a logo with a transparent background, which
1115 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
1116 /// giving `scale::Composer` a blend over the lane below.
1117 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
1118 let reader = image::ImageReader::open(path)?.with_guessed_format()?;
1119 let rgb = reader
1120 .decode()
1121 .map_err(|e| format!("{}: {e}", path.display()))?
1122 .to_rgb8();
1123 let (width, height) = rgb.dimensions();
1124 if !crate::is_resolution(width, height) {
1125 return Err(format!(
1126 "{} is {width}x{height}, which is not a picture this engine composes",
1127 path.display()
1128 )
1129 .into());
1130 }
1131 let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize);
1132 Ok(Self {
1133 y,
1134 u,
1135 v,
1136 width,
1137 height,
1138 })
1139 }
1140
1141 /// The planes as an export's decoder hands them over, so a still and a
1142 /// decoded picture are the same value to `export::run`.
1143 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
1144 (&self.y, &self.u, &self.v, self.width, self.height)
1145 }
1146}
1147
1148/// How big the picture in `path` is, from its header alone -- what a library row
1149/// says about a file it has not placed anywhere. The whole file is not decoded.
1150pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
1151 Ok(image::ImageReader::open(path)?
1152 .with_guessed_format()?
1153 .into_dimensions()
1154 .map_err(|e| format!("{}: {e}", path.display()))?)
1155}
1156
1157/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
1158/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why
1159/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and
1160/// not the timeline's. A still has no stream to be tagged by; it round-trips to
1161/// the colour it was authored in through this pair and nothing else sees these
1162/// planes (`images::still_pixels_match_the_source_image` measures it).
1163///
1164/// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
1165/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
1166/// [`crate::scale::Composer::place`] panics on anything else for.
1167fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1168 let (cw, ch) = crate::scale::chroma_dims(width, height);
1169 let mut y = vec![0u8; width * height];
1170 let mut u = vec![0u8; cw * ch];
1171 let mut v = vec![0u8; cw * ch];
1172 for row in 0..height {
1173 for col in 0..width {
1174 let p = (row * width + col) * 3;
1175 let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32);
1176 y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
1177 }
1178 }
1179 for crow in 0..ch {
1180 for ccol in 0..cw {
1181 let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32);
1182 for row in crow * 2..(crow * 2 + 2).min(height) {
1183 for col in ccol * 2..(ccol * 2 + 2).min(width) {
1184 let p = (row * width + col) * 3;
1185 sr += rgb[p] as i32;
1186 sg += rgb[p + 1] as i32;
1187 sb += rgb[p + 2] as i32;
1188 n += 1;
1189 }
1190 }
1191 let n = n.max(1);
1192 let (r, g, b) = (sr / n, sg / n, sb / n);
1193 u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
1194 v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
1195 }
1196 }
1197 (y, u, v)
1198}
1199
1200/// `None` when the software path must be used: forced by `VE_SW=1`, or the
1201/// plugin is absent/broken/unable to open this particular file.
1202fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> {
1203 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
1204 return None;
1205 }
1206 HwSession::open_at(path, start_frame)
1207}
1208
1209/// `Ok` when the plugin really decodes this file: it opens *and* hands back a
1210/// first picture. Opening only reads the container -- a stream the vendored
1211/// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and
1212/// then produces nothing, which reaches the user as a black picture with an
1213/// instant `eof` unless the door asks for that first frame. Costs one decoded
1214/// frame per probe.
1215///
1216/// The `Err` says which half failed, because "there is no decoder for this
1217/// codec" and "the decoder here would not take this stream" are different
1218/// refusals and a user acts on them differently.
1219fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), String> {
1220 let Some(mut hw) = open_hw(path, start_frame) else {
1221 return Err(codec.needs_plugin());
1222 };
1223 // End of stream counts as a refusal, not as a pass: a session that hands
1224 // back no picture at all is exactly the black-frame-and-instant-eof this
1225 // probe exists to catch, and `Ok(None)` is how the plugin says it.
1226 match hw.next_frame() {
1227 Ok(Some(_)) => Ok(()),
1228 _ => Err(codec.undecodable()),
1229 }
1230}
1231
1232/// Returns whether the session was handled; `false` only when hardware decode
1233/// failed without emitting a single frame, so software can still take over.
1234///
1235/// The plugin already positioned itself at `start_frame`, so indices are
1236/// counted from there (a stream whose very first sample is not a sync sample
1237/// cannot be decoded from its start at all, and is not accounted for).
1238fn run_hw(
1239 hw: &mut HwSession,
1240 tx: &SyncSender<Frame>,
1241 start_frame: u32,
1242 end_frame: u32,
1243 render: &mut Render,
1244 abort: &Abort,
1245) -> bool {
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;
1250 loop {
1251 if abort.hit() {
1252 return true;
1253 }
1254 match hw.next_frame() {
1255 Ok(Some((y, u, v, width, height))) => {
1256 let due = index;
1257 index += 1;
1258 if abort.late(due) && skipped < LATE_RUN {
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 }
1266 }
1267 if index >= end_frame {
1268 return true; // end of the requested range
1269 }
1270 }
1271 Ok(None) => return true,
1272 Err(e) => {
1273 if index == start_frame {
1274 return false;
1275 }
1276 eprintln!("hardware decode error at frame {index}: {e}");
1277 return true;
1278 }
1279 }
1280 }
1281}
1282
1283#[cfg(test)]
1284mod tests {
1285 use super::*;
1286 use std::sync::mpsc::RecvTimeoutError;
1287 use std::time::{Duration, Instant};
1288
1289 fn asset(name: &str) -> PathBuf {
1290 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1291 .join("../../assets")
1292 .join(name)
1293 }
1294
1295 /// Drops `path` from the page cache, so the open below really goes to disk
1296 /// -- the case the deferred opener exists for, and the one that costs
1297 /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a
1298 /// no-op wherever `python3` is not around: the assertions hold either way,
1299 /// the numbers printed are simply the warm ones.
1300 fn evict(path: &Path) {
1301 let _ = std::process::Command::new("python3")
1302 .arg("-c")
1303 .arg(
1304 "import os,sys\n\
1305 fd=os.open(sys.argv[1],os.O_RDONLY)\n\
1306 os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\
1307 os.close(fd)",
1308 )
1309 .arg(path)
1310 .status();
1311 }
1312
1313 /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller
1314 /// gets its stream back in the time a thread takes to spawn, and the file
1315 /// is opened behind it -- so the first frame necessarily arrives *after*
1316 /// the call returned, and the sync opener on the same cold file pays on the
1317 /// calling thread what this one does not.
1318 #[test]
1319 fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() {
1320 let path = asset("test_baseline.mp4");
1321 evict(&path);
1322 let start = Instant::now();
1323 let stream = DecodeSession::open_worker_deferred(
1324 &path,
1325 0,
1326 u32::MAX,
1327 ColorParams::default(),
1328 Composer::passthrough(),
1329 tonemap::Preset::default(),
1330 );
1331 let returned = start.elapsed();
1332 let frame = stream
1333 .frames
1334 .recv_timeout(Duration::from_secs(10))
1335 .expect("first frame");
1336 let first_frame = start.elapsed();
1337
1338 // The same file, equally cold, through the door the import path keeps:
1339 // that one hands back metadata, and the demux it reads to do so is on
1340 // this thread.
1341 evict(&path);
1342 let sync_start = Instant::now();
1343 let sync = DecodeSession::open_worker(
1344 &path,
1345 0,
1346 u32::MAX,
1347 ColorParams::default(),
1348 Composer::passthrough(),
1349 tonemap::Preset::default(),
1350 )
1351 .expect("sync open");
1352 let sync_returned = sync_start.elapsed();
1353 drop(sync);
1354
1355 eprintln!(
1356 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
1357 sync open returned in {sync_returned:?}"
1358 );
1359 assert_eq!(frame.index, 0, "the deferred worker starts where it is told");
1360 assert!(
1361 returned < Duration::from_millis(10),
1362 "the caller waited {returned:?} -- something is still being read \
1363 from the file before this returns"
1364 );
1365 assert!(
1366 first_frame > returned,
1367 "the first frame arrived within the call ({first_frame:?} vs \
1368 {returned:?}), which cannot happen if the open is deferred"
1369 );
1370 assert!(
1371 returned < sync_returned,
1372 "the deferred open ({returned:?}) cost as much as the sync one \
1373 ({sync_returned:?}): the demux is still on the caller's thread"
1374 );
1375 }
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
1430 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
1431 /// The channel is bounded, so such a worker is parked in `send` within a
1432 /// few frames, and the only thing that can wake it is its receiver going
1433 /// away -- which is why the receiver is the first field and the join inside
1434 /// `Worker::drop` is the second. Swap those two fields and this hangs.
1435 ///
1436 /// This is the whole basis of every teardown path in the engine, so it is
1437 /// asserted rather than commented: the drop runs on a second thread and a
1438 /// regression fails in ten seconds instead of hanging the suite forever.
1439 #[test]
1440 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
1441 let (_meta, stream) = DecodeSession::open_worker(
1442 &asset("test_baseline.mp4"),
1443 0,
1444 u32::MAX,
1445 ColorParams::default(),
1446 Composer::passthrough(),
1447 tonemap::Preset::default(),
1448 )
1449 .expect("open");
1450 // Nothing is ever received: two frames fill the channel and the next
1451 // send parks the decode thread, exactly as a refused project load does.
1452 thread::sleep(Duration::from_millis(500));
1453
1454 let (done_tx, done_rx) = sync_channel(1);
1455 thread::spawn(move || {
1456 drop(stream);
1457 let _ = done_tx.send(());
1458 });
1459 assert!(
1460 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
1461 "dropping a parked stream deadlocked: it joined a decode thread \
1462 while still holding the receiver that thread is waiting on"
1463 );
1464 }
1465}
1466
1467fn run(
1468 demuxer: &mut Demuxer,
1469 tx: &SyncSender<Frame>,
1470 start_frame: u32,
1471 end_frame: u32,
1472 render: &mut Render,
1473 abort: &Abort,
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.
1478 let mut decoder = Decoder::new();
1479 // Decoding has to restart at a sync sample, so pictures between it and
1480 // `start_frame` are decoded (the target frame references them) but never
1481 // converted or sent. Signed, because the landing sync sample can sit inside
1482 // what the file's edit list trims, i.e. *before* frame 0.
1483 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1484 let mut skipped = 0;
1485
1486 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);
1487 // reordering streams need POC-sorted output before display.
1488 loop {
1489 if abort.hit() {
1490 break;
1491 }
1492 let au = match demuxer.next_access_unit() {
1493 Ok(Some(au)) => au,
1494 Ok(None) => break,
1495 Err(e) => {
1496 eprintln!("demux error: {e}");
1497 break;
1498 }
1499 };
1500 let yuv = match decoder.decode(&au) {
1501 Ok(Some(yuv)) => yuv,
1502 Ok(None) => continue,
1503 Err(e) => {
1504 eprintln!("decode error at access unit {index}: {e}");
1505 break;
1506 }
1507 };
1508 if index < i64::from(start_frame) {
1509 index += 1;
1510 continue;
1511 }
1512 let due = index as u32;
1513 index += 1;
1514 if abort.late(due) && skipped < LATE_RUN {
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 }
1529 }
1530 if index >= i64::from(end_frame) {
1531 break; // end of the requested range
1532 }
1533 }
1534}