forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

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