forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBe3392c8Tahinli3 months ago529 commits

decode.rs1644 lines, 66.1 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::project::Speed;
18use crate::scale::Composer;
19use crate::tonemap::{self, ToneMapper};
20
21/// One decoded picture, ready to hand to a renderer.
22pub struct Frame {
23 /// Position in decode order, starting at 0.
24 pub index: u32,
25 pub width: u32,
26 pub height: u32,
27 /// BGRA8, straight alpha, tightly packed.
28 pub bgra: Vec<u8>,
29}
30
31/// Which decoder a source is really running on. Read-only introspection: it
32/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose --
33/// a hardware session that opened and then failed before its first picture
34/// falls back to software and this says so, because it is written where the
35/// fallback happens rather than where it was hoped for.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum Backend {
38 /// The worker has not reached its decoder yet: the plugin's VA-API init is
39 /// ~90 ms, and this is what a caller reads in that window.
40 #[default]
41 Opening,
42 /// The VA-API plugin (`libengine_hw.so`).
43 Hardware,
44 /// `rusty_h264`, in this process.
45 Software,
46 /// A still image: one `image` decode, no stream and no decoder to pick.
47 Still,
48 /// A gap: black frames, nothing decoded at all.
49 Gap,
50}
51
52impl Backend {
53 /// Short enough for a library row and a transport line.
54 pub fn label(self) -> &'static str {
55 match self {
56 Self::Opening => "opening",
57 Self::Hardware => "HW",
58 Self::Software => "SW",
59 Self::Still => "still",
60 Self::Gap => "gap",
61 }
62 }
63
64 fn code(self) -> u8 {
65 match self {
66 Self::Opening => 0,
67 Self::Hardware => 1,
68 Self::Software => 2,
69 Self::Still => 3,
70 Self::Gap => 4,
71 }
72 }
73
74 fn from_code(code: u8) -> Self {
75 match code {
76 1 => Self::Hardware,
77 2 => Self::Software,
78 3 => Self::Still,
79 4 => Self::Gap,
80 _ => Self::Opening,
81 }
82 }
83}
84
85/// Where a worker publishes the decoder it opened, for whoever holds the other
86/// end of its channel. One atomic byte, written once at open (and once more if
87/// hardware hands the range back to software), read whenever a caller repaints
88/// -- never per frame on either side.
89#[derive(Clone, Default)]
90pub struct BackendCell(Arc<AtomicU8>);
91
92impl BackendCell {
93 pub(crate) fn new(backend: Backend) -> Self {
94 Self(Arc::new(AtomicU8::new(backend.code())))
95 }
96
97 fn set(&self, backend: Backend) {
98 self.0.store(backend.code(), Ordering::Relaxed);
99 }
100
101 pub fn get(&self) -> Backend {
102 Backend::from_code(self.0.load(Ordering::Relaxed))
103 }
104}
105
106/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`]
107/// decides it: the same `VE_SW` pin and the same plugin probe against this very
108/// file. What lets a front-end name the decoder *before* anything plays.
109///
110/// The codec is `None` for a still image, which has no coded stream. A stream
111/// no decoder here can take is an `Err` naming the plugin, exactly as opening
112/// it would be -- the same refusal, one VA-API init earlier.
113///
114/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per
115/// file, off a render thread, and keep the answer.
116pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
117 if crate::is_image(path) {
118 return Ok((None, Backend::Still));
119 }
120 let path = path.to_path_buf();
121 let (meta, _demuxer) = Demuxer::open(&path)?;
122 match hw_decodes(&path, 0, meta.codec) {
123 Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)),
124 Err(e) if meta.codec != Codec::H264 => return Err(e.into()),
125 Err(_) => {}
126 }
127 Ok((Some(meta.codec), Backend::Software))
128}
129
130/// A running decode worker: the flag that stops it, and the handle to wait on.
131///
132/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
133/// outlives the process otherwise, and Mesa's `atexit` handlers free the state
134/// it is still reading -- a SIGSEGV at exit, long after the last test passed.
135pub(crate) struct Worker {
136 cancel: Arc<AtomicBool>,
137 /// `None` once detached, and for a range with nothing to decode: either way
138 /// there is no thread left to wait for.
139 handle: Option<thread::JoinHandle<()>>,
140 /// How a *later* span reaches this same thread ([`Worker::reseek`]), for the
141 /// workers that decode a file: the still, the gap and a detached worker have
142 /// no such door and are the one-span threads they always were.
143 reuse: Option<Reuse>,
144}
145
146/// The door a persistent decode worker is steered through: the file it has open,
147/// the channel its next span arrives on, and the generation counter that tells
148/// the span it is decoding *now* that nobody is waiting for it any more.
149///
150/// The point of all three is that a seek onto the same file costs a demuxer
151/// seek and a decoder flush ([`crate::hw::HwSession::seek`]) rather than a
152/// thread, a container parse and a VA-API initialisation (98 ms measured).
153struct Reuse {
154 path: PathBuf,
155 spans: std::sync::mpsc::Sender<SpanCmd>,
156 /// Bumped by every reseek and by [`Worker::abandon`]; the decode loop stops
157 /// the moment it no longer matches the span it was handed.
158 generation: Arc<AtomicU64>,
159 /// The worker's decoder, published once and read across every span it
160 /// decodes -- so a reseek onto a file already open says "hardware" from the
161 /// first repaint instead of going back through `opening`.
162 backend: BackendCell,
163 /// Where the caller's playhead stands, in this file's own frames
164 /// ([`Worker::playhead`]): the worker converts and sends nothing behind it.
165 /// Rewritten to the target by every reseek, so it can never carry one span's
166 /// position into the next.
167 floor: Arc<AtomicU32>,
168}
169
170/// One span asked of a persistent worker: the range in the file's own frames,
171/// everything a picture is graded, placed and mapped by, and the channel the
172/// pictures go down. Carries its generation, so a command already superseded on
173/// its way through the queue is dropped rather than decoded.
174struct SpanCmd {
175 generation: u64,
176 start: u32,
177 end: u32,
178 color: ColorParams,
179 canvas: Composer,
180 tone: tonemap::Preset,
181 /// The clip's own playback speed ([`crate::project::Clip::speed`]), for
182 /// [`skip_for_speed`]: at faster than real time several source frames in a
183 /// row land on the same timeline frame, and only the last of a run is ever
184 /// shown. [`Speed::NORMAL`] for a file-level open ([`DecodeSession::open`]
185 /// and friends), which has no clip and skips nothing.
186 speed: Speed,
187 tx: SyncSender<Frame>,
188}
189
190/// What stops a decode loop: the worker's terminal flag (the thread itself is
191/// going away) and the generation of the span it was handed (only *this* span is
192/// going away). One check, so every loop treats them alike.
193///
194/// ...and where the playhead has reached ([`Abort::late`]), which is the same
195/// question one picture at a time: a frame due before it is a frame nobody can
196/// be shown any more.
197struct Abort<'a> {
198 cancel: &'a AtomicBool,
199 generation: &'a AtomicU64,
200 mine: u64,
201 floor: &'a AtomicU32,
202}
203
204impl Abort<'_> {
205 fn hit(&self) -> bool {
206 self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine
207 }
208
209 /// Whether the picture at source frame `index` is already past due: the
210 /// caller's playhead has gone by it, so converting it (a full BGRA pass over
211 /// 8 MB at 1080p) and queueing it would only push a picture nobody sees in
212 /// front of the one they are waiting for.
213 ///
214 /// It is still *decoded* -- the pictures after it reference it -- and the
215 /// floor only ever moves with the playhead the session publishes, so a
216 /// paused session (and every seek, which republishes its own target) drops
217 /// nothing at all.
218 fn late(&self, index: u32) -> bool {
219 self.floor.load(Ordering::Relaxed) > index
220 }
221}
222
223/// Whether the picture at source frame `due` (of a span starting at `start` and
224/// ending at `end`) is redundant *by construction* at `speed`, and its convert
225/// and send can be skipped without ever waiting on the playhead
226/// ([`Abort::late`]): at faster than real time several source frames in a row
227/// map to the same timeline frame ([`Speed::timeline_at`]), and only the last
228/// of such a run is ever shown -- the newest one always lands after the others
229/// in `try_frame`'s stamp comparison. Unlike a late drop this needs no run
230/// limit: the gap between two kept frames is at most `speed` source frames, so
231/// the picture stream this leaves is never silent, only sparser.
232///
233/// The last frame of the whole span is never skipped by this: it is the
234/// picture [`crate::project::Span::source_len`] was built to land exactly on,
235/// and this is what proves that promise here instead of trusting it blind.
236///
237/// corner-cut: `due` and `start` are the file's own frame numbers, so this
238/// is only correct when the file plays at the timeline's own rate
239/// ([`crate::project::Rate::is_real_time`]) -- callers pass [`Speed::NORMAL`]
240/// (never skip) otherwise. Upgrade path is composing `Rate` into this the way
241/// [`crate::project::Span::timeline_at`] does.
242fn skip_for_speed(speed: Speed, start: u32, due: u32, end: u32) -> bool {
243 if speed.is_normal() || due + 1 >= end {
244 return false;
245 }
246 let rel = due - start;
247 speed.timeline_at(rel) == speed.timeline_at(rel + 1)
248}
249
250impl Worker {
251 /// Stops the worker *and its thread* at their next check, without waiting.
252 /// Callers that replace a worker should do this first and drop the receiver
253 /// second: a worker parked in `send` only wakes on the disconnect, so the
254 /// join below would otherwise wait for a consumer that is never coming.
255 ///
256 /// The command channel goes with it, which is what wakes a persistent worker
257 /// parked between spans -- without that it would sit in `recv` forever and a
258 /// retired worker would never be reaped (nor joined at exit in any bounded
259 /// time, which is the Mesa `atexit` hazard this whole type exists for).
260 pub(crate) fn cancel(&mut self) {
261 self.cancel.store(true, Ordering::Release);
262 self.reuse = None;
263 }
264
265 /// Stops the span the worker is decoding, keeping the *thread* -- and with
266 /// it the open file and the open decoder -- for the span that follows. What
267 /// a seek does, since the next thing it says is [`Worker::reseek`].
268 ///
269 /// Falls back to [`cancel`](Self::cancel) for a worker with nothing to
270 /// reuse (a still, a gap, a detached one), where the two mean the same
271 /// thing: this worker has no next span.
272 pub(crate) fn abandon(&mut self) {
273 match &self.reuse {
274 Some(reuse) => {
275 reuse.generation.fetch_add(1, Ordering::Release);
276 }
277 None => self.cancel(),
278 }
279 }
280
281 /// Tells the worker where the caller's playhead stands, in the file's own
282 /// frames: it converts and queues nothing behind that, because a picture
283 /// whose moment has passed cannot be shown and would only delay the one that
284 /// can (see [`Abort::late`]). A worker with no reuse door -- a still, a gap
285 /// -- has nothing to tell, and this costs it nothing to say.
286 pub(crate) fn playhead(&self, source_frame: u32) {
287 if let Some(reuse) = &self.reuse {
288 reuse.floor.store(source_frame, Ordering::Relaxed);
289 }
290 }
291
292 /// Points this worker at another range of the file it already has open,
293 /// handing back the channel the new span's pictures arrive on and the cell
294 /// that says what is decoding them. `None` when this worker cannot take the
295 /// job -- another file, no reuse door, or a thread that has already returned
296 /// -- and the caller then opens a worker of its own, exactly as it always
297 /// did.
298 ///
299 /// The pictures of the *old* span are left in their own channel, which the
300 /// caller drops: that disconnect is what wakes this worker if it is parked
301 /// in `send`, and only then does it reach the command below. So the order at
302 /// the call site is unchanged -- install the new receiver, and the old
303 /// worker finds out by losing its consumer.
304 #[allow(clippy::too_many_arguments)]
305 pub(crate) fn reseek(
306 &mut self,
307 path: &Path,
308 start: u32,
309 end: u32,
310 color: ColorParams,
311 canvas: Composer,
312 tone: tonemap::Preset,
313 speed: Speed,
314 ) -> Option<(Receiver<Frame>, BackendCell)> {
315 let reuse = self.reuse.as_ref()?;
316 if reuse.path != path || self.is_finished() {
317 return None;
318 }
319 let (tx, rx) = sync_channel(canvas.queue_depth());
320 // The new span's own playhead, before its first picture is decoded: a
321 // floor left over from where the timeline *was* would drop every
322 // picture of a seek that went backwards.
323 reuse.floor.store(start, Ordering::Relaxed);
324 // Bumped before the command is queued, so the span running now stops at
325 // its next picture whatever order the two threads are scheduled in.
326 let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1;
327 reuse
328 .spans
329 .send(SpanCmd {
330 generation,
331 start,
332 end,
333 color,
334 canvas,
335 tone,
336 speed,
337 tx,
338 })
339 .ok()?;
340 Some((rx, reuse.backend.clone()))
341 }
342
343 /// Whether the thread has already returned, i.e. dropping this would not
344 /// wait. `true` for a worker that never had a thread. What lets a caller
345 /// park cancelled workers and reap them without ever blocking.
346 pub(crate) fn is_finished(&self) -> bool {
347 self.handle
348 .as_ref()
349 .is_none_or(thread::JoinHandle::is_finished)
350 }
351
352 /// Lets the worker run on unwatched -- what the public API does, since it
353 /// hands out the flag alone.
354 ///
355 /// The reuse door goes with the handle: nothing can steer a worker nobody
356 /// holds, and dropping the command channel is what makes such a thread end
357 /// at its span rather than park waiting for a next one it can never be
358 /// given -- with a VA-API session open, into Mesa's `atexit`.
359 fn detach(mut self) -> Arc<AtomicBool> {
360 self.handle = None;
361 self.reuse = None;
362 Arc::clone(&self.cancel)
363 }
364}
365
366impl Drop for Worker {
367 fn drop(&mut self) {
368 if let Some(handle) = self.handle.take() {
369 // `cancel` drops the command channel too, so a worker parked between
370 // spans wakes on the disconnect and this join is bounded.
371 self.cancel();
372 let _ = handle.join();
373 }
374 }
375}
376
377/// A running worker and the frames it is sending, handed out as one value
378/// because they must be *dropped* as one, in this order: the receiver
379/// disconnects first, which is the only thing that wakes a worker parked in a
380/// full `send`, and the join inside [`Worker::drop`] runs second.
381///
382/// Rust drops fields in declaration order, so this struct *is* that rule, and
383/// it holds wherever the value goes: an early return out of a half-built
384/// session, an unwind, a caller not written yet. Two separate locals do not
385/// hold it -- they drop in reverse order of declaration, so the worker there
386/// joins a thread nobody will ever drain, which is a hang and not a slow path.
387pub(crate) struct FrameStream {
388 pub(crate) frames: Receiver<Frame>,
389 pub(crate) worker: Worker,
390 /// What this stream's pictures are being decoded by. Dropped last and read
391 /// by the caller, so it outlives nothing and blocks nothing.
392 pub(crate) backend: BackendCell,
393}
394
395pub struct DecodeSession;
396
397impl DecodeSession {
398 /// Opens `path`, returning stream metadata immediately and a receiver that
399 /// yields frames as the worker decodes them. The worker stops when the
400 /// receiver is dropped, at end of stream, or on the first decode error.
401 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
402 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
403 Ok((meta, rx))
404 }
405
406 /// As [`DecodeSession::open`], but the first frame delivered is
407 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
408 /// Setting the returned flag stops the worker at its next access unit,
409 /// which is how a caller abandons a session it no longer wants to drain.
410 pub fn open_at(
411 path: impl AsRef<Path>,
412 start_frame: u32,
413 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
414 // `u32::MAX` is clamped to the stream's frame count below, so this is
415 // "to the end of the file".
416 Self::open_range(path, start_frame, u32::MAX)
417 }
418
419 /// As [`DecodeSession::open_at`], but the worker also stops on its own
420 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
421 /// absolute source frames, which is what a clip of a longer file needs.
422 /// `end_frame` is capped at the stream's frame count, and an empty range
423 /// yields a receiver that is simply already disconnected.
424 pub fn open_range(
425 path: impl AsRef<Path>,
426 start_frame: u32,
427 end_frame: u32,
428 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
429 // Ungraded: the public API opens a *file*, and a colour grade belongs to
430 // a clip of a timeline. `PlaybackSession` is what has one to pass.
431 let (meta, stream) = Self::open_worker(
432 path,
433 start_frame,
434 end_frame,
435 ColorParams::default(),
436 // No project, no canvas: the file-level API hands back the
437 // pictures the file holds, at the size it holds them.
438 Composer::passthrough(),
439 // ...and no project means no picked rendition either: an HDR file
440 // opened through this door is mapped the published way.
441 tonemap::Preset::default(),
442 )?;
443 // The public API hands out the flag alone, so the worker is detached and
444 // the receiver goes to the caller: nothing here joins anything.
445 Ok((meta, stream.frames, stream.worker.detach()))
446 }
447
448 /// A worker that decodes nothing and emits `len` black frames, indexed from
449 /// zero -- what a *gap* in the video lane looks like. It goes down the same
450 /// channel as decoded frames, so a gap costs the caller no branch at all
451 /// beyond choosing this opener: same bounded channel, same backpressure,
452 /// same cancel, same retire path.
453 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
454 let (tx, rx) = sync_channel(2);
455 let cancel = Arc::new(AtomicBool::new(false));
456 if len == 0 {
457 return FrameStream {
458 frames: rx,
459 worker: Worker {
460 cancel,
461 handle: None,
462 reuse: None,
463 },
464 backend: BackendCell::new(Backend::Gap),
465 };
466 }
467 let worker_cancel = Arc::clone(&cancel);
468 // One buffer, cloned per frame: opaque black is a constant, and the
469 // clone is a memcpy against a decode this replaces entirely.
470 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
471 let handle = thread::Builder::new()
472 .name("black".into())
473 .spawn(move || {
474 for index in 0..len {
475 if worker_cancel.load(Ordering::Relaxed) {
476 return;
477 }
478 let frame = Frame {
479 index,
480 width,
481 height,
482 bgra: black.clone(),
483 };
484 if tx.send(frame).is_err() {
485 return; // caller moved on
486 }
487 }
488 })
489 .ok();
490 FrameStream {
491 frames: rx,
492 worker: Worker {
493 cancel,
494 handle,
495 reuse: None,
496 },
497 backend: BackendCell::new(Backend::Gap),
498 }
499 }
500
501 /// A worker for a still image ([`crate::is_image`]): the file is decoded
502 /// *once* and the same picture goes down the channel `len` times, indexed
503 /// from `start_frame` exactly as a decoder's pictures are -- so a placed
504 /// image is a clip like any other to everything downstream (`try_frame`
505 /// rewrites those indices, `next_clip` walks off the end of the range).
506 ///
507 /// Graded and placed on the canvas once too, before the repeat: a still is
508 /// the same pixels every frame, so the whole cost of one is one conversion
509 /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays.
510 pub(crate) fn open_still(
511 path: &Path,
512 start_frame: u32,
513 len: u32,
514 color: ColorParams,
515 canvas: Composer,
516 ) -> crate::Result<FrameStream> {
517 let still = Still::open(path)?;
518 let (tx, rx) = sync_channel(2);
519 let cancel = Arc::new(AtomicBool::new(false));
520 if len == 0 {
521 return Ok(FrameStream {
522 frames: rx,
523 worker: Worker {
524 cancel,
525 handle: None,
526 reuse: None,
527 },
528 backend: BackendCell::new(Backend::Still),
529 });
530 }
531 // The one conversion, on this thread: it is a few milliseconds and the
532 // error it could raise has already been raised by `Still::open`.
533 // BT.601 limited, because that is what `rgb_to_i420` above wrote these
534 // planes in: a still round-trips through the pair, not through the
535 // colour of whatever file is on the timeline beside it.
536 // No preset argument, and none wanted: a still is decoded into BT.601
537 // SDR planes, so the tone map is not built at all whichever rendition
538 // the project is watching.
539 let first = Render::new(
540 color,
541 ColorDescription::default(),
542 canvas,
543 tonemap::Preset::default(),
544 // ...and no declared peak either, for the same reason: there is no
545 // tone map on this path to hand one to.
546 None,
547 )
548 .frame(
549 start_frame,
550 &still.y,
551 &still.u,
552 &still.v,
553 still.width,
554 still.height,
555 );
556 let worker_cancel = Arc::clone(&cancel);
557 let handle = thread::Builder::new()
558 .name("still".into())
559 .spawn(move || {
560 let (width, height, bgra) = (first.width, first.height, first.bgra);
561 for index in 0..len {
562 if worker_cancel.load(Ordering::Relaxed) {
563 return;
564 }
565 let frame = Frame {
566 index: start_frame + index,
567 width,
568 height,
569 bgra: bgra.clone(),
570 };
571 if tx.send(frame).is_err() {
572 return; // caller moved on
573 }
574 }
575 })
576 .ok();
577 Ok(FrameStream {
578 frames: rx,
579 worker: Worker {
580 cancel,
581 handle,
582 reuse: None,
583 },
584 backend: BackendCell::new(Backend::Still),
585 })
586 }
587
588 /// As [`DecodeSession::open_range`], but the caller gets the whole
589 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
590 /// `color` -- the clip's own setting, folded into the conversion the frames
591 /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
592 /// than read per frame because a worker *is* one clip's range: a grade
593 /// changed while this one runs reaches the picture when the session reseeks
594 /// onto the new one, which every edit does.
595 ///
596 /// In-process only: a caller that outlives its workers has to be able to
597 /// join them at exit.
598 ///
599 /// `canvas` is the project's own resolution and this clip's fit policy: the
600 /// frames come out at *that* size, whatever the file's is. A
601 /// [`Composer::passthrough`] (or one already the source's size) leaves every
602 /// picture exactly as it was decoded.
603 ///
604 /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured
605 /// here for the reason the grade is: it is constant across one span, and a
606 /// preset picked while this worker runs reaches the picture when the session
607 /// reseeks onto the new one. An SDR source ignores it entirely.
608 pub(crate) fn open_worker(
609 path: impl AsRef<Path>,
610 start_frame: u32,
611 end_frame: u32,
612 color: ColorParams,
613 canvas: Composer,
614 tone: tonemap::Preset,
615 ) -> crate::Result<(VideoMeta, FrameStream)> {
616 let path = path.as_ref().to_path_buf();
617 let (meta, demuxer) = Demuxer::open(&path)?;
618 // No software HEVC or VP9 decoder exists, so such a file the plugin will
619 // not take is refused *here*, where the caller still has somewhere to
620 // show it -- a worker that opened and then produced nothing is a black
621 // screen with no explanation. The probe session is opened, made to
622 // decode one picture and dropped: it costs one extra VA-API init
623 // (~90 ms) plus that frame, and only off the H.264 path.
624 if meta.codec != Codec::H264 {
625 hw_decodes(&path, start_frame, meta.codec)?;
626 }
627 let end_frame = end_frame.min(meta.frame_count);
628 if end_frame <= start_frame {
629 // Nothing to decode: a disconnected receiver and no thread at all,
630 // so the caller sees an immediate end of stream rather than an error.
631 let (_, rx) = sync_channel(1);
632 return Ok((
633 meta,
634 FrameStream {
635 frames: rx,
636 worker: Worker {
637 cancel: Arc::new(AtomicBool::new(false)),
638 handle: None,
639 reuse: None,
640 },
641 backend: BackendCell::default(),
642 },
643 ));
644 }
645 Ok((
646 meta,
647 span_worker(
648 path,
649 Some(Source::demuxed(demuxer, meta)),
650 start_frame,
651 end_frame,
652 color,
653 canvas,
654 tone,
655 // A file-level open has no clip and no speed to skip frames
656 // for: every picture in range is delivered, as it always was.
657 Speed::NORMAL,
658 ),
659 ))
660 }
661
662 /// As [`open_worker`](Self::open_worker), but the *file* is opened on the
663 /// worker too: nothing here touches the disk, so the caller pays a thread
664 /// spawn and not a demux -- 550-750 ms warm on a 25 GB film, seconds cold,
665 /// which is what a seek or a clip boundary used to cost the UI thread.
666 ///
667 /// The price is that there is no [`VideoMeta`] to return and no synchronous
668 /// refusal either: a file that will not open, and a codec no decoder here
669 /// takes (the plugin probe is skipped -- the worker's own refusal below
670 /// covers it), simply drop the sender. The disconnected receiver is what
671 /// carries a session on to the next span, which is exactly what a failed
672 /// open did on this path before. Callers that must *tell* the user why --
673 /// an import at the door -- keep the sync opener.
674 #[allow(clippy::too_many_arguments)]
675 pub(crate) fn open_worker_deferred(
676 path: impl AsRef<Path>,
677 start_frame: u32,
678 end_frame: u32,
679 color: ColorParams,
680 canvas: Composer,
681 tone: tonemap::Preset,
682 speed: Speed,
683 ) -> FrameStream {
684 span_worker(
685 path.as_ref().to_path_buf(),
686 None,
687 start_frame,
688 end_frame,
689 color,
690 canvas,
691 tone,
692 speed,
693 )
694 }
695}
696
697/// Spawns a decode worker over `path` and gives it its first span. The thread
698/// **outlives that span**: it parks on its command channel afterwards, so the
699/// next seek onto the same file reaches it through [`Worker::reseek`] and costs
700/// a demuxer seek and a decoder flush instead of a thread, a container parse and
701/// a VA-API initialisation (98 ms measured worst case).
702///
703/// `opened` is the file when the caller already read it (the sync opener, which
704/// demuxes on the caller's thread to have metadata to return); `None` is the
705/// deferred one, where the worker opens it and nothing here touches the disk.
706#[allow(clippy::too_many_arguments)]
707fn span_worker(
708 path: PathBuf,
709 opened: Option<Source>,
710 start_frame: u32,
711 end_frame: u32,
712 color: ColorParams,
713 canvas: Composer,
714 tone: tonemap::Preset,
715 speed: Speed,
716) -> FrameStream {
717 // The depth is the size of the pictures this worker will *emit*, which for a
718 // pass-through canvas is the stream's own -- and the sync opener has already
719 // read that on the caller's thread. Asking the canvas alone is how the file
720 // door came up with 2: every session opens pass-through (a freshly opened
721 // file *is* the project resolution), so a whole file would play at the
722 // decode-ahead this engine had before there was one, until the first seek
723 // built a real canvas.
724 let depth = match (&opened, canvas.places_nothing()) {
725 (Some(source), true) => crate::scale::queue_depth(source.meta.width, source.meta.height),
726 _ => canvas.queue_depth(),
727 };
728 let (tx, rx) = sync_channel(depth);
729 let cancel = Arc::new(AtomicBool::new(false));
730 // Written by the worker the moment it knows, so a caller reading it sees
731 // what opened rather than what was hoped for -- and kept across the spans
732 // that follow, since they are decoded by that very decoder.
733 let backend = BackendCell::default();
734 let generation = Arc::new(AtomicU64::new(0));
735 // The playhead starts where the span does: nothing is behind it yet.
736 let floor = Arc::new(AtomicU32::new(start_frame));
737 let (spans, commands) = std::sync::mpsc::channel();
738 let first = SpanCmd {
739 generation: 0,
740 start: start_frame,
741 end: end_frame,
742 color,
743 canvas,
744 tone,
745 speed,
746 tx,
747 };
748 let worker_cancel = Arc::clone(&cancel);
749 let worker_backend = backend.clone();
750 let worker_generation = Arc::clone(&generation);
751 let worker_floor = Arc::clone(&floor);
752 let worker_path = path.clone();
753 let handle = thread::Builder::new()
754 .name("decode".into())
755 .spawn(move || {
756 let mut source = opened;
757 let mut cmd = first;
758 loop {
759 let abort = Abort {
760 cancel: &worker_cancel,
761 generation: &worker_generation,
762 mine: cmd.generation,
763 floor: &worker_floor,
764 };
765 // Superseded (or cancelled) before this thread was even
766 // scheduled: do not open the file, and do not enter VA-API
767 // initialisation, which is the one stretch a cancel cannot
768 // interrupt. A scrub abandons spans by the dozen and this is
769 // where all but the last of them stop.
770 if !abort.hit() {
771 run_span(&worker_path, &mut source, cmd, &abort, &worker_backend);
772 }
773 // Parked between spans. A seek and a clip boundary arrive in
774 // milliseconds and find the decoder still open, which is the
775 // whole point of this thread -- but a session nobody comes back
776 // to (the timeline played out, the window was left alone) must
777 // not sit on the driver: it would hold a live libva thread into
778 // whatever exit path the process takes, which is the SIGSEGV in
779 // Mesa's `atexit` the retired pool exists to prevent, and
780 // holding it *while idle* would widen that from "quit during a
781 // decode" to "quit any time after opening a file".
782 //
783 // So the wait is in two halves: the fast one keeps everything,
784 // and past [`IDLE`] the hardware session is closed. The demuxer
785 // stays -- it is a file handle and an index, not driver state,
786 // and rebuilding it is what costs seconds on a big Matroska --
787 // so the reseek after a long pause pays one VA-API init and
788 // nothing else.
789 match commands.recv_timeout(IDLE) {
790 Ok(next) => cmd = next,
791 Err(RecvTimeoutError::Timeout) => {
792 if let Some(source) = &mut source
793 && source.hw.take().is_some()
794 {
795 eprintln!("decode worker idle: hardware session closed");
796 }
797 // The session dropped the command channel: this worker
798 // is retired (or was detached), so the file goes now.
799 match commands.recv() {
800 Ok(next) => cmd = next,
801 Err(_) => return,
802 }
803 }
804 Err(RecvTimeoutError::Disconnected) => return,
805 }
806 }
807 })
808 .ok();
809 FrameStream {
810 frames: rx,
811 worker: Worker {
812 cancel,
813 handle,
814 reuse: Some(Reuse {
815 path,
816 spans,
817 generation,
818 backend: backend.clone(),
819 floor,
820 }),
821 },
822 backend,
823 }
824}
825
826/// How long a parked worker keeps its hardware session before closing it. Long
827/// enough that a seek, a scrub step and a clip boundary all find the decoder
828/// where they left it; short enough that a session left alone is not holding
829/// libva when the process exits.
830const IDLE: std::time::Duration = std::time::Duration::from_secs(2);
831
832/// How many pictures in a row a worker may drop for being late before it hands
833/// one over regardless. The policy needs a floor of its own: a machine that
834/// cannot decode a file in real time is late on *every* picture, and dropping
835/// every picture is a black screen rather than a stutter -- so the slowest seat
836/// still gets one in nine, which is roughly what it could paint before (the
837/// front-end restarted the decoder once every two seconds to the same effect,
838/// and paid a VA-API init for each restart).
839const LATE_RUN: u32 = 8;
840
841/// What a decode worker keeps **between** the spans it is asked for: the
842/// container it read, what the stream says about itself, and the hardware
843/// session -- the three things a seek used to throw away and buy again.
844struct Source {
845 meta: VideoMeta,
846 /// What the film says its brightest picture is ([`Demuxer::light`]): the
847 /// tone map's assumed peak on the reference rendition, so a 1759 cd/m^2
848 /// grade is converted at 1759 rather than at the 1000 a file that declared
849 /// nothing is assumed at. A property of the stream, read once with it.
850 peak: Option<f32>,
851 demuxer: Demuxer,
852 /// The plugin's session, opened on this thread (its VA-API state is not
853 /// `Send`-safe across a hand-off) and *kept*. `None` for software: forced by
854 /// `VE_SW`, refused by the plugin, or handed back by a session that opened
855 /// and then decoded nothing.
856 hw: Option<HwSession>,
857}
858
859impl Source {
860 /// The file as the sync opener already read it.
861 fn demuxed(demuxer: Demuxer, meta: VideoMeta) -> Self {
862 Self {
863 meta,
864 peak: demuxer.light().peak(),
865 demuxer,
866 hw: None,
867 }
868 }
869
870 /// ...and as the deferred opener reads it, on the worker. `None` is a file
871 /// that would not open: the caller drops the sender, and the disconnected
872 /// receiver is the session's "walk on to the next span".
873 fn open(path: &Path) -> Option<Self> {
874 match Demuxer::open(path) {
875 Ok((meta, demuxer)) => Some(Self::demuxed(demuxer, meta)),
876 Err(e) => {
877 eprintln!("video open failed: {e}");
878 None
879 }
880 }
881 }
882
883 /// Puts the hardware decoder at `start`, keeping the session open where the
884 /// plugin can reposition it. `None` when there is no hardware here at all;
885 /// otherwise whether the session was **reused** -- which is what lets the
886 /// caller tell a driver that cannot decode this stream from one that merely
887 /// did not follow a reseek.
888 fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {
889 if let Some(hw) = &mut self.hw {
890 if hw.seek(start) {
891 eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})");
892 return Some(true);
893 }
894 // A plugin too old to reposition, or a decoder that would not
895 // flush: closed and opened again, which is what every seek did.
896 self.hw = None;
897 }
898 self.hw = open_hw(path, start);
899 self.hw.as_ref().map(|_| {
900 eprintln!("decode backend: hardware (VA-API plugin)");
901 false
902 })
903 }
904}
905
906/// One span on a worker's thread: position the decoder, decode
907/// `[start, end)`, send the pictures. Every opener ends here -- the sync one,
908/// which demuxed on the caller's thread, the deferred one, which demuxes on
909/// this one, and every reseek after them -- so there is exactly one description
910/// of what a decode worker does.
911fn run_span(
912 path: &Path,
913 source: &mut Option<Source>,
914 cmd: SpanCmd,
915 abort: &Abort,
916 backend: &BackendCell,
917) {
918 let SpanCmd {
919 start,
920 end,
921 color,
922 canvas,
923 tone,
924 speed,
925 tx,
926 ..
927 } = cmd;
928 let opened = match source {
929 Some(opened) => opened,
930 None => {
931 let Some(fresh) = Source::open(path) else {
932 backend.set(Backend::Gap);
933 return;
934 };
935 source.insert(fresh)
936 }
937 };
938 // The clamp the sync opener does with the metadata it read on the caller's
939 // thread; here the metadata arrives first.
940 let end = end.min(opened.meta.frame_count);
941 // An empty range decodes nothing and must send nothing: `run_hw` counts a
942 // frame *out* before it compares, so without this a zero-length span would
943 // emit one picture.
944 if end <= start {
945 return;
946 }
947 // The stream's own colour and peak brightness: properties of the stream, so
948 // neither can change while one range decodes -- but the grade, the canvas
949 // and the rendition are the *span's*, so this is built per span.
950 let mut render = Render::new(color, opened.meta.color, canvas, tone, opened.peak);
951 if let Some(reused) = opened.position_hw(path, start) {
952 // Cancelled during the init (or the seek): leave without decoding.
953 if abort.hit() {
954 return;
955 }
956 backend.set(Backend::Hardware);
957 let mut decoded = run_hw(
958 opened.hw.as_mut().expect("positioned above"),
959 &tx,
960 start,
961 end,
962 &mut render,
963 abort,
964 speed,
965 );
966 // A *reused* session that produced nothing may simply be one this
967 // reseek left where the driver would not follow; a session opened fresh
968 // at the same frame is the honest second question, and only its silence
969 // is a software fallback. Without this a single unfollowed seek would
970 // collapse the rest of the file to software.
971 if !decoded && reused {
972 eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}");
973 opened.hw = open_hw(path, start);
974 if let Some(hw) = opened.hw.as_mut() {
975 decoded = run_hw(hw, &tx, start, end, &mut render, abort, speed);
976 }
977 }
978 if decoded {
979 return;
980 }
981 // A driver that opens but cannot decode a single frame is still a
982 // fallback case, not a dead session.
983 opened.hw = None;
984 eprintln!("hardware decode failed before any frame, falling back to software");
985 }
986 // ...except where there is nothing to fall back to. Feeding HEVC or VP9
987 // bytes to `rusty_h264` would be garbage, not a fallback.
988 if opened.meta.codec != Codec::H264 {
989 eprintln!("{}", opened.meta.codec.needs_plugin());
990 return;
991 }
992 eprintln!("decode backend: software (rusty_h264)");
993 backend.set(Backend::Software);
994 run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed)
995}
996
997/// One clip's pictures on their way to the renderer: graded, placed on the
998/// project canvas, converted. Both decode loops go through it, so hardware and
999/// software cannot show two different pictures.
1000///
1001/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
1002/// applied at the resolution it was shot at, and the letterbox bars around it
1003/// are not the clip -- a brightness grade must not lift them off black.
1004///
1005/// A project at the media's own resolution never reaches any of that: it takes
1006/// the fused graded conversion, the one path this engine had before there was a
1007/// project resolution, byte for byte and allocation for allocation.
1008struct Render {
1009 color: ColorParams,
1010 /// What the source's samples mean -- the stream's own matrix and range,
1011 /// which is what the conversion below is done in rather than the BT.601 it
1012 /// used to assume of every file.
1013 desc: ColorDescription,
1014 canvas: Composer,
1015 /// This stream's HDR-to-SDR map, built once here because building it is
1016 /// float work over 9 537 grid nodes and the transfer is a property of the
1017 /// stream. `None` for an SDR stream, which is what keeps that path exactly
1018 /// the one it was.
1019 tone: Option<ToneMapper>,
1020 /// The working copy of the source planes, refilled per frame and kept
1021 /// across the worker's whole range. Empty unless the clip needs one: it is
1022 /// tone-mapped in place, graded in place, or both.
1023 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
1024}
1025
1026/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's
1027/// output contract ([`crate::tonemap`]), and no longer the HDR space the file
1028/// declared.
1029const TONE_MAPPED: ColorDescription = ColorDescription {
1030 matrix: Matrix::Bt709,
1031 transfer: Transfer::Sdr,
1032 full_range: false,
1033};
1034
1035impl Render {
1036 /// `peak` is what the file declared about its own brightness
1037 /// ([`Demuxer::light`]), which only an HDR stream has and only the
1038 /// reference rendition reads (see [`tonemap::Preset`]).
1039 fn new(
1040 color: ColorParams,
1041 desc: ColorDescription,
1042 canvas: Composer,
1043 preset: tonemap::Preset,
1044 peak: Option<f32>,
1045 ) -> Self {
1046 Self {
1047 color,
1048 desc,
1049 canvas,
1050 // corner-cut: the ceiling is that the map reads limited-range codes
1051 // (`tonemap`'s input contract), so a full-range PQ file -- which
1052 // no encoder writes and no camera produces -- is mapped as if it
1053 // were limited and comes out slightly crushed. The upgrade is a
1054 // range argument to `ToneMapper::new`.
1055 tone: match desc.transfer {
1056 Transfer::Sdr => None,
1057 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)),
1058 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
1059 },
1060 graded: (Vec::new(), Vec::new(), Vec::new()),
1061 }
1062 }
1063
1064 fn frame(
1065 &mut self,
1066 index: u32,
1067 y: &[u8],
1068 u: &[u8],
1069 v: &[u8],
1070 width: u32,
1071 height: u32,
1072 ) -> Frame {
1073 let passthrough = self.canvas.is_passthrough(width, height);
1074 // Everything that has to happen to the samples before the canvas sees
1075 // them, on one copy: the tone map (HDR streams only) and, unless the
1076 // conversion below can fuse it, the grade. An SDR stream that is either
1077 // ungraded or passing through takes neither and never allocates.
1078 //
1079 // The grade lands *after* the map on purpose: it is a look on the
1080 // picture a viewer is shown, so its brightness and saturation mean what
1081 // they say in the SDR the tone map just produced, not in the 10-stop
1082 // HDR the file was in.
1083 let (y, u, v, desc) = if self.tone.is_some() || (!passthrough && !self.color.is_identity())
1084 {
1085 let (gy, gu, gv) = &mut self.graded;
1086 gy.clear();
1087 gy.extend_from_slice(y);
1088 gu.clear();
1089 gu.extend_from_slice(u);
1090 gv.clear();
1091 gv.extend_from_slice(v);
1092 if let Some(tone) = &self.tone {
1093 tone.map(gy, gu, gv, width as usize, height as usize);
1094 }
1095 if !passthrough && !self.color.is_identity() {
1096 crate::color::apply_yuv(&self.color, gy, gu, gv);
1097 }
1098 let desc = if self.tone.is_some() {
1099 TONE_MAPPED
1100 } else {
1101 self.desc
1102 };
1103 (&gy[..], &gu[..], &gv[..], desc)
1104 } else {
1105 (y, u, v, self.desc)
1106 };
1107 if passthrough {
1108 return Frame {
1109 index,
1110 width,
1111 height,
1112 bgra: i420_to_bgra_with(
1113 &desc,
1114 &self.color,
1115 y,
1116 u,
1117 v,
1118 width as usize,
1119 height as usize,
1120 ),
1121 };
1122 }
1123 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
1124 Frame {
1125 index,
1126 width,
1127 height,
1128 // Ungraded on purpose: the grade is already in the pixels above and
1129 // the canvas around them must stay the black it was filled with.
1130 bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize),
1131 }
1132 }
1133}
1134
1135/// One still image, decoded to tightly packed I420 -- the shape every other
1136/// source arrives in, so a placed image goes through the same grade, the same
1137/// canvas and the same conversion as a decoded picture and there is no second
1138/// pixel path to keep in step.
1139///
1140/// Held whole rather than streamed: an image *is* one picture, and the file is
1141/// read once per span that plays it.
1142pub(crate) struct Still {
1143 pub(crate) y: Vec<u8>,
1144 pub(crate) u: Vec<u8>,
1145 pub(crate) v: Vec<u8>,
1146 pub(crate) width: u32,
1147 pub(crate) height: u32,
1148}
1149
1150impl Still {
1151 /// Decodes `path`. Refused by name for a picture that is not one
1152 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
1153 /// file are both held to cannot be walked around by a 30000-pixel-wide PNG.
1154 ///
1155 /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a
1156 /// transparent PNG arrives fully opaque over its own colours rather than
1157 /// over the clip beneath it. I420 has nowhere to carry it and this engine
1158 /// composes one picture per frame (topmost lane wins), so there is nothing
1159 /// for a blend to blend with.
1160 ///
1161 /// corner-cut: the ceiling is a logo with a transparent background, which
1162 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
1163 /// giving `scale::Composer` a blend over the lane below.
1164 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
1165 let reader = image::ImageReader::open(path)?.with_guessed_format()?;
1166 let rgb = reader
1167 .decode()
1168 .map_err(|e| format!("{}: {e}", path.display()))?
1169 .to_rgb8();
1170 let (width, height) = rgb.dimensions();
1171 if !crate::is_resolution(width, height) {
1172 return Err(format!(
1173 "{} is {width}x{height}, which is not a picture this engine composes",
1174 path.display()
1175 )
1176 .into());
1177 }
1178 let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize);
1179 Ok(Self {
1180 y,
1181 u,
1182 v,
1183 width,
1184 height,
1185 })
1186 }
1187
1188 /// The planes as an export's decoder hands them over, so a still and a
1189 /// decoded picture are the same value to `export::run`.
1190 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
1191 (&self.y, &self.u, &self.v, self.width, self.height)
1192 }
1193}
1194
1195/// How big the picture in `path` is, from its header alone -- what a library row
1196/// says about a file it has not placed anywhere. The whole file is not decoded.
1197pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
1198 Ok(image::ImageReader::open(path)?
1199 .with_guessed_format()?
1200 .into_dimensions()
1201 .map_err(|e| format!("{}: {e}", path.display()))?)
1202}
1203
1204/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
1205/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why
1206/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and
1207/// not the timeline's. A still has no stream to be tagged by; it round-trips to
1208/// the colour it was authored in through this pair and nothing else sees these
1209/// planes (`images::still_pixels_match_the_source_image` measures it).
1210///
1211/// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
1212/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
1213/// [`crate::scale::Composer::place`] panics on anything else for.
1214fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1215 let (cw, ch) = crate::scale::chroma_dims(width, height);
1216 let mut y = vec![0u8; width * height];
1217 let mut u = vec![0u8; cw * ch];
1218 let mut v = vec![0u8; cw * ch];
1219 for row in 0..height {
1220 for col in 0..width {
1221 let p = (row * width + col) * 3;
1222 let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32);
1223 y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
1224 }
1225 }
1226 for crow in 0..ch {
1227 for ccol in 0..cw {
1228 let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32);
1229 for row in crow * 2..(crow * 2 + 2).min(height) {
1230 for col in ccol * 2..(ccol * 2 + 2).min(width) {
1231 let p = (row * width + col) * 3;
1232 sr += rgb[p] as i32;
1233 sg += rgb[p + 1] as i32;
1234 sb += rgb[p + 2] as i32;
1235 n += 1;
1236 }
1237 }
1238 let n = n.max(1);
1239 let (r, g, b) = (sr / n, sg / n, sb / n);
1240 u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
1241 v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
1242 }
1243 }
1244 (y, u, v)
1245}
1246
1247/// `None` when the software path must be used: forced by `VE_SW=1`, or the
1248/// plugin is absent/broken/unable to open this particular file.
1249fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> {
1250 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
1251 return None;
1252 }
1253 HwSession::open_at(path, start_frame)
1254}
1255
1256/// `Ok` when the plugin really decodes this file: it opens *and* hands back a
1257/// first picture. Opening only reads the container -- a stream the vendored
1258/// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and
1259/// then produces nothing, which reaches the user as a black picture with an
1260/// instant `eof` unless the door asks for that first frame. Costs one decoded
1261/// frame per probe.
1262///
1263/// The `Err` says which half failed, because "there is no decoder for this
1264/// codec" and "the decoder here would not take this stream" are different
1265/// refusals and a user acts on them differently.
1266fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), String> {
1267 let Some(mut hw) = open_hw(path, start_frame) else {
1268 return Err(codec.needs_plugin());
1269 };
1270 // End of stream counts as a refusal, not as a pass: a session that hands
1271 // back no picture at all is exactly the black-frame-and-instant-eof this
1272 // probe exists to catch, and `Ok(None)` is how the plugin says it.
1273 match hw.next_frame() {
1274 Ok(Some(_)) => Ok(()),
1275 _ => Err(codec.undecodable()),
1276 }
1277}
1278
1279/// Returns whether the session was handled; `false` only when hardware decode
1280/// failed without emitting a single frame, so software can still take over.
1281///
1282/// The plugin already positioned itself at `start_frame`, so indices are
1283/// counted from there (a stream whose very first sample is not a sync sample
1284/// cannot be decoded from its start at all, and is not accounted for).
1285fn run_hw(
1286 hw: &mut HwSession,
1287 tx: &SyncSender<Frame>,
1288 start_frame: u32,
1289 end_frame: u32,
1290 render: &mut Render,
1291 abort: &Abort,
1292 speed: Speed,
1293) -> bool {
1294 let mut index = start_frame;
1295 // Pictures dropped for being late since the last one handed over; see
1296 // [`LATE_RUN`].
1297 let mut skipped = 0;
1298 loop {
1299 if abort.hit() {
1300 return true;
1301 }
1302 match hw.next_frame() {
1303 Ok(Some((y, u, v, width, height))) => {
1304 let due = index;
1305 index += 1;
1306 if abort.late(due) {
1307 if skipped < LATE_RUN {
1308 skipped += 1;
1309 } else {
1310 skipped = 0;
1311 let frame = render.frame(due, y, u, v, width, height);
1312 if tx.send(frame).is_err() {
1313 return true; // consumer went away
1314 }
1315 }
1316 } else if skip_for_speed(speed, start_frame, due, end_frame) {
1317 // Redundant by construction, not by lateness: no run limit
1318 // needed (see `skip_for_speed`).
1319 } else {
1320 skipped = 0;
1321 let frame = render.frame(due, y, u, v, width, height);
1322 if tx.send(frame).is_err() {
1323 return true; // consumer went away
1324 }
1325 }
1326 if index >= end_frame {
1327 return true; // end of the requested range
1328 }
1329 }
1330 Ok(None) => return true,
1331 Err(e) => {
1332 if index == start_frame {
1333 return false;
1334 }
1335 eprintln!("hardware decode error at frame {index}: {e}");
1336 return true;
1337 }
1338 }
1339 }
1340}
1341
1342#[cfg(test)]
1343mod tests {
1344 use super::*;
1345 use std::sync::mpsc::RecvTimeoutError;
1346 use std::time::{Duration, Instant};
1347
1348 fn asset(name: &str) -> PathBuf {
1349 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1350 .join("../../assets")
1351 .join(name)
1352 }
1353
1354 /// Drops `path` from the page cache, so the open below really goes to disk
1355 /// -- the case the deferred opener exists for, and the one that costs
1356 /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a
1357 /// no-op wherever `python3` is not around: the assertions hold either way,
1358 /// the numbers printed are simply the warm ones.
1359 fn evict(path: &Path) {
1360 let _ = std::process::Command::new("python3")
1361 .arg("-c")
1362 .arg(
1363 "import os,sys\n\
1364 fd=os.open(sys.argv[1],os.O_RDONLY)\n\
1365 os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\
1366 os.close(fd)",
1367 )
1368 .arg(path)
1369 .status();
1370 }
1371
1372 /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller
1373 /// gets its stream back in the time a thread takes to spawn, and the file
1374 /// is opened behind it -- so the first frame necessarily arrives *after*
1375 /// the call returned, and the sync opener on the same cold file pays on the
1376 /// calling thread what this one does not.
1377 #[test]
1378 fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() {
1379 let path = asset("test_baseline.mp4");
1380 evict(&path);
1381 let start = Instant::now();
1382 let stream = DecodeSession::open_worker_deferred(
1383 &path,
1384 0,
1385 u32::MAX,
1386 ColorParams::default(),
1387 Composer::passthrough(),
1388 tonemap::Preset::default(),
1389 Speed::NORMAL,
1390 );
1391 let returned = start.elapsed();
1392 let frame = stream
1393 .frames
1394 .recv_timeout(Duration::from_secs(10))
1395 .expect("first frame");
1396 let first_frame = start.elapsed();
1397
1398 // The same file, equally cold, through the door the import path keeps:
1399 // that one hands back metadata, and the demux it reads to do so is on
1400 // this thread.
1401 evict(&path);
1402 let sync_start = Instant::now();
1403 let sync = DecodeSession::open_worker(
1404 &path,
1405 0,
1406 u32::MAX,
1407 ColorParams::default(),
1408 Composer::passthrough(),
1409 tonemap::Preset::default(),
1410 )
1411 .expect("sync open");
1412 let sync_returned = sync_start.elapsed();
1413 drop(sync);
1414
1415 eprintln!(
1416 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
1417 sync open returned in {sync_returned:?}"
1418 );
1419 assert_eq!(frame.index, 0, "the deferred worker starts where it is told");
1420 assert!(
1421 returned < Duration::from_millis(10),
1422 "the caller waited {returned:?} -- something is still being read \
1423 from the file before this returns"
1424 );
1425 assert!(
1426 first_frame > returned,
1427 "the first frame arrived within the call ({first_frame:?} vs \
1428 {returned:?}), which cannot happen if the open is deferred"
1429 );
1430 assert!(
1431 returned < sync_returned,
1432 "the deferred open ({returned:?}) cost as much as the sync one \
1433 ({sync_returned:?}): the demux is still on the caller's thread"
1434 );
1435 }
1436
1437 /// The late-picture policy, at the one place it is decided. A worker told
1438 /// the playhead is already at frame 20 must not spend a conversion and a
1439 /// queue slot on the twenty pictures behind it -- they can never be shown --
1440 /// and it must not go silent either, which is what [`LATE_RUN`] bounds: a
1441 /// machine that cannot decode in real time is late on every picture, and one
1442 /// in nine still reaches the screen.
1443 ///
1444 /// Deterministic on purpose: the floor is set by hand rather than by a clock
1445 /// that would have to outrun a debug-build decoder to prove anything.
1446 #[test]
1447 fn a_worker_skips_the_pictures_the_playhead_has_gone_past() {
1448 let take = |floor: u32| {
1449 let stream = DecodeSession::open_worker_deferred(
1450 asset("test_baseline.mp4"),
1451 0,
1452 u32::MAX,
1453 ColorParams::default(),
1454 Composer::passthrough(),
1455 tonemap::Preset::default(),
1456 Speed::NORMAL,
1457 );
1458 stream.worker.playhead(floor);
1459 let mut indices = Vec::new();
1460 while indices.len() < 4 {
1461 let frame = stream
1462 .frames
1463 .recv_timeout(Duration::from_secs(10))
1464 .expect("a picture");
1465 indices.push(frame.index);
1466 }
1467 indices
1468 };
1469
1470 // Nobody has moved: every picture of the range is owed, in order.
1471 assert_eq!(take(0), vec![0, 1, 2, 3]);
1472
1473 // The playhead is at 20, so the pictures before it are decoded (the ones
1474 // after reference them) and dropped unconverted -- all but the one in
1475 // nine [`LATE_RUN`] lets through, so the caller never goes blind.
1476 let caught_up = take(20);
1477 assert!(
1478 caught_up[0] > 0 && caught_up.windows(2).any(|w| w[1] > w[0] + 1),
1479 "nothing was skipped: {caught_up:?}"
1480 );
1481 assert!(
1482 caught_up.iter().any(|&i| i >= 20),
1483 "the playhead was never reached: {caught_up:?}"
1484 );
1485 assert!(
1486 caught_up.len() >= 4,
1487 "the worker went silent instead of dropping down to one in nine"
1488 );
1489 }
1490
1491 /// [`skip_for_speed`] on its own, with no worker or channel involved: at
1492 /// 2x every other source frame maps onto the same timeline frame
1493 /// ([`Speed::timeline_at`]), so `skip`/`keep` must alternate exactly, and
1494 /// the last frame of the span (the one [`crate::project::Span::source_len`]
1495 /// is built to land on) must never be skipped regardless of where the
1496 /// alternation lands.
1497 #[test]
1498 fn skip_for_speed_alternates_at_2x_and_never_drops_the_last_frame() {
1499 let speed = Speed::from_permille(2000);
1500 let start = 100;
1501 let end = 110;
1502
1503 let skips: Vec<bool> = (start..end)
1504 .map(|due| skip_for_speed(speed, start, due, end))
1505 .collect();
1506 // Alternation holds up to (but not including) the span's last frame,
1507 // which is special-cased below.
1508 for pair in (start..end - 2).zip(skips.windows(2)) {
1509 let (due, w) = pair;
1510 assert_eq!(
1511 w[0], !w[1],
1512 "frame {due} and its successor should alternate skip/keep at 2x: {skips:?}"
1513 );
1514 }
1515 assert!(
1516 !skip_for_speed(speed, start, end - 1, end),
1517 "the last frame of the span must never be skipped"
1518 );
1519 }
1520
1521 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
1522 /// The channel is bounded, so such a worker is parked in `send` within a
1523 /// few frames, and the only thing that can wake it is its receiver going
1524 /// away -- which is why the receiver is the first field and the join inside
1525 /// `Worker::drop` is the second. Swap those two fields and this hangs.
1526 ///
1527 /// This is the whole basis of every teardown path in the engine, so it is
1528 /// asserted rather than commented: the drop runs on a second thread and a
1529 /// regression fails in ten seconds instead of hanging the suite forever.
1530 #[test]
1531 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
1532 let (_meta, stream) = DecodeSession::open_worker(
1533 &asset("test_baseline.mp4"),
1534 0,
1535 u32::MAX,
1536 ColorParams::default(),
1537 Composer::passthrough(),
1538 tonemap::Preset::default(),
1539 )
1540 .expect("open");
1541 // Nothing is ever received: two frames fill the channel and the next
1542 // send parks the decode thread, exactly as a refused project load does.
1543 thread::sleep(Duration::from_millis(500));
1544
1545 let (done_tx, done_rx) = sync_channel(1);
1546 thread::spawn(move || {
1547 drop(stream);
1548 let _ = done_tx.send(());
1549 });
1550 assert!(
1551 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
1552 "dropping a parked stream deadlocked: it joined a decode thread \
1553 while still holding the receiver that thread is waiting on"
1554 );
1555 }
1556}
1557
1558fn run(
1559 demuxer: &mut Demuxer,
1560 tx: &SyncSender<Frame>,
1561 start_frame: u32,
1562 end_frame: u32,
1563 render: &mut Render,
1564 abort: &Abort,
1565 speed: Speed,
1566) {
1567 // A decoder per span, and cheap: it is a parameter-set map and a picture
1568 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
1569 // one this worker keeps.
1570 let mut decoder = Decoder::new();
1571 // Decoding has to restart at a sync sample, so pictures between it and
1572 // `start_frame` are decoded (the target frame references them) but never
1573 // converted or sent. Signed, because the landing sync sample can sit inside
1574 // what the file's edit list trims, i.e. *before* frame 0.
1575 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1576 let mut skipped = 0;
1577
1578 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);
1579 // reordering streams need POC-sorted output before display.
1580 loop {
1581 if abort.hit() {
1582 break;
1583 }
1584 let au = match demuxer.next_access_unit() {
1585 Ok(Some(au)) => au,
1586 Ok(None) => break,
1587 Err(e) => {
1588 eprintln!("demux error: {e}");
1589 break;
1590 }
1591 };
1592 let yuv = match decoder.decode(&au) {
1593 Ok(Some(yuv)) => yuv,
1594 Ok(None) => continue,
1595 Err(e) => {
1596 eprintln!("decode error at access unit {index}: {e}");
1597 break;
1598 }
1599 };
1600 if index < i64::from(start_frame) {
1601 index += 1;
1602 continue;
1603 }
1604 let due = index as u32;
1605 index += 1;
1606 if abort.late(due) {
1607 if skipped < LATE_RUN {
1608 skipped += 1;
1609 } else {
1610 skipped = 0;
1611 let frame = render.frame(
1612 due,
1613 &yuv.y,
1614 &yuv.u,
1615 &yuv.v,
1616 yuv.width as u32,
1617 yuv.height as u32,
1618 );
1619 if tx.send(frame).is_err() {
1620 break; // consumer went away
1621 }
1622 }
1623 } else if skip_for_speed(speed, start_frame, due, end_frame) {
1624 // Redundant by construction, not by lateness: no run limit needed
1625 // (see `skip_for_speed`).
1626 } else {
1627 skipped = 0;
1628 let frame = render.frame(
1629 due,
1630 &yuv.y,
1631 &yuv.u,
1632 &yuv.v,
1633 yuv.width as u32,
1634 yuv.height as u32,
1635 );
1636 if tx.send(frame).is_err() {
1637 break; // consumer went away
1638 }
1639 }
1640 if index >= i64::from(end_frame) {
1641 break; // end of the requested range
1642 }
1643 }
1644}