forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

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