forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs508 lines, 17.9 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::rc::Rc;
22use std::sync::atomic::Ordering;
23use std::time::{Duration, Instant};
24
25use ec_va::caps::{Entrypoint, Profile};
26use ec_va::va;
27use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec};
28
29use crate::error::{Error, Result};
30use crate::frame::Frame;
31use crate::pool::{PooledSurface, SurfacePool};
32
33pub use crate::types::Codec;
34
35mod av1;
36mod h264;
37mod vp9;
38
39#[doc(hidden)]
40pub use av1::Av1Decoder;
41#[doc(hidden)]
42pub use av1::fuzz_build_parameters as av1_fuzz_build_parameters;
43mod hevc;
44
45#[doc(hidden)]
46pub use h264::H264Decoder;
47#[doc(hidden)]
48pub use h264::fuzz_build_parameters as h264_fuzz_build_parameters;
49#[doc(hidden)]
50pub use vp9::Vp9Decoder;
51#[doc(hidden)]
52pub use vp9::fuzz_build_parameters as vp9_fuzz_build_parameters;
53pub use hevc::HevcDecoder;
54#[doc(hidden)]
55pub use hevc::fuzz_build_parameters as hevc_fuzz_build_parameters;
56
57/// What the stream turned out to be, once its first headers were parsed.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct StreamInfo {
60 /// Coded size, a multiple of the codec's block size.
61 pub coded_size: (u32, u32),
62 /// Size after cropping — what a player shows.
63 pub display_size: (u32, u32),
64 /// Luma bit depth.
65 pub bit_depth: u8,
66 /// The VA profile the context was created with.
67 pub profile: Profile,
68 /// Surfaces allocated for this stream.
69 pub num_surfaces: usize,
70}
71
72/// The units of a fuzz input: a run of little-endian `u32` lengths, each followed
73/// by that many bytes. A unit cut short by the end of the input is kept, and it ends
74/// the walk. Lets a fuzz target feed several chunks to one persistent parser.
75pub(crate) fn units(data: &[u8]) -> Vec<&[u8]> {
76 let mut out = Vec::new();
77 let mut rest = data;
78 while let Some((len, tail)) = rest.split_first_chunk::<4>() {
79 let take = (u32::from_le_bytes(*len) as usize).min(tail.len());
80 out.push(&tail[..take]);
81 rest = &tail[take..];
82 }
83 out
84}
85
86/// The RT format a decode context is created with: P010 (`YUV420_10`) for any
87/// stream above 8 bits, HEVC Main 10 included, and 8-bit 4:2:0 otherwise. A
88/// context that asks for 8-bit only cannot take a 10-bit surface.
89pub(crate) fn rt_format_for_bit_depth(bit_depth: u8) -> u32 {
90 if bit_depth > 8 {
91 va::VA_RT_FORMAT_YUV420_10
92 } else {
93 va::VA_RT_FORMAT_YUV420
94 }
95}
96
97/// A hardware decoder for one elementary stream.
98pub struct Decoder {
99 inner: Inner,
100}
101
102enum Inner {
103 H264(Box<H264Decoder>),
104 Vp9(Box<Vp9Decoder>),
105 Av1(Box<Av1Decoder>),
106 H265(Box<HevcDecoder>),
107}
108
109impl Decoder {
110 /// Open a decoder for `codec` on `display`.
111 ///
112 /// Nothing is allocated on the GPU yet: the surface pool and context need
113 /// the stream's size and bit depth, which only its first parameter set
114 /// carries, so they are created on the first [`Decoder::decode`] call.
115 pub fn new(display: &Rc<Display>, codec: Codec) -> Result<Decoder> {
116 let inner = match codec {
117 Codec::H264 => Inner::H264(Box::new(H264Decoder::new(display))),
118 Codec::Vp9 => Inner::Vp9(Box::new(Vp9Decoder::new(display))),
119 Codec::Av1 => Inner::Av1(Box::new(Av1Decoder::new(display))),
120 Codec::H265 => Inner::H265(Box::new(HevcDecoder::new(display))),
121 };
122 Ok(Decoder { inner })
123 }
124
125 /// Feed one access unit (H.264/HEVC: Annex B; VP9: one chunk; AV1: one
126 /// temporal unit) and queue whatever pictures it completed.
127 pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
128 match &mut self.inner {
129 Inner::H264(d) => d.decode(data, timestamp),
130 Inner::Vp9(d) => d.decode(data, timestamp),
131 Inner::Av1(d) => d.decode(data, timestamp),
132 Inner::H265(d) => d.decode(data, timestamp),
133 }
134 }
135
136 /// The next frame in display order, if one is ready.
137 pub fn next_frame(&mut self) -> Option<Frame> {
138 match &mut self.inner {
139 Inner::H264(d) => d.next_frame(),
140 Inner::Vp9(d) => d.next_frame(),
141 Inner::Av1(d) => d.next_frame(),
142 Inner::H265(d) => d.next_frame(),
143 }
144 }
145
146 /// End of stream: push every buffered picture out.
147 pub fn flush(&mut self) -> Result<()> {
148 match &mut self.inner {
149 Inner::H264(d) => d.flush(),
150 Inner::Vp9(d) => d.flush(),
151 Inner::Av1(d) => d.flush(),
152 Inner::H265(d) => d.flush(),
153 }
154 Ok(())
155 }
156
157 /// Discard all state after a seek. Parameter sets are kept.
158 pub fn reset(&mut self) {
159 match &mut self.inner {
160 Inner::H264(d) => d.reset(),
161 Inner::Vp9(d) => d.reset(),
162 Inner::Av1(d) => d.reset(),
163 Inner::H265(d) => d.reset(),
164 }
165 }
166
167 /// Pictures inferred for H.264 `frame_num` gaps (8.2.5.2); zero for the
168 /// other codecs, which have no such concept.
169 pub fn gap_frames_synthesized(&self) -> u64 {
170 match &self.inner {
171 Inner::H264(d) => d.gap_frames_synthesized(),
172 Inner::Vp9(_) | Inner::Av1(_) => 0,
173 Inner::H265(_) => 0,
174 }
175 }
176
177 /// What the stream turned out to be, once a session exists.
178 pub fn stream_info(&self) -> Option<StreamInfo> {
179 match &self.inner {
180 Inner::H264(d) => d.stream_info(),
181 Inner::Vp9(d) => d.stream_info(),
182 Inner::Av1(d) => d.stream_info(),
183 Inner::H265(d) => d.stream_info(),
184 }
185 }
186
187 /// This stream's colour metadata, once a session exists. [`None`] for VP9
188 /// and AV1: neither's sequence header colour config is parsed by this
189 /// family yet.
190 pub fn colour(&self) -> Option<crate::frame::Colour> {
191 match &self.inner {
192 Inner::H264(d) => d.colour(),
193 Inner::Vp9(_) | Inner::Av1(_) => None,
194 Inner::H265(d) => d.colour(),
195 }
196 }
197}
198
199/// Frames waiting to be collected, oldest first.
200///
201/// A decode call produces frames rather than returning one, because one access
202/// unit can complete none, one or several pictures. There is no event fd behind
203/// it: nothing in this family polls a decoder from an event loop, and adding an
204/// `eventfd(2)` would mean a second FFI surface in a crate whose whole unsafe
205/// budget is meant to be libva.
206#[derive(Debug, Default)]
207pub(crate) struct ReadyFrames {
208 queue: VecDeque<Frame>,
209}
210
211impl ReadyFrames {
212 pub(crate) fn push(&mut self, frame: Frame) {
213 self.queue.push_back(frame);
214 }
215
216 pub(crate) fn pop(&mut self) -> Option<Frame> {
217 self.queue.pop_front()
218 }
219
220 pub(crate) fn clear(&mut self) {
221 self.queue.clear();
222 }
223
224 pub(crate) fn len(&self) -> usize {
225 self.queue.len()
226 }
227}
228
229/// The GPU-side state one decoded stream needs: config, context, surfaces.
230/// A pending picture older than this is settled before the next submit, so a
231/// session that sat idle never submits behind an unchecked picture.
232const IDLE_SETTLE: Duration = Duration::from_millis(250);
233
234/// VA statuses that mean the context or the hardware is gone, not that one
235/// parameter was wrong.
236fn context_gone(status: i32) -> bool {
237 status_is(
238 status,
239 &[
240 va::VA_STATUS_ERROR_INVALID_CONTEXT,
241 va::VA_STATUS_ERROR_OPERATION_FAILED,
242 va::VA_STATUS_ERROR_HW_BUSY,
243 va::VA_STATUS_ERROR_TIMEDOUT,
244 va::VA_STATUS_ERROR_DECODING_ERROR,
245 ],
246 )
247}
248
249/// Whether a `VAStatus` is one of `codes` (libva's constants are unsigned,
250/// `VAStatus` is signed).
251fn status_is(status: i32, codes: &[u32]) -> bool {
252 codes.iter().any(|&c| c as i32 == status)
253}
254
255/// A picture submitted but not yet waited for.
256struct Pending {
257 surface: Rc<Surface>,
258 since: Instant,
259}
260
261pub(crate) struct Session {
262 /// The process-wide reset epoch this session was created in. Once it moves
263 /// the context has been reset along with the guilty one.
264 born_epoch: u64,
265 /// The last submitted picture, waited for after the next one is submitted
266 /// (depth-1 pipelining; see [`Session::submit`]).
267 pending: std::sync::Mutex<Option<Pending>>,
268 /// Set once a picture hung or lost the GPU context. Every submission after
269 /// that is refused: on Mesa, submitting to a context the kernel has reset
270 /// aborts the whole process from the driver's own thread, which no
271 /// `catch_unwind` can stop.
272 pub(crate) poisoned: std::sync::atomic::AtomicBool,
273 pub(crate) context: Rc<Context>,
274 display: Rc<Display>,
275 /// The readback image every frame of this stream reuses.
276 pub(crate) pool: SurfacePool,
277 pub(crate) coded_size: (u32, u32),
278 pub(crate) display_size: (u32, u32),
279 pub(crate) bit_depth: u8,
280 pub(crate) profile: Profile,
281}
282
283impl Session {
284 /// Create a decode session, deriving the surface format from the *stream's*
285 /// bit depth.
286 ///
287 /// The bit depth is the whole point of this signature. An 8-bit context on
288 /// a 10-bit stream is the incumbent defect this crate exists to not repeat:
289 /// the driver either refuses the config or silently decodes to NV12 and
290 /// throws away two bits per sample.
291 pub(crate) fn new(
292 display: &Rc<Display>,
293 profile: Profile,
294 coded_size: (u32, u32),
295 display_size: (u32, u32),
296 bit_depth: u8,
297 num_surfaces: usize,
298 ) -> Result<Session> {
299 let born_epoch = crate::reset::gpu_reset_epoch();
300 if crate::reset::gpu_recently_reset() {
301 return Err(Error::hw_reset(
302 "the GPU was reset moments ago; new hardware sessions wait out the grace period",
303 ));
304 }
305 let caps = CapReport::probe(display)?;
306 let entry = caps.entry(profile, Entrypoint::VLD).ok_or_else(|| {
307 Error::unsupported(
308 format!("{profile:?} decode"),
309 "the driver advertises no VLD entrypoint for this profile",
310 )
311 })?;
312
313 let rt_format = rt_format_for_bit_depth(bit_depth);
314 if !entry.supports_rt_format(rt_format) {
315 return Err(Error::unsupported(
316 format!("{bit_depth}-bit {profile:?} decode"),
317 format!(
318 "the driver's RT format mask for this profile is {:#x}",
319 entry.rt_formats
320 ),
321 ));
322 }
323
324 let (w, h) = coded_size;
325 let (dw, dh) = display_size;
326 if let Some(surfaces) = &entry.surfaces
327 && !(surfaces.allows(w, h) && surfaces.allows(dw.max(1), dh.max(1)))
328 {
329 return Err(Error::unsupported(
330 format!("{dw}x{dh} {profile:?} decode"),
331 format!(
332 "the driver accepts {:?}..{:?} x {:?}..{:?}",
333 surfaces.min_width,
334 surfaces.max_width,
335 surfaces.min_height,
336 surfaces.max_height
337 ),
338 ));
339 }
340
341 let config = Config::new(
342 display,
343 profile,
344 Entrypoint::VLD,
345 &[ConfigAttrib::rt_format(rt_format)],
346 )?;
347
348 let spec = if bit_depth > 8 {
349 SurfaceSpec::p010(w, h)
350 } else {
351 SurfaceSpec::nv12(w, h)
352 }
353 .with_usage_hint(va::VA_SURFACE_ATTRIB_USAGE_HINT_DECODER);
354 let surfaces = ec_va::create_pool(display, &spec, num_surfaces)?;
355 let context =
356 ec_va::picture::create_context(display, &config, w, h, Some(&surfaces), true)?;
357 let pool = SurfacePool::from_surfaces(surfaces, &spec);
358
359 if crate::reset::gpu_reset_epoch() != born_epoch {
360 return Err(Error::hw_reset(
361 "the GPU was reset while the session was created",
362 ));
363 }
364 Ok(Session {
365 born_epoch,
366 pending: std::sync::Mutex::new(None),
367 poisoned: std::sync::atomic::AtomicBool::new(false),
368 context,
369 display: Rc::clone(display),
370 pool,
371 coded_size,
372 display_size,
373 bit_depth,
374 profile,
375 })
376 }
377
378 /// A free surface for the next picture. Frames the caller has not taken yet hold
379 /// their surfaces, so when the pool runs dry it grows by one surface instead of
380 /// failing the decode.
381 pub(crate) fn acquire(&self) -> Result<Rc<PooledSurface>> {
382 if let Some(surface) = self.pool.acquire() {
383 return Ok(surface);
384 }
385 let spec = *self.pool.spec();
386 self.pool.grow(ec_va::create_pool(&self.display, &spec, 1)?);
387 self.pool
388 .acquire()
389 .ok_or_else(|| Error::config("surface pool empty after growing"))
390 }
391
392 /// Submit one picture: begin, render every buffer, end, then wait for the
393 /// *previous* picture (depth-1 pipelining).
394 ///
395 /// A corrupt slice can hang the ring; the kernel resets it after its job
396 /// timeout, and every context that submits afterwards is aborted by the
397 /// driver. So a wait that errors or runs long condemns the whole process's
398 /// sessions ([`crate::reset`]) and nothing submits to a reset context.
399 ///
400 /// Waiting for picture N-1 after submitting N keeps the GPU one picture
401 /// ahead of the CPU. It never submits behind an undetected reset: the hung
402 /// picture is waited for right after the next submit (the ring cannot have
403 /// been reset yet, the job timeout is seconds), and a pending picture
404 /// older than [`IDLE_SETTLE`] is settled before anything is submitted.
405 /// Frames read back also watch their wait ([`crate::reset::sync_watched`]).
406 pub(crate) fn submit(&self, target: &Rc<Surface>, buffers: Vec<ec_va::Buffer>) -> Result<()> {
407 if buffers.is_empty() {
408 // radeonsi answers an empty submission with INVALID_CONTEXT, which
409 // reads like a driver bug report rather than what it is: a picture
410 // with no slices, i.e. a stream that lost its data.
411 return Err(Error::config(
412 "refusing to submit a picture with no parameter buffers",
413 ));
414 }
415 self.check_alive()?;
416 // An old pending picture is waited for first: its wait is instant when
417 // it is done, and an error condemns the session before we submit.
418 let stale = self
419 .pending_slot()
420 .as_ref()
421 .filter(|p| p.since.elapsed() > IDLE_SETTLE)
422 .map(|p| Rc::clone(&p.surface));
423 if let Some(old) = stale {
424 self.settle(&old)?;
425 self.check_alive()?;
426 }
427 let outcome = ec_va::picture::submit(&self.context, Rc::clone(target), buffers);
428 if let Err(e) = outcome {
429 match e.status() {
430 Some(status)
431 if status_is(
432 status,
433 &[
434 va::VA_STATUS_ERROR_OPERATION_FAILED,
435 va::VA_STATUS_ERROR_DECODING_ERROR,
436 ],
437 ) =>
438 {
439 self.poison()
440 }
441 Some(status) if context_gone(status) => crate::reset::report_gpu_reset(),
442 _ => {}
443 }
444 return Err(e.into());
445 }
446 let previous = self.pending_slot().replace(Pending {
447 surface: Rc::clone(target),
448 since: Instant::now(),
449 });
450 if let Some(previous) = previous {
451 self.settle(&previous.surface)?;
452 }
453 Ok(())
454 }
455
456 fn pending_slot(&self) -> std::sync::MutexGuard<'_, Option<Pending>> {
457 match self.pending.lock() {
458 Ok(slot) => slot,
459 Err(poisoned) => poisoned.into_inner(),
460 }
461 }
462
463 fn check_alive(&self) -> Result<()> {
464 if crate::reset::gpu_reset_epoch() != self.born_epoch {
465 return Err(Error::hw_reset(
466 "the GPU was reset after this session was created; its context is lost",
467 ));
468 }
469 if self.poisoned.load(Ordering::Acquire) {
470 return Err(Error::poisoned("an earlier picture failed on the GPU"));
471 }
472 Ok(())
473 }
474
475 fn poison(&self) {
476 self.poisoned.store(true, Ordering::Release);
477 }
478
479 /// Wait for a submitted picture, condemning every session on a reset.
480 fn settle(&self, surface: &Surface) -> Result<()> {
481 crate::reset::sync_watched(surface)
482 }
483
484 pub(crate) fn info(&self) -> StreamInfo {
485 StreamInfo {
486 coded_size: self.coded_size,
487 display_size: self.display_size,
488 bit_depth: self.bit_depth,
489 profile: self.profile,
490 num_surfaces: self.pool.len(),
491 }
492 }
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 // Regression: a decode context was always created 8-bit 4:2:0, so no HEVC
500 // Main 10 stream could decode into its P010 surfaces (cros-codecs patch
501 // in edith vendor/, backend/vaapi/decoder.rs, "upstream's own TODO").
502 #[test]
503 fn decode_context_rt_format_follows_the_bit_depth() {
504 assert_eq!(rt_format_for_bit_depth(8), va::VA_RT_FORMAT_YUV420);
505 assert_eq!(rt_format_for_bit_depth(10), va::VA_RT_FORMAT_YUV420_10);
506 assert_ne!(rt_format_for_bit_depth(10), rt_format_for_bit_depth(8));
507 }
508}