forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB9eac4beTahinli3 months ago20 commits

decode.rs203 lines, 7.5 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
26pub struct DecodeSession;
27
28impl DecodeSession {
29 /// Opens `path`, returning stream metadata immediately and a receiver that
30 /// yields frames as the worker decodes them. The worker stops when the
31 /// receiver is dropped, at end of stream, or on the first decode error.
32 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
33 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
34 Ok((meta, rx))
35 }
36
37 /// As [`DecodeSession::open`], but the first frame delivered is
38 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
39 /// Setting the returned flag stops the worker at its next access unit,
40 /// which is how a caller abandons a session it no longer wants to drain.
41 pub fn open_at(
42 path: impl AsRef<Path>,
43 start_frame: u32,
44 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
45 // `u32::MAX` is clamped to the stream's frame count below, so this is
46 // "to the end of the file".
47 Self::open_range(path, start_frame, u32::MAX)
48 }
49
50 /// As [`DecodeSession::open_at`], but the worker also stops on its own
51 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
52 /// absolute source frames, which is what a clip of a longer file needs.
53 /// `end_frame` is capped at the stream's frame count, and an empty range
54 /// yields a receiver that is simply already disconnected.
55 pub fn open_range(
56 path: impl AsRef<Path>,
57 start_frame: u32,
58 end_frame: u32,
59 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
60 let path = path.as_ref().to_path_buf();
61 let (meta, demuxer) = Demuxer::open(&path)?;
62 let end_frame = end_frame.min(meta.frame_count);
63 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
64 // decoder run ahead of the display without limit.
65 let (tx, rx) = sync_channel(2);
66 let cancel = Arc::new(AtomicBool::new(false));
67 if end_frame <= start_frame {
68 // Nothing to decode: dropping `tx` here closes the channel cleanly,
69 // so the caller sees an immediate end of stream rather than an error.
70 return Ok((meta, rx, cancel));
71 }
72 let worker_cancel = Arc::clone(&cancel);
73 thread::Builder::new()
74 .name("decode".into())
75 .spawn(move || {
76 // The plugin has to be opened on the thread that uses it: its
77 // VA-API state is not `Send`-safe across a later hand-off.
78 if let Some(hw) = open_hw(&path, start_frame) {
79 eprintln!("decode backend: hardware (VA-API plugin)");
80 if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) {
81 return;
82 }
83 // A driver that opens but cannot decode a single frame is
84 // still a fallback case, not a dead session.
85 eprintln!("hardware decode failed before any frame, falling back to software");
86 }
87 eprintln!("decode backend: software (rusty_h264)");
88 run(demuxer, tx, start_frame, end_frame, &worker_cancel)
89 })?;
90 Ok((meta, rx, cancel))
91 }
92}
93
94/// `None` when the software path must be used: forced by `VE_SW=1`, or the
95/// plugin is absent/broken/unable to open this particular file.
96fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
97 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
98 return None;
99 }
100 HwSession::open_at(path, start_frame)
101}
102
103/// Returns whether the session was handled; `false` only when hardware decode
104/// failed without emitting a single frame, so software can still take over.
105///
106/// The plugin already positioned itself at `start_frame`, so indices are
107/// counted from there (a stream whose very first sample is not a sync sample
108/// cannot be decoded from its start at all, and is not accounted for).
109fn run_hw(
110 mut hw: HwSession,
111 tx: &SyncSender<Frame>,
112 start_frame: u32,
113 end_frame: u32,
114 cancel: &AtomicBool,
115) -> bool {
116 let mut index = start_frame;
117 loop {
118 if cancel.load(Ordering::Relaxed) {
119 return true;
120 }
121 match hw.next_frame() {
122 Ok(Some((y, u, v, width, height))) => {
123 let frame = Frame {
124 index,
125 width,
126 height,
127 bgra: i420_to_bgra(y, u, v, width as usize, height as usize),
128 };
129 index += 1;
130 if tx.send(frame).is_err() {
131 return true; // consumer went away
132 }
133 if index >= end_frame {
134 return true; // end of the requested range
135 }
136 }
137 Ok(None) => return true,
138 Err(e) => {
139 if index == start_frame {
140 return false;
141 }
142 eprintln!("hardware decode error at frame {index}: {e}");
143 return true;
144 }
145 }
146 }
147}
148
149fn run(
150 mut demuxer: Demuxer,
151 tx: SyncSender<Frame>,
152 start_frame: u32,
153 end_frame: u32,
154 cancel: &AtomicBool,
155) {
156 let mut decoder = Decoder::new();
157 // Sample ids are 1-based, frame indices 0-based. Decoding has to restart at
158 // a sync sample, so pictures between it and `start_frame` are decoded (the
159 // target frame references them) but never converted or sent.
160 let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1));
161 let mut index = sync - 1;
162
163 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
164 // reordering streams need POC-sorted output before display.
165 loop {
166 if cancel.load(Ordering::Relaxed) {
167 break;
168 }
169 let au = match demuxer.next_access_unit() {
170 Ok(Some(au)) => au,
171 Ok(None) => break,
172 Err(e) => {
173 eprintln!("demux error: {e}");
174 break;
175 }
176 };
177 let yuv = match decoder.decode(&au) {
178 Ok(Some(yuv)) => yuv,
179 Ok(None) => continue,
180 Err(e) => {
181 eprintln!("decode error at access unit {index}: {e}");
182 break;
183 }
184 };
185 if index < start_frame {
186 index += 1;
187 continue;
188 }
189 let frame = Frame {
190 index,
191 width: yuv.width as u32,
192 height: yuv.height as u32,
193 bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height),
194 };
195 index += 1;
196 if tx.send(frame).is_err() {
197 break; // consumer went away
198 }
199 if index >= end_frame {
200 break; // end of the requested range
201 }
202 }
203}