forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa2e4154Tahinli3 months ago297 commits

decode.rs916 lines, 36.1 KiBHistoryRawDownload
1//! Background decode worker. Frames leave over a bounded channel so the caller's
2//! thread (the UI thread) never blocks on decode and memory stays capped.
3
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, AtomicU8, 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 // Read off the file once, here, and carried into the worker: it is a
418 // property of the stream, so it cannot change while one range decodes.
419 let source_color = meta.color;
420 // ...and with it what the film says its own brightest picture is
421 // ([`Demuxer::light`]): the tone map's assumed peak on the reference
422 // rendition, so a 1759 cd/m^2 grade is converted at 1759 rather than at
423 // the 1000 a file that declared nothing is assumed at. Read here
424 // because the demuxer is moved into the worker below.
425 let declared_peak = demuxer.light().peak();
426 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
427 // decoder run ahead of the display without limit.
428 let (tx, rx) = sync_channel(2);
429 let cancel = Arc::new(AtomicBool::new(false));
430 // Written by the worker below the moment it knows, so a caller reading
431 // it sees what opened rather than what was hoped for.
432 let backend = BackendCell::default();
433 if end_frame <= start_frame {
434 // Nothing to decode: dropping `tx` here closes the channel cleanly,
435 // so the caller sees an immediate end of stream rather than an error.
436 return Ok((
437 meta,
438 FrameStream {
439 frames: rx,
440 worker: Worker {
441 cancel,
442 handle: None,
443 },
444 backend,
445 },
446 ));
447 }
448 let worker_cancel = Arc::clone(&cancel);
449 let worker_backend = backend.clone();
450 let handle = thread::Builder::new()
451 .name("decode".into())
452 .spawn(move || {
453 // Cancelled before this thread was even scheduled -- do not
454 // enter VA-API initialisation at all, because that is the one
455 // stretch a cancel cannot interrupt (~65-90 ms of driver setup
456 // that would then have to be torn down again).
457 if worker_cancel.load(Ordering::Relaxed) {
458 return;
459 }
460 let mut render = Render::new(color, source_color, canvas, tone, declared_peak);
461 // The plugin has to be opened on the thread that uses it: its
462 // VA-API state is not `Send`-safe across a later hand-off.
463 if let Some(hw) = open_hw(&path, start_frame) {
464 // Cancelled *during* init: close the session (dropping `hw`
465 // does it) and leave without decoding anything.
466 if worker_cancel.load(Ordering::Relaxed) {
467 return;
468 }
469 eprintln!("decode backend: hardware (VA-API plugin)");
470 worker_backend.set(Backend::Hardware);
471 if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) {
472 return;
473 }
474 // A driver that opens but cannot decode a single frame is
475 // still a fallback case, not a dead session.
476 eprintln!("hardware decode failed before any frame, falling back to software");
477 }
478 // ...except where there is nothing to fall back to. Feeding HEVC
479 // or VP9 bytes to `rusty_h264` would be garbage, not a fallback.
480 if meta.codec != Codec::H264 {
481 eprintln!("{}", meta.codec.needs_plugin());
482 return;
483 }
484 eprintln!("decode backend: software (rusty_h264)");
485 worker_backend.set(Backend::Software);
486 run(
487 demuxer,
488 tx,
489 start_frame,
490 end_frame,
491 &mut render,
492 &worker_cancel,
493 )
494 })?;
495 Ok((
496 meta,
497 FrameStream {
498 frames: rx,
499 worker: Worker {
500 cancel,
501 handle: Some(handle),
502 },
503 backend,
504 },
505 ))
506 }
507}
508
509/// One clip's pictures on their way to the renderer: graded, placed on the
510/// project canvas, converted. Both decode loops go through it, so hardware and
511/// software cannot show two different pictures.
512///
513/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
514/// applied at the resolution it was shot at, and the letterbox bars around it
515/// are not the clip -- a brightness grade must not lift them off black.
516///
517/// A project at the media's own resolution never reaches any of that: it takes
518/// the fused graded conversion, the one path this engine had before there was a
519/// project resolution, byte for byte and allocation for allocation.
520struct Render {
521 color: ColorParams,
522 /// What the source's samples mean -- the stream's own matrix and range,
523 /// which is what the conversion below is done in rather than the BT.601 it
524 /// used to assume of every file.
525 desc: ColorDescription,
526 canvas: Composer,
527 /// This stream's HDR-to-SDR map, built once here because building it is
528 /// float work over 9 537 grid nodes and the transfer is a property of the
529 /// stream. `None` for an SDR stream, which is what keeps that path exactly
530 /// the one it was.
531 tone: Option<ToneMapper>,
532 /// The working copy of the source planes, refilled per frame and kept
533 /// across the worker's whole range. Empty unless the clip needs one: it is
534 /// tone-mapped in place, graded in place, or both.
535 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
536}
537
538/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's
539/// output contract ([`crate::tonemap`]), and no longer the HDR space the file
540/// declared.
541const TONE_MAPPED: ColorDescription = ColorDescription {
542 matrix: Matrix::Bt709,
543 transfer: Transfer::Sdr,
544 full_range: false,
545};
546
547impl Render {
548 /// `peak` is what the file declared about its own brightness
549 /// ([`Demuxer::light`]), which only an HDR stream has and only the
550 /// reference rendition reads (see [`tonemap::Preset`]).
551 fn new(
552 color: ColorParams,
553 desc: ColorDescription,
554 canvas: Composer,
555 preset: tonemap::Preset,
556 peak: Option<f32>,
557 ) -> Self {
558 Self {
559 color,
560 desc,
561 canvas,
562 // ponytail: the ceiling is that the map reads limited-range codes
563 // (`tonemap`'s input contract), so a full-range PQ file -- which
564 // no encoder writes and no camera produces -- is mapped as if it
565 // were limited and comes out slightly crushed. The upgrade is a
566 // range argument to `ToneMapper::new`.
567 tone: match desc.transfer {
568 Transfer::Sdr => None,
569 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)),
570 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
571 },
572 graded: (Vec::new(), Vec::new(), Vec::new()),
573 }
574 }
575
576 fn frame(
577 &mut self,
578 index: u32,
579 y: &[u8],
580 u: &[u8],
581 v: &[u8],
582 width: u32,
583 height: u32,
584 ) -> Frame {
585 let passthrough = self.canvas.is_passthrough(width, height);
586 // Everything that has to happen to the samples before the canvas sees
587 // them, on one copy: the tone map (HDR streams only) and, unless the
588 // conversion below can fuse it, the grade. An SDR stream that is either
589 // ungraded or passing through takes neither and never allocates.
590 //
591 // The grade lands *after* the map on purpose: it is a look on the
592 // picture a viewer is shown, so its brightness and saturation mean what
593 // they say in the SDR the tone map just produced, not in the 10-stop
594 // HDR the file was in.
595 let (y, u, v, desc) = if self.tone.is_some() || (!passthrough && !self.color.is_identity())
596 {
597 let (gy, gu, gv) = &mut self.graded;
598 gy.clear();
599 gy.extend_from_slice(y);
600 gu.clear();
601 gu.extend_from_slice(u);
602 gv.clear();
603 gv.extend_from_slice(v);
604 if let Some(tone) = &self.tone {
605 tone.map(gy, gu, gv, width as usize, height as usize);
606 }
607 if !passthrough && !self.color.is_identity() {
608 crate::color::apply_yuv(&self.color, gy, gu, gv);
609 }
610 let desc = if self.tone.is_some() {
611 TONE_MAPPED
612 } else {
613 self.desc
614 };
615 (&gy[..], &gu[..], &gv[..], desc)
616 } else {
617 (y, u, v, self.desc)
618 };
619 if passthrough {
620 return Frame {
621 index,
622 width,
623 height,
624 bgra: i420_to_bgra_with(
625 &desc,
626 &self.color,
627 y,
628 u,
629 v,
630 width as usize,
631 height as usize,
632 ),
633 };
634 }
635 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
636 Frame {
637 index,
638 width,
639 height,
640 // Ungraded on purpose: the grade is already in the pixels above and
641 // the canvas around them must stay the black it was filled with.
642 bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize),
643 }
644 }
645}
646
647/// One still image, decoded to tightly packed I420 -- the shape every other
648/// source arrives in, so a placed image goes through the same grade, the same
649/// canvas and the same conversion as a decoded picture and there is no second
650/// pixel path to keep in step.
651///
652/// Held whole rather than streamed: an image *is* one picture, and the file is
653/// read once per span that plays it.
654pub(crate) struct Still {
655 pub(crate) y: Vec<u8>,
656 pub(crate) u: Vec<u8>,
657 pub(crate) v: Vec<u8>,
658 pub(crate) width: u32,
659 pub(crate) height: u32,
660}
661
662impl Still {
663 /// Decodes `path`. Refused by name for a picture that is not one
664 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
665 /// file are both held to cannot be walked around by a 30000-pixel-wide PNG.
666 ///
667 /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a
668 /// transparent PNG arrives fully opaque over its own colours rather than
669 /// over the clip beneath it. I420 has nowhere to carry it and this engine
670 /// composes one picture per frame (topmost lane wins), so there is nothing
671 /// for a blend to blend with.
672 ///
673 /// ponytail: the ceiling is a logo with a transparent background, which
674 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
675 /// giving `scale::Composer` a blend over the lane below.
676 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
677 let reader = image::ImageReader::open(path)?.with_guessed_format()?;
678 let rgb = reader
679 .decode()
680 .map_err(|e| format!("{}: {e}", path.display()))?
681 .to_rgb8();
682 let (width, height) = rgb.dimensions();
683 if !crate::is_resolution(width, height) {
684 return Err(format!(
685 "{} is {width}x{height}, which is not a picture this engine composes",
686 path.display()
687 )
688 .into());
689 }
690 let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize);
691 Ok(Self {
692 y,
693 u,
694 v,
695 width,
696 height,
697 })
698 }
699
700 /// The planes as an export's decoder hands them over, so a still and a
701 /// decoded picture are the same value to `export::run`.
702 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
703 (&self.y, &self.u, &self.v, self.width, self.height)
704 }
705}
706
707/// How big the picture in `path` is, from its header alone -- what a library row
708/// says about a file it has not placed anywhere. The whole file is not decoded.
709pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
710 Ok(image::ImageReader::open(path)?
711 .with_guessed_format()?
712 .into_dimensions()
713 .map_err(|e| format!("{}: {e}", path.display()))?)
714}
715
716/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
717/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why
718/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and
719/// not the timeline's. A still has no stream to be tagged by; it round-trips to
720/// the colour it was authored in through this pair and nothing else sees these
721/// planes (`images::still_pixels_match_the_source_image` measures it).
722///
723/// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
724/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
725/// [`crate::scale::Composer::place`] panics on anything else for.
726fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
727 let (cw, ch) = crate::scale::chroma_dims(width, height);
728 let mut y = vec![0u8; width * height];
729 let mut u = vec![0u8; cw * ch];
730 let mut v = vec![0u8; cw * ch];
731 for row in 0..height {
732 for col in 0..width {
733 let p = (row * width + col) * 3;
734 let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32);
735 y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
736 }
737 }
738 for crow in 0..ch {
739 for ccol in 0..cw {
740 let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32);
741 for row in crow * 2..(crow * 2 + 2).min(height) {
742 for col in ccol * 2..(ccol * 2 + 2).min(width) {
743 let p = (row * width + col) * 3;
744 sr += rgb[p] as i32;
745 sg += rgb[p + 1] as i32;
746 sb += rgb[p + 2] as i32;
747 n += 1;
748 }
749 }
750 let n = n.max(1);
751 let (r, g, b) = (sr / n, sg / n, sb / n);
752 u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
753 v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
754 }
755 }
756 (y, u, v)
757}
758
759/// `None` when the software path must be used: forced by `VE_SW=1`, or the
760/// plugin is absent/broken/unable to open this particular file.
761fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
762 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
763 return None;
764 }
765 HwSession::open_at(path, start_frame)
766}
767
768/// Returns whether the session was handled; `false` only when hardware decode
769/// failed without emitting a single frame, so software can still take over.
770///
771/// The plugin already positioned itself at `start_frame`, so indices are
772/// counted from there (a stream whose very first sample is not a sync sample
773/// cannot be decoded from its start at all, and is not accounted for).
774fn run_hw(
775 mut hw: HwSession,
776 tx: &SyncSender<Frame>,
777 start_frame: u32,
778 end_frame: u32,
779 render: &mut Render,
780 cancel: &AtomicBool,
781) -> bool {
782 let mut index = start_frame;
783 loop {
784 if cancel.load(Ordering::Relaxed) {
785 return true;
786 }
787 match hw.next_frame() {
788 Ok(Some((y, u, v, width, height))) => {
789 let frame = render.frame(index, y, u, v, width, height);
790 index += 1;
791 if tx.send(frame).is_err() {
792 return true; // consumer went away
793 }
794 if index >= end_frame {
795 return true; // end of the requested range
796 }
797 }
798 Ok(None) => return true,
799 Err(e) => {
800 if index == start_frame {
801 return false;
802 }
803 eprintln!("hardware decode error at frame {index}: {e}");
804 return true;
805 }
806 }
807 }
808}
809
810#[cfg(test)]
811mod tests {
812 use super::*;
813 use std::sync::mpsc::RecvTimeoutError;
814 use std::time::Duration;
815
816 fn asset(name: &str) -> PathBuf {
817 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
818 .join("../../assets")
819 .join(name)
820 }
821
822 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
823 /// The channel is bounded, so such a worker is parked in `send` within a
824 /// few frames, and the only thing that can wake it is its receiver going
825 /// away -- which is why the receiver is the first field and the join inside
826 /// `Worker::drop` is the second. Swap those two fields and this hangs.
827 ///
828 /// This is the whole basis of every teardown path in the engine, so it is
829 /// asserted rather than commented: the drop runs on a second thread and a
830 /// regression fails in ten seconds instead of hanging the suite forever.
831 #[test]
832 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
833 let (_meta, stream) = DecodeSession::open_worker(
834 &asset("test_baseline.mp4"),
835 0,
836 u32::MAX,
837 ColorParams::default(),
838 Composer::passthrough(),
839 tonemap::Preset::default(),
840 )
841 .expect("open");
842 // Nothing is ever received: two frames fill the channel and the next
843 // send parks the decode thread, exactly as a refused project load does.
844 thread::sleep(Duration::from_millis(500));
845
846 let (done_tx, done_rx) = sync_channel(1);
847 thread::spawn(move || {
848 drop(stream);
849 let _ = done_tx.send(());
850 });
851 assert!(
852 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
853 "dropping a parked stream deadlocked: it joined a decode thread \
854 while still holding the receiver that thread is waiting on"
855 );
856 }
857}
858
859fn run(
860 mut demuxer: Demuxer,
861 tx: SyncSender<Frame>,
862 start_frame: u32,
863 end_frame: u32,
864 render: &mut Render,
865 cancel: &AtomicBool,
866) {
867 let mut decoder = Decoder::new();
868 // Decoding has to restart at a sync sample, so pictures between it and
869 // `start_frame` are decoded (the target frame references them) but never
870 // converted or sent. Signed, because the landing sync sample can sit inside
871 // what the file's edit list trims, i.e. *before* frame 0.
872 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
873
874 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
875 // reordering streams need POC-sorted output before display.
876 loop {
877 if cancel.load(Ordering::Relaxed) {
878 break;
879 }
880 let au = match demuxer.next_access_unit() {
881 Ok(Some(au)) => au,
882 Ok(None) => break,
883 Err(e) => {
884 eprintln!("demux error: {e}");
885 break;
886 }
887 };
888 let yuv = match decoder.decode(&au) {
889 Ok(Some(yuv)) => yuv,
890 Ok(None) => continue,
891 Err(e) => {
892 eprintln!("decode error at access unit {index}: {e}");
893 break;
894 }
895 };
896 if index < i64::from(start_frame) {
897 index += 1;
898 continue;
899 }
900 let frame = render.frame(
901 index as u32,
902 &yuv.y,
903 &yuv.u,
904 &yuv.v,
905 yuv.width as u32,
906 yuv.height as u32,
907 );
908 index += 1;
909 if tx.send(frame).is_err() {
910 break; // consumer went away
911 }
912 if index >= i64::from(end_frame) {
913 break; // end of the requested range
914 }
915 }
916}