forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2b647eaTahinli3 months ago190 commits

decode.rs810 lines, 31.0 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::convert::{i420_to_bgra, i420_to_bgra_with};
14use crate::demux::{Codec, Demuxer, VideoMeta};
15use crate::hw::HwSession;
16use crate::scale::Composer;
17
18/// One decoded picture, ready to hand to a renderer.
19pub struct Frame {
20 /// Position in decode order, starting at 0.
21 pub index: u32,
22 pub width: u32,
23 pub height: u32,
24 /// BGRA8, straight alpha, tightly packed.
25 pub bgra: Vec<u8>,
26}
27
28/// Which decoder a source is really running on. Read-only introspection: it
29/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose --
30/// a hardware session that opened and then failed before its first picture
31/// falls back to software and this says so, because it is written where the
32/// fallback happens rather than where it was hoped for.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub enum Backend {
35 /// The worker has not reached its decoder yet: the plugin's VA-API init is
36 /// ~90 ms, and this is what a caller reads in that window.
37 #[default]
38 Opening,
39 /// The VA-API plugin (`libengine_hw.so`).
40 Hardware,
41 /// `rusty_h264`, in this process.
42 Software,
43 /// A still image: one `image` decode, no stream and no decoder to pick.
44 Still,
45 /// A gap: black frames, nothing decoded at all.
46 Gap,
47}
48
49impl Backend {
50 /// Short enough for a library row and a transport line.
51 pub fn label(self) -> &'static str {
52 match self {
53 Self::Opening => "opening",
54 Self::Hardware => "HW",
55 Self::Software => "SW",
56 Self::Still => "still",
57 Self::Gap => "gap",
58 }
59 }
60
61 fn code(self) -> u8 {
62 match self {
63 Self::Opening => 0,
64 Self::Hardware => 1,
65 Self::Software => 2,
66 Self::Still => 3,
67 Self::Gap => 4,
68 }
69 }
70
71 fn from_code(code: u8) -> Self {
72 match code {
73 1 => Self::Hardware,
74 2 => Self::Software,
75 3 => Self::Still,
76 4 => Self::Gap,
77 _ => Self::Opening,
78 }
79 }
80}
81
82/// Where a worker publishes the decoder it opened, for whoever holds the other
83/// end of its channel. One atomic byte, written once at open (and once more if
84/// hardware hands the range back to software), read whenever a caller repaints
85/// -- never per frame on either side.
86#[derive(Clone, Default)]
87pub struct BackendCell(Arc<AtomicU8>);
88
89impl BackendCell {
90 fn new(backend: Backend) -> Self {
91 Self(Arc::new(AtomicU8::new(backend.code())))
92 }
93
94 fn set(&self, backend: Backend) {
95 self.0.store(backend.code(), Ordering::Relaxed);
96 }
97
98 pub fn get(&self) -> Backend {
99 Backend::from_code(self.0.load(Ordering::Relaxed))
100 }
101}
102
103/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`]
104/// decides it: the same `VE_SW` pin and the same plugin probe against this very
105/// file. What lets a front-end name the decoder *before* anything plays.
106///
107/// The codec is `None` for a still image, which has no coded stream. A stream
108/// no decoder here can take is an `Err` naming the plugin, exactly as opening
109/// it would be -- the same refusal, one VA-API init earlier.
110///
111/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per
112/// file, off a render thread, and keep the answer.
113pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
114 if crate::is_image(path) {
115 return Ok((None, Backend::Still));
116 }
117 let path = path.to_path_buf();
118 let (meta, _demuxer) = Demuxer::open(&path)?;
119 if open_hw(&path, 0).is_some() {
120 return Ok((Some(meta.codec), Backend::Hardware));
121 }
122 if meta.codec != Codec::H264 {
123 return Err(meta.codec.needs_plugin().into());
124 }
125 Ok((Some(meta.codec), Backend::Software))
126}
127
128/// A running decode worker: the flag that stops it, and the handle to wait on.
129///
130/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
131/// outlives the process otherwise, and Mesa's `atexit` handlers free the state
132/// it is still reading -- a SIGSEGV at exit, long after the last test passed.
133pub(crate) struct Worker {
134 cancel: Arc<AtomicBool>,
135 /// `None` once detached, and for a range with nothing to decode: either way
136 /// there is no thread left to wait for.
137 handle: Option<thread::JoinHandle<()>>,
138}
139
140impl Worker {
141 /// Stops the worker at its next check without waiting. Callers that replace
142 /// a worker should do this first and drop the receiver second: a worker
143 /// parked in `send` only wakes on the disconnect, so the join below would
144 /// otherwise wait for a consumer that is never coming.
145 pub(crate) fn cancel(&self) {
146 self.cancel.store(true, Ordering::Release);
147 }
148
149 /// Whether the thread has already returned, i.e. dropping this would not
150 /// wait. `true` for a worker that never had a thread. What lets a caller
151 /// park cancelled workers and reap them without ever blocking.
152 pub(crate) fn is_finished(&self) -> bool {
153 self.handle
154 .as_ref()
155 .is_none_or(thread::JoinHandle::is_finished)
156 }
157
158 /// Lets the worker run on unwatched -- what the public API does, since it
159 /// hands out the flag alone.
160 fn detach(mut self) -> Arc<AtomicBool> {
161 self.handle = None;
162 Arc::clone(&self.cancel)
163 }
164}
165
166impl Drop for Worker {
167 fn drop(&mut self) {
168 if let Some(handle) = self.handle.take() {
169 self.cancel();
170 let _ = handle.join();
171 }
172 }
173}
174
175/// A running worker and the frames it is sending, handed out as one value
176/// because they must be *dropped* as one, in this order: the receiver
177/// disconnects first, which is the only thing that wakes a worker parked in a
178/// full `send`, and the join inside [`Worker::drop`] runs second.
179///
180/// Rust drops fields in declaration order, so this struct *is* that rule, and
181/// it holds wherever the value goes: an early return out of a half-built
182/// session, an unwind, a caller not written yet. Two separate locals do not
183/// hold it -- they drop in reverse order of declaration, so the worker there
184/// joins a thread nobody will ever drain, which is a hang and not a slow path.
185pub(crate) struct FrameStream {
186 pub(crate) frames: Receiver<Frame>,
187 pub(crate) worker: Worker,
188 /// What this stream's pictures are being decoded by. Dropped last and read
189 /// by the caller, so it outlives nothing and blocks nothing.
190 pub(crate) backend: BackendCell,
191}
192
193pub struct DecodeSession;
194
195impl DecodeSession {
196 /// Opens `path`, returning stream metadata immediately and a receiver that
197 /// yields frames as the worker decodes them. The worker stops when the
198 /// receiver is dropped, at end of stream, or on the first decode error.
199 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
200 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
201 Ok((meta, rx))
202 }
203
204 /// As [`DecodeSession::open`], but the first frame delivered is
205 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
206 /// Setting the returned flag stops the worker at its next access unit,
207 /// which is how a caller abandons a session it no longer wants to drain.
208 pub fn open_at(
209 path: impl AsRef<Path>,
210 start_frame: u32,
211 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
212 // `u32::MAX` is clamped to the stream's frame count below, so this is
213 // "to the end of the file".
214 Self::open_range(path, start_frame, u32::MAX)
215 }
216
217 /// As [`DecodeSession::open_at`], but the worker also stops on its own
218 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
219 /// absolute source frames, which is what a clip of a longer file needs.
220 /// `end_frame` is capped at the stream's frame count, and an empty range
221 /// yields a receiver that is simply already disconnected.
222 pub fn open_range(
223 path: impl AsRef<Path>,
224 start_frame: u32,
225 end_frame: u32,
226 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
227 // Ungraded: the public API opens a *file*, and a colour grade belongs to
228 // a clip of a timeline. `PlaybackSession` is what has one to pass.
229 let (meta, stream) = Self::open_worker(
230 path,
231 start_frame,
232 end_frame,
233 ColorParams::default(),
234 // No project, no canvas: the file-level API hands back the
235 // pictures the file holds, at the size it holds them.
236 Composer::passthrough(),
237 )?;
238 // The public API hands out the flag alone, so the worker is detached and
239 // the receiver goes to the caller: nothing here joins anything.
240 Ok((meta, stream.frames, stream.worker.detach()))
241 }
242
243 /// A worker that decodes nothing and emits `len` black frames, indexed from
244 /// zero -- what a *gap* in the video lane looks like. It goes down the same
245 /// channel as decoded frames, so a gap costs the caller no branch at all
246 /// beyond choosing this opener: same bounded channel, same backpressure,
247 /// same cancel, same retire path.
248 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
249 let (tx, rx) = sync_channel(2);
250 let cancel = Arc::new(AtomicBool::new(false));
251 if len == 0 {
252 return FrameStream {
253 frames: rx,
254 worker: Worker {
255 cancel,
256 handle: None,
257 },
258 backend: BackendCell::new(Backend::Gap),
259 };
260 }
261 let worker_cancel = Arc::clone(&cancel);
262 // One buffer, cloned per frame: opaque black is a constant, and the
263 // clone is a memcpy against a decode this replaces entirely.
264 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
265 let handle = thread::Builder::new()
266 .name("black".into())
267 .spawn(move || {
268 for index in 0..len {
269 if worker_cancel.load(Ordering::Relaxed) {
270 return;
271 }
272 let frame = Frame {
273 index,
274 width,
275 height,
276 bgra: black.clone(),
277 };
278 if tx.send(frame).is_err() {
279 return; // caller moved on
280 }
281 }
282 })
283 .ok();
284 FrameStream {
285 frames: rx,
286 worker: Worker { cancel, handle },
287 backend: BackendCell::new(Backend::Gap),
288 }
289 }
290
291 /// A worker for a still image ([`crate::is_image`]): the file is decoded
292 /// *once* and the same picture goes down the channel `len` times, indexed
293 /// from `start_frame` exactly as a decoder's pictures are -- so a placed
294 /// image is a clip like any other to everything downstream (`try_frame`
295 /// rewrites those indices, `next_clip` walks off the end of the range).
296 ///
297 /// Graded and placed on the canvas once too, before the repeat: a still is
298 /// the same pixels every frame, so the whole cost of one is one conversion
299 /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays.
300 pub(crate) fn open_still(
301 path: &Path,
302 start_frame: u32,
303 len: u32,
304 color: ColorParams,
305 canvas: Composer,
306 ) -> crate::Result<FrameStream> {
307 let still = Still::open(path)?;
308 let (tx, rx) = sync_channel(2);
309 let cancel = Arc::new(AtomicBool::new(false));
310 if len == 0 {
311 return Ok(FrameStream {
312 frames: rx,
313 worker: Worker {
314 cancel,
315 handle: None,
316 },
317 backend: BackendCell::new(Backend::Still),
318 });
319 }
320 // The one conversion, on this thread: it is a few milliseconds and the
321 // error it could raise has already been raised by `Still::open`.
322 let first = Render::new(color, canvas).frame(
323 start_frame,
324 &still.y,
325 &still.u,
326 &still.v,
327 still.width,
328 still.height,
329 );
330 let worker_cancel = Arc::clone(&cancel);
331 let handle = thread::Builder::new()
332 .name("still".into())
333 .spawn(move || {
334 let (width, height, bgra) = (first.width, first.height, first.bgra);
335 for index in 0..len {
336 if worker_cancel.load(Ordering::Relaxed) {
337 return;
338 }
339 let frame = Frame {
340 index: start_frame + index,
341 width,
342 height,
343 bgra: bgra.clone(),
344 };
345 if tx.send(frame).is_err() {
346 return; // caller moved on
347 }
348 }
349 })
350 .ok();
351 Ok(FrameStream {
352 frames: rx,
353 worker: Worker { cancel, handle },
354 backend: BackendCell::new(Backend::Still),
355 })
356 }
357
358 /// As [`DecodeSession::open_range`], but the caller gets the whole
359 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
360 /// `color` -- the clip's own setting, folded into the conversion the frames
361 /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
362 /// than read per frame because a worker *is* one clip's range: a grade
363 /// changed while this one runs reaches the picture when the session reseeks
364 /// onto the new one, which every edit does.
365 ///
366 /// In-process only: a caller that outlives its workers has to be able to
367 /// join them at exit.
368 ///
369 /// `canvas` is the project's own resolution and this clip's fit policy: the
370 /// frames come out at *that* size, whatever the file's is. A
371 /// [`Composer::passthrough`] (or one already the source's size) leaves every
372 /// picture exactly as it was decoded.
373 pub(crate) fn open_worker(
374 path: impl AsRef<Path>,
375 start_frame: u32,
376 end_frame: u32,
377 color: ColorParams,
378 canvas: Composer,
379 ) -> crate::Result<(VideoMeta, FrameStream)> {
380 let path = path.as_ref().to_path_buf();
381 let (meta, demuxer) = Demuxer::open(&path)?;
382 // No software HEVC or VP9 decoder exists, so such a file the plugin will
383 // not take is refused *here*, where the caller still has somewhere to
384 // show it -- a worker that opened and then produced nothing is a black
385 // screen with no explanation. The probe session is opened and dropped:
386 // it costs one extra VA-API init (~90 ms) and only off the H.264 path.
387 if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() {
388 return Err(meta.codec.needs_plugin().into());
389 }
390 let end_frame = end_frame.min(meta.frame_count);
391 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
392 // decoder run ahead of the display without limit.
393 let (tx, rx) = sync_channel(2);
394 let cancel = Arc::new(AtomicBool::new(false));
395 // Written by the worker below the moment it knows, so a caller reading
396 // it sees what opened rather than what was hoped for.
397 let backend = BackendCell::default();
398 if end_frame <= start_frame {
399 // Nothing to decode: dropping `tx` here closes the channel cleanly,
400 // so the caller sees an immediate end of stream rather than an error.
401 return Ok((
402 meta,
403 FrameStream {
404 frames: rx,
405 worker: Worker {
406 cancel,
407 handle: None,
408 },
409 backend,
410 },
411 ));
412 }
413 let worker_cancel = Arc::clone(&cancel);
414 let worker_backend = backend.clone();
415 let handle = thread::Builder::new()
416 .name("decode".into())
417 .spawn(move || {
418 // Cancelled before this thread was even scheduled -- do not
419 // enter VA-API initialisation at all, because that is the one
420 // stretch a cancel cannot interrupt (~65-90 ms of driver setup
421 // that would then have to be torn down again).
422 if worker_cancel.load(Ordering::Relaxed) {
423 return;
424 }
425 let mut render = Render::new(color, canvas);
426 // The plugin has to be opened on the thread that uses it: its
427 // VA-API state is not `Send`-safe across a later hand-off.
428 if let Some(hw) = open_hw(&path, start_frame) {
429 // Cancelled *during* init: close the session (dropping `hw`
430 // does it) and leave without decoding anything.
431 if worker_cancel.load(Ordering::Relaxed) {
432 return;
433 }
434 eprintln!("decode backend: hardware (VA-API plugin)");
435 worker_backend.set(Backend::Hardware);
436 if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) {
437 return;
438 }
439 // A driver that opens but cannot decode a single frame is
440 // still a fallback case, not a dead session.
441 eprintln!("hardware decode failed before any frame, falling back to software");
442 }
443 // ...except where there is nothing to fall back to. Feeding HEVC
444 // or VP9 bytes to `rusty_h264` would be garbage, not a fallback.
445 if meta.codec != Codec::H264 {
446 eprintln!("{}", meta.codec.needs_plugin());
447 return;
448 }
449 eprintln!("decode backend: software (rusty_h264)");
450 worker_backend.set(Backend::Software);
451 run(
452 demuxer,
453 tx,
454 start_frame,
455 end_frame,
456 &mut render,
457 &worker_cancel,
458 )
459 })?;
460 Ok((
461 meta,
462 FrameStream {
463 frames: rx,
464 worker: Worker {
465 cancel,
466 handle: Some(handle),
467 },
468 backend,
469 },
470 ))
471 }
472}
473
474/// One clip's pictures on their way to the renderer: graded, placed on the
475/// project canvas, converted. Both decode loops go through it, so hardware and
476/// software cannot show two different pictures.
477///
478/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
479/// applied at the resolution it was shot at, and the letterbox bars around it
480/// are not the clip -- a brightness grade must not lift them off black.
481///
482/// A project at the media's own resolution never reaches any of that: it takes
483/// the fused graded conversion, the one path this engine had before there was a
484/// project resolution, byte for byte and allocation for allocation.
485struct Render {
486 color: ColorParams,
487 canvas: Composer,
488 /// The graded copy of the source planes, refilled per frame and kept across
489 /// the worker's whole range. Empty unless the clip is both graded *and*
490 /// placed, which is the only case that needs it.
491 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
492}
493
494impl Render {
495 fn new(color: ColorParams, canvas: Composer) -> Self {
496 Self {
497 color,
498 canvas,
499 graded: (Vec::new(), Vec::new(), Vec::new()),
500 }
501 }
502
503 fn frame(
504 &mut self,
505 index: u32,
506 y: &[u8],
507 u: &[u8],
508 v: &[u8],
509 width: u32,
510 height: u32,
511 ) -> Frame {
512 if self.canvas.is_passthrough(width, height) {
513 return Frame {
514 index,
515 width,
516 height,
517 bgra: i420_to_bgra_with(&self.color, y, u, v, width as usize, height as usize),
518 };
519 }
520 let (gy, gu, gv) = &mut self.graded;
521 let (y, u, v) = if self.color.is_identity() {
522 (y, u, v)
523 } else {
524 gy.clear();
525 gy.extend_from_slice(y);
526 gu.clear();
527 gu.extend_from_slice(u);
528 gv.clear();
529 gv.extend_from_slice(v);
530 crate::color::apply_yuv(&self.color, gy, gu, gv);
531 (&gy[..], &gu[..], &gv[..])
532 };
533 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
534 Frame {
535 index,
536 width,
537 height,
538 // Ungraded on purpose: the grade is already in the pixels above and
539 // the canvas around them must stay the black it was filled with.
540 bgra: i420_to_bgra(y, u, v, width as usize, height as usize),
541 }
542 }
543}
544
545/// One still image, decoded to tightly packed I420 -- the shape every other
546/// source arrives in, so a placed image goes through the same grade, the same
547/// canvas and the same conversion as a decoded picture and there is no second
548/// pixel path to keep in step.
549///
550/// Held whole rather than streamed: an image *is* one picture, and the file is
551/// read once per span that plays it.
552pub(crate) struct Still {
553 pub(crate) y: Vec<u8>,
554 pub(crate) u: Vec<u8>,
555 pub(crate) v: Vec<u8>,
556 pub(crate) width: u32,
557 pub(crate) height: u32,
558}
559
560impl Still {
561 /// Decodes `path`. Refused by name for a picture that is not one
562 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
563 /// file are both held to cannot be walked around by a 30000-pixel-wide PNG.
564 ///
565 /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a
566 /// transparent PNG arrives fully opaque over its own colours rather than
567 /// over the clip beneath it. I420 has nowhere to carry it and this engine
568 /// composes one picture per frame (topmost lane wins), so there is nothing
569 /// for a blend to blend with.
570 ///
571 /// ponytail: the ceiling is a logo with a transparent background, which
572 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
573 /// giving `scale::Composer` a blend over the lane below.
574 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
575 let reader = image::ImageReader::open(path)?.with_guessed_format()?;
576 let rgb = reader
577 .decode()
578 .map_err(|e| format!("{}: {e}", path.display()))?
579 .to_rgb8();
580 let (width, height) = rgb.dimensions();
581 if !crate::is_resolution(width, height) {
582 return Err(format!(
583 "{} is {width}x{height}, which is not a picture this engine composes",
584 path.display()
585 )
586 .into());
587 }
588 let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize);
589 Ok(Self {
590 y,
591 u,
592 v,
593 width,
594 height,
595 })
596 }
597
598 /// The planes as an export's decoder hands them over, so a still and a
599 /// decoded picture are the same value to `export::run`.
600 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
601 (&self.y, &self.u, &self.v, self.width, self.height)
602 }
603}
604
605/// How big the picture in `path` is, from its header alone -- what a library row
606/// says about a file it has not placed anywhere. The whole file is not decoded.
607pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
608 Ok(image::ImageReader::open(path)?
609 .with_guessed_format()?
610 .into_dimensions()
611 .map_err(|e| format!("{}: {e}", path.display()))?)
612}
613
614/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
615/// of [`crate::convert::i420_to_bgra`], so a still round-trips to the colour it
616/// was authored in (`images::still_pixels_match_the_source_image` measures it).
617///
618/// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
619/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
620/// [`crate::scale::Composer::place`] panics on anything else for.
621fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
622 let (cw, ch) = crate::scale::chroma_dims(width, height);
623 let mut y = vec![0u8; width * height];
624 let mut u = vec![0u8; cw * ch];
625 let mut v = vec![0u8; cw * ch];
626 for row in 0..height {
627 for col in 0..width {
628 let p = (row * width + col) * 3;
629 let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32);
630 y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
631 }
632 }
633 for crow in 0..ch {
634 for ccol in 0..cw {
635 let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32);
636 for row in crow * 2..(crow * 2 + 2).min(height) {
637 for col in ccol * 2..(ccol * 2 + 2).min(width) {
638 let p = (row * width + col) * 3;
639 sr += rgb[p] as i32;
640 sg += rgb[p + 1] as i32;
641 sb += rgb[p + 2] as i32;
642 n += 1;
643 }
644 }
645 let n = n.max(1);
646 let (r, g, b) = (sr / n, sg / n, sb / n);
647 u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
648 v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
649 }
650 }
651 (y, u, v)
652}
653
654/// `None` when the software path must be used: forced by `VE_SW=1`, or the
655/// plugin is absent/broken/unable to open this particular file.
656fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
657 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
658 return None;
659 }
660 HwSession::open_at(path, start_frame)
661}
662
663/// Returns whether the session was handled; `false` only when hardware decode
664/// failed without emitting a single frame, so software can still take over.
665///
666/// The plugin already positioned itself at `start_frame`, so indices are
667/// counted from there (a stream whose very first sample is not a sync sample
668/// cannot be decoded from its start at all, and is not accounted for).
669fn run_hw(
670 mut hw: HwSession,
671 tx: &SyncSender<Frame>,
672 start_frame: u32,
673 end_frame: u32,
674 render: &mut Render,
675 cancel: &AtomicBool,
676) -> bool {
677 let mut index = start_frame;
678 loop {
679 if cancel.load(Ordering::Relaxed) {
680 return true;
681 }
682 match hw.next_frame() {
683 Ok(Some((y, u, v, width, height))) => {
684 let frame = render.frame(index, y, u, v, width, height);
685 index += 1;
686 if tx.send(frame).is_err() {
687 return true; // consumer went away
688 }
689 if index >= end_frame {
690 return true; // end of the requested range
691 }
692 }
693 Ok(None) => return true,
694 Err(e) => {
695 if index == start_frame {
696 return false;
697 }
698 eprintln!("hardware decode error at frame {index}: {e}");
699 return true;
700 }
701 }
702 }
703}
704
705#[cfg(test)]
706mod tests {
707 use super::*;
708 use std::sync::mpsc::RecvTimeoutError;
709 use std::time::Duration;
710
711 fn asset(name: &str) -> PathBuf {
712 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
713 .join("../../assets")
714 .join(name)
715 }
716
717 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
718 /// The channel is bounded, so such a worker is parked in `send` within a
719 /// few frames, and the only thing that can wake it is its receiver going
720 /// away -- which is why the receiver is the first field and the join inside
721 /// `Worker::drop` is the second. Swap those two fields and this hangs.
722 ///
723 /// This is the whole basis of every teardown path in the engine, so it is
724 /// asserted rather than commented: the drop runs on a second thread and a
725 /// regression fails in ten seconds instead of hanging the suite forever.
726 #[test]
727 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
728 let (_meta, stream) = DecodeSession::open_worker(
729 &asset("test_baseline.mp4"),
730 0,
731 u32::MAX,
732 ColorParams::default(),
733 Composer::passthrough(),
734 )
735 .expect("open");
736 // Nothing is ever received: two frames fill the channel and the next
737 // send parks the decode thread, exactly as a refused project load does.
738 thread::sleep(Duration::from_millis(500));
739
740 let (done_tx, done_rx) = sync_channel(1);
741 thread::spawn(move || {
742 drop(stream);
743 let _ = done_tx.send(());
744 });
745 assert!(
746 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
747 "dropping a parked stream deadlocked: it joined a decode thread \
748 while still holding the receiver that thread is waiting on"
749 );
750 }
751}
752
753fn run(
754 mut demuxer: Demuxer,
755 tx: SyncSender<Frame>,
756 start_frame: u32,
757 end_frame: u32,
758 render: &mut Render,
759 cancel: &AtomicBool,
760) {
761 let mut decoder = Decoder::new();
762 // Decoding has to restart at a sync sample, so pictures between it and
763 // `start_frame` are decoded (the target frame references them) but never
764 // converted or sent. Signed, because the landing sync sample can sit inside
765 // what the file's edit list trims, i.e. *before* frame 0.
766 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
767
768 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
769 // reordering streams need POC-sorted output before display.
770 loop {
771 if cancel.load(Ordering::Relaxed) {
772 break;
773 }
774 let au = match demuxer.next_access_unit() {
775 Ok(Some(au)) => au,
776 Ok(None) => break,
777 Err(e) => {
778 eprintln!("demux error: {e}");
779 break;
780 }
781 };
782 let yuv = match decoder.decode(&au) {
783 Ok(Some(yuv)) => yuv,
784 Ok(None) => continue,
785 Err(e) => {
786 eprintln!("decode error at access unit {index}: {e}");
787 break;
788 }
789 };
790 if index < i64::from(start_frame) {
791 index += 1;
792 continue;
793 }
794 let frame = render.frame(
795 index as u32,
796 &yuv.y,
797 &yuv.u,
798 &yuv.v,
799 yuv.width as u32,
800 yuv.height as u32,
801 );
802 index += 1;
803 if tx.send(frame).is_err() {
804 break; // consumer went away
805 }
806 if index >= i64::from(end_frame) {
807 break; // end of the requested range
808 }
809 }
810}