forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

decode.rs521 lines, 19.9 KiBHistoryRawDownload
1//! Background decode worker. Frames leave over a bounded channel so the caller's
2//! thread (the UI thread) never blocks on decode and memory stays capped.
3
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, 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/// A running decode worker: the flag that stops it, and the handle to wait on.
29///
30/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
31/// outlives the process otherwise, and Mesa's `atexit` handlers free the state
32/// it is still reading -- a SIGSEGV at exit, long after the last test passed.
33pub(crate) struct Worker {
34 cancel: Arc<AtomicBool>,
35 /// `None` once detached, and for a range with nothing to decode: either way
36 /// there is no thread left to wait for.
37 handle: Option<thread::JoinHandle<()>>,
38}
39
40impl Worker {
41 /// Stops the worker at its next check without waiting. Callers that replace
42 /// a worker should do this first and drop the receiver second: a worker
43 /// parked in `send` only wakes on the disconnect, so the join below would
44 /// otherwise wait for a consumer that is never coming.
45 pub(crate) fn cancel(&self) {
46 self.cancel.store(true, Ordering::Release);
47 }
48
49 /// Whether the thread has already returned, i.e. dropping this would not
50 /// wait. `true` for a worker that never had a thread. What lets a caller
51 /// park cancelled workers and reap them without ever blocking.
52 pub(crate) fn is_finished(&self) -> bool {
53 self.handle
54 .as_ref()
55 .is_none_or(thread::JoinHandle::is_finished)
56 }
57
58 /// Lets the worker run on unwatched -- what the public API does, since it
59 /// hands out the flag alone.
60 fn detach(mut self) -> Arc<AtomicBool> {
61 self.handle = None;
62 Arc::clone(&self.cancel)
63 }
64}
65
66impl Drop for Worker {
67 fn drop(&mut self) {
68 if let Some(handle) = self.handle.take() {
69 self.cancel();
70 let _ = handle.join();
71 }
72 }
73}
74
75/// A running worker and the frames it is sending, handed out as one value
76/// because they must be *dropped* as one, in this order: the receiver
77/// disconnects first, which is the only thing that wakes a worker parked in a
78/// full `send`, and the join inside [`Worker::drop`] runs second.
79///
80/// Rust drops fields in declaration order, so this struct *is* that rule, and
81/// it holds wherever the value goes: an early return out of a half-built
82/// session, an unwind, a caller not written yet. Two separate locals do not
83/// hold it -- they drop in reverse order of declaration, so the worker there
84/// joins a thread nobody will ever drain, which is a hang and not a slow path.
85pub(crate) struct FrameStream {
86 pub(crate) frames: Receiver<Frame>,
87 pub(crate) worker: Worker,
88}
89
90pub struct DecodeSession;
91
92impl DecodeSession {
93 /// Opens `path`, returning stream metadata immediately and a receiver that
94 /// yields frames as the worker decodes them. The worker stops when the
95 /// receiver is dropped, at end of stream, or on the first decode error.
96 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
97 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
98 Ok((meta, rx))
99 }
100
101 /// As [`DecodeSession::open`], but the first frame delivered is
102 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
103 /// Setting the returned flag stops the worker at its next access unit,
104 /// which is how a caller abandons a session it no longer wants to drain.
105 pub fn open_at(
106 path: impl AsRef<Path>,
107 start_frame: u32,
108 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
109 // `u32::MAX` is clamped to the stream's frame count below, so this is
110 // "to the end of the file".
111 Self::open_range(path, start_frame, u32::MAX)
112 }
113
114 /// As [`DecodeSession::open_at`], but the worker also stops on its own
115 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
116 /// absolute source frames, which is what a clip of a longer file needs.
117 /// `end_frame` is capped at the stream's frame count, and an empty range
118 /// yields a receiver that is simply already disconnected.
119 pub fn open_range(
120 path: impl AsRef<Path>,
121 start_frame: u32,
122 end_frame: u32,
123 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
124 // Ungraded: the public API opens a *file*, and a colour grade belongs to
125 // a clip of a timeline. `PlaybackSession` is what has one to pass.
126 let (meta, stream) = Self::open_worker(
127 path,
128 start_frame,
129 end_frame,
130 ColorParams::default(),
131 // No project, no canvas: the file-level API hands back the
132 // pictures the file holds, at the size it holds them.
133 Composer::passthrough(),
134 )?;
135 // The public API hands out the flag alone, so the worker is detached and
136 // the receiver goes to the caller: nothing here joins anything.
137 Ok((meta, stream.frames, stream.worker.detach()))
138 }
139
140 /// A worker that decodes nothing and emits `len` black frames, indexed from
141 /// zero -- what a *gap* in the video lane looks like. It goes down the same
142 /// channel as decoded frames, so a gap costs the caller no branch at all
143 /// beyond choosing this opener: same bounded channel, same backpressure,
144 /// same cancel, same retire path.
145 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
146 let (tx, rx) = sync_channel(2);
147 let cancel = Arc::new(AtomicBool::new(false));
148 if len == 0 {
149 return FrameStream {
150 frames: rx,
151 worker: Worker {
152 cancel,
153 handle: None,
154 },
155 };
156 }
157 let worker_cancel = Arc::clone(&cancel);
158 // One buffer, cloned per frame: opaque black is a constant, and the
159 // clone is a memcpy against a decode this replaces entirely.
160 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
161 let handle = thread::Builder::new()
162 .name("black".into())
163 .spawn(move || {
164 for index in 0..len {
165 if worker_cancel.load(Ordering::Relaxed) {
166 return;
167 }
168 let frame = Frame {
169 index,
170 width,
171 height,
172 bgra: black.clone(),
173 };
174 if tx.send(frame).is_err() {
175 return; // caller moved on
176 }
177 }
178 })
179 .ok();
180 FrameStream {
181 frames: rx,
182 worker: Worker { cancel, handle },
183 }
184 }
185
186 /// As [`DecodeSession::open_range`], but the caller gets the whole
187 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
188 /// `color` -- the clip's own setting, folded into the conversion the frames
189 /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
190 /// than read per frame because a worker *is* one clip's range: a grade
191 /// changed while this one runs reaches the picture when the session reseeks
192 /// onto the new one, which every edit does.
193 ///
194 /// In-process only: a caller that outlives its workers has to be able to
195 /// join them at exit.
196 ///
197 /// `canvas` is the project's own resolution and this clip's fit policy: the
198 /// frames come out at *that* size, whatever the file's is. A
199 /// [`Composer::passthrough`] (or one already the source's size) leaves every
200 /// picture exactly as it was decoded.
201 pub(crate) fn open_worker(
202 path: impl AsRef<Path>,
203 start_frame: u32,
204 end_frame: u32,
205 color: ColorParams,
206 canvas: Composer,
207 ) -> crate::Result<(VideoMeta, FrameStream)> {
208 let path = path.as_ref().to_path_buf();
209 let (meta, demuxer) = Demuxer::open(&path)?;
210 // No software HEVC or VP9 decoder exists, so such a file the plugin will
211 // not take is refused *here*, where the caller still has somewhere to
212 // show it -- a worker that opened and then produced nothing is a black
213 // screen with no explanation. The probe session is opened and dropped:
214 // it costs one extra VA-API init (~90 ms) and only off the H.264 path.
215 if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() {
216 return Err(meta.codec.needs_plugin().into());
217 }
218 let end_frame = end_frame.min(meta.frame_count);
219 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
220 // decoder run ahead of the display without limit.
221 let (tx, rx) = sync_channel(2);
222 let cancel = Arc::new(AtomicBool::new(false));
223 if end_frame <= start_frame {
224 // Nothing to decode: dropping `tx` here closes the channel cleanly,
225 // so the caller sees an immediate end of stream rather than an error.
226 return Ok((
227 meta,
228 FrameStream {
229 frames: rx,
230 worker: Worker {
231 cancel,
232 handle: None,
233 },
234 },
235 ));
236 }
237 let worker_cancel = Arc::clone(&cancel);
238 let handle = thread::Builder::new()
239 .name("decode".into())
240 .spawn(move || {
241 // Cancelled before this thread was even scheduled -- do not
242 // enter VA-API initialisation at all, because that is the one
243 // stretch a cancel cannot interrupt (~65-90 ms of driver setup
244 // that would then have to be torn down again).
245 if worker_cancel.load(Ordering::Relaxed) {
246 return;
247 }
248 let mut render = Render::new(color, canvas);
249 // The plugin has to be opened on the thread that uses it: its
250 // VA-API state is not `Send`-safe across a later hand-off.
251 if let Some(hw) = open_hw(&path, start_frame) {
252 // Cancelled *during* init: close the session (dropping `hw`
253 // does it) and leave without decoding anything.
254 if worker_cancel.load(Ordering::Relaxed) {
255 return;
256 }
257 eprintln!("decode backend: hardware (VA-API plugin)");
258 if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) {
259 return;
260 }
261 // A driver that opens but cannot decode a single frame is
262 // still a fallback case, not a dead session.
263 eprintln!("hardware decode failed before any frame, falling back to software");
264 }
265 // ...except where there is nothing to fall back to. Feeding HEVC
266 // or VP9 bytes to `rusty_h264` would be garbage, not a fallback.
267 if meta.codec != Codec::H264 {
268 eprintln!("{}", meta.codec.needs_plugin());
269 return;
270 }
271 eprintln!("decode backend: software (rusty_h264)");
272 run(
273 demuxer,
274 tx,
275 start_frame,
276 end_frame,
277 &mut render,
278 &worker_cancel,
279 )
280 })?;
281 Ok((
282 meta,
283 FrameStream {
284 frames: rx,
285 worker: Worker {
286 cancel,
287 handle: Some(handle),
288 },
289 },
290 ))
291 }
292}
293
294/// One clip's pictures on their way to the renderer: graded, placed on the
295/// project canvas, converted. Both decode loops go through it, so hardware and
296/// software cannot show two different pictures.
297///
298/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
299/// applied at the resolution it was shot at, and the letterbox bars around it
300/// are not the clip -- a brightness grade must not lift them off black.
301///
302/// A project at the media's own resolution never reaches any of that: it takes
303/// the fused graded conversion, the one path this engine had before there was a
304/// project resolution, byte for byte and allocation for allocation.
305struct Render {
306 color: ColorParams,
307 canvas: Composer,
308 /// The graded copy of the source planes, refilled per frame and kept across
309 /// the worker's whole range. Empty unless the clip is both graded *and*
310 /// placed, which is the only case that needs it.
311 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
312}
313
314impl Render {
315 fn new(color: ColorParams, canvas: Composer) -> Self {
316 Self {
317 color,
318 canvas,
319 graded: (Vec::new(), Vec::new(), Vec::new()),
320 }
321 }
322
323 fn frame(
324 &mut self,
325 index: u32,
326 y: &[u8],
327 u: &[u8],
328 v: &[u8],
329 width: u32,
330 height: u32,
331 ) -> Frame {
332 if self.canvas.is_passthrough(width, height) {
333 return Frame {
334 index,
335 width,
336 height,
337 bgra: i420_to_bgra_with(&self.color, y, u, v, width as usize, height as usize),
338 };
339 }
340 let (gy, gu, gv) = &mut self.graded;
341 let (y, u, v) = if self.color.is_identity() {
342 (y, u, v)
343 } else {
344 gy.clear();
345 gy.extend_from_slice(y);
346 gu.clear();
347 gu.extend_from_slice(u);
348 gv.clear();
349 gv.extend_from_slice(v);
350 crate::color::apply_yuv(&self.color, gy, gu, gv);
351 (&gy[..], &gu[..], &gv[..])
352 };
353 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
354 Frame {
355 index,
356 width,
357 height,
358 // Ungraded on purpose: the grade is already in the pixels above and
359 // the canvas around them must stay the black it was filled with.
360 bgra: i420_to_bgra(y, u, v, width as usize, height as usize),
361 }
362 }
363}
364
365/// `None` when the software path must be used: forced by `VE_SW=1`, or the
366/// plugin is absent/broken/unable to open this particular file.
367fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
368 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
369 return None;
370 }
371 HwSession::open_at(path, start_frame)
372}
373
374/// Returns whether the session was handled; `false` only when hardware decode
375/// failed without emitting a single frame, so software can still take over.
376///
377/// The plugin already positioned itself at `start_frame`, so indices are
378/// counted from there (a stream whose very first sample is not a sync sample
379/// cannot be decoded from its start at all, and is not accounted for).
380fn run_hw(
381 mut hw: HwSession,
382 tx: &SyncSender<Frame>,
383 start_frame: u32,
384 end_frame: u32,
385 render: &mut Render,
386 cancel: &AtomicBool,
387) -> bool {
388 let mut index = start_frame;
389 loop {
390 if cancel.load(Ordering::Relaxed) {
391 return true;
392 }
393 match hw.next_frame() {
394 Ok(Some((y, u, v, width, height))) => {
395 let frame = render.frame(index, y, u, v, width, height);
396 index += 1;
397 if tx.send(frame).is_err() {
398 return true; // consumer went away
399 }
400 if index >= end_frame {
401 return true; // end of the requested range
402 }
403 }
404 Ok(None) => return true,
405 Err(e) => {
406 if index == start_frame {
407 return false;
408 }
409 eprintln!("hardware decode error at frame {index}: {e}");
410 return true;
411 }
412 }
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419 use std::sync::mpsc::RecvTimeoutError;
420 use std::time::Duration;
421
422 fn asset(name: &str) -> PathBuf {
423 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
424 .join("../../assets")
425 .join(name)
426 }
427
428 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
429 /// The channel is bounded, so such a worker is parked in `send` within a
430 /// few frames, and the only thing that can wake it is its receiver going
431 /// away -- which is why the receiver is the first field and the join inside
432 /// `Worker::drop` is the second. Swap those two fields and this hangs.
433 ///
434 /// This is the whole basis of every teardown path in the engine, so it is
435 /// asserted rather than commented: the drop runs on a second thread and a
436 /// regression fails in ten seconds instead of hanging the suite forever.
437 #[test]
438 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
439 let (_meta, stream) = DecodeSession::open_worker(
440 &asset("test_baseline.mp4"),
441 0,
442 u32::MAX,
443 ColorParams::default(),
444 Composer::passthrough(),
445 )
446 .expect("open");
447 // Nothing is ever received: two frames fill the channel and the next
448 // send parks the decode thread, exactly as a refused project load does.
449 thread::sleep(Duration::from_millis(500));
450
451 let (done_tx, done_rx) = sync_channel(1);
452 thread::spawn(move || {
453 drop(stream);
454 let _ = done_tx.send(());
455 });
456 assert!(
457 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
458 "dropping a parked stream deadlocked: it joined a decode thread \
459 while still holding the receiver that thread is waiting on"
460 );
461 }
462}
463
464fn run(
465 mut demuxer: Demuxer,
466 tx: SyncSender<Frame>,
467 start_frame: u32,
468 end_frame: u32,
469 render: &mut Render,
470 cancel: &AtomicBool,
471) {
472 let mut decoder = Decoder::new();
473 // Decoding has to restart at a sync sample, so pictures between it and
474 // `start_frame` are decoded (the target frame references them) but never
475 // converted or sent. Signed, because the landing sync sample can sit inside
476 // what the file's edit list trims, i.e. *before* frame 0.
477 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
478
479 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
480 // reordering streams need POC-sorted output before display.
481 loop {
482 if cancel.load(Ordering::Relaxed) {
483 break;
484 }
485 let au = match demuxer.next_access_unit() {
486 Ok(Some(au)) => au,
487 Ok(None) => break,
488 Err(e) => {
489 eprintln!("demux error: {e}");
490 break;
491 }
492 };
493 let yuv = match decoder.decode(&au) {
494 Ok(Some(yuv)) => yuv,
495 Ok(None) => continue,
496 Err(e) => {
497 eprintln!("decode error at access unit {index}: {e}");
498 break;
499 }
500 };
501 if index < i64::from(start_frame) {
502 index += 1;
503 continue;
504 }
505 let frame = render.frame(
506 index as u32,
507 &yuv.y,
508 &yuv.u,
509 &yuv.v,
510 yuv.width as u32,
511 yuv.height as u32,
512 );
513 index += 1;
514 if tx.send(frame).is_err() {
515 break; // consumer went away
516 }
517 if index >= i64::from(end_frame) {
518 break; // end of the requested range
519 }
520 }
521}