forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB46e8379Tahinli3 months ago307 commits

decode.rs1096 lines, 42.7 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 if open_hw(&path, 0).is_some() {
122 return Ok((Some(meta.codec), Backend::Hardware));
123 }
124 if meta.codec != Codec::H264 {
125 return Err(meta.codec.needs_plugin().into());
126 }
127 Ok((Some(meta.codec), Backend::Software))
128}
129
130/// A running decode worker: the flag that stops it, and the handle to wait on.
131///
132/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
133/// outlives the process otherwise, and Mesa's `atexit` handlers free the state
134/// it is still reading -- a SIGSEGV at exit, long after the last test passed.
135pub(crate) struct Worker {
136 cancel: Arc<AtomicBool>,
137 /// `None` once detached, and for a range with nothing to decode: either way
138 /// there is no thread left to wait for.
139 handle: Option<thread::JoinHandle<()>>,
140}
141
142impl Worker {
143 /// Stops the worker at its next check without waiting. Callers that replace
144 /// a worker should do this first and drop the receiver second: a worker
145 /// parked in `send` only wakes on the disconnect, so the join below would
146 /// otherwise wait for a consumer that is never coming.
147 pub(crate) fn cancel(&self) {
148 self.cancel.store(true, Ordering::Release);
149 }
150
151 /// Whether the thread has already returned, i.e. dropping this would not
152 /// wait. `true` for a worker that never had a thread. What lets a caller
153 /// park cancelled workers and reap them without ever blocking.
154 pub(crate) fn is_finished(&self) -> bool {
155 self.handle
156 .as_ref()
157 .is_none_or(thread::JoinHandle::is_finished)
158 }
159
160 /// Lets the worker run on unwatched -- what the public API does, since it
161 /// hands out the flag alone.
162 fn detach(mut self) -> Arc<AtomicBool> {
163 self.handle = None;
164 Arc::clone(&self.cancel)
165 }
166}
167
168impl Drop for Worker {
169 fn drop(&mut self) {
170 if let Some(handle) = self.handle.take() {
171 self.cancel();
172 let _ = handle.join();
173 }
174 }
175}
176
177/// A running worker and the frames it is sending, handed out as one value
178/// because they must be *dropped* as one, in this order: the receiver
179/// disconnects first, which is the only thing that wakes a worker parked in a
180/// full `send`, and the join inside [`Worker::drop`] runs second.
181///
182/// Rust drops fields in declaration order, so this struct *is* that rule, and
183/// it holds wherever the value goes: an early return out of a half-built
184/// session, an unwind, a caller not written yet. Two separate locals do not
185/// hold it -- they drop in reverse order of declaration, so the worker there
186/// joins a thread nobody will ever drain, which is a hang and not a slow path.
187pub(crate) struct FrameStream {
188 pub(crate) frames: Receiver<Frame>,
189 pub(crate) worker: Worker,
190 /// What this stream's pictures are being decoded by. Dropped last and read
191 /// by the caller, so it outlives nothing and blocks nothing.
192 pub(crate) backend: BackendCell,
193}
194
195pub struct DecodeSession;
196
197impl DecodeSession {
198 /// Opens `path`, returning stream metadata immediately and a receiver that
199 /// yields frames as the worker decodes them. The worker stops when the
200 /// receiver is dropped, at end of stream, or on the first decode error.
201 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
202 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
203 Ok((meta, rx))
204 }
205
206 /// As [`DecodeSession::open`], but the first frame delivered is
207 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
208 /// Setting the returned flag stops the worker at its next access unit,
209 /// which is how a caller abandons a session it no longer wants to drain.
210 pub fn open_at(
211 path: impl AsRef<Path>,
212 start_frame: u32,
213 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
214 // `u32::MAX` is clamped to the stream's frame count below, so this is
215 // "to the end of the file".
216 Self::open_range(path, start_frame, u32::MAX)
217 }
218
219 /// As [`DecodeSession::open_at`], but the worker also stops on its own
220 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
221 /// absolute source frames, which is what a clip of a longer file needs.
222 /// `end_frame` is capped at the stream's frame count, and an empty range
223 /// yields a receiver that is simply already disconnected.
224 pub fn open_range(
225 path: impl AsRef<Path>,
226 start_frame: u32,
227 end_frame: u32,
228 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
229 // Ungraded: the public API opens a *file*, and a colour grade belongs to
230 // a clip of a timeline. `PlaybackSession` is what has one to pass.
231 let (meta, stream) = Self::open_worker(
232 path,
233 start_frame,
234 end_frame,
235 ColorParams::default(),
236 // No project, no canvas: the file-level API hands back the
237 // pictures the file holds, at the size it holds them.
238 Composer::passthrough(),
239 // ...and no project means no picked rendition either: an HDR file
240 // opened through this door is mapped the published way.
241 tonemap::Preset::default(),
242 )?;
243 // The public API hands out the flag alone, so the worker is detached and
244 // the receiver goes to the caller: nothing here joins anything.
245 Ok((meta, stream.frames, stream.worker.detach()))
246 }
247
248 /// A worker that decodes nothing and emits `len` black frames, indexed from
249 /// zero -- what a *gap* in the video lane looks like. It goes down the same
250 /// channel as decoded frames, so a gap costs the caller no branch at all
251 /// beyond choosing this opener: same bounded channel, same backpressure,
252 /// same cancel, same retire path.
253 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
254 let (tx, rx) = sync_channel(2);
255 let cancel = Arc::new(AtomicBool::new(false));
256 if len == 0 {
257 return FrameStream {
258 frames: rx,
259 worker: Worker {
260 cancel,
261 handle: None,
262 },
263 backend: BackendCell::new(Backend::Gap),
264 };
265 }
266 let worker_cancel = Arc::clone(&cancel);
267 // One buffer, cloned per frame: opaque black is a constant, and the
268 // clone is a memcpy against a decode this replaces entirely.
269 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
270 let handle = thread::Builder::new()
271 .name("black".into())
272 .spawn(move || {
273 for index in 0..len {
274 if worker_cancel.load(Ordering::Relaxed) {
275 return;
276 }
277 let frame = Frame {
278 index,
279 width,
280 height,
281 bgra: black.clone(),
282 };
283 if tx.send(frame).is_err() {
284 return; // caller moved on
285 }
286 }
287 })
288 .ok();
289 FrameStream {
290 frames: rx,
291 worker: Worker { cancel, handle },
292 backend: BackendCell::new(Backend::Gap),
293 }
294 }
295
296 /// A worker for a still image ([`crate::is_image`]): the file is decoded
297 /// *once* and the same picture goes down the channel `len` times, indexed
298 /// from `start_frame` exactly as a decoder's pictures are -- so a placed
299 /// image is a clip like any other to everything downstream (`try_frame`
300 /// rewrites those indices, `next_clip` walks off the end of the range).
301 ///
302 /// Graded and placed on the canvas once too, before the repeat: a still is
303 /// the same pixels every frame, so the whole cost of one is one conversion
304 /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays.
305 pub(crate) fn open_still(
306 path: &Path,
307 start_frame: u32,
308 len: u32,
309 color: ColorParams,
310 canvas: Composer,
311 ) -> crate::Result<FrameStream> {
312 let still = Still::open(path)?;
313 let (tx, rx) = sync_channel(2);
314 let cancel = Arc::new(AtomicBool::new(false));
315 if len == 0 {
316 return Ok(FrameStream {
317 frames: rx,
318 worker: Worker {
319 cancel,
320 handle: None,
321 },
322 backend: BackendCell::new(Backend::Still),
323 });
324 }
325 // The one conversion, on this thread: it is a few milliseconds and the
326 // error it could raise has already been raised by `Still::open`.
327 // BT.601 limited, because that is what `rgb_to_i420` above wrote these
328 // planes in: a still round-trips through the pair, not through the
329 // colour of whatever file is on the timeline beside it.
330 // No preset argument, and none wanted: a still is decoded into BT.601
331 // SDR planes, so the tone map is not built at all whichever rendition
332 // the project is watching.
333 let first = Render::new(
334 color,
335 ColorDescription::default(),
336 canvas,
337 tonemap::Preset::default(),
338 // ...and no declared peak either, for the same reason: there is no
339 // tone map on this path to hand one to.
340 None,
341 )
342 .frame(
343 start_frame,
344 &still.y,
345 &still.u,
346 &still.v,
347 still.width,
348 still.height,
349 );
350 let worker_cancel = Arc::clone(&cancel);
351 let handle = thread::Builder::new()
352 .name("still".into())
353 .spawn(move || {
354 let (width, height, bgra) = (first.width, first.height, first.bgra);
355 for index in 0..len {
356 if worker_cancel.load(Ordering::Relaxed) {
357 return;
358 }
359 let frame = Frame {
360 index: start_frame + index,
361 width,
362 height,
363 bgra: bgra.clone(),
364 };
365 if tx.send(frame).is_err() {
366 return; // caller moved on
367 }
368 }
369 })
370 .ok();
371 Ok(FrameStream {
372 frames: rx,
373 worker: Worker { cancel, handle },
374 backend: BackendCell::new(Backend::Still),
375 })
376 }
377
378 /// As [`DecodeSession::open_range`], but the caller gets the whole
379 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
380 /// `color` -- the clip's own setting, folded into the conversion the frames
381 /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
382 /// than read per frame because a worker *is* one clip's range: a grade
383 /// changed while this one runs reaches the picture when the session reseeks
384 /// onto the new one, which every edit does.
385 ///
386 /// In-process only: a caller that outlives its workers has to be able to
387 /// join them at exit.
388 ///
389 /// `canvas` is the project's own resolution and this clip's fit policy: the
390 /// frames come out at *that* size, whatever the file's is. A
391 /// [`Composer::passthrough`] (or one already the source's size) leaves every
392 /// picture exactly as it was decoded.
393 ///
394 /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured
395 /// here for the reason the grade is: it is constant across one span, and a
396 /// preset picked while this worker runs reaches the picture when the session
397 /// reseeks onto the new one. An SDR source ignores it entirely.
398 pub(crate) fn open_worker(
399 path: impl AsRef<Path>,
400 start_frame: u32,
401 end_frame: u32,
402 color: ColorParams,
403 canvas: Composer,
404 tone: tonemap::Preset,
405 ) -> crate::Result<(VideoMeta, FrameStream)> {
406 let path = path.as_ref().to_path_buf();
407 let (meta, demuxer) = Demuxer::open(&path)?;
408 // No software HEVC or VP9 decoder exists, so such a file the plugin will
409 // not take is refused *here*, where the caller still has somewhere to
410 // show it -- a worker that opened and then produced nothing is a black
411 // screen with no explanation. The probe session is opened and dropped:
412 // it costs one extra VA-API init (~90 ms) and only off the H.264 path.
413 if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() {
414 return Err(meta.codec.needs_plugin().into());
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 // ponytail: 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 /// ponytail: 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/// Returns whether the session was handled; `false` only when hardware decode
867/// failed without emitting a single frame, so software can still take over.
868///
869/// The plugin already positioned itself at `start_frame`, so indices are
870/// counted from there (a stream whose very first sample is not a sync sample
871/// cannot be decoded from its start at all, and is not accounted for).
872fn run_hw(
873 mut hw: HwSession,
874 tx: &SyncSender<Frame>,
875 start_frame: u32,
876 end_frame: u32,
877 render: &mut Render,
878 cancel: &AtomicBool,
879) -> bool {
880 let mut index = start_frame;
881 loop {
882 if cancel.load(Ordering::Relaxed) {
883 return true;
884 }
885 match hw.next_frame() {
886 Ok(Some((y, u, v, width, height))) => {
887 let frame = render.frame(index, y, u, v, width, height);
888 index += 1;
889 if tx.send(frame).is_err() {
890 return true; // consumer went away
891 }
892 if index >= end_frame {
893 return true; // end of the requested range
894 }
895 }
896 Ok(None) => return true,
897 Err(e) => {
898 if index == start_frame {
899 return false;
900 }
901 eprintln!("hardware decode error at frame {index}: {e}");
902 return true;
903 }
904 }
905 }
906}
907
908#[cfg(test)]
909mod tests {
910 use super::*;
911 use std::sync::mpsc::RecvTimeoutError;
912 use std::time::{Duration, Instant};
913
914 fn asset(name: &str) -> PathBuf {
915 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
916 .join("../../assets")
917 .join(name)
918 }
919
920 /// Drops `path` from the page cache, so the open below really goes to disk
921 /// -- the case the deferred opener exists for, and the one that costs
922 /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a
923 /// no-op wherever `python3` is not around: the assertions hold either way,
924 /// the numbers printed are simply the warm ones.
925 fn evict(path: &Path) {
926 let _ = std::process::Command::new("python3")
927 .arg("-c")
928 .arg(
929 "import os,sys\n\
930 fd=os.open(sys.argv[1],os.O_RDONLY)\n\
931 os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\
932 os.close(fd)",
933 )
934 .arg(path)
935 .status();
936 }
937
938 /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller
939 /// gets its stream back in the time a thread takes to spawn, and the file
940 /// is opened behind it -- so the first frame necessarily arrives *after*
941 /// the call returned, and the sync opener on the same cold file pays on the
942 /// calling thread what this one does not.
943 #[test]
944 fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() {
945 let path = asset("test_baseline.mp4");
946 evict(&path);
947 let start = Instant::now();
948 let stream = DecodeSession::open_worker_deferred(
949 &path,
950 0,
951 u32::MAX,
952 ColorParams::default(),
953 Composer::passthrough(),
954 tonemap::Preset::default(),
955 );
956 let returned = start.elapsed();
957 let frame = stream
958 .frames
959 .recv_timeout(Duration::from_secs(10))
960 .expect("first frame");
961 let first_frame = start.elapsed();
962
963 // The same file, equally cold, through the door the import path keeps:
964 // that one hands back metadata, and the demux it reads to do so is on
965 // this thread.
966 evict(&path);
967 let sync_start = Instant::now();
968 let sync = DecodeSession::open_worker(
969 &path,
970 0,
971 u32::MAX,
972 ColorParams::default(),
973 Composer::passthrough(),
974 tonemap::Preset::default(),
975 )
976 .expect("sync open");
977 let sync_returned = sync_start.elapsed();
978 drop(sync);
979
980 eprintln!(
981 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
982 sync open returned in {sync_returned:?}"
983 );
984 assert_eq!(frame.index, 0, "the deferred worker starts where it is told");
985 assert!(
986 returned < Duration::from_millis(10),
987 "the caller waited {returned:?} -- something is still being read \
988 from the file before this returns"
989 );
990 assert!(
991 first_frame > returned,
992 "the first frame arrived within the call ({first_frame:?} vs \
993 {returned:?}), which cannot happen if the open is deferred"
994 );
995 assert!(
996 returned < sync_returned,
997 "the deferred open ({returned:?}) cost as much as the sync one \
998 ({sync_returned:?}): the demux is still on the caller's thread"
999 );
1000 }
1001
1002 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
1003 /// The channel is bounded, so such a worker is parked in `send` within a
1004 /// few frames, and the only thing that can wake it is its receiver going
1005 /// away -- which is why the receiver is the first field and the join inside
1006 /// `Worker::drop` is the second. Swap those two fields and this hangs.
1007 ///
1008 /// This is the whole basis of every teardown path in the engine, so it is
1009 /// asserted rather than commented: the drop runs on a second thread and a
1010 /// regression fails in ten seconds instead of hanging the suite forever.
1011 #[test]
1012 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
1013 let (_meta, stream) = DecodeSession::open_worker(
1014 &asset("test_baseline.mp4"),
1015 0,
1016 u32::MAX,
1017 ColorParams::default(),
1018 Composer::passthrough(),
1019 tonemap::Preset::default(),
1020 )
1021 .expect("open");
1022 // Nothing is ever received: two frames fill the channel and the next
1023 // send parks the decode thread, exactly as a refused project load does.
1024 thread::sleep(Duration::from_millis(500));
1025
1026 let (done_tx, done_rx) = sync_channel(1);
1027 thread::spawn(move || {
1028 drop(stream);
1029 let _ = done_tx.send(());
1030 });
1031 assert!(
1032 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
1033 "dropping a parked stream deadlocked: it joined a decode thread \
1034 while still holding the receiver that thread is waiting on"
1035 );
1036 }
1037}
1038
1039fn run(
1040 mut demuxer: Demuxer,
1041 tx: SyncSender<Frame>,
1042 start_frame: u32,
1043 end_frame: u32,
1044 render: &mut Render,
1045 cancel: &AtomicBool,
1046) {
1047 let mut decoder = Decoder::new();
1048 // Decoding has to restart at a sync sample, so pictures between it and
1049 // `start_frame` are decoded (the target frame references them) but never
1050 // converted or sent. Signed, because the landing sync sample can sit inside
1051 // what the file's edit list trims, i.e. *before* frame 0.
1052 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1053
1054 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
1055 // reordering streams need POC-sorted output before display.
1056 loop {
1057 if cancel.load(Ordering::Relaxed) {
1058 break;
1059 }
1060 let au = match demuxer.next_access_unit() {
1061 Ok(Some(au)) => au,
1062 Ok(None) => break,
1063 Err(e) => {
1064 eprintln!("demux error: {e}");
1065 break;
1066 }
1067 };
1068 let yuv = match decoder.decode(&au) {
1069 Ok(Some(yuv)) => yuv,
1070 Ok(None) => continue,
1071 Err(e) => {
1072 eprintln!("decode error at access unit {index}: {e}");
1073 break;
1074 }
1075 };
1076 if index < i64::from(start_frame) {
1077 index += 1;
1078 continue;
1079 }
1080 let frame = render.frame(
1081 index as u32,
1082 &yuv.y,
1083 &yuv.u,
1084 &yuv.v,
1085 yuv.width as u32,
1086 yuv.height as u32,
1087 );
1088 index += 1;
1089 if tx.send(frame).is_err() {
1090 break; // consumer went away
1091 }
1092 if index >= i64::from(end_frame) {
1093 break; // end of the requested range
1094 }
1095 }
1096}