forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB81510b3Tahinli3 months ago382 commits

decode.rs1119 lines, 43.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, Ordering};
7use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
8use std::thread;
9
10use rusty_h264::Decoder;
11
12use crate::color::ColorParams;
13use crate::colorspace::{ColorDescription, Matrix, Transfer};
14use crate::convert::{i420_to_bgra, i420_to_bgra_with};
15use crate::demux::{Codec, Demuxer, VideoMeta};
16use crate::hw::HwSession;
17use crate::scale::Composer;
18use crate::tonemap::{self, ToneMapper};
19
20/// One decoded picture, ready to hand to a renderer.
21pub struct Frame {
22 /// Position in decode order, starting at 0.
23 pub index: u32,
24 pub width: u32,
25 pub height: u32,
26 /// BGRA8, straight alpha, tightly packed.
27 pub bgra: Vec<u8>,
28}
29
30/// Which decoder a source is really running on. Read-only introspection: it
31/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose --
32/// a hardware session that opened and then failed before its first picture
33/// falls back to software and this says so, because it is written where the
34/// fallback happens rather than where it was hoped for.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Backend {
37 /// The worker has not reached its decoder yet: the plugin's VA-API init is
38 /// ~90 ms, and this is what a caller reads in that window.
39 #[default]
40 Opening,
41 /// The VA-API plugin (`libengine_hw.so`).
42 Hardware,
43 /// `rusty_h264`, in this process.
44 Software,
45 /// A still image: one `image` decode, no stream and no decoder to pick.
46 Still,
47 /// A gap: black frames, nothing decoded at all.
48 Gap,
49}
50
51impl Backend {
52 /// Short enough for a library row and a transport line.
53 pub fn label(self) -> &'static str {
54 match self {
55 Self::Opening => "opening",
56 Self::Hardware => "HW",
57 Self::Software => "SW",
58 Self::Still => "still",
59 Self::Gap => "gap",
60 }
61 }
62
63 fn code(self) -> u8 {
64 match self {
65 Self::Opening => 0,
66 Self::Hardware => 1,
67 Self::Software => 2,
68 Self::Still => 3,
69 Self::Gap => 4,
70 }
71 }
72
73 fn from_code(code: u8) -> Self {
74 match code {
75 1 => Self::Hardware,
76 2 => Self::Software,
77 3 => Self::Still,
78 4 => Self::Gap,
79 _ => Self::Opening,
80 }
81 }
82}
83
84/// Where a worker publishes the decoder it opened, for whoever holds the other
85/// end of its channel. One atomic byte, written once at open (and once more if
86/// hardware hands the range back to software), read whenever a caller repaints
87/// -- never per frame on either side.
88#[derive(Clone, Default)]
89pub struct BackendCell(Arc<AtomicU8>);
90
91impl BackendCell {
92 pub(crate) fn new(backend: Backend) -> Self {
93 Self(Arc::new(AtomicU8::new(backend.code())))
94 }
95
96 fn set(&self, backend: Backend) {
97 self.0.store(backend.code(), Ordering::Relaxed);
98 }
99
100 pub fn get(&self) -> Backend {
101 Backend::from_code(self.0.load(Ordering::Relaxed))
102 }
103}
104
105/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`]
106/// decides it: the same `VE_SW` pin and the same plugin probe against this very
107/// file. What lets a front-end name the decoder *before* anything plays.
108///
109/// The codec is `None` for a still image, which has no coded stream. A stream
110/// no decoder here can take is an `Err` naming the plugin, exactly as opening
111/// it would be -- the same refusal, one VA-API init earlier.
112///
113/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per
114/// file, off a render thread, and keep the answer.
115pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
116 if crate::is_image(path) {
117 return Ok((None, Backend::Still));
118 }
119 let path = path.to_path_buf();
120 let (meta, _demuxer) = Demuxer::open(&path)?;
121 match hw_decodes(&path, 0, meta.codec) {
122 Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)),
123 Err(e) if meta.codec != Codec::H264 => return Err(e.into()),
124 Err(_) => {}
125 }
126 Ok((Some(meta.codec), Backend::Software))
127}
128
129/// A running decode worker: the flag that stops it, and the handle to wait on.
130///
131/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
132/// outlives the process otherwise, and Mesa's `atexit` handlers free the state
133/// it is still reading -- a SIGSEGV at exit, long after the last test passed.
134pub(crate) struct Worker {
135 cancel: Arc<AtomicBool>,
136 /// `None` once detached, and for a range with nothing to decode: either way
137 /// there is no thread left to wait for.
138 handle: Option<thread::JoinHandle<()>>,
139}
140
141impl Worker {
142 /// Stops the worker at its next check without waiting. Callers that replace
143 /// a worker should do this first and drop the receiver second: a worker
144 /// parked in `send` only wakes on the disconnect, so the join below would
145 /// otherwise wait for a consumer that is never coming.
146 pub(crate) fn cancel(&self) {
147 self.cancel.store(true, Ordering::Release);
148 }
149
150 /// Whether the thread has already returned, i.e. dropping this would not
151 /// wait. `true` for a worker that never had a thread. What lets a caller
152 /// park cancelled workers and reap them without ever blocking.
153 pub(crate) fn is_finished(&self) -> bool {
154 self.handle
155 .as_ref()
156 .is_none_or(thread::JoinHandle::is_finished)
157 }
158
159 /// Lets the worker run on unwatched -- what the public API does, since it
160 /// hands out the flag alone.
161 fn detach(mut self) -> Arc<AtomicBool> {
162 self.handle = None;
163 Arc::clone(&self.cancel)
164 }
165}
166
167impl Drop for Worker {
168 fn drop(&mut self) {
169 if let Some(handle) = self.handle.take() {
170 self.cancel();
171 let _ = handle.join();
172 }
173 }
174}
175
176/// A running worker and the frames it is sending, handed out as one value
177/// because they must be *dropped* as one, in this order: the receiver
178/// disconnects first, which is the only thing that wakes a worker parked in a
179/// full `send`, and the join inside [`Worker::drop`] runs second.
180///
181/// Rust drops fields in declaration order, so this struct *is* that rule, and
182/// it holds wherever the value goes: an early return out of a half-built
183/// session, an unwind, a caller not written yet. Two separate locals do not
184/// hold it -- they drop in reverse order of declaration, so the worker there
185/// joins a thread nobody will ever drain, which is a hang and not a slow path.
186pub(crate) struct FrameStream {
187 pub(crate) frames: Receiver<Frame>,
188 pub(crate) worker: Worker,
189 /// What this stream's pictures are being decoded by. Dropped last and read
190 /// by the caller, so it outlives nothing and blocks nothing.
191 pub(crate) backend: BackendCell,
192}
193
194pub struct DecodeSession;
195
196impl DecodeSession {
197 /// Opens `path`, returning stream metadata immediately and a receiver that
198 /// yields frames as the worker decodes them. The worker stops when the
199 /// receiver is dropped, at end of stream, or on the first decode error.
200 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
201 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
202 Ok((meta, rx))
203 }
204
205 /// As [`DecodeSession::open`], but the first frame delivered is
206 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
207 /// Setting the returned flag stops the worker at its next access unit,
208 /// which is how a caller abandons a session it no longer wants to drain.
209 pub fn open_at(
210 path: impl AsRef<Path>,
211 start_frame: u32,
212 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
213 // `u32::MAX` is clamped to the stream's frame count below, so this is
214 // "to the end of the file".
215 Self::open_range(path, start_frame, u32::MAX)
216 }
217
218 /// As [`DecodeSession::open_at`], but the worker also stops on its own
219 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
220 /// absolute source frames, which is what a clip of a longer file needs.
221 /// `end_frame` is capped at the stream's frame count, and an empty range
222 /// yields a receiver that is simply already disconnected.
223 pub fn open_range(
224 path: impl AsRef<Path>,
225 start_frame: u32,
226 end_frame: u32,
227 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
228 // Ungraded: the public API opens a *file*, and a colour grade belongs to
229 // a clip of a timeline. `PlaybackSession` is what has one to pass.
230 let (meta, stream) = Self::open_worker(
231 path,
232 start_frame,
233 end_frame,
234 ColorParams::default(),
235 // No project, no canvas: the file-level API hands back the
236 // pictures the file holds, at the size it holds them.
237 Composer::passthrough(),
238 // ...and no project means no picked rendition either: an HDR file
239 // opened through this door is mapped the published way.
240 tonemap::Preset::default(),
241 )?;
242 // The public API hands out the flag alone, so the worker is detached and
243 // the receiver goes to the caller: nothing here joins anything.
244 Ok((meta, stream.frames, stream.worker.detach()))
245 }
246
247 /// A worker that decodes nothing and emits `len` black frames, indexed from
248 /// zero -- what a *gap* in the video lane looks like. It goes down the same
249 /// channel as decoded frames, so a gap costs the caller no branch at all
250 /// beyond choosing this opener: same bounded channel, same backpressure,
251 /// same cancel, same retire path.
252 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
253 let (tx, rx) = sync_channel(2);
254 let cancel = Arc::new(AtomicBool::new(false));
255 if len == 0 {
256 return FrameStream {
257 frames: rx,
258 worker: Worker {
259 cancel,
260 handle: None,
261 },
262 backend: BackendCell::new(Backend::Gap),
263 };
264 }
265 let worker_cancel = Arc::clone(&cancel);
266 // One buffer, cloned per frame: opaque black is a constant, and the
267 // clone is a memcpy against a decode this replaces entirely.
268 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
269 let handle = thread::Builder::new()
270 .name("black".into())
271 .spawn(move || {
272 for index in 0..len {
273 if worker_cancel.load(Ordering::Relaxed) {
274 return;
275 }
276 let frame = Frame {
277 index,
278 width,
279 height,
280 bgra: black.clone(),
281 };
282 if tx.send(frame).is_err() {
283 return; // caller moved on
284 }
285 }
286 })
287 .ok();
288 FrameStream {
289 frames: rx,
290 worker: Worker { cancel, handle },
291 backend: BackendCell::new(Backend::Gap),
292 }
293 }
294
295 /// A worker for a still image ([`crate::is_image`]): the file is decoded
296 /// *once* and the same picture goes down the channel `len` times, indexed
297 /// from `start_frame` exactly as a decoder's pictures are -- so a placed
298 /// image is a clip like any other to everything downstream (`try_frame`
299 /// rewrites those indices, `next_clip` walks off the end of the range).
300 ///
301 /// Graded and placed on the canvas once too, before the repeat: a still is
302 /// the same pixels every frame, so the whole cost of one is one conversion
303 /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays.
304 pub(crate) fn open_still(
305 path: &Path,
306 start_frame: u32,
307 len: u32,
308 color: ColorParams,
309 canvas: Composer,
310 ) -> crate::Result<FrameStream> {
311 let still = Still::open(path)?;
312 let (tx, rx) = sync_channel(2);
313 let cancel = Arc::new(AtomicBool::new(false));
314 if len == 0 {
315 return Ok(FrameStream {
316 frames: rx,
317 worker: Worker {
318 cancel,
319 handle: None,
320 },
321 backend: BackendCell::new(Backend::Still),
322 });
323 }
324 // The one conversion, on this thread: it is a few milliseconds and the
325 // error it could raise has already been raised by `Still::open`.
326 // BT.601 limited, because that is what `rgb_to_i420` above wrote these
327 // planes in: a still round-trips through the pair, not through the
328 // colour of whatever file is on the timeline beside it.
329 // No preset argument, and none wanted: a still is decoded into BT.601
330 // SDR planes, so the tone map is not built at all whichever rendition
331 // the project is watching.
332 let first = Render::new(
333 color,
334 ColorDescription::default(),
335 canvas,
336 tonemap::Preset::default(),
337 // ...and no declared peak either, for the same reason: there is no
338 // tone map on this path to hand one to.
339 None,
340 )
341 .frame(
342 start_frame,
343 &still.y,
344 &still.u,
345 &still.v,
346 still.width,
347 still.height,
348 );
349 let worker_cancel = Arc::clone(&cancel);
350 let handle = thread::Builder::new()
351 .name("still".into())
352 .spawn(move || {
353 let (width, height, bgra) = (first.width, first.height, first.bgra);
354 for index in 0..len {
355 if worker_cancel.load(Ordering::Relaxed) {
356 return;
357 }
358 let frame = Frame {
359 index: start_frame + index,
360 width,
361 height,
362 bgra: bgra.clone(),
363 };
364 if tx.send(frame).is_err() {
365 return; // caller moved on
366 }
367 }
368 })
369 .ok();
370 Ok(FrameStream {
371 frames: rx,
372 worker: Worker { cancel, handle },
373 backend: BackendCell::new(Backend::Still),
374 })
375 }
376
377 /// As [`DecodeSession::open_range`], but the caller gets the whole
378 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
379 /// `color` -- the clip's own setting, folded into the conversion the frames
380 /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
381 /// than read per frame because a worker *is* one clip's range: a grade
382 /// changed while this one runs reaches the picture when the session reseeks
383 /// onto the new one, which every edit does.
384 ///
385 /// In-process only: a caller that outlives its workers has to be able to
386 /// join them at exit.
387 ///
388 /// `canvas` is the project's own resolution and this clip's fit policy: the
389 /// frames come out at *that* size, whatever the file's is. A
390 /// [`Composer::passthrough`] (or one already the source's size) leaves every
391 /// picture exactly as it was decoded.
392 ///
393 /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured
394 /// here for the reason the grade is: it is constant across one span, and a
395 /// preset picked while this worker runs reaches the picture when the session
396 /// reseeks onto the new one. An SDR source ignores it entirely.
397 pub(crate) fn open_worker(
398 path: impl AsRef<Path>,
399 start_frame: u32,
400 end_frame: u32,
401 color: ColorParams,
402 canvas: Composer,
403 tone: tonemap::Preset,
404 ) -> crate::Result<(VideoMeta, FrameStream)> {
405 let path = path.as_ref().to_path_buf();
406 let (meta, demuxer) = Demuxer::open(&path)?;
407 // No software HEVC or VP9 decoder exists, so such a file the plugin will
408 // not take is refused *here*, where the caller still has somewhere to
409 // show it -- a worker that opened and then produced nothing is a black
410 // screen with no explanation. The probe session is opened, made to
411 // decode one picture and dropped: it costs one extra VA-API init
412 // (~90 ms) plus that frame, and only off the H.264 path.
413 if meta.codec != Codec::H264 {
414 hw_decodes(&path, start_frame, meta.codec)?;
415 }
416 let end_frame = end_frame.min(meta.frame_count);
417 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
418 // decoder run ahead of the display without limit.
419 let (tx, rx) = sync_channel(2);
420 let cancel = Arc::new(AtomicBool::new(false));
421 // Written by the worker below the moment it knows, so a caller reading
422 // it sees what opened rather than what was hoped for.
423 let backend = BackendCell::default();
424 if end_frame <= start_frame {
425 // Nothing to decode: dropping `tx` here closes the channel cleanly,
426 // so the caller sees an immediate end of stream rather than an error.
427 return Ok((
428 meta,
429 FrameStream {
430 frames: rx,
431 worker: Worker {
432 cancel,
433 handle: None,
434 },
435 backend,
436 },
437 ));
438 }
439 let worker_cancel = Arc::clone(&cancel);
440 let worker_backend = backend.clone();
441 let handle = thread::Builder::new()
442 .name("decode".into())
443 .spawn(move || {
444 decode_span(
445 &path,
446 demuxer,
447 meta,
448 start_frame,
449 end_frame,
450 color,
451 canvas,
452 tone,
453 tx,
454 &worker_cancel,
455 &worker_backend,
456 )
457 })?;
458 Ok((
459 meta,
460 FrameStream {
461 frames: rx,
462 worker: Worker {
463 cancel,
464 handle: Some(handle),
465 },
466 backend,
467 },
468 ))
469 }
470
471 /// As [`open_worker`](Self::open_worker), but the *file* is opened on the
472 /// worker too: nothing here touches the disk, so the caller pays a thread
473 /// spawn and not a demux -- 550-750 ms warm on a 25 GB film, seconds cold,
474 /// which is what a seek or a clip boundary used to cost the UI thread.
475 ///
476 /// The price is that there is no [`VideoMeta`] to return and no synchronous
477 /// refusal either: a file that will not open, and a codec no decoder here
478 /// takes (the plugin probe is skipped -- the worker's own refusal below
479 /// covers it), simply drop the sender. The disconnected receiver is what
480 /// carries a session on to the next span, which is exactly what a failed
481 /// open did on this path before. Callers that must *tell* the user why --
482 /// an import at the door -- keep the sync opener.
483 pub(crate) fn open_worker_deferred(
484 path: impl AsRef<Path>,
485 start_frame: u32,
486 end_frame: u32,
487 color: ColorParams,
488 canvas: Composer,
489 tone: tonemap::Preset,
490 ) -> FrameStream {
491 let path = path.as_ref().to_path_buf();
492 let (tx, rx) = sync_channel(2);
493 let cancel = Arc::new(AtomicBool::new(false));
494 let backend = BackendCell::default();
495 let worker_cancel = Arc::clone(&cancel);
496 let worker_backend = backend.clone();
497 let handle = thread::Builder::new()
498 .name("decode".into())
499 .spawn(move || {
500 // Cancelled before this thread was even scheduled: do not open
501 // the file at all. A scrub abandons workers by the dozen and
502 // this is where all but the last of them stop.
503 if worker_cancel.load(Ordering::Relaxed) {
504 return;
505 }
506 let (meta, demuxer) = match Demuxer::open(&path) {
507 Ok(opened) => opened,
508 Err(e) => {
509 eprintln!("video open failed: {e}");
510 // Dropping `tx` disconnects the receiver, which is the
511 // session's "walk on to the next span".
512 worker_backend.set(Backend::Gap);
513 return;
514 }
515 };
516 decode_span(
517 &path,
518 demuxer,
519 meta,
520 start_frame,
521 // The clamp the sync opener does with the metadata it read
522 // on the caller's thread; here the metadata arrives first.
523 end_frame.min(meta.frame_count),
524 color,
525 canvas,
526 tone,
527 tx,
528 &worker_cancel,
529 &worker_backend,
530 )
531 })
532 .ok();
533 FrameStream {
534 frames: rx,
535 worker: Worker { cancel, handle },
536 backend,
537 }
538 }
539}
540
541/// One worker thread's whole job, on that thread: pick the decoder, decode
542/// `[start_frame, end_frame)`, send the pictures. Both openers end here -- the
543/// sync one, which demuxed on the caller's thread, and the deferred one, which
544/// demuxed on this one -- so there is exactly one description of what a decode
545/// worker does, whoever opened the file.
546#[allow(clippy::too_many_arguments)]
547fn decode_span(
548 path: &PathBuf,
549 demuxer: Demuxer,
550 meta: VideoMeta,
551 start_frame: u32,
552 end_frame: u32,
553 color: ColorParams,
554 canvas: Composer,
555 tone: tonemap::Preset,
556 tx: SyncSender<Frame>,
557 cancel: &AtomicBool,
558 backend: &BackendCell,
559) {
560 // An empty range decodes nothing and must send nothing: `run_hw` counts a
561 // frame *out* before it compares, so without this a zero-length span would
562 // emit one picture. The sync opener never even spawns for this case.
563 if end_frame <= start_frame {
564 return;
565 }
566 // Cancelled before this thread was even scheduled -- do not enter VA-API
567 // initialisation at all, because that is the one stretch a cancel cannot
568 // interrupt (~65-90 ms of driver setup that would then have to be torn
569 // down again).
570 if cancel.load(Ordering::Relaxed) {
571 return;
572 }
573 // The stream's own colour, and with it what the film says its brightest
574 // picture is ([`Demuxer::light`]): the tone map's assumed peak on the
575 // reference rendition, so a 1759 cd/m^2 grade is converted at 1759 rather
576 // than at the 1000 a file that declared nothing is assumed at. Both are
577 // properties of the stream, so neither can change while one range decodes.
578 let mut render = Render::new(color, meta.color, canvas, tone, demuxer.light().peak());
579 // The plugin has to be opened on the thread that uses it: its VA-API state
580 // is not `Send`-safe across a later hand-off.
581 if let Some(hw) = open_hw(path, start_frame) {
582 // Cancelled *during* init: close the session (dropping `hw` does it)
583 // and leave without decoding anything.
584 if cancel.load(Ordering::Relaxed) {
585 return;
586 }
587 eprintln!("decode backend: hardware (VA-API plugin)");
588 backend.set(Backend::Hardware);
589 if run_hw(hw, &tx, start_frame, end_frame, &mut render, cancel) {
590 return;
591 }
592 // A driver that opens but cannot decode a single frame is still a
593 // fallback case, not a dead session.
594 eprintln!("hardware decode failed before any frame, falling back to software");
595 }
596 // ...except where there is nothing to fall back to. Feeding HEVC or VP9
597 // bytes to `rusty_h264` would be garbage, not a fallback.
598 if meta.codec != Codec::H264 {
599 eprintln!("{}", meta.codec.needs_plugin());
600 return;
601 }
602 eprintln!("decode backend: software (rusty_h264)");
603 backend.set(Backend::Software);
604 run(demuxer, tx, start_frame, end_frame, &mut render, cancel)
605}
606
607/// One clip's pictures on their way to the renderer: graded, placed on the
608/// project canvas, converted. Both decode loops go through it, so hardware and
609/// software cannot show two different pictures.
610///
611/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
612/// applied at the resolution it was shot at, and the letterbox bars around it
613/// are not the clip -- a brightness grade must not lift them off black.
614///
615/// A project at the media's own resolution never reaches any of that: it takes
616/// the fused graded conversion, the one path this engine had before there was a
617/// project resolution, byte for byte and allocation for allocation.
618struct Render {
619 color: ColorParams,
620 /// What the source's samples mean -- the stream's own matrix and range,
621 /// which is what the conversion below is done in rather than the BT.601 it
622 /// used to assume of every file.
623 desc: ColorDescription,
624 canvas: Composer,
625 /// This stream's HDR-to-SDR map, built once here because building it is
626 /// float work over 9 537 grid nodes and the transfer is a property of the
627 /// stream. `None` for an SDR stream, which is what keeps that path exactly
628 /// the one it was.
629 tone: Option<ToneMapper>,
630 /// The working copy of the source planes, refilled per frame and kept
631 /// across the worker's whole range. Empty unless the clip needs one: it is
632 /// tone-mapped in place, graded in place, or both.
633 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
634}
635
636/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's
637/// output contract ([`crate::tonemap`]), and no longer the HDR space the file
638/// declared.
639const TONE_MAPPED: ColorDescription = ColorDescription {
640 matrix: Matrix::Bt709,
641 transfer: Transfer::Sdr,
642 full_range: false,
643};
644
645impl Render {
646 /// `peak` is what the file declared about its own brightness
647 /// ([`Demuxer::light`]), which only an HDR stream has and only the
648 /// reference rendition reads (see [`tonemap::Preset`]).
649 fn new(
650 color: ColorParams,
651 desc: ColorDescription,
652 canvas: Composer,
653 preset: tonemap::Preset,
654 peak: Option<f32>,
655 ) -> Self {
656 Self {
657 color,
658 desc,
659 canvas,
660 // corner-cut: the ceiling is that the map reads limited-range codes
661 // (`tonemap`'s input contract), so a full-range PQ file -- which
662 // no encoder writes and no camera produces -- is mapped as if it
663 // were limited and comes out slightly crushed. The upgrade is a
664 // range argument to `ToneMapper::new`.
665 tone: match desc.transfer {
666 Transfer::Sdr => None,
667 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)),
668 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
669 },
670 graded: (Vec::new(), Vec::new(), Vec::new()),
671 }
672 }
673
674 fn frame(
675 &mut self,
676 index: u32,
677 y: &[u8],
678 u: &[u8],
679 v: &[u8],
680 width: u32,
681 height: u32,
682 ) -> Frame {
683 let passthrough = self.canvas.is_passthrough(width, height);
684 // Everything that has to happen to the samples before the canvas sees
685 // them, on one copy: the tone map (HDR streams only) and, unless the
686 // conversion below can fuse it, the grade. An SDR stream that is either
687 // ungraded or passing through takes neither and never allocates.
688 //
689 // The grade lands *after* the map on purpose: it is a look on the
690 // picture a viewer is shown, so its brightness and saturation mean what
691 // they say in the SDR the tone map just produced, not in the 10-stop
692 // HDR the file was in.
693 let (y, u, v, desc) = if self.tone.is_some() || (!passthrough && !self.color.is_identity())
694 {
695 let (gy, gu, gv) = &mut self.graded;
696 gy.clear();
697 gy.extend_from_slice(y);
698 gu.clear();
699 gu.extend_from_slice(u);
700 gv.clear();
701 gv.extend_from_slice(v);
702 if let Some(tone) = &self.tone {
703 tone.map(gy, gu, gv, width as usize, height as usize);
704 }
705 if !passthrough && !self.color.is_identity() {
706 crate::color::apply_yuv(&self.color, gy, gu, gv);
707 }
708 let desc = if self.tone.is_some() {
709 TONE_MAPPED
710 } else {
711 self.desc
712 };
713 (&gy[..], &gu[..], &gv[..], desc)
714 } else {
715 (y, u, v, self.desc)
716 };
717 if passthrough {
718 return Frame {
719 index,
720 width,
721 height,
722 bgra: i420_to_bgra_with(
723 &desc,
724 &self.color,
725 y,
726 u,
727 v,
728 width as usize,
729 height as usize,
730 ),
731 };
732 }
733 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
734 Frame {
735 index,
736 width,
737 height,
738 // Ungraded on purpose: the grade is already in the pixels above and
739 // the canvas around them must stay the black it was filled with.
740 bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize),
741 }
742 }
743}
744
745/// One still image, decoded to tightly packed I420 -- the shape every other
746/// source arrives in, so a placed image goes through the same grade, the same
747/// canvas and the same conversion as a decoded picture and there is no second
748/// pixel path to keep in step.
749///
750/// Held whole rather than streamed: an image *is* one picture, and the file is
751/// read once per span that plays it.
752pub(crate) struct Still {
753 pub(crate) y: Vec<u8>,
754 pub(crate) u: Vec<u8>,
755 pub(crate) v: Vec<u8>,
756 pub(crate) width: u32,
757 pub(crate) height: u32,
758}
759
760impl Still {
761 /// Decodes `path`. Refused by name for a picture that is not one
762 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
763 /// file are both held to cannot be walked around by a 30000-pixel-wide PNG.
764 ///
765 /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a
766 /// transparent PNG arrives fully opaque over its own colours rather than
767 /// over the clip beneath it. I420 has nowhere to carry it and this engine
768 /// composes one picture per frame (topmost lane wins), so there is nothing
769 /// for a blend to blend with.
770 ///
771 /// corner-cut: the ceiling is a logo with a transparent background, which
772 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
773 /// giving `scale::Composer` a blend over the lane below.
774 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
775 let reader = image::ImageReader::open(path)?.with_guessed_format()?;
776 let rgb = reader
777 .decode()
778 .map_err(|e| format!("{}: {e}", path.display()))?
779 .to_rgb8();
780 let (width, height) = rgb.dimensions();
781 if !crate::is_resolution(width, height) {
782 return Err(format!(
783 "{} is {width}x{height}, which is not a picture this engine composes",
784 path.display()
785 )
786 .into());
787 }
788 let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize);
789 Ok(Self {
790 y,
791 u,
792 v,
793 width,
794 height,
795 })
796 }
797
798 /// The planes as an export's decoder hands them over, so a still and a
799 /// decoded picture are the same value to `export::run`.
800 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
801 (&self.y, &self.u, &self.v, self.width, self.height)
802 }
803}
804
805/// How big the picture in `path` is, from its header alone -- what a library row
806/// says about a file it has not placed anywhere. The whole file is not decoded.
807pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
808 Ok(image::ImageReader::open(path)?
809 .with_guessed_format()?
810 .into_dimensions()
811 .map_err(|e| format!("{}: {e}", path.display()))?)
812}
813
814/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
815/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why
816/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and
817/// not the timeline's. A still has no stream to be tagged by; it round-trips to
818/// the colour it was authored in through this pair and nothing else sees these
819/// planes (`images::still_pixels_match_the_source_image` measures it).
820///
821/// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
822/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
823/// [`crate::scale::Composer::place`] panics on anything else for.
824fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
825 let (cw, ch) = crate::scale::chroma_dims(width, height);
826 let mut y = vec![0u8; width * height];
827 let mut u = vec![0u8; cw * ch];
828 let mut v = vec![0u8; cw * ch];
829 for row in 0..height {
830 for col in 0..width {
831 let p = (row * width + col) * 3;
832 let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32);
833 y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
834 }
835 }
836 for crow in 0..ch {
837 for ccol in 0..cw {
838 let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32);
839 for row in crow * 2..(crow * 2 + 2).min(height) {
840 for col in ccol * 2..(ccol * 2 + 2).min(width) {
841 let p = (row * width + col) * 3;
842 sr += rgb[p] as i32;
843 sg += rgb[p + 1] as i32;
844 sb += rgb[p + 2] as i32;
845 n += 1;
846 }
847 }
848 let n = n.max(1);
849 let (r, g, b) = (sr / n, sg / n, sb / n);
850 u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
851 v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
852 }
853 }
854 (y, u, v)
855}
856
857/// `None` when the software path must be used: forced by `VE_SW=1`, or the
858/// plugin is absent/broken/unable to open this particular file.
859fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
860 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
861 return None;
862 }
863 HwSession::open_at(path, start_frame)
864}
865
866/// `Ok` when the plugin really decodes this file: it opens *and* hands back a
867/// first picture. Opening only reads the container -- a stream the vendored
868/// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and
869/// then produces nothing, which reaches the user as a black picture with an
870/// instant `eof` unless the door asks for that first frame. Costs one decoded
871/// frame per probe.
872///
873/// The `Err` says which half failed, because "there is no decoder for this
874/// codec" and "the decoder here would not take this stream" are different
875/// refusals and a user acts on them differently.
876fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), String> {
877 let Some(mut hw) = open_hw(path, start_frame) else {
878 return Err(codec.needs_plugin());
879 };
880 // End of stream counts as a refusal, not as a pass: a session that hands
881 // back no picture at all is exactly the black-frame-and-instant-eof this
882 // probe exists to catch, and `Ok(None)` is how the plugin says it.
883 match hw.next_frame() {
884 Ok(Some(_)) => Ok(()),
885 _ => Err(codec.undecodable()),
886 }
887}
888
889/// Returns whether the session was handled; `false` only when hardware decode
890/// failed without emitting a single frame, so software can still take over.
891///
892/// The plugin already positioned itself at `start_frame`, so indices are
893/// counted from there (a stream whose very first sample is not a sync sample
894/// cannot be decoded from its start at all, and is not accounted for).
895fn run_hw(
896 mut hw: HwSession,
897 tx: &SyncSender<Frame>,
898 start_frame: u32,
899 end_frame: u32,
900 render: &mut Render,
901 cancel: &AtomicBool,
902) -> bool {
903 let mut index = start_frame;
904 loop {
905 if cancel.load(Ordering::Relaxed) {
906 return true;
907 }
908 match hw.next_frame() {
909 Ok(Some((y, u, v, width, height))) => {
910 let frame = render.frame(index, y, u, v, width, height);
911 index += 1;
912 if tx.send(frame).is_err() {
913 return true; // consumer went away
914 }
915 if index >= end_frame {
916 return true; // end of the requested range
917 }
918 }
919 Ok(None) => return true,
920 Err(e) => {
921 if index == start_frame {
922 return false;
923 }
924 eprintln!("hardware decode error at frame {index}: {e}");
925 return true;
926 }
927 }
928 }
929}
930
931#[cfg(test)]
932mod tests {
933 use super::*;
934 use std::sync::mpsc::RecvTimeoutError;
935 use std::time::{Duration, Instant};
936
937 fn asset(name: &str) -> PathBuf {
938 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
939 .join("../../assets")
940 .join(name)
941 }
942
943 /// Drops `path` from the page cache, so the open below really goes to disk
944 /// -- the case the deferred opener exists for, and the one that costs
945 /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a
946 /// no-op wherever `python3` is not around: the assertions hold either way,
947 /// the numbers printed are simply the warm ones.
948 fn evict(path: &Path) {
949 let _ = std::process::Command::new("python3")
950 .arg("-c")
951 .arg(
952 "import os,sys\n\
953 fd=os.open(sys.argv[1],os.O_RDONLY)\n\
954 os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\
955 os.close(fd)",
956 )
957 .arg(path)
958 .status();
959 }
960
961 /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller
962 /// gets its stream back in the time a thread takes to spawn, and the file
963 /// is opened behind it -- so the first frame necessarily arrives *after*
964 /// the call returned, and the sync opener on the same cold file pays on the
965 /// calling thread what this one does not.
966 #[test]
967 fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() {
968 let path = asset("test_baseline.mp4");
969 evict(&path);
970 let start = Instant::now();
971 let stream = DecodeSession::open_worker_deferred(
972 &path,
973 0,
974 u32::MAX,
975 ColorParams::default(),
976 Composer::passthrough(),
977 tonemap::Preset::default(),
978 );
979 let returned = start.elapsed();
980 let frame = stream
981 .frames
982 .recv_timeout(Duration::from_secs(10))
983 .expect("first frame");
984 let first_frame = start.elapsed();
985
986 // The same file, equally cold, through the door the import path keeps:
987 // that one hands back metadata, and the demux it reads to do so is on
988 // this thread.
989 evict(&path);
990 let sync_start = Instant::now();
991 let sync = DecodeSession::open_worker(
992 &path,
993 0,
994 u32::MAX,
995 ColorParams::default(),
996 Composer::passthrough(),
997 tonemap::Preset::default(),
998 )
999 .expect("sync open");
1000 let sync_returned = sync_start.elapsed();
1001 drop(sync);
1002
1003 eprintln!(
1004 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
1005 sync open returned in {sync_returned:?}"
1006 );
1007 assert_eq!(frame.index, 0, "the deferred worker starts where it is told");
1008 assert!(
1009 returned < Duration::from_millis(10),
1010 "the caller waited {returned:?} -- something is still being read \
1011 from the file before this returns"
1012 );
1013 assert!(
1014 first_frame > returned,
1015 "the first frame arrived within the call ({first_frame:?} vs \
1016 {returned:?}), which cannot happen if the open is deferred"
1017 );
1018 assert!(
1019 returned < sync_returned,
1020 "the deferred open ({returned:?}) cost as much as the sync one \
1021 ({sync_returned:?}): the demux is still on the caller's thread"
1022 );
1023 }
1024
1025 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
1026 /// The channel is bounded, so such a worker is parked in `send` within a
1027 /// few frames, and the only thing that can wake it is its receiver going
1028 /// away -- which is why the receiver is the first field and the join inside
1029 /// `Worker::drop` is the second. Swap those two fields and this hangs.
1030 ///
1031 /// This is the whole basis of every teardown path in the engine, so it is
1032 /// asserted rather than commented: the drop runs on a second thread and a
1033 /// regression fails in ten seconds instead of hanging the suite forever.
1034 #[test]
1035 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
1036 let (_meta, stream) = DecodeSession::open_worker(
1037 &asset("test_baseline.mp4"),
1038 0,
1039 u32::MAX,
1040 ColorParams::default(),
1041 Composer::passthrough(),
1042 tonemap::Preset::default(),
1043 )
1044 .expect("open");
1045 // Nothing is ever received: two frames fill the channel and the next
1046 // send parks the decode thread, exactly as a refused project load does.
1047 thread::sleep(Duration::from_millis(500));
1048
1049 let (done_tx, done_rx) = sync_channel(1);
1050 thread::spawn(move || {
1051 drop(stream);
1052 let _ = done_tx.send(());
1053 });
1054 assert!(
1055 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
1056 "dropping a parked stream deadlocked: it joined a decode thread \
1057 while still holding the receiver that thread is waiting on"
1058 );
1059 }
1060}
1061
1062fn run(
1063 mut demuxer: Demuxer,
1064 tx: SyncSender<Frame>,
1065 start_frame: u32,
1066 end_frame: u32,
1067 render: &mut Render,
1068 cancel: &AtomicBool,
1069) {
1070 let mut decoder = Decoder::new();
1071 // Decoding has to restart at a sync sample, so pictures between it and
1072 // `start_frame` are decoded (the target frame references them) but never
1073 // converted or sent. Signed, because the landing sync sample can sit inside
1074 // what the file's edit list trims, i.e. *before* frame 0.
1075 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1076
1077 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);
1078 // reordering streams need POC-sorted output before display.
1079 loop {
1080 if cancel.load(Ordering::Relaxed) {
1081 break;
1082 }
1083 let au = match demuxer.next_access_unit() {
1084 Ok(Some(au)) => au,
1085 Ok(None) => break,
1086 Err(e) => {
1087 eprintln!("demux error: {e}");
1088 break;
1089 }
1090 };
1091 let yuv = match decoder.decode(&au) {
1092 Ok(Some(yuv)) => yuv,
1093 Ok(None) => continue,
1094 Err(e) => {
1095 eprintln!("decode error at access unit {index}: {e}");
1096 break;
1097 }
1098 };
1099 if index < i64::from(start_frame) {
1100 index += 1;
1101 continue;
1102 }
1103 let frame = render.frame(
1104 index as u32,
1105 &yuv.y,
1106 &yuv.u,
1107 &yuv.v,
1108 yuv.width as u32,
1109 yuv.height as u32,
1110 );
1111 index += 1;
1112 if tx.send(frame).is_err() {
1113 break; // consumer went away
1114 }
1115 if index >= i64::from(end_frame) {
1116 break; // end of the requested range
1117 }
1118 }
1119}