forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB86e9455Tahinli3 months ago398 commits

decode.rs1491 lines, 58.8 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, 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 let (tx, rx) = sync_channel(canvas.queue_depth());
674 let cancel = Arc::new(AtomicBool::new(false));
675 // Written by the worker the moment it knows, so a caller reading it sees
676 // what opened rather than what was hoped for -- and kept across the spans
677 // that follow, since they are decoded by that very decoder.
678 let backend = BackendCell::default();
679 let generation = Arc::new(AtomicU64::new(0));
680 // The playhead starts where the span does: nothing is behind it yet.
681 let floor = Arc::new(AtomicU32::new(start_frame));
682 let (spans, commands) = std::sync::mpsc::channel();
683 let first = SpanCmd {
684 generation: 0,
685 start: start_frame,
686 end: end_frame,
687 color,
688 canvas,
689 tone,
690 tx,
691 };
692 let worker_cancel = Arc::clone(&cancel);
693 let worker_backend = backend.clone();
694 let worker_generation = Arc::clone(&generation);
695 let worker_floor = Arc::clone(&floor);
696 let worker_path = path.clone();
697 let handle = thread::Builder::new()
698 .name("decode".into())
699 .spawn(move || {
700 let mut source = opened;
701 let mut cmd = first;
702 loop {
703 let abort = Abort {
704 cancel: &worker_cancel,
705 generation: &worker_generation,
706 mine: cmd.generation,
707 floor: &worker_floor,
708 };
709 // Superseded (or cancelled) before this thread was even
710 // scheduled: do not open the file, and do not enter VA-API
711 // initialisation, which is the one stretch a cancel cannot
712 // interrupt. A scrub abandons spans by the dozen and this is
713 // where all but the last of them stop.
714 if !abort.hit() {
715 run_span(&worker_path, &mut source, cmd, &abort, &worker_backend);
716 }
717 // The session dropped the command channel: this worker is
718 // retired (or was detached), so the file, the decoder and the
719 // VA-API session it holds go now -- before Mesa's `atexit`.
720 match commands.recv() {
721 Ok(next) => cmd = next,
722 Err(_) => return,
723 }
724 }
725 })
726 .ok();
727 FrameStream {
728 frames: rx,
729 worker: Worker {
730 cancel,
731 handle,
732 reuse: Some(Reuse {
733 path,
734 spans,
735 generation,
736 backend: backend.clone(),
737 floor,
738 }),
739 },
740 backend,
741 }
742}
743
744/// How many pictures in a row a worker may drop for being late before it hands
745/// one over regardless. The policy needs a floor of its own: a machine that
746/// cannot decode a file in real time is late on *every* picture, and dropping
747/// every picture is a black screen rather than a stutter -- so the slowest seat
748/// still gets one in nine, which is roughly what it could paint before (the
749/// front-end restarted the decoder once every two seconds to the same effect,
750/// and paid a VA-API init for each restart).
751const LATE_RUN: u32 = 8;
752
753/// What a decode worker keeps **between** the spans it is asked for: the
754/// container it read, what the stream says about itself, and the hardware
755/// session -- the three things a seek used to throw away and buy again.
756struct Source {
757 meta: VideoMeta,
758 /// What the film says its brightest picture is ([`Demuxer::light`]): the
759 /// tone map's assumed peak on the reference rendition, so a 1759 cd/m^2
760 /// grade is converted at 1759 rather than at the 1000 a file that declared
761 /// nothing is assumed at. A property of the stream, read once with it.
762 peak: Option<f32>,
763 demuxer: Demuxer,
764 /// The plugin's session, opened on this thread (its VA-API state is not
765 /// `Send`-safe across a hand-off) and *kept*. `None` for software: forced by
766 /// `VE_SW`, refused by the plugin, or handed back by a session that opened
767 /// and then decoded nothing.
768 hw: Option<HwSession>,
769}
770
771impl Source {
772 /// The file as the sync opener already read it.
773 fn demuxed(demuxer: Demuxer, meta: VideoMeta) -> Self {
774 Self {
775 meta,
776 peak: demuxer.light().peak(),
777 demuxer,
778 hw: None,
779 }
780 }
781
782 /// ...and as the deferred opener reads it, on the worker. `None` is a file
783 /// that would not open: the caller drops the sender, and the disconnected
784 /// receiver is the session's "walk on to the next span".
785 fn open(path: &Path) -> Option<Self> {
786 match Demuxer::open(path) {
787 Ok((meta, demuxer)) => Some(Self::demuxed(demuxer, meta)),
788 Err(e) => {
789 eprintln!("video open failed: {e}");
790 None
791 }
792 }
793 }
794
795 /// Puts the hardware decoder at `start`, keeping the session open where the
796 /// plugin can reposition it. `None` when there is no hardware here at all;
797 /// otherwise whether the session was **reused** -- which is what lets the
798 /// caller tell a driver that cannot decode this stream from one that merely
799 /// did not follow a reseek.
800 fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {
801 if let Some(hw) = &mut self.hw {
802 if hw.seek(start) {
803 eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})");
804 return Some(true);
805 }
806 // A plugin too old to reposition, or a decoder that would not
807 // flush: closed and opened again, which is what every seek did.
808 self.hw = None;
809 }
810 self.hw = open_hw(path, start);
811 self.hw.as_ref().map(|_| {
812 eprintln!("decode backend: hardware (VA-API plugin)");
813 false
814 })
815 }
816}
817
818/// One span on a worker's thread: position the decoder, decode
819/// `[start, end)`, send the pictures. Every opener ends here -- the sync one,
820/// which demuxed on the caller's thread, the deferred one, which demuxes on
821/// this one, and every reseek after them -- so there is exactly one description
822/// of what a decode worker does.
823fn run_span(
824 path: &Path,
825 source: &mut Option<Source>,
826 cmd: SpanCmd,
827 abort: &Abort,
828 backend: &BackendCell,
829) {
830 let SpanCmd {
831 start,
832 end,
833 color,
834 canvas,
835 tone,
836 tx,
837 ..
838 } = cmd;
839 let opened = match source {
840 Some(opened) => opened,
841 None => {
842 let Some(fresh) = Source::open(path) else {
843 backend.set(Backend::Gap);
844 return;
845 };
846 source.insert(fresh)
847 }
848 };
849 // The clamp the sync opener does with the metadata it read on the caller's
850 // thread; here the metadata arrives first.
851 let end = end.min(opened.meta.frame_count);
852 // An empty range decodes nothing and must send nothing: `run_hw` counts a
853 // frame *out* before it compares, so without this a zero-length span would
854 // emit one picture.
855 if end <= start {
856 return;
857 }
858 // The stream's own colour and peak brightness: properties of the stream, so
859 // neither can change while one range decodes -- but the grade, the canvas
860 // and the rendition are the *span's*, so this is built per span.
861 let mut render = Render::new(color, opened.meta.color, canvas, tone, opened.peak);
862 if let Some(reused) = opened.position_hw(path, start) {
863 // Cancelled during the init (or the seek): leave without decoding.
864 if abort.hit() {
865 return;
866 }
867 backend.set(Backend::Hardware);
868 let mut decoded = run_hw(
869 opened.hw.as_mut().expect("positioned above"),
870 &tx,
871 start,
872 end,
873 &mut render,
874 abort,
875 );
876 // A *reused* session that produced nothing may simply be one this
877 // reseek left where the driver would not follow; a session opened fresh
878 // at the same frame is the honest second question, and only its silence
879 // is a software fallback. Without this a single unfollowed seek would
880 // collapse the rest of the file to software.
881 if !decoded && reused {
882 eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}");
883 opened.hw = open_hw(path, start);
884 if let Some(hw) = opened.hw.as_mut() {
885 decoded = run_hw(hw, &tx, start, end, &mut render, abort);
886 }
887 }
888 if decoded {
889 return;
890 }
891 // A driver that opens but cannot decode a single frame is still a
892 // fallback case, not a dead session.
893 opened.hw = None;
894 eprintln!("hardware decode failed before any frame, falling back to software");
895 }
896 // ...except where there is nothing to fall back to. Feeding HEVC or VP9
897 // bytes to `rusty_h264` would be garbage, not a fallback.
898 if opened.meta.codec != Codec::H264 {
899 eprintln!("{}", opened.meta.codec.needs_plugin());
900 return;
901 }
902 eprintln!("decode backend: software (rusty_h264)");
903 backend.set(Backend::Software);
904 run(&mut opened.demuxer, &tx, start, end, &mut render, abort)
905}
906
907/// One clip's pictures on their way to the renderer: graded, placed on the
908/// project canvas, converted. Both decode loops go through it, so hardware and
909/// software cannot show two different pictures.
910///
911/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
912/// applied at the resolution it was shot at, and the letterbox bars around it
913/// are not the clip -- a brightness grade must not lift them off black.
914///
915/// A project at the media's own resolution never reaches any of that: it takes
916/// the fused graded conversion, the one path this engine had before there was a
917/// project resolution, byte for byte and allocation for allocation.
918struct Render {
919 color: ColorParams,
920 /// What the source's samples mean -- the stream's own matrix and range,
921 /// which is what the conversion below is done in rather than the BT.601 it
922 /// used to assume of every file.
923 desc: ColorDescription,
924 canvas: Composer,
925 /// This stream's HDR-to-SDR map, built once here because building it is
926 /// float work over 9 537 grid nodes and the transfer is a property of the
927 /// stream. `None` for an SDR stream, which is what keeps that path exactly
928 /// the one it was.
929 tone: Option<ToneMapper>,
930 /// The working copy of the source planes, refilled per frame and kept
931 /// across the worker's whole range. Empty unless the clip needs one: it is
932 /// tone-mapped in place, graded in place, or both.
933 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
934}
935
936/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's
937/// output contract ([`crate::tonemap`]), and no longer the HDR space the file
938/// declared.
939const TONE_MAPPED: ColorDescription = ColorDescription {
940 matrix: Matrix::Bt709,
941 transfer: Transfer::Sdr,
942 full_range: false,
943};
944
945impl Render {
946 /// `peak` is what the file declared about its own brightness
947 /// ([`Demuxer::light`]), which only an HDR stream has and only the
948 /// reference rendition reads (see [`tonemap::Preset`]).
949 fn new(
950 color: ColorParams,
951 desc: ColorDescription,
952 canvas: Composer,
953 preset: tonemap::Preset,
954 peak: Option<f32>,
955 ) -> Self {
956 Self {
957 color,
958 desc,
959 canvas,
960 // corner-cut: the ceiling is that the map reads limited-range codes
961 // (`tonemap`'s input contract), so a full-range PQ file -- which
962 // no encoder writes and no camera produces -- is mapped as if it
963 // were limited and comes out slightly crushed. The upgrade is a
964 // range argument to `ToneMapper::new`.
965 tone: match desc.transfer {
966 Transfer::Sdr => None,
967 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)),
968 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
969 },
970 graded: (Vec::new(), Vec::new(), Vec::new()),
971 }
972 }
973
974 fn frame(
975 &mut self,
976 index: u32,
977 y: &[u8],
978 u: &[u8],
979 v: &[u8],
980 width: u32,
981 height: u32,
982 ) -> Frame {
983 let passthrough = self.canvas.is_passthrough(width, height);
984 // Everything that has to happen to the samples before the canvas sees
985 // them, on one copy: the tone map (HDR streams only) and, unless the
986 // conversion below can fuse it, the grade. An SDR stream that is either
987 // ungraded or passing through takes neither and never allocates.
988 //
989 // The grade lands *after* the map on purpose: it is a look on the
990 // picture a viewer is shown, so its brightness and saturation mean what
991 // they say in the SDR the tone map just produced, not in the 10-stop
992 // HDR the file was in.
993 let (y, u, v, desc) = if self.tone.is_some() || (!passthrough && !self.color.is_identity())
994 {
995 let (gy, gu, gv) = &mut self.graded;
996 gy.clear();
997 gy.extend_from_slice(y);
998 gu.clear();
999 gu.extend_from_slice(u);
1000 gv.clear();
1001 gv.extend_from_slice(v);
1002 if let Some(tone) = &self.tone {
1003 tone.map(gy, gu, gv, width as usize, height as usize);
1004 }
1005 if !passthrough && !self.color.is_identity() {
1006 crate::color::apply_yuv(&self.color, gy, gu, gv);
1007 }
1008 let desc = if self.tone.is_some() {
1009 TONE_MAPPED
1010 } else {
1011 self.desc
1012 };
1013 (&gy[..], &gu[..], &gv[..], desc)
1014 } else {
1015 (y, u, v, self.desc)
1016 };
1017 if passthrough {
1018 return Frame {
1019 index,
1020 width,
1021 height,
1022 bgra: i420_to_bgra_with(
1023 &desc,
1024 &self.color,
1025 y,
1026 u,
1027 v,
1028 width as usize,
1029 height as usize,
1030 ),
1031 };
1032 }
1033 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
1034 Frame {
1035 index,
1036 width,
1037 height,
1038 // Ungraded on purpose: the grade is already in the pixels above and
1039 // the canvas around them must stay the black it was filled with.
1040 bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize),
1041 }
1042 }
1043}
1044
1045/// One still image, decoded to tightly packed I420 -- the shape every other
1046/// source arrives in, so a placed image goes through the same grade, the same
1047/// canvas and the same conversion as a decoded picture and there is no second
1048/// pixel path to keep in step.
1049///
1050/// Held whole rather than streamed: an image *is* one picture, and the file is
1051/// read once per span that plays it.
1052pub(crate) struct Still {
1053 pub(crate) y: Vec<u8>,
1054 pub(crate) u: Vec<u8>,
1055 pub(crate) v: Vec<u8>,
1056 pub(crate) width: u32,
1057 pub(crate) height: u32,
1058}
1059
1060impl Still {
1061 /// Decodes `path`. Refused by name for a picture that is not one
1062 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
1063 /// file are both held to cannot be walked around by a 30000-pixel-wide PNG.
1064 ///
1065 /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a
1066 /// transparent PNG arrives fully opaque over its own colours rather than
1067 /// over the clip beneath it. I420 has nowhere to carry it and this engine
1068 /// composes one picture per frame (topmost lane wins), so there is nothing
1069 /// for a blend to blend with.
1070 ///
1071 /// corner-cut: the ceiling is a logo with a transparent background, which
1072 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
1073 /// giving `scale::Composer` a blend over the lane below.
1074 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
1075 let reader = image::ImageReader::open(path)?.with_guessed_format()?;
1076 let rgb = reader
1077 .decode()
1078 .map_err(|e| format!("{}: {e}", path.display()))?
1079 .to_rgb8();
1080 let (width, height) = rgb.dimensions();
1081 if !crate::is_resolution(width, height) {
1082 return Err(format!(
1083 "{} is {width}x{height}, which is not a picture this engine composes",
1084 path.display()
1085 )
1086 .into());
1087 }
1088 let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize);
1089 Ok(Self {
1090 y,
1091 u,
1092 v,
1093 width,
1094 height,
1095 })
1096 }
1097
1098 /// The planes as an export's decoder hands them over, so a still and a
1099 /// decoded picture are the same value to `export::run`.
1100 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
1101 (&self.y, &self.u, &self.v, self.width, self.height)
1102 }
1103}
1104
1105/// How big the picture in `path` is, from its header alone -- what a library row
1106/// says about a file it has not placed anywhere. The whole file is not decoded.
1107pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
1108 Ok(image::ImageReader::open(path)?
1109 .with_guessed_format()?
1110 .into_dimensions()
1111 .map_err(|e| format!("{}: {e}", path.display()))?)
1112}
1113
1114/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
1115/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why
1116/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and
1117/// not the timeline's. A still has no stream to be tagged by; it round-trips to
1118/// the colour it was authored in through this pair and nothing else sees these
1119/// planes (`images::still_pixels_match_the_source_image` measures it).
1120///
1121/// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
1122/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
1123/// [`crate::scale::Composer::place`] panics on anything else for.
1124fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1125 let (cw, ch) = crate::scale::chroma_dims(width, height);
1126 let mut y = vec![0u8; width * height];
1127 let mut u = vec![0u8; cw * ch];
1128 let mut v = vec![0u8; cw * ch];
1129 for row in 0..height {
1130 for col in 0..width {
1131 let p = (row * width + col) * 3;
1132 let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32);
1133 y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
1134 }
1135 }
1136 for crow in 0..ch {
1137 for ccol in 0..cw {
1138 let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32);
1139 for row in crow * 2..(crow * 2 + 2).min(height) {
1140 for col in ccol * 2..(ccol * 2 + 2).min(width) {
1141 let p = (row * width + col) * 3;
1142 sr += rgb[p] as i32;
1143 sg += rgb[p + 1] as i32;
1144 sb += rgb[p + 2] as i32;
1145 n += 1;
1146 }
1147 }
1148 let n = n.max(1);
1149 let (r, g, b) = (sr / n, sg / n, sb / n);
1150 u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
1151 v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
1152 }
1153 }
1154 (y, u, v)
1155}
1156
1157/// `None` when the software path must be used: forced by `VE_SW=1`, or the
1158/// plugin is absent/broken/unable to open this particular file.
1159fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> {
1160 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
1161 return None;
1162 }
1163 HwSession::open_at(path, start_frame)
1164}
1165
1166/// `Ok` when the plugin really decodes this file: it opens *and* hands back a
1167/// first picture. Opening only reads the container -- a stream the vendored
1168/// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and
1169/// then produces nothing, which reaches the user as a black picture with an
1170/// instant `eof` unless the door asks for that first frame. Costs one decoded
1171/// frame per probe.
1172///
1173/// The `Err` says which half failed, because "there is no decoder for this
1174/// codec" and "the decoder here would not take this stream" are different
1175/// refusals and a user acts on them differently.
1176fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), String> {
1177 let Some(mut hw) = open_hw(path, start_frame) else {
1178 return Err(codec.needs_plugin());
1179 };
1180 // End of stream counts as a refusal, not as a pass: a session that hands
1181 // back no picture at all is exactly the black-frame-and-instant-eof this
1182 // probe exists to catch, and `Ok(None)` is how the plugin says it.
1183 match hw.next_frame() {
1184 Ok(Some(_)) => Ok(()),
1185 _ => Err(codec.undecodable()),
1186 }
1187}
1188
1189/// Returns whether the session was handled; `false` only when hardware decode
1190/// failed without emitting a single frame, so software can still take over.
1191///
1192/// The plugin already positioned itself at `start_frame`, so indices are
1193/// counted from there (a stream whose very first sample is not a sync sample
1194/// cannot be decoded from its start at all, and is not accounted for).
1195fn run_hw(
1196 hw: &mut HwSession,
1197 tx: &SyncSender<Frame>,
1198 start_frame: u32,
1199 end_frame: u32,
1200 render: &mut Render,
1201 abort: &Abort,
1202) -> bool {
1203 let mut index = start_frame;
1204 // Pictures dropped for being late since the last one handed over; see
1205 // [`LATE_RUN`].
1206 let mut skipped = 0;
1207 loop {
1208 if abort.hit() {
1209 return true;
1210 }
1211 match hw.next_frame() {
1212 Ok(Some((y, u, v, width, height))) => {
1213 let due = index;
1214 index += 1;
1215 if abort.late(due) && skipped < LATE_RUN {
1216 skipped += 1;
1217 } else {
1218 skipped = 0;
1219 let frame = render.frame(due, y, u, v, width, height);
1220 if tx.send(frame).is_err() {
1221 return true; // consumer went away
1222 }
1223 }
1224 if index >= end_frame {
1225 return true; // end of the requested range
1226 }
1227 }
1228 Ok(None) => return true,
1229 Err(e) => {
1230 if index == start_frame {
1231 return false;
1232 }
1233 eprintln!("hardware decode error at frame {index}: {e}");
1234 return true;
1235 }
1236 }
1237 }
1238}
1239
1240#[cfg(test)]
1241mod tests {
1242 use super::*;
1243 use std::sync::mpsc::RecvTimeoutError;
1244 use std::time::{Duration, Instant};
1245
1246 fn asset(name: &str) -> PathBuf {
1247 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1248 .join("../../assets")
1249 .join(name)
1250 }
1251
1252 /// Drops `path` from the page cache, so the open below really goes to disk
1253 /// -- the case the deferred opener exists for, and the one that costs
1254 /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a
1255 /// no-op wherever `python3` is not around: the assertions hold either way,
1256 /// the numbers printed are simply the warm ones.
1257 fn evict(path: &Path) {
1258 let _ = std::process::Command::new("python3")
1259 .arg("-c")
1260 .arg(
1261 "import os,sys\n\
1262 fd=os.open(sys.argv[1],os.O_RDONLY)\n\
1263 os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\
1264 os.close(fd)",
1265 )
1266 .arg(path)
1267 .status();
1268 }
1269
1270 /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller
1271 /// gets its stream back in the time a thread takes to spawn, and the file
1272 /// is opened behind it -- so the first frame necessarily arrives *after*
1273 /// the call returned, and the sync opener on the same cold file pays on the
1274 /// calling thread what this one does not.
1275 #[test]
1276 fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() {
1277 let path = asset("test_baseline.mp4");
1278 evict(&path);
1279 let start = Instant::now();
1280 let stream = DecodeSession::open_worker_deferred(
1281 &path,
1282 0,
1283 u32::MAX,
1284 ColorParams::default(),
1285 Composer::passthrough(),
1286 tonemap::Preset::default(),
1287 );
1288 let returned = start.elapsed();
1289 let frame = stream
1290 .frames
1291 .recv_timeout(Duration::from_secs(10))
1292 .expect("first frame");
1293 let first_frame = start.elapsed();
1294
1295 // The same file, equally cold, through the door the import path keeps:
1296 // that one hands back metadata, and the demux it reads to do so is on
1297 // this thread.
1298 evict(&path);
1299 let sync_start = Instant::now();
1300 let sync = DecodeSession::open_worker(
1301 &path,
1302 0,
1303 u32::MAX,
1304 ColorParams::default(),
1305 Composer::passthrough(),
1306 tonemap::Preset::default(),
1307 )
1308 .expect("sync open");
1309 let sync_returned = sync_start.elapsed();
1310 drop(sync);
1311
1312 eprintln!(
1313 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
1314 sync open returned in {sync_returned:?}"
1315 );
1316 assert_eq!(frame.index, 0, "the deferred worker starts where it is told");
1317 assert!(
1318 returned < Duration::from_millis(10),
1319 "the caller waited {returned:?} -- something is still being read \
1320 from the file before this returns"
1321 );
1322 assert!(
1323 first_frame > returned,
1324 "the first frame arrived within the call ({first_frame:?} vs \
1325 {returned:?}), which cannot happen if the open is deferred"
1326 );
1327 assert!(
1328 returned < sync_returned,
1329 "the deferred open ({returned:?}) cost as much as the sync one \
1330 ({sync_returned:?}): the demux is still on the caller's thread"
1331 );
1332 }
1333
1334 /// The late-picture policy, at the one place it is decided. A worker told
1335 /// the playhead is already at frame 20 must not spend a conversion and a
1336 /// queue slot on the twenty pictures behind it -- they can never be shown --
1337 /// and it must not go silent either, which is what [`LATE_RUN`] bounds: a
1338 /// machine that cannot decode in real time is late on every picture, and one
1339 /// in nine still reaches the screen.
1340 ///
1341 /// Deterministic on purpose: the floor is set by hand rather than by a clock
1342 /// that would have to outrun a debug-build decoder to prove anything.
1343 #[test]
1344 fn a_worker_skips_the_pictures_the_playhead_has_gone_past() {
1345 let take = |floor: u32| {
1346 let stream = DecodeSession::open_worker_deferred(
1347 asset("test_baseline.mp4"),
1348 0,
1349 u32::MAX,
1350 ColorParams::default(),
1351 Composer::passthrough(),
1352 tonemap::Preset::default(),
1353 );
1354 stream.worker.playhead(floor);
1355 let mut indices = Vec::new();
1356 while indices.len() < 4 {
1357 let frame = stream
1358 .frames
1359 .recv_timeout(Duration::from_secs(10))
1360 .expect("a picture");
1361 indices.push(frame.index);
1362 }
1363 indices
1364 };
1365
1366 // Nobody has moved: every picture of the range is owed, in order.
1367 assert_eq!(take(0), vec![0, 1, 2, 3]);
1368
1369 // The playhead is at 20, so the pictures before it are decoded (the ones
1370 // after reference them) and dropped unconverted -- all but the one in
1371 // nine [`LATE_RUN`] lets through, so the caller never goes blind.
1372 let caught_up = take(20);
1373 assert!(
1374 caught_up[0] > 0 && caught_up.windows(2).any(|w| w[1] > w[0] + 1),
1375 "nothing was skipped: {caught_up:?}"
1376 );
1377 assert!(
1378 caught_up.iter().any(|&i| i >= 20),
1379 "the playhead was never reached: {caught_up:?}"
1380 );
1381 assert!(
1382 caught_up.len() >= 4,
1383 "the worker went silent instead of dropping down to one in nine"
1384 );
1385 }
1386
1387 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
1388 /// The channel is bounded, so such a worker is parked in `send` within a
1389 /// few frames, and the only thing that can wake it is its receiver going
1390 /// away -- which is why the receiver is the first field and the join inside
1391 /// `Worker::drop` is the second. Swap those two fields and this hangs.
1392 ///
1393 /// This is the whole basis of every teardown path in the engine, so it is
1394 /// asserted rather than commented: the drop runs on a second thread and a
1395 /// regression fails in ten seconds instead of hanging the suite forever.
1396 #[test]
1397 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
1398 let (_meta, stream) = DecodeSession::open_worker(
1399 &asset("test_baseline.mp4"),
1400 0,
1401 u32::MAX,
1402 ColorParams::default(),
1403 Composer::passthrough(),
1404 tonemap::Preset::default(),
1405 )
1406 .expect("open");
1407 // Nothing is ever received: two frames fill the channel and the next
1408 // send parks the decode thread, exactly as a refused project load does.
1409 thread::sleep(Duration::from_millis(500));
1410
1411 let (done_tx, done_rx) = sync_channel(1);
1412 thread::spawn(move || {
1413 drop(stream);
1414 let _ = done_tx.send(());
1415 });
1416 assert!(
1417 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
1418 "dropping a parked stream deadlocked: it joined a decode thread \
1419 while still holding the receiver that thread is waiting on"
1420 );
1421 }
1422}
1423
1424fn run(
1425 demuxer: &mut Demuxer,
1426 tx: &SyncSender<Frame>,
1427 start_frame: u32,
1428 end_frame: u32,
1429 render: &mut Render,
1430 abort: &Abort,
1431) {
1432 // A decoder per span, and cheap: it is a parameter-set map and a picture
1433 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
1434 // one this worker keeps.
1435 let mut decoder = Decoder::new();
1436 // Decoding has to restart at a sync sample, so pictures between it and
1437 // `start_frame` are decoded (the target frame references them) but never
1438 // converted or sent. Signed, because the landing sync sample can sit inside
1439 // what the file's edit list trims, i.e. *before* frame 0.
1440 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1441 let mut skipped = 0;
1442
1443 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);
1444 // reordering streams need POC-sorted output before display.
1445 loop {
1446 if abort.hit() {
1447 break;
1448 }
1449 let au = match demuxer.next_access_unit() {
1450 Ok(Some(au)) => au,
1451 Ok(None) => break,
1452 Err(e) => {
1453 eprintln!("demux error: {e}");
1454 break;
1455 }
1456 };
1457 let yuv = match decoder.decode(&au) {
1458 Ok(Some(yuv)) => yuv,
1459 Ok(None) => continue,
1460 Err(e) => {
1461 eprintln!("decode error at access unit {index}: {e}");
1462 break;
1463 }
1464 };
1465 if index < i64::from(start_frame) {
1466 index += 1;
1467 continue;
1468 }
1469 let due = index as u32;
1470 index += 1;
1471 if abort.late(due) && skipped < LATE_RUN {
1472 skipped += 1;
1473 } else {
1474 skipped = 0;
1475 let frame = render.frame(
1476 due,
1477 &yuv.y,
1478 &yuv.u,
1479 &yuv.v,
1480 yuv.width as u32,
1481 yuv.height as u32,
1482 );
1483 if tx.send(frame).is_err() {
1484 break; // consumer went away
1485 }
1486 }
1487 if index >= i64::from(end_frame) {
1488 break; // end of the requested range
1489 }
1490 }
1491}