forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

mod.rs311 lines, 10.2 KiBHistoryRawDownload
1//! Stateless hardware decoders, one per codec, behind one [`Decoder`].
2//!
3//! # The shape of a stateless decode
4//!
5//! For every picture: parse the headers in Rust, fill the codec's
6//! `VAPictureParameterBuffer*` from them, fill one
7//! `VASliceParameterBuffer*` per slice or tile, hand the driver the original
8//! (still escaped) bitstream bytes, and submit. Between pictures the decoder
9//! keeps whatever the codec spreads across frames — the H.264 DPB and its
10//! reference lists, HEVC's reference picture sets, VP9's and AV1's reference
11//! slots — because the driver keeps nothing.
12//!
13//! # Output order
14//!
15//! Frames leave in *display* order. H.264 and HEVC reorder through their
16//! decoded picture buffer (bumping, C.4.5.3); VP9 and AV1 emit in decode order
17//! with `show_existing_frame` handled. A caller that wants decode order has the
18//! per-frame timestamp it fed in.
19
20use std::collections::VecDeque;
21use std::sync::Arc;
22
23use ec_va::caps::{Entrypoint, Profile};
24use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, sys};
25
26use crate::error::{Error, Result};
27use crate::frame::Frame;
28use crate::pool::SurfacePool;
29
30mod av1;
31mod dpb264;
32mod h264;
33mod hevc;
34mod vp9;
35
36pub use av1::Av1Decoder;
37pub use h264::H264Decoder;
38pub use hevc::HevcDecoder;
39pub use vp9::Vp9Decoder;
40
41/// The codecs this crate decodes in hardware.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Codec {
44 /// H.264 / AVC, Annex B byte stream.
45 H264,
46 /// H.265 / HEVC, Annex B byte stream.
47 H265,
48 /// VP9, one frame (or superframe) per call.
49 Vp9,
50 /// AV1, one temporal unit per call.
51 Av1,
52}
53
54/// What the stream turned out to be, once its first headers were parsed.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct StreamInfo {
57 /// Coded size, a multiple of the codec's block size.
58 pub coded_size: (u32, u32),
59 /// Size after cropping — what a player shows.
60 pub display_size: (u32, u32),
61 /// Luma bit depth.
62 pub bit_depth: u8,
63 /// The VA profile the context was created with.
64 pub profile: Profile,
65 /// Surfaces allocated for this stream.
66 pub num_surfaces: usize,
67}
68
69/// A hardware decoder for one elementary stream.
70pub struct Decoder {
71 inner: Inner,
72}
73
74enum Inner {
75 H264(Box<H264Decoder>),
76 H265(Box<HevcDecoder>),
77 Vp9(Box<Vp9Decoder>),
78 Av1(Box<Av1Decoder>),
79}
80
81impl Decoder {
82 /// Open a decoder for `codec` on `display`.
83 ///
84 /// Nothing is allocated on the GPU yet: the surface pool and context need
85 /// the stream's size and bit depth, which only its first parameter set
86 /// carries, so they are created on the first [`Decoder::decode`] call.
87 pub fn new(display: &Arc<Display>, codec: Codec) -> Result<Decoder> {
88 let inner = match codec {
89 Codec::H264 => Inner::H264(Box::new(H264Decoder::new(display))),
90 Codec::H265 => Inner::H265(Box::new(HevcDecoder::new(display))),
91 Codec::Vp9 => Inner::Vp9(Box::new(Vp9Decoder::new(display))),
92 Codec::Av1 => Inner::Av1(Box::new(Av1Decoder::new(display))),
93 };
94 Ok(Decoder { inner })
95 }
96
97 /// Feed one access unit (H.264/HEVC: Annex B; VP9: one chunk; AV1: one
98 /// temporal unit) and queue whatever pictures it completed.
99 pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
100 match &mut self.inner {
101 Inner::H264(d) => d.decode(data, timestamp),
102 Inner::H265(d) => d.decode(data, timestamp),
103 Inner::Vp9(d) => d.decode(data, timestamp),
104 Inner::Av1(d) => d.decode(data, timestamp),
105 }
106 }
107
108 /// The next frame in display order, if one is ready.
109 pub fn next_frame(&mut self) -> Option<Frame> {
110 match &mut self.inner {
111 Inner::H264(d) => d.next_frame(),
112 Inner::H265(d) => d.next_frame(),
113 Inner::Vp9(d) => d.next_frame(),
114 Inner::Av1(d) => d.next_frame(),
115 }
116 }
117
118 /// End of stream: push every buffered picture out.
119 pub fn flush(&mut self) -> Result<()> {
120 match &mut self.inner {
121 Inner::H264(d) => d.flush(),
122 Inner::H265(d) => d.flush(),
123 Inner::Vp9(d) => d.flush(),
124 Inner::Av1(d) => d.flush(),
125 }
126 Ok(())
127 }
128
129 /// Discard all state after a seek. Parameter sets are kept.
130 pub fn reset(&mut self) {
131 match &mut self.inner {
132 Inner::H264(d) => d.reset(),
133 Inner::H265(d) => d.reset(),
134 Inner::Vp9(d) => d.reset(),
135 Inner::Av1(d) => d.reset(),
136 }
137 }
138
139 /// Pictures inferred for H.264 `frame_num` gaps (8.2.5.2); zero for the
140 /// other codecs, which have no such concept.
141 pub fn gap_frames_synthesized(&self) -> u64 {
142 match &self.inner {
143 Inner::H264(d) => d.gap_frames_synthesized(),
144 _ => 0,
145 }
146 }
147
148 /// What the stream turned out to be, once a session exists.
149 pub fn stream_info(&self) -> Option<StreamInfo> {
150 match &self.inner {
151 Inner::H264(d) => d.stream_info(),
152 Inner::H265(d) => d.stream_info(),
153 Inner::Vp9(d) => d.stream_info(),
154 Inner::Av1(d) => d.stream_info(),
155 }
156 }
157}
158
159/// Frames waiting to be collected, oldest first.
160///
161/// A decode call produces frames rather than returning one, because one access
162/// unit can complete none, one or several pictures. There is no event fd behind
163/// it: nothing in this family polls a decoder from an event loop, and adding an
164/// `eventfd(2)` would mean a second FFI surface in a crate whose whole unsafe
165/// budget is meant to be libva.
166#[derive(Debug, Default)]
167pub(crate) struct ReadyFrames {
168 queue: VecDeque<Frame>,
169}
170
171impl ReadyFrames {
172 pub(crate) fn push(&mut self, frame: Frame) {
173 self.queue.push_back(frame);
174 }
175
176 pub(crate) fn pop(&mut self) -> Option<Frame> {
177 self.queue.pop_front()
178 }
179
180 pub(crate) fn clear(&mut self) {
181 self.queue.clear();
182 }
183
184 pub(crate) fn len(&self) -> usize {
185 self.queue.len()
186 }
187}
188
189/// The GPU-side state one decoded stream needs: config, context, surfaces.
190pub(crate) struct Session {
191 pub(crate) context: Arc<Context>,
192 /// The readback image every frame of this stream reuses.
193 pub(crate) images: crate::frame::ImageCache,
194 pub(crate) pool: SurfacePool,
195 pub(crate) coded_size: (u32, u32),
196 pub(crate) display_size: (u32, u32),
197 pub(crate) bit_depth: u8,
198 pub(crate) profile: Profile,
199}
200
201impl Session {
202 /// Create a decode session, deriving the surface format from the *stream's*
203 /// bit depth.
204 ///
205 /// The bit depth is the whole point of this signature. An 8-bit context on
206 /// a 10-bit stream is the incumbent defect this crate exists to not repeat:
207 /// the driver either refuses the config or silently decodes to NV12 and
208 /// throws away two bits per sample.
209 pub(crate) fn new(
210 display: &Arc<Display>,
211 profile: Profile,
212 coded_size: (u32, u32),
213 display_size: (u32, u32),
214 bit_depth: u8,
215 num_surfaces: usize,
216 ) -> Result<Session> {
217 let caps = CapReport::probe(display)?;
218 let entry = caps.entry(profile, Entrypoint::VLD).ok_or_else(|| {
219 Error::unsupported(
220 format!("{profile:?} decode"),
221 "the driver advertises no VLD entrypoint for this profile",
222 )
223 })?;
224
225 let rt_format = if bit_depth > 8 {
226 sys::VA_RT_FORMAT_YUV420_10
227 } else {
228 sys::VA_RT_FORMAT_YUV420
229 };
230 if !entry.supports_rt_format(rt_format) {
231 return Err(Error::unsupported(
232 format!("{bit_depth}-bit {profile:?} decode"),
233 format!(
234 "the driver's RT format mask for this profile is {:#x}",
235 entry.rt_formats
236 ),
237 ));
238 }
239
240 let (w, h) = coded_size;
241 if let Some(surfaces) = &entry.surfaces
242 && !surfaces.allows(w, h)
243 {
244 return Err(Error::unsupported(
245 format!("{w}x{h} {profile:?} decode"),
246 format!(
247 "the driver accepts {:?}..{:?} x {:?}..{:?}",
248 surfaces.min_width,
249 surfaces.max_width,
250 surfaces.min_height,
251 surfaces.max_height
252 ),
253 ));
254 }
255
256 let config = Config::new(
257 display,
258 profile,
259 Entrypoint::VLD,
260 &[ConfigAttrib::rt_format(rt_format)],
261 )?;
262
263 let spec = if bit_depth > 8 {
264 SurfaceSpec::p010(w, h)
265 } else {
266 SurfaceSpec::nv12(w, h)
267 }
268 .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_DECODER);
269 let pool = SurfacePool::new(display, &spec, num_surfaces)?;
270 let context = Context::new(&config, w, h, sys::VA_PROGRESSIVE, pool.targets())?;
271
272 Ok(Session {
273 context,
274 images: crate::frame::ImageCache::default(),
275 pool,
276 coded_size,
277 display_size,
278 bit_depth,
279 profile,
280 })
281 }
282
283 /// Submit one picture: begin, render every buffer, end. No sync — the
284 /// driver keeps submissions in order within a context, and the wait belongs
285 /// where the pixels are actually read.
286 pub(crate) fn submit(&self, target: &Arc<Surface>, buffers: Vec<ec_va::Buffer>) -> Result<()> {
287 if buffers.is_empty() {
288 // radeonsi answers an empty submission with INVALID_CONTEXT, which
289 // reads like a driver bug report rather than what it is: a picture
290 // with no slices, i.e. a stream that lost its data.
291 return Err(Error::config(
292 "refusing to submit a picture with no parameter buffers",
293 ));
294 }
295 ec_va::Picture::new(&self.context, Arc::clone(target))
296 .begin()?
297 .render_all(buffers)?
298 .end()?;
299 Ok(())
300 }
301
302 pub(crate) fn info(&self) -> StreamInfo {
303 StreamInfo {
304 coded_size: self.coded_size,
305 display_size: self.display_size,
306 bit_depth: self.bit_depth,
307 profile: self.profile,
308 num_surfaces: self.pool.len(),
309 }
310 }
311}