forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB4e75992Tahinli2 months ago844 commits

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