forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

mod.rs322 lines, 10.6 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 /// This stream's colour metadata, once a session exists. [`None`] for VP9
159 /// and AV1: neither's sequence header colour config is parsed by this
160 /// family yet.
161 pub fn colour(&self) -> Option<crate::frame::Colour> {
162 match &self.inner {
163 Inner::H264(d) => d.colour(),
164 Inner::H265(d) => d.colour(),
165 Inner::Vp9(_) | Inner::Av1(_) => None,
166 }
167 }
168}
169
170/// Frames waiting to be collected, oldest first.
171///
172/// A decode call produces frames rather than returning one, because one access
173/// unit can complete none, one or several pictures. There is no event fd behind
174/// it: nothing in this family polls a decoder from an event loop, and adding an
175/// `eventfd(2)` would mean a second FFI surface in a crate whose whole unsafe
176/// budget is meant to be libva.
177#[derive(Debug, Default)]
178pub(crate) struct ReadyFrames {
179 queue: VecDeque<Frame>,
180}
181
182impl ReadyFrames {
183 pub(crate) fn push(&mut self, frame: Frame) {
184 self.queue.push_back(frame);
185 }
186
187 pub(crate) fn pop(&mut self) -> Option<Frame> {
188 self.queue.pop_front()
189 }
190
191 pub(crate) fn clear(&mut self) {
192 self.queue.clear();
193 }
194
195 pub(crate) fn len(&self) -> usize {
196 self.queue.len()
197 }
198}
199
200/// The GPU-side state one decoded stream needs: config, context, surfaces.
201pub(crate) struct Session {
202 pub(crate) context: Arc<Context>,
203 /// The readback image every frame of this stream reuses.
204 pub(crate) images: crate::frame::ImageCache,
205 pub(crate) pool: SurfacePool,
206 pub(crate) coded_size: (u32, u32),
207 pub(crate) display_size: (u32, u32),
208 pub(crate) bit_depth: u8,
209 pub(crate) profile: Profile,
210}
211
212impl Session {
213 /// Create a decode session, deriving the surface format from the *stream's*
214 /// bit depth.
215 ///
216 /// The bit depth is the whole point of this signature. An 8-bit context on
217 /// a 10-bit stream is the incumbent defect this crate exists to not repeat:
218 /// the driver either refuses the config or silently decodes to NV12 and
219 /// throws away two bits per sample.
220 pub(crate) fn new(
221 display: &Arc<Display>,
222 profile: Profile,
223 coded_size: (u32, u32),
224 display_size: (u32, u32),
225 bit_depth: u8,
226 num_surfaces: usize,
227 ) -> Result<Session> {
228 let caps = CapReport::probe(display)?;
229 let entry = caps.entry(profile, Entrypoint::VLD).ok_or_else(|| {
230 Error::unsupported(
231 format!("{profile:?} decode"),
232 "the driver advertises no VLD entrypoint for this profile",
233 )
234 })?;
235
236 let rt_format = if bit_depth > 8 {
237 sys::VA_RT_FORMAT_YUV420_10
238 } else {
239 sys::VA_RT_FORMAT_YUV420
240 };
241 if !entry.supports_rt_format(rt_format) {
242 return Err(Error::unsupported(
243 format!("{bit_depth}-bit {profile:?} decode"),
244 format!(
245 "the driver's RT format mask for this profile is {:#x}",
246 entry.rt_formats
247 ),
248 ));
249 }
250
251 let (w, h) = coded_size;
252 if let Some(surfaces) = &entry.surfaces
253 && !surfaces.allows(w, h)
254 {
255 return Err(Error::unsupported(
256 format!("{w}x{h} {profile:?} decode"),
257 format!(
258 "the driver accepts {:?}..{:?} x {:?}..{:?}",
259 surfaces.min_width,
260 surfaces.max_width,
261 surfaces.min_height,
262 surfaces.max_height
263 ),
264 ));
265 }
266
267 let config = Config::new(
268 display,
269 profile,
270 Entrypoint::VLD,
271 &[ConfigAttrib::rt_format(rt_format)],
272 )?;
273
274 let spec = if bit_depth > 8 {
275 SurfaceSpec::p010(w, h)
276 } else {
277 SurfaceSpec::nv12(w, h)
278 }
279 .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_DECODER);
280 let pool = SurfacePool::new(display, &spec, num_surfaces)?;
281 let context = Context::new(&config, w, h, sys::VA_PROGRESSIVE, pool.targets())?;
282
283 Ok(Session {
284 context,
285 images: crate::frame::ImageCache::default(),
286 pool,
287 coded_size,
288 display_size,
289 bit_depth,
290 profile,
291 })
292 }
293
294 /// Submit one picture: begin, render every buffer, end. No sync — the
295 /// driver keeps submissions in order within a context, and the wait belongs
296 /// where the pixels are actually read.
297 pub(crate) fn submit(&self, target: &Arc<Surface>, buffers: Vec<ec_va::Buffer>) -> Result<()> {
298 if buffers.is_empty() {
299 // radeonsi answers an empty submission with INVALID_CONTEXT, which
300 // reads like a driver bug report rather than what it is: a picture
301 // with no slices, i.e. a stream that lost its data.
302 return Err(Error::config(
303 "refusing to submit a picture with no parameter buffers",
304 ));
305 }
306 ec_va::Picture::new(&self.context, Arc::clone(target))
307 .begin()?
308 .render_all(buffers)?
309 .end()?;
310 Ok(())
311 }
312
313 pub(crate) fn info(&self) -> StreamInfo {
314 StreamInfo {
315 coded_size: self.coded_size,
316 display_size: self.display_size,
317 bit_depth: self.bit_depth,
318 profile: self.profile,
319 num_surfaces: self.pool.len(),
320 }
321 }
322}