forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB591afa3Tahinli3 months ago55 commits

decode.rs331 lines, 12.3 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
73pub struct DecodeSession;
74
75impl DecodeSession {
76 /// Opens `path`, returning stream metadata immediately and a receiver that
77 /// yields frames as the worker decodes them. The worker stops when the
78 /// receiver is dropped, at end of stream, or on the first decode error.
79 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
80 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
81 Ok((meta, rx))
82 }
83
84 /// As [`DecodeSession::open`], but the first frame delivered is
85 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
86 /// Setting the returned flag stops the worker at its next access unit,
87 /// which is how a caller abandons a session it no longer wants to drain.
88 pub fn open_at(
89 path: impl AsRef<Path>,
90 start_frame: u32,
91 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
92 // `u32::MAX` is clamped to the stream's frame count below, so this is
93 // "to the end of the file".
94 Self::open_range(path, start_frame, u32::MAX)
95 }
96
97 /// As [`DecodeSession::open_at`], but the worker also stops on its own
98 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
99 /// absolute source frames, which is what a clip of a longer file needs.
100 /// `end_frame` is capped at the stream's frame count, and an empty range
101 /// yields a receiver that is simply already disconnected.
102 pub fn open_range(
103 path: impl AsRef<Path>,
104 start_frame: u32,
105 end_frame: u32,
106 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
107 let (meta, rx, worker) = Self::open_worker(path, start_frame, end_frame)?;
108 Ok((meta, rx, worker.detach()))
109 }
110
111 /// A worker that decodes nothing and emits `len` black frames, indexed from
112 /// zero -- what a *gap* in the video lane looks like. It goes down the same
113 /// channel as decoded frames, so a gap costs the caller no branch at all
114 /// beyond choosing this opener: same bounded channel, same backpressure,
115 /// same cancel, same retire path.
116 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> (Receiver<Frame>, Worker) {
117 let (tx, rx) = sync_channel(2);
118 let cancel = Arc::new(AtomicBool::new(false));
119 if len == 0 {
120 return (
121 rx,
122 Worker {
123 cancel,
124 handle: None,
125 },
126 );
127 }
128 let worker_cancel = Arc::clone(&cancel);
129 // One buffer, cloned per frame: opaque black is a constant, and the
130 // clone is a memcpy against a decode this replaces entirely.
131 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
132 let handle = thread::Builder::new()
133 .name("black".into())
134 .spawn(move || {
135 for index in 0..len {
136 if worker_cancel.load(Ordering::Relaxed) {
137 return;
138 }
139 let frame = Frame {
140 index,
141 width,
142 height,
143 bgra: black.clone(),
144 };
145 if tx.send(frame).is_err() {
146 return; // caller moved on
147 }
148 }
149 })
150 .ok();
151 (rx, Worker { cancel, handle })
152 }
153
154 /// As [`DecodeSession::open_range`], but the caller gets the whole
155 /// [`Worker`] and can therefore *wait* for it. In-process only: a caller
156 /// that outlives its workers has to be able to join them at exit.
157 pub(crate) fn open_worker(
158 path: impl AsRef<Path>,
159 start_frame: u32,
160 end_frame: u32,
161 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Worker)> {
162 let path = path.as_ref().to_path_buf();
163 let (meta, demuxer) = Demuxer::open(&path)?;
164 let end_frame = end_frame.min(meta.frame_count);
165 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
166 // decoder run ahead of the display without limit.
167 let (tx, rx) = sync_channel(2);
168 let cancel = Arc::new(AtomicBool::new(false));
169 if end_frame <= start_frame {
170 // Nothing to decode: dropping `tx` here closes the channel cleanly,
171 // so the caller sees an immediate end of stream rather than an error.
172 return Ok((
173 meta,
174 rx,
175 Worker {
176 cancel,
177 handle: None,
178 },
179 ));
180 }
181 let worker_cancel = Arc::clone(&cancel);
182 let handle = thread::Builder::new()
183 .name("decode".into())
184 .spawn(move || {
185 // Cancelled before this thread was even scheduled -- do not
186 // enter VA-API initialisation at all, because that is the one
187 // stretch a cancel cannot interrupt (~65-90 ms of driver setup
188 // that would then have to be torn down again).
189 if worker_cancel.load(Ordering::Relaxed) {
190 return;
191 }
192 // The plugin has to be opened on the thread that uses it: its
193 // VA-API state is not `Send`-safe across a later hand-off.
194 if let Some(hw) = open_hw(&path, start_frame) {
195 // Cancelled *during* init: close the session (dropping `hw`
196 // does it) and leave without decoding anything.
197 if worker_cancel.load(Ordering::Relaxed) {
198 return;
199 }
200 eprintln!("decode backend: hardware (VA-API plugin)");
201 if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) {
202 return;
203 }
204 // A driver that opens but cannot decode a single frame is
205 // still a fallback case, not a dead session.
206 eprintln!("hardware decode failed before any frame, falling back to software");
207 }
208 eprintln!("decode backend: software (rusty_h264)");
209 run(demuxer, tx, start_frame, end_frame, &worker_cancel)
210 })?;
211 Ok((
212 meta,
213 rx,
214 Worker {
215 cancel,
216 handle: Some(handle),
217 },
218 ))
219 }
220}
221
222/// `None` when the software path must be used: forced by `VE_SW=1`, or the
223/// plugin is absent/broken/unable to open this particular file.
224fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
225 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
226 return None;
227 }
228 HwSession::open_at(path, start_frame)
229}
230
231/// Returns whether the session was handled; `false` only when hardware decode
232/// failed without emitting a single frame, so software can still take over.
233///
234/// The plugin already positioned itself at `start_frame`, so indices are
235/// counted from there (a stream whose very first sample is not a sync sample
236/// cannot be decoded from its start at all, and is not accounted for).
237fn run_hw(
238 mut hw: HwSession,
239 tx: &SyncSender<Frame>,
240 start_frame: u32,
241 end_frame: u32,
242 cancel: &AtomicBool,
243) -> bool {
244 let mut index = start_frame;
245 loop {
246 if cancel.load(Ordering::Relaxed) {
247 return true;
248 }
249 match hw.next_frame() {
250 Ok(Some((y, u, v, width, height))) => {
251 let frame = Frame {
252 index,
253 width,
254 height,
255 bgra: i420_to_bgra(y, u, v, width as usize, height as usize),
256 };
257 index += 1;
258 if tx.send(frame).is_err() {
259 return true; // consumer went away
260 }
261 if index >= end_frame {
262 return true; // end of the requested range
263 }
264 }
265 Ok(None) => return true,
266 Err(e) => {
267 if index == start_frame {
268 return false;
269 }
270 eprintln!("hardware decode error at frame {index}: {e}");
271 return true;
272 }
273 }
274 }
275}
276
277fn run(
278 mut demuxer: Demuxer,
279 tx: SyncSender<Frame>,
280 start_frame: u32,
281 end_frame: u32,
282 cancel: &AtomicBool,
283) {
284 let mut decoder = Decoder::new();
285 // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at
286 // a sync sample, so pictures between it and `start_frame` are decoded (the
287 // target frame references them) but never converted or sent.
288 let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1));
289 let mut index = sync - 1;
290
291 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
292 // reordering streams need POC-sorted output before display.
293 loop {
294 if cancel.load(Ordering::Relaxed) {
295 break;
296 }
297 let au = match demuxer.next_access_unit() {
298 Ok(Some(au)) => au,
299 Ok(None) => break,
300 Err(e) => {
301 eprintln!("demux error: {e}");
302 break;
303 }
304 };
305 let yuv = match decoder.decode(&au) {
306 Ok(Some(yuv)) => yuv,
307 Ok(None) => continue,
308 Err(e) => {
309 eprintln!("decode error at access unit {index}: {e}");
310 break;
311 }
312 };
313 if index < start_frame {
314 index += 1;
315 continue;
316 }
317 let frame = Frame {
318 index,
319 width: yuv.width as u32,
320 height: yuv.height as u32,
321 bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height),
322 };
323 index += 1;
324 if tx.send(frame).is_err() {
325 break; // consumer went away
326 }
327 if index >= end_frame {
328 break; // end of the requested range
329 }
330 }
331}