forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfc06b75Tahinli3 months ago2 commits

decode.rs130 lines, 4.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::mpsc::{Receiver, SyncSender, sync_channel};
6use std::thread;
7
8use rusty_h264::Decoder;
9
10use crate::convert::i420_to_bgra;
11use crate::demux::{Demuxer, VideoMeta};
12use crate::hw::HwSession;
13
14/// One decoded picture, ready to hand to a renderer.
15pub struct Frame {
16 /// Position in decode order, starting at 0.
17 pub index: u32,
18 pub width: u32,
19 pub height: u32,
20 /// BGRA8, straight alpha, tightly packed.
21 pub bgra: Vec<u8>,
22}
23
24pub struct DecodeSession;
25
26impl DecodeSession {
27 /// Opens `path`, returning stream metadata immediately and a receiver that
28 /// yields frames as the worker decodes them. The worker stops when the
29 /// receiver is dropped, at end of stream, or on the first decode error.
30 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
31 let path = path.as_ref().to_path_buf();
32 let (meta, demuxer) = Demuxer::open(&path)?;
33 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
34 // decoder run ahead of the display without limit.
35 let (tx, rx) = sync_channel(2);
36 thread::Builder::new()
37 .name("decode".into())
38 .spawn(move || {
39 // The plugin has to be opened on the thread that uses it: its
40 // VA-API state is not `Send`-safe across a later hand-off.
41 if let Some(hw) = open_hw(&path) {
42 eprintln!("decode backend: hardware (VA-API plugin)");
43 if run_hw(hw, &tx) {
44 return;
45 }
46 // A driver that opens but cannot decode a single frame is
47 // still a fallback case, not a dead session.
48 eprintln!("hardware decode failed before any frame, falling back to software");
49 }
50 eprintln!("decode backend: software (rusty_h264)");
51 run(demuxer, tx)
52 })?;
53 Ok((meta, rx))
54 }
55}
56
57/// `None` when the software path must be used: forced by `VE_SW=1`, or the
58/// plugin is absent/broken/unable to open this particular file.
59fn open_hw(path: &PathBuf) -> Option<HwSession> {
60 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
61 return None;
62 }
63 HwSession::open(path)
64}
65
66/// Returns whether the session was handled; `false` only when hardware decode
67/// failed without emitting a single frame, so software can still take over.
68fn run_hw(mut hw: HwSession, tx: &SyncSender<Frame>) -> bool {
69 let mut index = 0u32;
70 loop {
71 match hw.next_frame() {
72 Ok(Some((y, u, v, width, height))) => {
73 let frame = Frame {
74 index,
75 width,
76 height,
77 bgra: i420_to_bgra(y, u, v, width as usize, height as usize),
78 };
79 index += 1;
80 if tx.send(frame).is_err() {
81 return true; // consumer went away
82 }
83 }
84 Ok(None) => return true,
85 Err(e) => {
86 if index == 0 {
87 return false;
88 }
89 eprintln!("hardware decode error at frame {index}: {e}");
90 return true;
91 }
92 }
93 }
94}
95
96fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>) {
97 let mut decoder = Decoder::new();
98 let mut index = 0u32;
99
100 // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
101 // reordering streams need POC-sorted output before display.
102 loop {
103 let au = match demuxer.next_access_unit() {
104 Ok(Some(au)) => au,
105 Ok(None) => break,
106 Err(e) => {
107 eprintln!("demux error: {e}");
108 break;
109 }
110 };
111 let yuv = match decoder.decode(&au) {
112 Ok(Some(yuv)) => yuv,
113 Ok(None) => continue,
114 Err(e) => {
115 eprintln!("decode error at access unit {index}: {e}");
116 break;
117 }
118 };
119 let frame = Frame {
120 index,
121 width: yuv.width as u32,
122 height: yuv.height as u32,
123 bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height),
124 };
125 index += 1;
126 if tx.send(frame).is_err() {
127 break; // consumer went away
128 }
129 }
130}