forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa2ebaacTahinli3 months ago107 commits

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