forge
Explore
Log in

Don't you dare go Hollow

Stateless decoding for H.264, HEVC, VP9 and AV1

Browse files at this commit

eb589d4476ae5c7ee75760efd049f3af32b61708Ahmet Kaan GümüşParent: 89d28a7
  • feat
    • stateless decoding for H.264, HEVC, VP9 and AV1
Show full message
feat(hw): stateless decoding for H.264, HEVC, VP9 and AV1

One decoder per codec behind one `Decoder`. The driver keeps nothing
between pictures, so everything the format spreads across frames lives
here: the H.264 decoded picture buffer with its picture order counts,
reference numbering, list initialisation and modification and marking
(clause 8.2); HEVC's reference picture sets and bumping; VP9's and AV1's
reference slots with `show_existing_frame`. Frames leave in display
order.

Three of the four incumbent defects are addressed by construction:

- The RT format follows the *stream's* bit depth, so a Main10 stream
  gets a 10-bit config and a P010 surface instead of losing two bits per
  sample.
- A `frame_num` gap is a normal condition — a seek, a lost packet, an
  encoder that skipped a picture — and the missing pictures are inferred
  per 8.2.5.2 rather than ending the hardware session. The inferred
  frames share the newest reference's surface, which is both a better
  guess than grey and the only choice this driver accepts.
- Surfaces come from a pool and mappings are guards, so a long export
  neither reallocates nor leaks.

The scaling matrices are sent for every H.264 picture whether or not the
stream carries any: a driver that never receives them dequantises with a
zero matrix and hands back a uniformly grey frame.
crates/ec-hw/src/dec/av1.rsadded+402 -0
@@ -0,0 +1,402 @@
1+//! Stateless AV1 decoding.
2+
3+use std::sync::Arc;
4+
5+use ec_av1_syntax::{
6+ Av1Parser, FrameHeader, FrameType, NUM_REF_FRAMES, ObuKind, REFS_PER_FRAME, SequenceHeader,
7+ Tile,
8+};
9+use ec_va::caps::Profile;
10+use ec_va::{Buffer, Display, sys};
11+
12+use super::{ReadyFrames, Session, StreamInfo};
13+use crate::error::{Error, Result};
14+use crate::frame::Frame;
15+use crate::params::av1::{
16+ PictureParameterBufferAV1, SliceParameterBufferAV1, WarpedMotionParamsAV1,
17+};
18+use crate::params::param_buffer;
19+use crate::pool::PooledSurface;
20+
21+/// Reference slots plus the picture being decoded plus caller-held frames.
22+const EXTRA_SURFACES: usize = 6;
23+
24+/// A stateless AV1 decoder.
25+pub struct Av1Decoder {
26+ display: Arc<Display>,
27+ parser: Av1Parser,
28+ session: Option<Session>,
29+ refs: [Option<Arc<PooledSurface>>; NUM_REF_FRAMES],
30+ ready: ReadyFrames,
31+}
32+
33+impl Av1Decoder {
34+ /// A decoder with no stream state.
35+ pub fn new(display: &Arc<Display>) -> Av1Decoder {
36+ Av1Decoder {
37+ display: Arc::clone(display),
38+ parser: Av1Parser::new(),
39+ session: None,
40+ refs: [const { None }; NUM_REF_FRAMES],
41+ ready: ReadyFrames::default(),
42+ }
43+ }
44+
45+ /// Decode one temporal unit — every OBU of it, in order.
46+ pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
47+ if data.is_empty() {
48+ return Ok(());
49+ }
50+ // Tile offsets in the parse result are relative to `data`, and `data`
51+ // is what the driver is handed, so no rebasing is needed anywhere.
52+ let obus = self.parser.parse_temporal_unit(data)?;
53+ let mut pending: Option<Box<FrameHeader>> = None;
54+ for obu in obus {
55+ match obu.kind {
56+ ObuKind::FrameHeader(header) => {
57+ if header.show_existing_frame {
58+ self.show_existing(&header, timestamp)?;
59+ } else {
60+ pending = Some(header);
61+ }
62+ }
63+ ObuKind::TileGroup(tiles) => {
64+ if let Some(header) = pending.take() {
65+ self.decode_frame(&header, &tiles, data, timestamp)?;
66+ }
67+ }
68+ ObuKind::Frame(header, tiles) => {
69+ if header.show_existing_frame {
70+ self.show_existing(&header, timestamp)?;
71+ } else {
72+ self.decode_frame(&header, &tiles, data, timestamp)?;
73+ }
74+ }
75+ _ => {}
76+ }
77+ }
78+ Ok(())
79+ }
80+
81+ /// The next frame to show.
82+ pub fn next_frame(&mut self) -> Option<Frame> {
83+ self.ready.pop()
84+ }
85+
86+ /// Nothing is buffered beyond the reference slots.
87+ pub fn flush(&mut self) {}
88+
89+ /// Drop reference state after a seek.
90+ pub fn reset(&mut self) {
91+ self.parser = Av1Parser::new();
92+ self.refs = [const { None }; NUM_REF_FRAMES];
93+ self.ready.clear();
94+ }
95+
96+ /// What the stream turned out to be.
97+ pub fn stream_info(&self) -> Option<StreamInfo> {
98+ self.session.as_ref().map(Session::info)
99+ }
100+
101+ fn show_existing(&mut self, header: &FrameHeader, timestamp: i64) -> Result<()> {
102+ let slot = usize::from(header.frame_to_show_map_idx);
103+ let (Some(surface), Some(session)) = (
104+ self.refs.get(slot).and_then(|s| s.clone()),
105+ self.session.as_ref(),
106+ ) else {
107+ return Err(Error::Stream(ec_core::Error::corrupt(
108+ "AV1 show_existing_frame names an empty reference slot",
109+ )));
110+ };
111+ self.ready.push(Frame::new(
112+ Arc::clone(&surface),
113+ Arc::clone(&session.images),
114+ timestamp,
115+ (header.render_width, header.render_height),
116+ session.coded_size,
117+ session.bit_depth,
118+ ));
119+ // 7.21: showing a KEY frame again refreshes every reference slot with
120+ // it, which the reference *surfaces* have to follow too.
121+ if header.frame_type == FrameType::Key {
122+ for entry in &mut self.refs {
123+ *entry = Some(Arc::clone(&surface));
124+ }
125+ }
126+ Ok(())
127+ }
128+
129+ fn decode_frame(
130+ &mut self,
131+ header: &FrameHeader,
132+ tiles: &[Tile],
133+ data: &[u8],
134+ timestamp: i64,
135+ ) -> Result<()> {
136+ let sequence = self
137+ .parser
138+ .sequence_header()
139+ .cloned()
140+ .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?;
141+ self.ensure_session(&sequence, header)?;
142+ let session = self
143+ .session
144+ .as_ref()
145+ .ok_or_else(|| Error::config("AV1 frame before any session"))?;
146+ let surface = session
147+ .pool
148+ .acquire()
149+ .ok_or_else(|| Error::config("AV1 decode: every surface is still in use"))?;
150+
151+ let pic_param = self.picture_parameters(&sequence, header, surface.id());
152+ let mut buffers = Vec::with_capacity(tiles.len() + 2);
153+ buffers.push(param_buffer(&session.context, &pic_param)?);
154+ for tile in tiles {
155+ let slice = SliceParameterBufferAV1 {
156+ slice_data_size: tile.size as u32,
157+ slice_data_offset: tile.offset as u32,
158+ slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL
159+ tile_row: tile.row as u16,
160+ tile_column: tile.column as u16,
161+ ..SliceParameterBufferAV1::default()
162+ };
163+ buffers.push(param_buffer(&session.context, &slice)?);
164+ }
165+ buffers.push(Buffer::from_bytes(
166+ &session.context,
167+ sys::VASliceDataBufferType,
168+ data,
169+ )?);
170+ session.submit(&surface, buffers)?;
171+
172+ for slot in 0..NUM_REF_FRAMES {
173+ if header.refresh_frame_flags & (1 << slot) != 0 {
174+ self.refs[slot] = Some(Arc::clone(&surface));
175+ }
176+ }
177+
178+ if header.show_frame {
179+ self.ready.push(Frame::new(
180+ surface,
181+ Arc::clone(&session.images),
182+ timestamp,
183+ (header.render_width, header.render_height),
184+ session.coded_size,
185+ session.bit_depth,
186+ ));
187+ }
188+ Ok(())
189+ }
190+
191+ fn ensure_session(&mut self, seq: &SequenceHeader, header: &FrameHeader) -> Result<()> {
192+ let bit_depth = seq.color_config.bit_depth;
193+ let profile = match (seq.seq_profile, bit_depth) {
194+ (0, _) => Profile::AV1Profile0,
195+ (2, _) => Profile::AV1Profile2,
196+ (other, _) => {
197+ return Err(Error::unsupported(
198+ format!("AV1 profile {other}"),
199+ "only the 4:2:0 profiles 0 and 2 are decoded in hardware",
200+ ));
201+ }
202+ };
203+ // Superblocks are 64x64 or 128x128; a surface holds whole ones.
204+ let sb = if seq.use_128x128_superblock { 128 } else { 64 };
205+ let coded = (
206+ header.upscaled_width.next_multiple_of(sb).max(sb),
207+ header.frame_height.next_multiple_of(sb).max(sb),
208+ );
209+ if let Some(session) = &self.session
210+ && session.coded_size.0 >= coded.0
211+ && session.coded_size.1 >= coded.1
212+ && session.bit_depth == bit_depth
213+ && session.profile == profile
214+ {
215+ return Ok(());
216+ }
217+ self.refs = [const { None }; NUM_REF_FRAMES];
218+ self.session = Some(Session::new(
219+ &self.display,
220+ profile,
221+ coded,
222+ (header.render_width, header.render_height),
223+ bit_depth,
224+ NUM_REF_FRAMES + EXTRA_SURFACES,
225+ )?);
226+ Ok(())
227+ }
228+
229+ fn picture_parameters(
230+ &self,
231+ seq: &SequenceHeader,
232+ h: &FrameHeader,
233+ current: sys::VASurfaceID,
234+ ) -> PictureParameterBufferAV1 {
235+ let sb_shift = if seq.use_128x128_superblock { 5 } else { 4 };
236+ let mut p = PictureParameterBufferAV1 {
237+ profile: seq.seq_profile,
238+ order_hint_bits_minus_1: seq.order_hint_bits.saturating_sub(1) as u8,
239+ bit_depth_idx: match seq.color_config.bit_depth {
240+ 8 => 0,
241+ 10 => 1,
242+ _ => 2,
243+ },
244+ matrix_coefficients: seq.color_config.matrix_coefficients,
245+ current_frame: current,
246+ current_display_picture: current,
247+ frame_width_minus1: (h.upscaled_width.max(1) - 1) as u16,
248+ frame_height_minus1: (h.frame_height.max(1) - 1) as u16,
249+ primary_ref_frame: h.primary_ref_frame,
250+ order_hint: h.order_hint as u8,
251+ tile_cols: h.tile_info.cols.min(255) as u8,
252+ tile_rows: h.tile_info.rows.min(255) as u8,
253+ tile_count_minus_1: (h.tile_info.cols * h.tile_info.rows).max(1) as u16 - 1,
254+ context_update_tile_id: h.tile_info.context_update_tile_id as u16,
255+ superres_scale_denominator: h.superres_denom,
256+ interp_filter: h.interpolation_filter as u8,
257+ filter_level: [h.loop_filter.level[0], h.loop_filter.level[1]],
258+ filter_level_u: h.loop_filter.level[2],
259+ filter_level_v: h.loop_filter.level[3],
260+ ref_deltas: h.loop_filter.ref_deltas,
261+ mode_deltas: h.loop_filter.mode_deltas,
262+ base_qindex: h.quantization.base_q_idx,
263+ y_dc_delta_q: h.quantization.delta_q_y_dc,
264+ u_dc_delta_q: h.quantization.delta_q_u_dc,
265+ u_ac_delta_q: h.quantization.delta_q_u_ac,
266+ v_dc_delta_q: h.quantization.delta_q_v_dc,
267+ v_ac_delta_q: h.quantization.delta_q_v_ac,
268+ cdef_damping_minus_3: h.cdef.damping.saturating_sub(3),
269+ cdef_bits: h.cdef.bits,
270+ cdef_y_strengths: h.cdef.y_strengths(),
271+ cdef_uv_strengths: h.cdef.uv_strengths(),
272+ ..PictureParameterBufferAV1::default()
273+ };
274+
275+ for (slot, surface) in self.refs.iter().enumerate() {
276+ if let Some(surface) = surface {
277+ p.ref_frame_map[slot] = surface.id();
278+ }
279+ }
280+ for i in 0..REFS_PER_FRAME {
281+ p.ref_frame_idx[i] = h.ref_frame_idx[i];
282+ }
283+
284+ for (i, sbs) in h
285+ .tile_info
286+ .width_in_sbs_minus_1(sb_shift)
287+ .into_iter()
288+ .take(p.width_in_sbs_minus_1.len())
289+ .enumerate()
290+ {
291+ p.width_in_sbs_minus_1[i] = sbs;
292+ }
293+ for (i, sbs) in h
294+ .tile_info
295+ .height_in_sbs_minus_1(sb_shift)
296+ .into_iter()
297+ .take(p.height_in_sbs_minus_1.len())
298+ .enumerate()
299+ {
300+ p.height_in_sbs_minus_1[i] = sbs;
301+ }
302+
303+ p.seq_info_fields = p
304+ .seq_info_fields
305+ .still_picture(u32::from(seq.still_picture))
306+ .use_128x128_superblock(u32::from(seq.use_128x128_superblock))
307+ .enable_filter_intra(u32::from(seq.enable_filter_intra))
308+ .enable_intra_edge_filter(u32::from(seq.enable_intra_edge_filter))
309+ .enable_interintra_compound(u32::from(seq.enable_interintra_compound))
310+ .enable_masked_compound(u32::from(seq.enable_masked_compound))
311+ .enable_dual_filter(u32::from(seq.enable_dual_filter))
312+ .enable_order_hint(u32::from(seq.enable_order_hint))
313+ .enable_jnt_comp(u32::from(seq.enable_jnt_comp))
314+ .enable_cdef(u32::from(seq.enable_cdef))
315+ .mono_chrome(u32::from(seq.color_config.mono_chrome))
316+ .color_range(u32::from(seq.color_config.color_range))
317+ .subsampling_x(u32::from(seq.color_config.subsampling_x))
318+ .subsampling_y(u32::from(seq.color_config.subsampling_y))
319+ .film_grain_params_present(u32::from(seq.film_grain_params_present));
320+
321+ p.pic_info_fields = p
322+ .pic_info_fields
323+ .frame_type(h.frame_type as u32)
324+ .show_frame(u32::from(h.show_frame))
325+ .showable_frame(u32::from(h.showable_frame))
326+ .error_resilient_mode(u32::from(h.error_resilient_mode))
327+ .disable_cdf_update(u32::from(h.disable_cdf_update))
328+ .allow_screen_content_tools(u32::from(h.allow_screen_content_tools))
329+ .force_integer_mv(u32::from(h.force_integer_mv))
330+ .allow_intrabc(u32::from(h.allow_intrabc))
331+ .use_superres(u32::from(h.use_superres))
332+ .allow_high_precision_mv(u32::from(h.allow_high_precision_mv))
333+ .is_motion_mode_switchable(u32::from(h.is_motion_mode_switchable))
334+ .use_ref_frame_mvs(u32::from(h.use_ref_frame_mvs))
335+ .disable_frame_end_update_cdf(u32::from(h.disable_frame_end_update_cdf))
336+ .uniform_tile_spacing_flag(u32::from(h.tile_info.uniform_spacing))
337+ .allow_warped_motion(u32::from(h.allow_warped_motion));
338+
339+ p.loop_filter_info_fields = p
340+ .loop_filter_info_fields
341+ .sharpness_level(h.loop_filter.sharpness)
342+ .mode_ref_delta_enabled(u8::from(h.loop_filter.delta_enabled))
343+ .mode_ref_delta_update(u8::from(h.loop_filter.delta_update));
344+
345+ p.qmatrix_fields = p
346+ .qmatrix_fields
347+ .using_qmatrix(u16::from(h.quantization.using_qmatrix))
348+ .qm_y(u16::from(h.quantization.qm_y))
349+ .qm_u(u16::from(h.quantization.qm_u))
350+ .qm_v(u16::from(h.quantization.qm_v));
351+
352+ p.mode_control_fields = p
353+ .mode_control_fields
354+ .delta_q_present_flag(u32::from(h.delta.q_present))
355+ .log2_delta_q_res(u32::from(h.delta.q_res))
356+ .delta_lf_present_flag(u32::from(h.delta.lf_present))
357+ .log2_delta_lf_res(u32::from(h.delta.lf_res))
358+ .delta_lf_multi(u32::from(h.delta.lf_multi))
359+ .tx_mode(h.tx_mode as u32)
360+ .reference_select(u32::from(h.reference_select))
361+ .reduced_tx_set_used(u32::from(h.reduced_tx_set))
362+ .skip_mode_present(u32::from(h.skip_mode_present));
363+
364+ p.loop_restoration_fields = p
365+ .loop_restoration_fields
366+ .yframe_restoration_type(h.loop_restoration.frame_restoration_type[0] as u16)
367+ .cbframe_restoration_type(h.loop_restoration.frame_restoration_type[1] as u16)
368+ .crframe_restoration_type(h.loop_restoration.frame_restoration_type[2] as u16)
369+ .lr_unit_shift(u16::from(h.loop_restoration.lr_unit_shift))
370+ .lr_uv_shift(u16::from(h.loop_restoration.lr_uv_shift));
371+
372+ p.seg_info.segment_info_fields = p
373+ .seg_info
374+ .segment_info_fields
375+ .enabled(u32::from(h.segmentation.enabled))
376+ .update_map(u32::from(h.segmentation.update_map))
377+ .temporal_update(u32::from(h.segmentation.temporal_update))
378+ .update_data(u32::from(h.segmentation.update_data));
379+ for segment in 0..ec_av1_syntax::MAX_SEGMENTS {
380+ p.seg_info.feature_data[segment] = h.segmentation.feature_data[segment];
381+ p.seg_info.feature_mask[segment] = h.segmentation.feature_mask(segment);
382+ }
383+
384+ for i in 0..REFS_PER_FRAME {
385+ let warp = &h.global_motion[i];
386+ let mut wm = WarpedMotionParamsAV1 {
387+ wmtype: warp.model as i32,
388+ invalid: u8::from(warp.invalid),
389+ ..WarpedMotionParamsAV1::default()
390+ };
391+ wm.wmmat[..6].copy_from_slice(&warp.params);
392+ p.wm[i] = wm;
393+ }
394+
395+ // Film grain is a display-side effect, and edith wants the ungrained
396+ // reconstruction to grade and scale; the parameters are still carried
397+ // so a caller that wants grain has them.
398+ p.film_grain_info.film_grain_info_fields =
399+ p.film_grain_info.film_grain_info_fields.apply_grain(0);
400+ p
401+ }
402+}
crates/ec-hw/src/dec/dpb264.rsadded+960 -0
@@ -0,0 +1,960 @@
1+//! The H.264 decoded picture buffer, clause 8.2, over surfaces.
2+//!
3+//! Same clauses as `ec-h264`'s software DPB — picture order count (8.2.1),
4+//! reference numbering (8.2.4.1), list initialisation and modification
5+//! (8.2.4.2/8.2.4.3), marking (8.2.5) and bumping (C.4.5.3) — but a stored
6+//! picture here is a *surface*, not a plane of samples. A stateless driver is
7+//! told the whole buffer on every picture, so these lists are the parameter
8+//! buffer's contents rather than an internal detail.
9+
10+use std::sync::Arc;
11+
12+use ec_h264_syntax::{DecRefPicMarking, RefPicListMod, SliceType, Sps};
13+
14+use crate::error::{Error, Result};
15+use crate::pool::PooledSurface;
16+
17+/// Maximum pictures held at once (Annex A caps the DPB at 16 frames; the extra
18+/// slot is the picture being decoded).
19+pub(crate) const MAX_STORED: usize = 17;
20+
21+/// How a stored picture is marked for reference (8.2.5.1).
22+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23+pub(crate) enum Mark {
24+ /// Not used for reference.
25+ Unused,
26+ /// Used for short-term reference.
27+ Short,
28+ /// Used for long-term reference.
29+ Long,
30+}
31+
32+/// One picture in the buffer.
33+pub(crate) struct Picture {
34+ /// Identity, so "the picture just stored" survives reordering.
35+ pub id: i32,
36+ /// The surface it decoded into.
37+ pub surface: Arc<PooledSurface>,
38+ /// Presentation timestamp of the access unit it came from.
39+ pub timestamp: i64,
40+ /// `frame_num`.
41+ pub frame_num: u32,
42+ /// `FrameNumWrap` (8.2.4.1).
43+ pub frame_num_wrap: i32,
44+ /// `PicNum` for short-term, `LongTermPicNum` for long-term pictures.
45+ pub pic_num: i32,
46+ /// `LongTermFrameIdx`.
47+ pub long_term_frame_idx: u32,
48+ /// `PicOrderCnt()`.
49+ pub poc: i32,
50+ /// `PicOrderCntMsb`, predicted from by the next picture.
51+ pub poc_msb: i32,
52+ /// `pic_order_cnt_lsb`.
53+ pub poc_lsb: i32,
54+ /// `FrameNumOffset`.
55+ pub frame_num_offset: i32,
56+ /// Reference marking.
57+ pub mark: Mark,
58+ /// Inferred for a `frame_num` gap (8.2.5.2): a legal P reference with
59+ /// unspecified samples, never output.
60+ pub non_existing: bool,
61+ /// Still waiting to be handed to the caller.
62+ pub output: bool,
63+}
64+
65+impl Picture {
66+ fn stored(&self) -> bool {
67+ self.output || self.mark != Mark::Unused
68+ }
69+}
70+
71+/// One reference picture list (`RefPicList0` / `RefPicList1`), as DPB indices.
72+#[derive(Clone, Copy, Debug)]
73+pub(crate) struct RefList {
74+ entries: [u8; 33],
75+ len: usize,
76+}
77+
78+impl Default for RefList {
79+ fn default() -> RefList {
80+ RefList {
81+ entries: [0; 33],
82+ len: 0,
83+ }
84+ }
85+}
86+
87+impl RefList {
88+ pub(crate) fn len(&self) -> usize {
89+ self.len
90+ }
91+
92+ /// The DPB index of `RefPicListX[idx]`, `None` past the end.
93+ pub(crate) fn get(&self, idx: usize) -> Option<usize> {
94+ (idx < self.len).then(|| usize::from(self.entries[idx]))
95+ }
96+
97+ fn push(&mut self, idx: usize) {
98+ if self.len < self.entries.len() {
99+ self.entries[self.len] = idx as u8;
100+ self.len += 1;
101+ }
102+ }
103+}
104+
105+/// Output of the picture order count derivation (8.2.1).
106+#[derive(Clone, Copy, Debug, Default)]
107+pub(crate) struct Poc {
108+ pub value: i32,
109+ pub frame_num_offset: i32,
110+ pub msb: i32,
111+ pub lsb: i32,
112+}
113+
114+/// What the DPB needs to know about the picture being decoded, taken from its
115+/// first slice header.
116+#[derive(Clone, Copy, Debug)]
117+pub(crate) struct PicInfo {
118+ pub is_idr: bool,
119+ pub is_reference: bool,
120+ pub frame_num: u32,
121+ pub pic_order_cnt_lsb: u32,
122+ pub delta_pic_order_cnt_bottom: i32,
123+ pub delta_pic_order_cnt: [i32; 2],
124+}
125+
126+/// The decoded picture buffer and the cross-picture state of clause 8.2.
127+pub(crate) struct Dpb {
128+ pub frames: Vec<Picture>,
129+ next_id: i32,
130+ max_frames: usize,
131+ max_reorder: usize,
132+ max_long_term_idx: Option<u32>,
133+ prev_poc_msb: i32,
134+ prev_poc_lsb: i32,
135+ prev_frame_num: u32,
136+ prev_frame_num_offset: i32,
137+ prev_has_mmco5: bool,
138+ prev_ref_frame_num: u32,
139+ started: bool,
140+ pending_flush: bool,
141+ last_id: i32,
142+}
143+
144+impl Default for Dpb {
145+ fn default() -> Dpb {
146+ Dpb {
147+ frames: Vec::new(),
148+ next_id: 0,
149+ max_frames: 16,
150+ max_reorder: 16,
151+ max_long_term_idx: None,
152+ prev_poc_msb: 0,
153+ prev_poc_lsb: 0,
154+ prev_frame_num: 0,
155+ prev_frame_num_offset: 0,
156+ prev_has_mmco5: false,
157+ prev_ref_frame_num: 0,
158+ started: false,
159+ pending_flush: false,
160+ last_id: -1,
161+ }
162+ }
163+}
164+
165+impl Dpb {
166+ /// Adopt the buffer limits of `sps` (Annex A / VUI).
167+ pub(crate) fn configure(&mut self, sps: &Sps) {
168+ let level_frames = max_dpb_frames(sps);
169+ let (buffering, reorder) = match sps.vui.as_ref().and_then(|v| v.bitstream_restriction) {
170+ Some(r) => (
171+ (r.max_dec_frame_buffering as usize).min(MAX_STORED - 1),
172+ (r.max_num_reorder_frames as usize).min(MAX_STORED - 1),
173+ ),
174+ None => (level_frames, level_frames),
175+ };
176+ self.max_frames = buffering.max(sps.max_num_ref_frames as usize).max(1);
177+ self.max_reorder = reorder.min(self.max_frames);
178+ }
179+
180+ /// How many frames the level allows, for sizing the surface pool.
181+ pub(crate) fn capacity(&self) -> usize {
182+ self.max_frames
183+ }
184+
185+ pub(crate) fn next_id(&mut self) -> i32 {
186+ let id = self.next_id;
187+ self.next_id = self.next_id.wrapping_add(1);
188+ id
189+ }
190+
191+ /// Drop every stored picture (seek or stream discontinuity).
192+ pub(crate) fn clear(&mut self) {
193+ self.frames.clear();
194+ self.max_long_term_idx = None;
195+ self.prev_poc_msb = 0;
196+ self.prev_poc_lsb = 0;
197+ self.prev_frame_num = 0;
198+ self.prev_frame_num_offset = 0;
199+ self.prev_has_mmco5 = false;
200+ self.prev_ref_frame_num = 0;
201+ self.started = false;
202+ self.pending_flush = false;
203+ self.last_id = -1;
204+ }
205+
206+ /// `PicOrderCnt()` of the picture about to be decoded (8.2.1).
207+ pub(crate) fn picture_order_count(&self, sps: &Sps, info: &PicInfo) -> Result<Poc> {
208+ match sps.pic_order_cnt_type {
209+ 0 => {
210+ let max_lsb = 1i32 << sps.log2_max_pic_order_cnt_lsb;
211+ let (prev_msb, prev_lsb) = if info.is_idr {
212+ (0, 0)
213+ } else {
214+ (self.prev_poc_msb, self.prev_poc_lsb)
215+ };
216+ let lsb = info.pic_order_cnt_lsb as i32;
217+ let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 {
218+ prev_msb + max_lsb
219+ } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 {
220+ prev_msb - max_lsb
221+ } else {
222+ prev_msb
223+ };
224+ let top = msb + lsb;
225+ let bottom = top + info.delta_pic_order_cnt_bottom;
226+ Ok(Poc {
227+ value: top.min(bottom),
228+ frame_num_offset: 0,
229+ msb,
230+ lsb,
231+ })
232+ }
233+ 1 => {
234+ let max_frame_num = 1i32 << sps.log2_max_frame_num;
235+ let offset = self.frame_num_offset(info, max_frame_num);
236+ let cycle_len = sps.offsets_for_ref_frame.len() as i32;
237+ let mut abs_frame_num = if cycle_len != 0 {
238+ offset + info.frame_num as i32
239+ } else {
240+ 0
241+ };
242+ if !info.is_reference && abs_frame_num > 0 {
243+ abs_frame_num -= 1;
244+ }
245+ let mut expected = 0i32;
246+ if abs_frame_num > 0 {
247+ let expected_delta: i32 = sps.offsets_for_ref_frame.iter().sum();
248+ let cycle_cnt = (abs_frame_num - 1) / cycle_len;
249+ let in_cycle = (abs_frame_num - 1) % cycle_len;
250+ expected = cycle_cnt.wrapping_mul(expected_delta);
251+ for i in 0..=in_cycle as usize {
252+ expected = expected.wrapping_add(sps.offsets_for_ref_frame[i]);
253+ }
254+ }
255+ if !info.is_reference {
256+ expected = expected.wrapping_add(sps.offset_for_non_ref_pic);
257+ }
258+ let top = expected.wrapping_add(info.delta_pic_order_cnt[0]);
259+ let bottom = top
260+ .wrapping_add(sps.offset_for_top_to_bottom_field)
261+ .wrapping_add(info.delta_pic_order_cnt[1]);
262+ Ok(Poc {
263+ value: top.min(bottom),
264+ frame_num_offset: offset,
265+ msb: 0,
266+ lsb: 0,
267+ })
268+ }
269+ 2 => {
270+ let max_frame_num = 1i32 << sps.log2_max_frame_num;
271+ let offset = self.frame_num_offset(info, max_frame_num);
272+ let poc = if info.is_idr {
273+ 0
274+ } else if !info.is_reference {
275+ 2 * (offset + info.frame_num as i32) - 1
276+ } else {
277+ 2 * (offset + info.frame_num as i32)
278+ };
279+ Ok(Poc {
280+ value: poc,
281+ frame_num_offset: offset,
282+ msb: 0,
283+ lsb: 0,
284+ })
285+ }
286+ other => Err(Error::Stream(ec_core::Error::corrupt(format!(
287+ "H.264 pic_order_cnt_type {other}"
288+ )))),
289+ }
290+ }
291+
292+ /// `FrameNumOffset` (8-6, 8-11).
293+ fn frame_num_offset(&self, info: &PicInfo, max_frame_num: i32) -> i32 {
294+ if info.is_idr {
295+ return 0;
296+ }
297+ let prev = if self.prev_has_mmco5 {
298+ 0
299+ } else {
300+ self.prev_frame_num_offset
301+ };
302+ if self.prev_frame_num > info.frame_num {
303+ prev + max_frame_num
304+ } else {
305+ prev
306+ }
307+ }
308+
309+ /// True when `frame_num` skips values (8.2.5.2).
310+ ///
311+ /// This is a *normal* condition — an editor seek or a lossy transport
312+ /// produces it — and treating it as corruption is what used to knock a
313+ /// hardware session back to software mid-timeline.
314+ pub(crate) fn frame_num_gap(&self, sps: &Sps, frame_num: u32) -> bool {
315+ let max = 1u32 << sps.log2_max_frame_num;
316+ self.started
317+ && frame_num != self.prev_ref_frame_num
318+ && frame_num != (self.prev_ref_frame_num + 1) % max
319+ }
320+
321+ /// Insert the "non-existing" frames of 8.2.5.2 so that reference numbering
322+ /// stays aligned with the encoder's.
323+ ///
324+ /// The inferred frames share the newest reference picture's surface. Their
325+ /// samples are unspecified by the spec, and the previous reference is both
326+ /// a better guess than grey and the only choice this driver accepts: a
327+ /// reference surface it has never decoded into makes `vaEndPicture` fail
328+ /// with `operation failed` (measured on radeonsi with a two-picture gap).
329+ pub(crate) fn fill_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<usize> {
330+ let max = 1u32 << sps.log2_max_frame_num;
331+ let mut unused = (self.prev_ref_frame_num + 1) % max;
332+ let mut budget = MAX_STORED;
333+ let mut filled = 0;
334+ while unused != frame_num && budget > 0 {
335+ budget -= 1;
336+ let Some(surface) = self
337+ .frames
338+ .iter()
339+ .max_by_key(|p| p.frame_num_wrap)
340+ .map(|p| Arc::clone(&p.surface))
341+ else {
342+ // Nothing decoded yet: there is no picture to stand in for the
343+ // missing ones, and the next IDR will resynchronise anyway.
344+ break;
345+ };
346+ let info = PicInfo {
347+ is_idr: false,
348+ is_reference: true,
349+ frame_num: unused,
350+ pic_order_cnt_lsb: 0,
351+ delta_pic_order_cnt_bottom: 0,
352+ delta_pic_order_cnt: [0; 2],
353+ };
354+ // 8.2.5.2: a non-existing frame gets a picture order count only
355+ // when pic_order_cnt_type is not 0; under type 0 it has no output
356+ // order, and 8.2.4.2.3 keeps it out of the B lists.
357+ let poc = if sps.pic_order_cnt_type == 0 {
358+ Poc::default()
359+ } else {
360+ self.picture_order_count(sps, &info)?
361+ };
362+ self.number_short_term(unused, sps);
363+ self.sliding_window(sps);
364+ let id = self.next_id();
365+ self.frames.push(Picture {
366+ id,
367+ surface,
368+ timestamp: 0,
369+ frame_num: unused,
370+ frame_num_wrap: unused as i32,
371+ pic_num: unused as i32,
372+ long_term_frame_idx: 0,
373+ poc: poc.value,
374+ poc_msb: poc.msb,
375+ poc_lsb: poc.lsb,
376+ frame_num_offset: poc.frame_num_offset,
377+ mark: Mark::Short,
378+ non_existing: true,
379+ output: false,
380+ });
381+ self.prev_frame_num = unused;
382+ self.prev_frame_num_offset = poc.frame_num_offset;
383+ self.prev_has_mmco5 = false;
384+ self.prev_ref_frame_num = unused;
385+ unused = (unused + 1) % max;
386+ filled += 1;
387+ }
388+ Ok(filled)
389+ }
390+
391+ /// Recompute `FrameNumWrap` and `PicNum` against the current `frame_num`
392+ /// (8.2.4.1).
393+ pub(crate) fn number_short_term(&mut self, frame_num: u32, sps: &Sps) {
394+ let max_frame_num = 1i32 << sps.log2_max_frame_num;
395+ for pic in &mut self.frames {
396+ match pic.mark {
397+ Mark::Short => {
398+ pic.frame_num_wrap = if pic.frame_num > frame_num {
399+ pic.frame_num as i32 - max_frame_num
400+ } else {
401+ pic.frame_num as i32
402+ };
403+ pic.pic_num = pic.frame_num_wrap;
404+ }
405+ Mark::Long => pic.pic_num = pic.long_term_frame_idx as i32,
406+ Mark::Unused => {}
407+ }
408+ }
409+ }
410+
411+ /// Build `RefPicList0`/`RefPicList1` for one slice: initialisation
412+ /// (8.2.4.2.1 / 8.2.4.2.3) then modification (8.2.4.3).
413+ #[allow(clippy::too_many_arguments)]
414+ pub(crate) fn build_ref_lists(
415+ &self,
416+ slice_type: SliceType,
417+ curr_poc: i32,
418+ curr_pic_num: i32,
419+ max_pic_num: i32,
420+ num_l0: usize,
421+ num_l1: usize,
422+ mods: (&[RefPicListMod], &[RefPicListMod]),
423+ ) -> Result<[RefList; 2]> {
424+ let mut lists = [RefList::default(), RefList::default()];
425+ let mut short: [usize; MAX_STORED] = [0; MAX_STORED];
426+ let mut n_short = 0usize;
427+ let mut long: [usize; MAX_STORED] = [0; MAX_STORED];
428+ let mut n_long = 0usize;
429+ for (i, pic) in self.frames.iter().enumerate() {
430+ if pic.non_existing && slice_type == SliceType::B {
431+ continue;
432+ }
433+ match pic.mark {
434+ Mark::Short if n_short < MAX_STORED => {
435+ short[n_short] = i;
436+ n_short += 1;
437+ }
438+ Mark::Long if n_long < MAX_STORED => {
439+ long[n_long] = i;
440+ n_long += 1;
441+ }
442+ _ => {}
443+ }
444+ }
445+ let long = &mut long[..n_long];
446+ long.sort_unstable_by_key(|&i| self.frames[i].long_term_frame_idx);
447+
448+ if slice_type == SliceType::B {
449+ let short = &mut short[..n_short];
450+ short.sort_unstable_by_key(|&i| {
451+ let poc = self.frames[i].poc;
452+ if poc < curr_poc {
453+ (0i32, -poc)
454+ } else {
455+ (1, poc)
456+ }
457+ });
458+ for &i in short.iter() {
459+ lists[0].push(i);
460+ }
461+ for &i in long.iter() {
462+ lists[0].push(i);
463+ }
464+ short.sort_unstable_by_key(|&i| {
465+ let poc = self.frames[i].poc;
466+ if poc > curr_poc {
467+ (0i32, poc)
468+ } else {
469+ (1, -poc)
470+ }
471+ });
472+ for &i in short.iter() {
473+ lists[1].push(i);
474+ }
475+ for &i in long.iter() {
476+ lists[1].push(i);
477+ }
478+ // 8.2.4.2.3 step 3.
479+ if lists[1].len > 1
480+ && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len]
481+ {
482+ lists[1].entries.swap(0, 1);
483+ }
484+ } else {
485+ let short = &mut short[..n_short];
486+ short.sort_unstable_by_key(|&i| -self.frames[i].pic_num);
487+ for &i in short.iter() {
488+ lists[0].push(i);
489+ }
490+ for &i in long.iter() {
491+ lists[0].push(i);
492+ }
493+ }
494+
495+ let wanted = [num_l0, num_l1];
496+ let mods = [mods.0, mods.1];
497+ for x in 0..2 {
498+ if x == 1 && slice_type != SliceType::B {
499+ lists[1].len = 0;
500+ continue;
501+ }
502+ if lists[x].len == 0 {
503+ return Err(Error::Stream(ec_core::Error::corrupt(
504+ "H.264 inter slice with an empty reference list",
505+ )));
506+ }
507+ let first = lists[x].entries[0];
508+ while lists[x].len < wanted[x] {
509+ lists[x].push(usize::from(first));
510+ }
511+ lists[x].len = wanted[x];
512+ self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num);
513+ }
514+ Ok(lists)
515+ }
516+
517+ /// Reference picture list modification (8.2.4.3), by the insert-and-compact
518+ /// of equations 8-37 and 8-38.
519+ fn modify_list(
520+ &self,
521+ list: &mut RefList,
522+ mods: &[RefPicListMod],
523+ curr_pic_num: i32,
524+ max_pic_num: i32,
525+ ) {
526+ if mods.is_empty() {
527+ return;
528+ }
529+ let active = list.len;
530+ let mut tmp = [0u8; 34];
531+ tmp[..active].copy_from_slice(&list.entries[..active]);
532+ let mut pred = curr_pic_num;
533+ let mut ref_idx = 0usize;
534+ for op in mods {
535+ let target = match *op {
536+ RefPicListMod::ShortTerm {
537+ abs_diff_pic_num_minus1,
538+ add,
539+ } => {
540+ let diff = abs_diff_pic_num_minus1 as i32 + 1;
541+ let no_wrap = if add {
542+ if pred + diff >= max_pic_num {
543+ pred + diff - max_pic_num
544+ } else {
545+ pred + diff
546+ }
547+ } else if pred - diff < 0 {
548+ pred - diff + max_pic_num
549+ } else {
550+ pred - diff
551+ };
552+ pred = no_wrap;
553+ let pic_num = if no_wrap > curr_pic_num {
554+ no_wrap - max_pic_num
555+ } else {
556+ no_wrap
557+ };
558+ self.frames
559+ .iter()
560+ .position(|p| p.mark == Mark::Short && p.pic_num == pic_num)
561+ }
562+ RefPicListMod::LongTerm(num) => self
563+ .frames
564+ .iter()
565+ .position(|p| p.mark == Mark::Long && p.pic_num == num as i32),
566+ };
567+ // A modification naming a picture the buffer never received points
568+ // at something that was lost; keeping the initial entry decodes a
569+ // seek or a dropped packet instead of failing the slice.
570+ let Some(target) = target else { continue };
571+ if ref_idx >= active {
572+ break;
573+ }
574+ for c in (ref_idx + 1..=active).rev() {
575+ tmp[c] = tmp[c - 1];
576+ }
577+ tmp[ref_idx] = target as u8;
578+ ref_idx += 1;
579+ let mut n = ref_idx;
580+ for c in ref_idx..=active {
581+ if usize::from(tmp[c]) != target {
582+ tmp[n] = tmp[c];
583+ n += 1;
584+ }
585+ }
586+ }
587+ list.entries[..active].copy_from_slice(&tmp[..active]);
588+ list.len = active;
589+ }
590+
591+ /// Store a decoded picture and apply the reference marking of 8.2.5.
592+ pub(crate) fn store(
593+ &mut self,
594+ mut pic: Picture,
595+ sps: &Sps,
596+ info: &PicInfo,
597+ marking: Option<&DecRefPicMarking>,
598+ ) -> Result<()> {
599+ let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5));
600+ pic.output = true;
601+ self.number_short_term(info.frame_num, sps);
602+ pic.frame_num_wrap = pic.frame_num as i32;
603+ pic.pic_num = pic.frame_num as i32;
604+
605+ if info.is_idr {
606+ let no_output = marking.is_some_and(|m| m.no_output_of_prior_pics);
607+ self.drain_prior(no_output);
608+ pic.mark = Mark::Short;
609+ if marking.is_some_and(|m| m.long_term_reference) {
610+ pic.mark = Mark::Long;
611+ pic.long_term_frame_idx = 0;
612+ self.max_long_term_idx = Some(0);
613+ } else {
614+ self.max_long_term_idx = None;
615+ }
616+ } else if info.is_reference {
617+ pic.mark = Mark::Short;
618+ match marking {
619+ Some(m) if m.adaptive => self.apply_mmco(&mut pic, m, info)?,
620+ _ => self.sliding_window(sps),
621+ }
622+ }
623+
624+ if has_mmco5 {
625+ // 8.2.1: MMCO 5 restarts frame_num and picture order count here.
626+ pic.poc = 0;
627+ pic.frame_num = 0;
628+ pic.frame_num_offset = 0;
629+ pic.poc_msb = 0;
630+ pic.poc_lsb = 0;
631+ }
632+
633+ self.prev_frame_num = pic.frame_num;
634+ self.prev_frame_num_offset = pic.frame_num_offset;
635+ self.prev_has_mmco5 = has_mmco5;
636+ if info.is_reference {
637+ self.prev_ref_frame_num = pic.frame_num;
638+ self.prev_poc_msb = pic.poc_msb;
639+ self.prev_poc_lsb = pic.poc_lsb;
640+ }
641+ self.started = true;
642+ if (info.is_idr || has_mmco5) && self.frames.iter().any(|p| p.output) {
643+ self.pending_flush = true;
644+ }
645+ self.last_id = pic.id;
646+
647+ if self.frames.len() >= MAX_STORED {
648+ return Err(Error::Stream(ec_core::Error::corrupt(
649+ "H.264 decoded picture buffer overflow",
650+ )));
651+ }
652+ self.frames.push(pic);
653+ Ok(())
654+ }
655+
656+ /// Output and release every stored picture (IDR boundary or MMCO 5).
657+ fn drain_prior(&mut self, discard: bool) {
658+ for pic in &mut self.frames {
659+ pic.mark = Mark::Unused;
660+ if discard {
661+ pic.output = false;
662+ }
663+ }
664+ }
665+
666+ /// Sliding window marking (8.2.5.3).
667+ fn sliding_window(&mut self, sps: &Sps) {
668+ let max_refs = (sps.max_num_ref_frames as usize).max(1);
669+ loop {
670+ let n = self
671+ .frames
672+ .iter()
673+ .filter(|p| p.mark != Mark::Unused)
674+ .count();
675+ if n < max_refs {
676+ return;
677+ }
678+ let Some(oldest) = self
679+ .frames
680+ .iter_mut()
681+ .filter(|p| p.mark == Mark::Short)
682+ .min_by_key(|p| p.frame_num_wrap)
683+ else {
684+ // Only long-term references left: the stream must free one by
685+ // MMCO, and refusing here would break a conformant stream.
686+ return;
687+ };
688+ oldest.mark = Mark::Unused;
689+ }
690+ }
691+
692+ /// Adaptive marking (8.2.5.4).
693+ fn apply_mmco(
694+ &mut self,
695+ pic: &mut Picture,
696+ m: &DecRefPicMarking,
697+ info: &PicInfo,
698+ ) -> Result<()> {
699+ let curr_pic_num = info.frame_num as i32;
700+ for op in &m.mmcos {
701+ match op.op {
702+ 1 => {
703+ let target = curr_pic_num - (op.arg1 as i32 + 1);
704+ if let Some(p) = self
705+ .frames
706+ .iter_mut()
707+ .find(|p| p.mark == Mark::Short && p.pic_num == target)
708+ {
709+ p.mark = Mark::Unused;
710+ }
711+ }
712+ 2 => {
713+ if let Some(p) = self
714+ .frames
715+ .iter_mut()
716+ .find(|p| p.mark == Mark::Long && p.pic_num == op.arg1 as i32)
717+ {
718+ p.mark = Mark::Unused;
719+ }
720+ }
721+ 3 => {
722+ let target = curr_pic_num - (op.arg1 as i32 + 1);
723+ let idx = op.arg2;
724+ for p in &mut self.frames {
725+ if p.mark == Mark::Long && p.long_term_frame_idx == idx {
726+ p.mark = Mark::Unused;
727+ }
728+ }
729+ if let Some(p) = self
730+ .frames
731+ .iter_mut()
732+ .find(|p| p.mark == Mark::Short && p.pic_num == target)
733+ {
734+ p.mark = Mark::Long;
735+ p.long_term_frame_idx = idx;
736+ p.pic_num = idx as i32;
737+ }
738+ }
739+ 4 => {
740+ self.max_long_term_idx = op.arg1.checked_sub(1);
741+ let limit = self.max_long_term_idx;
742+ for p in &mut self.frames {
743+ if p.mark == Mark::Long
744+ && limit.is_none_or(|max| p.long_term_frame_idx > max)
745+ {
746+ p.mark = Mark::Unused;
747+ }
748+ }
749+ }
750+ 5 => {
751+ for p in &mut self.frames {
752+ p.mark = Mark::Unused;
753+ }
754+ self.max_long_term_idx = None;
755+ }
756+ 6 => {
757+ let idx = op.arg1;
758+ for p in &mut self.frames {
759+ if p.mark == Mark::Long && p.long_term_frame_idx == idx {
760+ p.mark = Mark::Unused;
761+ }
762+ }
763+ pic.mark = Mark::Long;
764+ pic.long_term_frame_idx = idx;
765+ pic.pic_num = idx as i32;
766+ }
767+ other => {
768+ return Err(Error::Stream(ec_core::Error::corrupt(format!(
769+ "H.264 memory_management_control_operation {other}"
770+ ))));
771+ }
772+ }
773+ }
774+ Ok(())
775+ }
776+
777+ /// The next picture to output, or `None` while the buffer is still within
778+ /// its reordering and storage limits (bumping, C.4.5.3).
779+ pub(crate) fn next_output(&mut self, flush: bool) -> Option<usize> {
780+ if self.pending_flush {
781+ let last = self.last_id;
782+ let best = self
783+ .frames
784+ .iter()
785+ .enumerate()
786+ .filter(|(_, p)| p.output && p.id != last)
787+ .min_by_key(|(_, p)| p.poc)
788+ .map(|(i, _)| i);
789+ if best.is_some() {
790+ return best;
791+ }
792+ self.pending_flush = false;
793+ }
794+ let pending = self.frames.iter().filter(|p| p.output).count();
795+ let stored = self.frames.iter().filter(|p| p.stored()).count();
796+ if !flush && pending <= self.max_reorder && stored <= self.max_frames {
797+ return None;
798+ }
799+ let mut best: Option<usize> = None;
800+ for (i, pic) in self.frames.iter().enumerate() {
801+ if !pic.output || pic.non_existing {
802+ continue;
803+ }
804+ if best.is_none_or(|b| pic.poc < self.frames[b].poc) {
805+ best = Some(i);
806+ }
807+ }
808+ best
809+ }
810+
811+ /// Mark picture `idx` as output and drop every slot that is now free.
812+ ///
813+ /// Dropping is what releases the surface back to the pool: nothing else
814+ /// holds it once the buffer and the caller are done, which is the leak this
815+ /// design makes structurally impossible.
816+ pub(crate) fn released(&mut self, idx: usize) {
817+ self.frames[idx].output = false;
818+ self.frames.retain(|p| p.stored());
819+ }
820+}
821+
822+/// `MaxDpbFrames` from the level limits of Annex A, Table A-1.
823+fn max_dpb_frames(sps: &Sps) -> usize {
824+ // MaxDpbMbs per level, in the level_idc order of Table A-1.
825+ const LIMITS: [(u8, u32); 17] = [
826+ (10, 396),
827+ (11, 900),
828+ (12, 2376),
829+ (13, 2376),
830+ (20, 2376),
831+ (21, 4752),
832+ (22, 8100),
833+ (30, 8100),
834+ (31, 18000),
835+ (32, 20480),
836+ (40, 32768),
837+ (41, 32768),
838+ (42, 34816),
839+ (50, 110400),
840+ (51, 184320),
841+ (52, 184320),
842+ (60, 696320),
843+ ];
844+ let mbs = sps.mbs_per_picture().max(1);
845+ let max_dpb_mbs = LIMITS
846+ .iter()
847+ .find(|(level, _)| *level >= sps.level_idc)
848+ .map(|(_, mbs)| *mbs)
849+ .unwrap_or(696_320);
850+ ((max_dpb_mbs / mbs) as usize).clamp(1, 16)
851+}
852+
853+#[cfg(test)]
854+mod tests {
855+ use super::*;
856+
857+ fn sps_for(poc_type: u8) -> Sps {
858+ let mut sps = Sps {
859+ profile_idc: 100,
860+ constraint_flags: 0,
861+ level_idc: 40,
862+ id: 0,
863+ chroma_format_idc: 1,
864+ separate_colour_plane: false,
865+ bit_depth_luma: 8,
866+ bit_depth_chroma: 8,
867+ transform_bypass: false,
868+ scaling_lists: None,
869+ log2_max_frame_num: 4,
870+ pic_order_cnt_type: poc_type,
871+ log2_max_pic_order_cnt_lsb: 4,
872+ delta_pic_order_always_zero: false,
873+ offset_for_non_ref_pic: 0,
874+ offset_for_top_to_bottom_field: 0,
875+ offsets_for_ref_frame: Vec::new(),
876+ max_num_ref_frames: 4,
877+ gaps_in_frame_num_allowed: true,
878+ frame_mbs_only: true,
879+ mb_adaptive_frame_field: false,
880+ direct_8x8_inference: true,
881+ crop: (0, 0, 0, 0),
882+ vui: None,
883+ mb_width: 120,
884+ mb_height: 68,
885+ coded_width: 1920,
886+ coded_height: 1088,
887+ width: 1920,
888+ height: 1088,
889+ };
890+ if poc_type == 1 {
891+ sps.offsets_for_ref_frame = vec![2, -2];
892+ }
893+ sps
894+ }
895+
896+ fn info(frame_num: u32, lsb: u32, is_ref: bool, is_idr: bool) -> PicInfo {
897+ PicInfo {
898+ is_idr,
899+ is_reference: is_ref,
900+ frame_num,
901+ pic_order_cnt_lsb: lsb,
902+ delta_pic_order_cnt_bottom: 0,
903+ delta_pic_order_cnt: [0; 2],
904+ }
905+ }
906+
907+ #[test]
908+ fn poc_type_0_tracks_the_msb_across_a_wrap() {
909+ let sps = sps_for(0);
910+ let mut dpb = Dpb::default();
911+ let poc = dpb
912+ .picture_order_count(&sps, &info(0, 0, true, true))
913+ .unwrap();
914+ assert_eq!(poc.value, 0);
915+ dpb.prev_poc_msb = poc.msb;
916+ dpb.prev_poc_lsb = poc.lsb;
917+
918+ let poc = dpb
919+ .picture_order_count(&sps, &info(1, 14, true, false))
920+ .unwrap();
921+ assert_eq!(poc.value, 14);
922+ dpb.prev_poc_msb = poc.msb;
923+ dpb.prev_poc_lsb = poc.lsb;
924+
925+ // lsb wraps 14 -> 2 with MaxPicOrderCntLsb 16: the msb must step up.
926+ let poc = dpb
927+ .picture_order_count(&sps, &info(2, 2, true, false))
928+ .unwrap();
929+ assert_eq!(poc.value, 18);
930+ }
931+
932+ #[test]
933+ fn frame_num_gaps_are_detected_but_not_at_the_start() {
934+ let sps = sps_for(0);
935+ let mut dpb = Dpb::default();
936+ // Nothing decoded yet: a jump is a seek, not a gap.
937+ assert!(!dpb.frame_num_gap(&sps, 7));
938+ dpb.started = true;
939+ dpb.prev_ref_frame_num = 3;
940+ assert!(!dpb.frame_num_gap(&sps, 3));
941+ assert!(!dpb.frame_num_gap(&sps, 4));
942+ assert!(dpb.frame_num_gap(&sps, 6));
943+ // MaxFrameNum is 16, so 15 -> 0 is contiguous, 15 -> 1 is a gap.
944+ dpb.prev_ref_frame_num = 15;
945+ assert!(!dpb.frame_num_gap(&sps, 0));
946+ assert!(dpb.frame_num_gap(&sps, 1));
947+ }
948+
949+ #[test]
950+ fn level_limits_size_the_buffer() {
951+ let mut sps = sps_for(0);
952+ let mut dpb = Dpb::default();
953+ dpb.configure(&sps);
954+ // 1080p at level 4.0: 32768 / 8160 = 4 frames.
955+ assert_eq!(dpb.capacity(), 4);
956+ sps.level_idc = 51;
957+ dpb.configure(&sps);
958+ assert_eq!(dpb.capacity(), 16);
959+ }
960+}
crates/ec-hw/src/dec/h264.rsadded+707 -0
@@ -0,0 +1,707 @@
1+//! Stateless H.264 decoding.
2+
3+use std::sync::Arc;
4+
5+use ec_h264_syntax::{
6+ AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader,
7+ SliceType, Sps, unescape_rbsp,
8+};
9+use ec_va::caps::Profile;
10+use ec_va::{Buffer, Display, sys};
11+
12+use super::dpb264::{Dpb, Mark, PicInfo, Picture, Poc, RefList};
13+use super::{ReadyFrames, Session, StreamInfo};
14+use crate::error::{Error, Result};
15+use crate::frame::Frame;
16+use crate::params::h264::{
17+ IQMatrixBufferH264, PICTURE_LONG_TERM_REFERENCE, PICTURE_SHORT_TERM_REFERENCE,
18+ PictureParameterBufferH264, SliceParameterBufferH264, VAPictureH264,
19+};
20+use crate::params::param_buffer;
21+use crate::pool::PooledSurface;
22+
23+/// Extra surfaces beyond the DPB: one being decoded, one or two in the caller's
24+/// hands, plus slack so a `frame_num` gap fill never starves the decoder.
25+const EXTRA_SURFACES: usize = 6;
26+
27+/// The picture currently being assembled from its slices.
28+struct Current {
29+ surface: Arc<PooledSurface>,
30+ id: i32,
31+ sps_id: u8,
32+ info: PicInfo,
33+ poc: Poc,
34+ timestamp: i64,
35+ /// `dec_ref_pic_marking()` from the picture's first slice header, which is
36+ /// what 8.2.5 applies once the whole picture is decoded.
37+ marking: Option<DecRefPicMarking>,
38+ /// Parameter and data buffers submitted so far.
39+ buffers: Vec<Buffer>,
40+ slices: usize,
41+}
42+
43+/// A stateless H.264 decoder.
44+pub struct H264Decoder {
45+ display: Arc<Display>,
46+ sps_map: [Option<Sps>; 32],
47+ pps_map: Vec<Option<Pps>>,
48+ session: Option<Session>,
49+ dpb: Dpb,
50+ ready: ReadyFrames,
51+ current: Option<Current>,
52+ /// Reusable unescape buffer; NAL payloads are rewritten into it in turn.
53+ rbsp: Vec<u8>,
54+ gap_frames: u64,
55+}
56+
57+impl H264Decoder {
58+ /// A decoder with no stream state. The GPU context is created when the
59+ /// first SPS arrives, because only then is the size and bit depth known.
60+ pub fn new(display: &Arc<Display>) -> H264Decoder {
61+ H264Decoder {
62+ display: Arc::clone(display),
63+ sps_map: [const { None }; 32],
64+ pps_map: (0..256).map(|_| None).collect(),
65+ session: None,
66+ dpb: Dpb::default(),
67+ ready: ReadyFrames::default(),
68+ current: None,
69+ rbsp: Vec::new(),
70+ gap_frames: 0,
71+ }
72+ }
73+
74+ /// Decode one Annex B access unit.
75+ pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
76+ for nal in AnnexBIter::new(data) {
77+ let Some((&first, payload)) = nal.split_first() else {
78+ continue;
79+ };
80+ let header = NalHeader::parse(first)?;
81+ match header.unit_type {
82+ NalUnitType::Sps => {
83+ let mut rbsp = std::mem::take(&mut self.rbsp);
84+ unescape_rbsp(payload, &mut rbsp);
85+ let sps = Sps::parse(&rbsp);
86+ self.rbsp = rbsp;
87+ let sps = sps?;
88+ self.dpb.configure(&sps);
89+ let id = usize::from(sps.id);
90+ self.sps_map[id] = Some(sps);
91+ }
92+ NalUnitType::Pps => {
93+ let mut rbsp = std::mem::take(&mut self.rbsp);
94+ unescape_rbsp(payload, &mut rbsp);
95+ let pps = Pps::parse(&rbsp, |id| self.sps_map[usize::from(id)].as_ref());
96+ self.rbsp = rbsp;
97+ let pps = pps?;
98+ let id = pps.id as usize;
99+ if id < self.pps_map.len() {
100+ self.pps_map[id] = Some(pps);
101+ }
102+ }
103+ NalUnitType::Slice | NalUnitType::SliceIdr => {
104+ self.slice(header, nal, payload, timestamp)?;
105+ }
106+ // SEI, AUD, filler and everything else carries nothing a
107+ // stateless decode submission needs.
108+ _ => {}
109+ }
110+ }
111+ // One access unit is one picture: close it here rather than waiting for
112+ // the next first_mb_in_slice == 0, so a caller gets its frame in the
113+ // call that fed the data.
114+ self.finish_picture()?;
115+ Ok(())
116+ }
117+
118+ /// The next frame in display order.
119+ pub fn next_frame(&mut self) -> Option<Frame> {
120+ self.ready.pop()
121+ }
122+
123+ /// Push every buffered picture out (end of stream).
124+ pub fn flush(&mut self) {
125+ let _ = self.finish_picture();
126+ self.bump(true);
127+ }
128+
129+ /// Drop all picture state; parameter sets and the GPU session survive.
130+ pub fn reset(&mut self) {
131+ self.current = None;
132+ self.dpb.clear();
133+ self.ready.clear();
134+ self.gap_frames = 0;
135+ }
136+
137+ /// What the stream turned out to be, once its first SPS was seen.
138+ pub fn stream_info(&self) -> Option<StreamInfo> {
139+ self.session.as_ref().map(Session::info)
140+ }
141+
142+ /// Pictures inferred for `frame_num` gaps (8.2.5.2) since the last reset.
143+ ///
144+ /// Exposed because it is the difference between a stream that stays on the
145+ /// hardware and one that falls back to software: a gap is normal, and a
146+ /// caller watching this counter can tell "the encoder skipped pictures"
147+ /// from "the decoder is guessing".
148+ pub fn gap_frames_synthesized(&self) -> u64 {
149+ self.gap_frames
150+ }
151+
152+ fn slice(
153+ &mut self,
154+ header: NalHeader,
155+ nal: &[u8],
156+ payload: &[u8],
157+ timestamp: i64,
158+ ) -> Result<()> {
159+ let mut rbsp = std::mem::take(&mut self.rbsp);
160+ unescape_rbsp(payload, &mut rbsp);
161+ let result = self.slice_rbsp(header, nal, &rbsp, timestamp);
162+ self.rbsp = rbsp;
163+ result
164+ }
165+
166+ fn slice_rbsp(
167+ &mut self,
168+ header: NalHeader,
169+ nal: &[u8],
170+ rbsp: &[u8],
171+ timestamp: i64,
172+ ) -> Result<()> {
173+ // Two passes over the parameter sets: the slice header needs the PPS to
174+ // parse, and the PPS names its SPS.
175+ let pps_id = peek_pps_id(rbsp)?;
176+ let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else {
177+ // A slice referring to a parameter set we never received is what a
178+ // seek into the middle of a stream looks like; skip it rather than
179+ // failing the whole access unit.
180+ return Ok(());
181+ };
182+ let Some(sps) = self.sps_map[usize::from(pps.sps_id)].clone() else {
183+ return Ok(());
184+ };
185+ let sh = SliceHeader::parse(rbsp, header, &sps, &pps)?;
186+
187+ if sh.first_mb_in_slice == 0 {
188+ self.finish_picture()?;
189+ self.start_picture(&sps, &sh, header, timestamp)?;
190+ }
191+ if self.current.is_none() {
192+ // Mid-picture entry after a seek: no first slice, nothing to add to.
193+ return Ok(());
194+ }
195+ self.render_slice(&sps, &pps, &sh, nal, header)
196+ }
197+
198+ /// Create the GPU session if this stream has not had one yet.
199+ fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
200+ let profile = profile_for(sps)?;
201+ let coded = (sps.coded_width, sps.coded_height);
202+ let bit_depth = sps.bit_depth_luma;
203+ if let Some(session) = &self.session
204+ && session.coded_size == coded
205+ && session.bit_depth == bit_depth
206+ && session.profile == profile
207+ {
208+ return Ok(());
209+ }
210+ // A resolution change starts a new session; the old one drops with its
211+ // surfaces once the frames still out there are released.
212+ self.current = None;
213+ self.dpb.clear();
214+ let surfaces = self.dpb.capacity() + EXTRA_SURFACES;
215+ self.session = Some(Session::new(
216+ &self.display,
217+ profile,
218+ coded,
219+ (sps.width, sps.height),
220+ bit_depth,
221+ surfaces,
222+ )?);
223+ Ok(())
224+ }
225+
226+ fn start_picture(
227+ &mut self,
228+ sps: &Sps,
229+ sh: &SliceHeader,
230+ header: NalHeader,
231+ timestamp: i64,
232+ ) -> Result<()> {
233+ self.ensure_session(sps)?;
234+ let info = PicInfo {
235+ is_idr: header.is_idr(),
236+ is_reference: header.ref_idc != 0,
237+ frame_num: sh.frame_num,
238+ pic_order_cnt_lsb: sh.pic_order_cnt_lsb,
239+ delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom,
240+ delta_pic_order_cnt: sh.delta_pic_order_cnt,
241+ };
242+
243+ // 8.2.5.2: missing frame_num values are normal (a seek, a dropped
244+ // packet, an encoder that skipped a picture). Synthesising the frames
245+ // keeps the reference numbering aligned, which is the difference
246+ // between decoding the rest of the GOP and falling back to software.
247+ if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) {
248+ self.gap_frames += self.dpb.fill_frame_num_gap(sps, sh.frame_num)? as u64;
249+ }
250+
251+ let poc = self.dpb.picture_order_count(sps, &info)?;
252+ let session = self
253+ .session
254+ .as_ref()
255+ .ok_or_else(|| Error::config("H.264 picture before any SPS"))?;
256+ let surface = session
257+ .pool
258+ .acquire()
259+ .ok_or_else(|| Error::config("H.264 decode: every surface is still in use"))?;
260+ let id = self.dpb.next_id();
261+ self.current = Some(Current {
262+ surface,
263+ id,
264+ sps_id: sps.id,
265+ info,
266+ poc,
267+ timestamp,
268+ marking: sh.dec_ref_pic_marking.clone(),
269+ buffers: Vec::new(),
270+ slices: 0,
271+ });
272+ Ok(())
273+ }
274+
275+ fn render_slice(
276+ &mut self,
277+ sps: &Sps,
278+ pps: &Pps,
279+ sh: &SliceHeader,
280+ nal: &[u8],
281+ header: NalHeader,
282+ ) -> Result<()> {
283+ let (Some(current), Some(session)) = (self.current.as_mut(), self.session.as_ref()) else {
284+ return Ok(());
285+ };
286+ if current.sps_id != sps.id {
287+ return Err(Error::Stream(ec_core::Error::corrupt(
288+ "H.264 SPS changed mid-picture",
289+ )));
290+ }
291+
292+ // The picture parameter buffer goes in once, with the first slice: it
293+ // describes the picture, and the DPB it names must not change under the
294+ // driver between slices.
295+ if current.slices == 0 {
296+ let pic_param = picture_parameters(sps, pps, sh, header, current, &self.dpb);
297+ current
298+ .buffers
299+ .push(param_buffer(&session.context, &pic_param)?);
300+ // The matrices are sent for every picture, flat or not: a driver
301+ // that never receives them dequantises with a zero matrix and
302+ // hands back a uniformly grey surface (radeonsi does exactly this).
303+ // A PPS scaling matrix overrides the SPS one (7.4.2.2).
304+ let iq = match pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref()) {
305+ Some(lists) => IQMatrixBufferH264 {
306+ scaling_list_4x4: lists.list_4x4,
307+ scaling_list_8x8: [lists.list_8x8[0], lists.list_8x8[1]],
308+ ..IQMatrixBufferH264::default()
309+ },
310+ None => IQMatrixBufferH264::default(),
311+ };
312+ current.buffers.push(param_buffer(&session.context, &iq)?);
313+ }
314+
315+ let max_pic_num = 1i32 << sps.log2_max_frame_num;
316+ let lists = if sh.slice_type.is_intra() {
317+ [RefList::default(), RefList::default()]
318+ } else {
319+ self.dpb.number_short_term(sh.frame_num, sps);
320+ self.dpb.build_ref_lists(
321+ sh.slice_type,
322+ current.poc.value,
323+ sh.frame_num as i32,
324+ max_pic_num,
325+ sh.num_ref_idx_l0_active as usize,
326+ sh.num_ref_idx_l1_active as usize,
327+ (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1),
328+ )?
329+ };
330+
331+ let slice_param = slice_parameters(sh, pps, nal, &lists, &self.dpb);
332+ current
333+ .buffers
334+ .push(param_buffer(&session.context, &slice_param)?);
335+ current.buffers.push(Buffer::from_bytes(
336+ &session.context,
337+ sys::VASliceDataBufferType,
338+ nal,
339+ )?);
340+ current.slices += 1;
341+ Ok(())
342+ }
343+
344+ fn finish_picture(&mut self) -> Result<()> {
345+ let Some(current) = self.current.take() else {
346+ return Ok(());
347+ };
348+ let Some(session) = self.session.as_ref() else {
349+ return Ok(());
350+ };
351+ if current.slices == 0 {
352+ // No slice data reached the driver, so there is nothing to submit;
353+ // the surface returns to the pool with `current`.
354+ return Ok(());
355+ }
356+ let Some(sps) = self.sps_map[usize::from(current.sps_id)].clone() else {
357+ return Ok(());
358+ };
359+
360+ session.submit(&current.surface, current.buffers)?;
361+
362+ let picture = Picture {
363+ id: current.id,
364+ surface: Arc::clone(&current.surface),
365+ timestamp: current.timestamp,
366+ frame_num: current.info.frame_num,
367+ frame_num_wrap: current.info.frame_num as i32,
368+ pic_num: current.info.frame_num as i32,
369+ long_term_frame_idx: 0,
370+ poc: current.poc.value,
371+ poc_msb: current.poc.msb,
372+ poc_lsb: current.poc.lsb,
373+ frame_num_offset: current.poc.frame_num_offset,
374+ mark: Mark::Unused,
375+ non_existing: false,
376+ output: true,
377+ };
378+ self.dpb
379+ .store(picture, &sps, &current.info, current.marking.as_ref())?;
380+ self.bump(false);
381+ Ok(())
382+ }
383+
384+ /// Move whatever the bumping process releases into the ready queue.
385+ fn bump(&mut self, flush: bool) {
386+ let Some(session) = self.session.as_ref() else {
387+ return;
388+ };
389+ while let Some(idx) = self.dpb.next_output(flush) {
390+ let pic = &self.dpb.frames[idx];
391+ let frame = Frame::new(
392+ Arc::clone(&pic.surface),
393+ Arc::clone(&session.images),
394+ pic.timestamp,
395+ session.display_size,
396+ session.coded_size,
397+ session.bit_depth,
398+ );
399+ self.ready.push(frame);
400+ self.dpb.released(idx);
401+ }
402+ }
403+}
404+
405+/// The `pic_parameter_set_id` of a slice header, which is the second syntax
406+/// element and needs no parameter set to read.
407+fn peek_pps_id(rbsp: &[u8]) -> Result<u32> {
408+ let mut r = ec_core::BitReader::new(rbsp);
409+ r.read_ue()?; // first_mb_in_slice
410+ r.read_ue()?; // slice_type
411+ Ok(r.read_ue()?)
412+}
413+
414+/// The VA profile for a stream, from its SPS.
415+fn profile_for(sps: &Sps) -> Result<Profile> {
416+ Ok(match sps.profile_idc {
417+ 66 => {
418+ // Constrained baseline is a subset of main and every driver that
419+ // decodes main decodes it; plain baseline (FMO/ASO) is not, and
420+ // this crate does not implement slice groups either way.
421+ Profile::H264ConstrainedBaseline
422+ }
423+ 77 | 88 => Profile::H264Main,
424+ 100 | 110 | 122 | 244 if sps.bit_depth_luma > 8 => Profile::H264High10,
425+ 100 => Profile::H264High,
426+ other => {
427+ return Err(Error::unsupported(
428+ format!("H.264 profile_idc {other}"),
429+ "no VA profile covers it",
430+ ));
431+ }
432+ })
433+}
434+
435+/// `slice_type` as the driver wants it: the modulo-5 value of Table 7-6.
436+fn slice_type_code(slice_type: SliceType) -> u8 {
437+ match slice_type {
438+ SliceType::P => 0,
439+ SliceType::B => 1,
440+ SliceType::I => 2,
441+ SliceType::Sp => 3,
442+ SliceType::Si => 4,
443+ }
444+}
445+
446+/// The VA reference entry for a stored picture.
447+fn reference_entry(pic: &Picture) -> VAPictureH264 {
448+ let flags = match pic.mark {
449+ Mark::Long => PICTURE_LONG_TERM_REFERENCE,
450+ _ => PICTURE_SHORT_TERM_REFERENCE,
451+ };
452+ let frame_idx = if pic.mark == Mark::Long {
453+ pic.long_term_frame_idx
454+ } else {
455+ pic.frame_num
456+ };
457+ VAPictureH264::frame(pic.surface.id(), frame_idx, pic.poc, flags)
458+}
459+
460+fn picture_parameters(
461+ sps: &Sps,
462+ pps: &Pps,
463+ sh: &SliceHeader,
464+ header: NalHeader,
465+ current: &Current,
466+ dpb: &Dpb,
467+) -> PictureParameterBufferH264 {
468+ let mut p = PictureParameterBufferH264 {
469+ curr_pic: VAPictureH264::frame(
470+ current.surface.id(),
471+ current.info.frame_num,
472+ current.poc.value,
473+ if current.info.is_reference {
474+ PICTURE_SHORT_TERM_REFERENCE
475+ } else {
476+ 0
477+ },
478+ ),
479+ picture_width_in_mbs_minus1: (sps.mb_width.max(1) - 1) as u16,
480+ picture_height_in_mbs_minus1: (sps.mb_height.max(1) - 1) as u16,
481+ bit_depth_luma_minus8: sps.bit_depth_luma.saturating_sub(8),
482+ bit_depth_chroma_minus8: sps.bit_depth_chroma.saturating_sub(8),
483+ num_ref_frames: sps.max_num_ref_frames.min(255) as u8,
484+ pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8,
485+ pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8,
486+ chroma_qp_index_offset: pps.chroma_qp_index_offset as i8,
487+ second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8,
488+ frame_num: sh.frame_num as u16,
489+ ..PictureParameterBufferH264::default()
490+ };
491+
492+ for (n, pic) in dpb
493+ .frames
494+ .iter()
495+ .filter(|p| p.mark != Mark::Unused)
496+ .take(p.reference_frames.len())
497+ .enumerate()
498+ {
499+ p.reference_frames[n] = reference_entry(pic);
500+ }
501+
502+ p.seq_fields = p
503+ .seq_fields
504+ .chroma_format_idc(u32::from(sps.chroma_format_idc))
505+ .residual_colour_transform_flag(u32::from(sps.separate_colour_plane))
506+ .gaps_in_frame_num_value_allowed_flag(u32::from(sps.gaps_in_frame_num_allowed))
507+ .frame_mbs_only_flag(u32::from(sps.frame_mbs_only))
508+ .mb_adaptive_frame_field_flag(u32::from(sps.mb_adaptive_frame_field))
509+ .direct_8x8_inference_flag(u32::from(sps.direct_8x8_inference))
510+ // A.3.3.2: 8x8 bi-prediction is restricted from level 3.1 up.
511+ .min_luma_bipred_size8x8(u32::from(sps.level_idc >= 31))
512+ .log2_max_frame_num_minus4(u32::from(sps.log2_max_frame_num.saturating_sub(4)))
513+ .pic_order_cnt_type(u32::from(sps.pic_order_cnt_type))
514+ .log2_max_pic_order_cnt_lsb_minus4(u32::from(
515+ sps.log2_max_pic_order_cnt_lsb.saturating_sub(4),
516+ ))
517+ .delta_pic_order_always_zero_flag(u32::from(sps.delta_pic_order_always_zero));
518+
519+ p.pic_fields = p
520+ .pic_fields
521+ .entropy_coding_mode_flag(u32::from(pps.entropy_coding_mode))
522+ .weighted_pred_flag(u32::from(pps.weighted_pred))
523+ .weighted_bipred_idc(u32::from(pps.weighted_bipred_idc))
524+ .transform_8x8_mode_flag(u32::from(pps.transform_8x8_mode))
525+ .field_pic_flag(u32::from(sh.field_pic))
526+ .constrained_intra_pred_flag(u32::from(pps.constrained_intra_pred))
527+ .pic_order_present_flag(u32::from(pps.bottom_field_pic_order_in_frame_present))
528+ .deblocking_filter_control_present_flag(u32::from(pps.deblocking_filter_control_present))
529+ .redundant_pic_cnt_present_flag(u32::from(pps.redundant_pic_cnt_present))
530+ .reference_pic_flag(u32::from(header.ref_idc != 0));
531+ p
532+}
533+
534+fn slice_parameters(
535+ sh: &SliceHeader,
536+ pps: &Pps,
537+ nal: &[u8],
538+ lists: &[RefList; 2],
539+ dpb: &Dpb,
540+) -> SliceParameterBufferH264 {
541+ let mut s = SliceParameterBufferH264 {
542+ slice_data_size: nal.len() as u32,
543+ slice_data_offset: 0,
544+ slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL
545+ // "relative to and includes the NAL unit byte", counted in the
546+ // unescaped RBSP: the syntax crate's header_bits starts *after* that
547+ // byte, hence the 8.
548+ slice_data_bit_offset: (sh.header_bits + 8) as u16,
549+ first_mb_in_slice: sh.first_mb_in_slice as u16,
550+ slice_type: slice_type_code(sh.slice_type),
551+ direct_spatial_mv_pred_flag: u8::from(sh.direct_spatial_mv_pred),
552+ num_ref_idx_l0_active_minus1: sh.num_ref_idx_l0_active.saturating_sub(1) as u8,
553+ num_ref_idx_l1_active_minus1: sh.num_ref_idx_l1_active.saturating_sub(1) as u8,
554+ cabac_init_idc: sh.cabac_init_idc as u8,
555+ // The syntax crate resolves SliceQPY; the driver wants the delta back.
556+ slice_qp_delta: (sh.slice_qp - pps.pic_init_qp) as i8,
557+ disable_deblocking_filter_idc: sh.deblock.disable_idc,
558+ slice_alpha_c0_offset_div2: (sh.deblock.alpha_c0_offset / 2) as i8,
559+ slice_beta_offset_div2: (sh.deblock.beta_offset / 2) as i8,
560+ ..SliceParameterBufferH264::default()
561+ };
562+
563+ for (x, list) in lists.iter().enumerate() {
564+ let out = if x == 0 {
565+ &mut s.ref_pic_list0
566+ } else {
567+ &mut s.ref_pic_list1
568+ };
569+ for i in 0..list.len().min(out.len()) {
570+ if let Some(idx) = list.get(i)
571+ && let Some(pic) = dpb.frames.get(idx)
572+ {
573+ out[i] = reference_entry(pic);
574+ }
575+ }
576+ }
577+
578+ if let Some(w) = sh.pred_weight_table.as_ref() {
579+ write_weights(&mut s, w);
580+ }
581+ s
582+}
583+
584+/// Copy a parsed `pred_weight_table()` into the slice parameter buffer.
585+///
586+/// The spec's default weights are `(1 << denom, 0)`, and a driver reads every
587+/// entry the active count names — so an absent entry has to be *written* as the
588+/// default rather than left at zero, which would black out the prediction.
589+fn write_weights(s: &mut SliceParameterBufferH264, w: &PredWeightTable) {
590+ s.luma_log2_weight_denom = w.luma_log2_weight_denom as u8;
591+ s.chroma_log2_weight_denom = w.chroma_log2_weight_denom as u8;
592+ let luma_default = 1i16 << w.luma_log2_weight_denom;
593+ let chroma_default = 1i16 << w.chroma_log2_weight_denom;
594+
595+ for (list, entries) in [(0usize, &w.l0), (1usize, &w.l1)] {
596+ let (weights, offsets, cweights, coffsets, luma_flag, chroma_flag) = if list == 0 {
597+ (
598+ &mut s.luma_weight_l0,
599+ &mut s.luma_offset_l0,
600+ &mut s.chroma_weight_l0,
601+ &mut s.chroma_offset_l0,
602+ &mut s.luma_weight_l0_flag,
603+ &mut s.chroma_weight_l0_flag,
604+ )
605+ } else {
606+ (
607+ &mut s.luma_weight_l1,
608+ &mut s.luma_offset_l1,
609+ &mut s.chroma_weight_l1,
610+ &mut s.chroma_offset_l1,
611+ &mut s.luma_weight_l1_flag,
612+ &mut s.chroma_weight_l1_flag,
613+ )
614+ };
615+ for (i, entry) in entries.iter().take(32).enumerate() {
616+ match entry.luma {
617+ Some((weight, offset)) => {
618+ *luma_flag = 1;
619+ weights[i] = weight as i16;
620+ offsets[i] = offset as i16;
621+ }
622+ None => {
623+ weights[i] = luma_default;
624+ offsets[i] = 0;
625+ }
626+ }
627+ match entry.chroma {
628+ Some(pair) => {
629+ *chroma_flag = 1;
630+ for c in 0..2 {
631+ cweights[i][c] = pair[c].0 as i16;
632+ coffsets[i][c] = pair[c].1 as i16;
633+ }
634+ }
635+ None => {
636+ for c in 0..2 {
637+ cweights[i][c] = chroma_default;
638+ coffsets[i][c] = 0;
639+ }
640+ }
641+ }
642+ }
643+ }
644+}
645+
646+#[cfg(test)]
647+mod tests {
648+ use super::*;
649+
650+ fn test_sps() -> Sps {
651+ Sps {
652+ profile_idc: 100,
653+ constraint_flags: 0,
654+ level_idc: 40,
655+ id: 0,
656+ chroma_format_idc: 1,
657+ separate_colour_plane: false,
658+ bit_depth_luma: 8,
659+ bit_depth_chroma: 8,
660+ transform_bypass: false,
661+ scaling_lists: None,
662+ log2_max_frame_num: 4,
663+ pic_order_cnt_type: 0,
664+ log2_max_pic_order_cnt_lsb: 4,
665+ delta_pic_order_always_zero: false,
666+ offset_for_non_ref_pic: 0,
667+ offset_for_top_to_bottom_field: 0,
668+ offsets_for_ref_frame: Vec::new(),
669+ max_num_ref_frames: 4,
670+ gaps_in_frame_num_allowed: true,
671+ frame_mbs_only: true,
672+ mb_adaptive_frame_field: false,
673+ direct_8x8_inference: true,
674+ crop: (0, 0, 0, 0),
675+ vui: None,
676+ mb_width: 120,
677+ mb_height: 68,
678+ coded_width: 1920,
679+ coded_height: 1088,
680+ width: 1920,
681+ height: 1080,
682+ }
683+ }
684+
685+ #[test]
686+ fn slice_type_codes_match_table_7_6() {
687+ assert_eq!(slice_type_code(SliceType::P), 0);
688+ assert_eq!(slice_type_code(SliceType::B), 1);
689+ assert_eq!(slice_type_code(SliceType::I), 2);
690+ assert_eq!(slice_type_code(SliceType::Sp), 3);
691+ assert_eq!(slice_type_code(SliceType::Si), 4);
692+ }
693+
694+ #[test]
695+ fn profiles_follow_the_stream_bit_depth() {
696+ let mut sps = test_sps();
697+ sps.profile_idc = 100;
698+ assert_eq!(profile_for(&sps).unwrap(), Profile::H264High);
699+ sps.bit_depth_luma = 10;
700+ assert_eq!(profile_for(&sps).unwrap(), Profile::H264High10);
701+ sps.profile_idc = 66;
702+ sps.bit_depth_luma = 8;
703+ assert_eq!(profile_for(&sps).unwrap(), Profile::H264ConstrainedBaseline);
704+ sps.profile_idc = 244;
705+ assert!(profile_for(&sps).is_err());
706+ }
707+}
crates/ec-hw/src/dec/hevc.rsadded+823 -0
@@ -0,0 +1,823 @@
1+//! Stateless HEVC decoding.
2+//!
3+//! HEVC keeps no `frame_num` and no sliding window: every picture states its
4+//! whole reference picture set, and anything the set does not name stops being
5+//! a reference there and then (8.3.2). That makes the DPB smaller than H.264's
6+//! but the *derivation* larger, and all of it has to happen here — a stateless
7+//! driver is handed `RefPicSetStCurrBefore`, `StCurrAfter` and `LtCurr` as
8+//! finished picture lists.
9+
10+use std::sync::Arc;
11+
12+use ec_h265_syntax::{
13+ NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b,
14+ unescape_rbsp,
15+};
16+use ec_va::caps::Profile;
17+use ec_va::{Buffer, Display, sys};
18+
19+use super::{ReadyFrames, Session, StreamInfo};
20+use crate::error::{Error, Result};
21+use crate::frame::Frame;
22+use crate::params::hevc::{
23+ IQMatrixBufferHEVC, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR,
24+ PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PictureParameterBufferHEVC,
25+ SliceParameterBufferHEVC, VAPictureHEVC,
26+};
27+use crate::params::param_buffer;
28+use crate::pool::PooledSurface;
29+
30+/// Beyond `sps_max_dec_pic_buffering`: the picture being decoded plus the ones
31+/// a caller is still holding.
32+const EXTRA_SURFACES: usize = 6;
33+
34+/// Reference marking of a stored picture (8.3.2).
35+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36+enum Mark {
37+ Unused,
38+ ShortTerm,
39+ LongTerm,
40+}
41+
42+struct StoredPicture {
43+ surface: Arc<PooledSurface>,
44+ poc: i32,
45+ timestamp: i64,
46+ mark: Mark,
47+ /// Still to be handed to the caller.
48+ output: bool,
49+}
50+
51+impl StoredPicture {
52+ fn stored(&self) -> bool {
53+ self.output || self.mark != Mark::Unused
54+ }
55+}
56+
57+/// The reference picture set of the picture being decoded, as DPB indices.
58+#[derive(Debug, Default, Clone)]
59+struct Rps {
60+ st_curr_before: Vec<usize>,
61+ st_curr_after: Vec<usize>,
62+ lt_curr: Vec<usize>,
63+}
64+
65+/// The picture being assembled from its slices.
66+struct Current {
67+ surface: Arc<PooledSurface>,
68+ sps_id: u32,
69+ poc: i32,
70+ timestamp: i64,
71+ is_reference: bool,
72+ output: bool,
73+ rps: Rps,
74+ buffers: Vec<Buffer>,
75+ slices: usize,
76+ /// Index into `PictureParameterBufferHEVC::reference_frames` per DPB index.
77+ va_index: Vec<u8>,
78+}
79+
80+/// A stateless HEVC decoder.
81+pub struct HevcDecoder {
82+ display: Arc<Display>,
83+ vps_map: Vec<Option<Vps>>,
84+ sps_map: Vec<Option<Sps>>,
85+ pps_map: Vec<Option<Pps>>,
86+ session: Option<Session>,
87+ dpb: Vec<StoredPicture>,
88+ ready: ReadyFrames,
89+ current: Option<Current>,
90+ /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1.
91+ prev_tid0_poc: i32,
92+ /// Set once a picture has been decoded since the last reset.
93+ started: bool,
94+ max_reorder: usize,
95+ max_dec_pic_buffering: usize,
96+}
97+
98+impl HevcDecoder {
99+ /// A decoder with no stream state.
100+ pub fn new(display: &Arc<Display>) -> HevcDecoder {
101+ HevcDecoder {
102+ display: Arc::clone(display),
103+ vps_map: (0..16).map(|_| None).collect(),
104+ sps_map: (0..16).map(|_| None).collect(),
105+ pps_map: (0..64).map(|_| None).collect(),
106+ session: None,
107+ dpb: Vec::new(),
108+ ready: ReadyFrames::default(),
109+ current: None,
110+ prev_tid0_poc: 0,
111+ started: false,
112+ max_reorder: 1,
113+ max_dec_pic_buffering: 6,
114+ }
115+ }
116+
117+ /// Decode one Annex B access unit.
118+ pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
119+ for nal in split_annex_b(data) {
120+ match nal.header.nal_type {
121+ NalUnitType::Vps => {
122+ let vps = Vps::parse(&nal.rbsp())?;
123+ let id = usize::from(vps.id);
124+ if id < self.vps_map.len() {
125+ self.vps_map[id] = Some(vps);
126+ }
127+ }
128+ NalUnitType::Sps => {
129+ let sps = Sps::parse(&nal.rbsp())?;
130+ self.max_reorder = sps.max_num_reorder_pics as usize;
131+ self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1;
132+ let id = sps.id as usize;
133+ if id < self.sps_map.len() {
134+ self.sps_map[id] = Some(sps);
135+ }
136+ }
137+ NalUnitType::Pps => {
138+ let pps = Pps::parse(&nal.rbsp())?;
139+ let id = pps.id as usize;
140+ if id < self.pps_map.len() {
141+ self.pps_map[id] = Some(pps);
142+ }
143+ }
144+ t if t.is_vcl() => {
145+ self.slice(t, nal.payload, timestamp)?;
146+ }
147+ _ => {}
148+ }
149+ }
150+ self.finish_picture()?;
151+ Ok(())
152+ }
153+
154+ /// The next frame in output order.
155+ pub fn next_frame(&mut self) -> Option<Frame> {
156+ self.ready.pop()
157+ }
158+
159+ /// Push every buffered picture out (end of stream).
160+ pub fn flush(&mut self) {
161+ let _ = self.finish_picture();
162+ self.bump(true);
163+ }
164+
165+ /// Drop all picture state after a seek; parameter sets survive.
166+ pub fn reset(&mut self) {
167+ self.current = None;
168+ self.dpb.clear();
169+ self.ready.clear();
170+ self.prev_tid0_poc = 0;
171+ self.started = false;
172+ }
173+
174+ /// What the stream turned out to be.
175+ pub fn stream_info(&self) -> Option<StreamInfo> {
176+ self.session.as_ref().map(Session::info)
177+ }
178+
179+ fn slice(&mut self, nal_type: NalUnitType, payload: &[u8], timestamp: i64) -> Result<()> {
180+ let rbsp = unescape_rbsp(payload);
181+ // The header cannot be parsed without its PPS, and the PPS names the SPS.
182+ let pps_id = peek_pps_id(&rbsp, nal_type)?;
183+ let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else {
184+ return Ok(());
185+ };
186+ let Some(sps) = self
187+ .sps_map
188+ .get(pps.sps_id as usize)
189+ .and_then(|s| s.clone())
190+ else {
191+ return Ok(());
192+ };
193+ let (sh, pos) = SliceHeader::parse(&rbsp, &sps, &pps, nal_type)?;
194+
195+ if sh.first_slice_segment_in_pic {
196+ self.finish_picture()?;
197+ self.start_picture(&sps, &sh, nal_type, timestamp)?;
198+ }
199+ if self.current.is_none() {
200+ return Ok(());
201+ }
202+ self.render_slice(&sps, &pps, &sh, &pos, payload, nal_type)
203+ }
204+
205+ fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
206+ let bit_depth = (sps.bit_depth_luma_minus8 + 8) as u8;
207+ let profile = match (sps.chroma_format_idc, bit_depth) {
208+ (1, 8) => Profile::HEVCMain,
209+ (1, 10) => Profile::HEVCMain10,
210+ (chroma, depth) => {
211+ return Err(Error::unsupported(
212+ format!("HEVC chroma_format_idc {chroma} at {depth} bits"),
213+ "only Main and Main10 (4:2:0, 8 or 10 bit) are decoded in hardware",
214+ ));
215+ }
216+ };
217+ let coded = (
218+ sps.pic_width_in_luma_samples,
219+ sps.pic_height_in_luma_samples,
220+ );
221+ if let Some(session) = &self.session
222+ && session.coded_size == coded
223+ && session.bit_depth == bit_depth
224+ && session.profile == profile
225+ {
226+ return Ok(());
227+ }
228+ self.current = None;
229+ self.dpb.clear();
230+ self.session = Some(Session::new(
231+ &self.display,
232+ profile,
233+ coded,
234+ sps.display_size(),
235+ bit_depth,
236+ self.max_dec_pic_buffering + EXTRA_SURFACES,
237+ )?);
238+ Ok(())
239+ }
240+
241+ fn start_picture(
242+ &mut self,
243+ sps: &Sps,
244+ sh: &SliceHeader,
245+ nal_type: NalUnitType,
246+ timestamp: i64,
247+ ) -> Result<()> {
248+ self.ensure_session(sps)?;
249+
250+ let poc = self.picture_order_count(sps, sh, nal_type);
251+ // 8.3.2 runs before the picture is decoded and after its POC is known:
252+ // every stored picture the set does not name stops being a reference.
253+ let rps = self.apply_rps(sps, sh, nal_type, poc);
254+
255+ if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) {
256+ // An IRAP that restarts output order: everything ahead of it in the
257+ // buffer belongs ahead of it on screen too.
258+ self.bump(true);
259+ }
260+
261+ let session = self
262+ .session
263+ .as_ref()
264+ .ok_or_else(|| Error::config("HEVC picture before any SPS"))?;
265+ let surface = session
266+ .pool
267+ .acquire()
268+ .ok_or_else(|| Error::config("HEVC decode: every surface is still in use"))?;
269+
270+ // The driver indexes RefPicList into `reference_frames`, so the mapping
271+ // from DPB slot to that array is fixed once, here.
272+ let mut va_index = vec![0xffu8; self.dpb.len()];
273+ let mut n = 0u8;
274+ for (i, pic) in self.dpb.iter().enumerate() {
275+ if pic.mark != Mark::Unused && n < 15 {
276+ va_index[i] = n;
277+ n += 1;
278+ }
279+ }
280+
281+ self.current = Some(Current {
282+ surface,
283+ sps_id: sps.id,
284+ poc,
285+ timestamp,
286+ is_reference: true,
287+ output: sh.pic_output_flag,
288+ rps,
289+ buffers: Vec::new(),
290+ slices: 0,
291+ va_index,
292+ });
293+ Ok(())
294+ }
295+
296+ /// `PicOrderCntVal` (8.3.1).
297+ fn picture_order_count(&self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType) -> i32 {
298+ if nal_type.is_idr() {
299+ return 0;
300+ }
301+ let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4);
302+ let lsb = sh.poc_lsb as i32;
303+ let (prev_msb, prev_lsb) = if !self.started {
304+ (0, 0)
305+ } else {
306+ (
307+ self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)),
308+ self.prev_tid0_poc.rem_euclid(max_lsb),
309+ )
310+ };
311+ // An IRAP that starts a new coded video sequence has no predecessor.
312+ if nal_type.is_irap() && !self.started {
313+ return lsb;
314+ }
315+ let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 {
316+ prev_msb + max_lsb
317+ } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 {
318+ prev_msb - max_lsb
319+ } else {
320+ prev_msb
321+ };
322+ msb + lsb
323+ }
324+
325+ /// Reference picture set derivation and marking (8.3.2).
326+ fn apply_rps(&mut self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType, poc: i32) -> Rps {
327+ if nal_type.is_irap() && (nal_type.is_idr() || !self.started) {
328+ for pic in &mut self.dpb {
329+ pic.mark = Mark::Unused;
330+ }
331+ self.dpb.retain(|p| p.stored());
332+ return Rps::default();
333+ }
334+
335+ let set = &sh.short_term_ref_pic_set;
336+ let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4);
337+ let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term)
338+ for i in 0..set.num_negative as usize {
339+ wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false));
340+ }
341+ for i in 0..set.num_positive as usize {
342+ wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false));
343+ }
344+ for lt in &sh.long_term {
345+ // 8.3.2: a long-term entry without an MSB cycle is matched on its
346+ // POC low bits alone, which is how a stream survives an MSB wrap.
347+ let target = if lt.delta_poc_msb_present {
348+ poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb)
349+ + lt.poc_lsb_lt as i32
350+ } else {
351+ lt.poc_lsb_lt as i32
352+ };
353+ wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present));
354+ }
355+
356+ let mut rps = Rps::default();
357+ let mut keep = vec![false; self.dpb.len()];
358+ for (target, used, lsb_only) in wanted {
359+ let found = self.dpb.iter().position(|p| {
360+ if lsb_only {
361+ p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb)
362+ } else {
363+ p.poc == target
364+ }
365+ });
366+ let Some(idx) = found else { continue };
367+ keep[idx] = true;
368+ if !used {
369+ continue;
370+ }
371+ // The three "current" lists are what the reference lists are built
372+ // from, in POC order relative to the current picture.
373+ if self.dpb[idx].mark == Mark::LongTerm || lsb_only {
374+ rps.lt_curr.push(idx);
375+ } else if self.dpb[idx].poc < poc {
376+ rps.st_curr_before.push(idx);
377+ } else {
378+ rps.st_curr_after.push(idx);
379+ }
380+ }
381+ rps.st_curr_before
382+ .sort_by_key(|&i| std::cmp::Reverse(self.dpb[i].poc));
383+ rps.st_curr_after.sort_by_key(|&i| self.dpb[i].poc);
384+
385+ for (i, pic) in self.dpb.iter_mut().enumerate() {
386+ if !keep[i] {
387+ pic.mark = Mark::Unused;
388+ }
389+ }
390+ // Dropping unreferenced, already-output pictures here is what returns
391+ // their surfaces to the pool; the indices in `rps` are recomputed after.
392+ let mut remap = vec![usize::MAX; self.dpb.len()];
393+ let mut next = 0usize;
394+ for (i, pic) in self.dpb.iter().enumerate() {
395+ if pic.stored() {
396+ remap[i] = next;
397+ next += 1;
398+ }
399+ }
400+ self.dpb.retain(|p| p.stored());
401+ for list in [
402+ &mut rps.st_curr_before,
403+ &mut rps.st_curr_after,
404+ &mut rps.lt_curr,
405+ ] {
406+ list.retain(|&i| remap[i] != usize::MAX);
407+ for entry in list.iter_mut() {
408+ *entry = remap[*entry];
409+ }
410+ }
411+ rps
412+ }
413+
414+ fn render_slice(
415+ &mut self,
416+ sps: &Sps,
417+ pps: &Pps,
418+ sh: &SliceHeader,
419+ pos: &ParsePositions,
420+ payload: &[u8],
421+ nal_type: NalUnitType,
422+ ) -> Result<()> {
423+ let (Some(current), Some(session)) = (self.current.as_mut(), self.session.as_ref()) else {
424+ return Ok(());
425+ };
426+ if current.sps_id != sps.id {
427+ return Err(Error::Stream(ec_core::Error::corrupt(
428+ "HEVC SPS changed mid-picture",
429+ )));
430+ }
431+
432+ if current.slices == 0 {
433+ let pic_param = picture_parameters(sps, pps, sh, nal_type, current, &self.dpb);
434+ current
435+ .buffers
436+ .push(param_buffer(&session.context, &pic_param)?);
437+ if sps.scaling_list_enabled {
438+ // The syntax crate refuses a stream that codes its own lists, so
439+ // "enabled" here always means the flat default matrices.
440+ current.buffers.push(param_buffer(
441+ &session.context,
442+ &IQMatrixBufferHEVC::default(),
443+ )?);
444+ }
445+ }
446+
447+ // The NAL unit header is part of the slice data the driver is handed,
448+ // and every offset it is given is measured from there.
449+ let nal_bytes = payload.len() + 2;
450+ let mut slice_param = SliceParameterBufferHEVC {
451+ slice_data_size: nal_bytes as u32,
452+ slice_data_offset: 0,
453+ slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL
454+ slice_data_byte_offset: pos.slice_data_byte_offset(payload) as u32,
455+ slice_segment_address: sh.segment_address,
456+ collocated_ref_idx: if sh.temporal_mvp_enabled {
457+ sh.collocated_ref_idx as u8
458+ } else {
459+ 0xff
460+ },
461+ num_ref_idx_l0_active_minus1: sh.num_ref_idx_l0_active_minus1 as u8,
462+ num_ref_idx_l1_active_minus1: sh.num_ref_idx_l1_active_minus1 as u8,
463+ slice_qp_delta: sh.qp_delta as i8,
464+ slice_cb_qp_offset: sh.cb_qp_offset as i8,
465+ slice_cr_qp_offset: sh.cr_qp_offset as i8,
466+ slice_beta_offset_div2: sh.beta_offset_div2 as i8,
467+ slice_tc_offset_div2: sh.tc_offset_div2 as i8,
468+ five_minus_max_num_merge_cand: sh.five_minus_max_num_merge_cand as u8,
469+ num_entry_point_offsets: sh.entry_point_offsets.len().min(u16::MAX as usize) as u16,
470+ slice_data_num_emu_prevn_bytes: ec_h265_syntax::count_emulation_prevention_bytes(
471+ payload,
472+ )
473+ .min(u16::MAX as usize) as u16,
474+ ..SliceParameterBufferHEVC::default()
475+ };
476+ slice_param.long_slice_flags = slice_param
477+ .long_slice_flags
478+ .last_slice_of_pic(0)
479+ .dependent_slice_segment_flag(u32::from(sh.dependent_slice_segment))
480+ .slice_type(sh.slice_type.code())
481+ .color_plane_id(u32::from(sh.colour_plane_id))
482+ .slice_sao_luma_flag(u32::from(sh.sao_luma))
483+ .slice_sao_chroma_flag(u32::from(sh.sao_chroma))
484+ .mvd_l1_zero_flag(u32::from(sh.mvd_l1_zero))
485+ .cabac_init_flag(u32::from(sh.cabac_init))
486+ .slice_temporal_mvp_enabled_flag(u32::from(sh.temporal_mvp_enabled))
487+ .slice_deblocking_filter_disabled_flag(u32::from(sh.deblocking_filter_disabled))
488+ .collocated_from_l0_flag(u32::from(sh.collocated_from_l0))
489+ .slice_loop_filter_across_slices_enabled_flag(u32::from(
490+ sh.loop_filter_across_slices_enabled,
491+ ));
492+
493+ if sh.slice_type != SliceType::I {
494+ let lists = reference_lists(sh, &current.rps);
495+ for (x, list) in lists.iter().enumerate() {
496+ for (i, &dpb_idx) in list.iter().take(15).enumerate() {
497+ slice_param.ref_pic_list[x][i] =
498+ current.va_index.get(dpb_idx).copied().unwrap_or(0xff);
499+ }
500+ }
501+ }
502+ write_weights(&mut slice_param, sh);
503+
504+ current
505+ .buffers
506+ .push(param_buffer(&session.context, &slice_param)?);
507+ // Rebuild the NAL unit: `split_annex_b` hands over the payload without
508+ // its two header bytes, and the driver counts from them.
509+ let mut nal = Vec::with_capacity(nal_bytes);
510+ nal.extend_from_slice(&ec_h265_syntax::NalHeader::new(nal_type).to_bytes());
511+ nal.extend_from_slice(payload);
512+ current.buffers.push(Buffer::from_bytes(
513+ &session.context,
514+ sys::VASliceDataBufferType,
515+ &nal,
516+ )?);
517+ current.slices += 1;
518+ Ok(())
519+ }
520+
521+ fn finish_picture(&mut self) -> Result<()> {
522+ let Some(current) = self.current.take() else {
523+ return Ok(());
524+ };
525+ let Some(session) = self.session.as_ref() else {
526+ return Ok(());
527+ };
528+ if current.slices == 0 {
529+ return Ok(());
530+ }
531+ session.submit(&current.surface, current.buffers)?;
532+
533+ self.dpb.push(StoredPicture {
534+ surface: Arc::clone(&current.surface),
535+ poc: current.poc,
536+ timestamp: current.timestamp,
537+ mark: if current.is_reference {
538+ Mark::ShortTerm
539+ } else {
540+ Mark::Unused
541+ },
542+ output: current.output,
543+ });
544+ self.prev_tid0_poc = current.poc;
545+ self.started = true;
546+ self.bump(false);
547+ Ok(())
548+ }
549+
550+ /// The bumping process (C.5.2.4): output while the buffer holds more than
551+ /// its reordering or storage limit allows.
552+ fn bump(&mut self, flush: bool) {
553+ let Some(session) = self.session.as_ref() else {
554+ return;
555+ };
556+ loop {
557+ let pending = self.dpb.iter().filter(|p| p.output).count();
558+ let stored = self.dpb.iter().filter(|p| p.stored()).count();
559+ if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering {
560+ return;
561+ }
562+ let Some(idx) = self
563+ .dpb
564+ .iter()
565+ .enumerate()
566+ .filter(|(_, p)| p.output)
567+ .min_by_key(|(_, p)| p.poc)
568+ .map(|(i, _)| i)
569+ else {
570+ return;
571+ };
572+ let pic = &self.dpb[idx];
573+ self.ready.push(Frame::new(
574+ Arc::clone(&pic.surface),
575+ Arc::clone(&session.images),
576+ pic.timestamp,
577+ session.display_size,
578+ session.coded_size,
579+ session.bit_depth,
580+ ));
581+ self.dpb[idx].output = false;
582+ self.dpb.retain(|p| p.stored());
583+ }
584+ }
585+}
586+
587+/// `slice_pic_parameter_set_id`, readable without any parameter set.
588+fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> {
589+ let mut r = ec_core::BitReader::new(rbsp);
590+ r.read_bit()?; // first_slice_segment_in_pic_flag
591+ if nal_type.is_irap() {
592+ r.read_bit()?; // no_output_of_prior_pics_flag
593+ }
594+ Ok(r.read_ue()?)
595+}
596+
597+/// Reference list construction (8.3.4), as DPB indices.
598+fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec<usize>; 2] {
599+ let mut out = [Vec::new(), Vec::new()];
600+ let counts = [
601+ sh.num_ref_idx_l0_active_minus1 as usize + 1,
602+ sh.num_ref_idx_l1_active_minus1 as usize + 1,
603+ ];
604+ for x in 0..2 {
605+ if x == 1 && sh.slice_type != SliceType::B {
606+ continue;
607+ }
608+ // RefPicListTemp0 is StCurrBefore, StCurrAfter, LtCurr; list 1 swaps the
609+ // first two, which is the whole difference between the two lists.
610+ let mut temp: Vec<usize> = Vec::new();
611+ while temp.len() < counts[x] {
612+ let before = if x == 0 {
613+ &rps.st_curr_before
614+ } else {
615+ &rps.st_curr_after
616+ };
617+ let after = if x == 0 {
618+ &rps.st_curr_after
619+ } else {
620+ &rps.st_curr_before
621+ };
622+ let round = before.len() + after.len() + rps.lt_curr.len();
623+ if round == 0 {
624+ break;
625+ }
626+ temp.extend(before.iter().copied());
627+ temp.extend(after.iter().copied());
628+ temp.extend(rps.lt_curr.iter().copied());
629+ }
630+ if temp.is_empty() {
631+ continue;
632+ }
633+ for i in 0..counts[x] {
634+ let idx = match sh.list_entry[x].get(i) {
635+ Some(&entry) => *temp.get(entry as usize).unwrap_or(&temp[0]),
636+ None => temp[i.min(temp.len() - 1)],
637+ };
638+ out[x].push(idx);
639+ }
640+ }
641+ out
642+}
643+
644+fn picture_parameters(
645+ sps: &Sps,
646+ pps: &Pps,
647+ sh: &SliceHeader,
648+ nal_type: NalUnitType,
649+ current: &Current,
650+ dpb: &[StoredPicture],
651+) -> PictureParameterBufferHEVC {
652+ let mut p = PictureParameterBufferHEVC {
653+ curr_pic: VAPictureHEVC::new(current.surface.id(), current.poc, 0),
654+ pic_width_in_luma_samples: sps.pic_width_in_luma_samples as u16,
655+ pic_height_in_luma_samples: sps.pic_height_in_luma_samples as u16,
656+ sps_max_dec_pic_buffering_minus1: sps.max_dec_pic_buffering_minus1 as u8,
657+ bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8,
658+ bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8,
659+ pcm_sample_bit_depth_luma_minus1: sps.pcm.map(|p| p.0 as u8).unwrap_or(0),
660+ pcm_sample_bit_depth_chroma_minus1: sps.pcm.map(|p| p.1 as u8).unwrap_or(0),
661+ log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8,
662+ log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8,
663+ log2_min_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8,
664+ log2_diff_max_min_transform_block_size: sps.log2_diff_max_min_tb_size as u8,
665+ log2_min_pcm_luma_coding_block_size_minus3: sps.pcm.map(|p| p.2 as u8).unwrap_or(0),
666+ log2_diff_max_min_pcm_luma_coding_block_size: sps.pcm.map(|p| p.3 as u8).unwrap_or(0),
667+ max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8,
668+ max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8,
669+ init_qp_minus26: pps.init_qp_minus26 as i8,
670+ diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8,
671+ pps_cb_qp_offset: pps.cb_qp_offset as i8,
672+ pps_cr_qp_offset: pps.cr_qp_offset as i8,
673+ log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8,
674+ num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8,
675+ num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8,
676+ log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8,
677+ num_short_term_ref_pic_sets: sps.num_short_term_ref_pic_sets as u8,
678+ num_long_term_ref_pic_sps: sps.num_long_term_ref_pics_sps as u8,
679+ num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8,
680+ num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8,
681+ pps_beta_offset_div2: pps.beta_offset_div2 as i8,
682+ pps_tc_offset_div2: pps.tc_offset_div2 as i8,
683+ num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8,
684+ // Zero when the slice took its set from the SPS, which is what the
685+ // parser reports; the field exists so the driver can skip a set the
686+ // header carried itself.
687+ st_rps_bits: 0,
688+ ..PictureParameterBufferHEVC::default()
689+ };
690+
691+ // Tile geometry: uniform spacing is expanded here because libva wants the
692+ // widths either way (`va_dec_hevc.h:125`).
693+ let (cols, rows) = (
694+ pps.num_tile_columns_minus1 as usize + 1,
695+ pps.num_tile_rows_minus1 as usize + 1,
696+ );
697+ if pps.tiles_enabled {
698+ let ctb_cols = sps.pic_width_in_ctbs();
699+ let ctb_rows = sps.pic_height_in_ctbs();
700+ for i in 0..cols.min(p.column_width_minus1.len()) {
701+ let width = if pps.uniform_spacing {
702+ ((i + 1) as u32 * ctb_cols) / cols as u32 - (i as u32 * ctb_cols) / cols as u32
703+ } else {
704+ pps.column_width_minus1.get(i).copied().unwrap_or(0) + 1
705+ };
706+ p.column_width_minus1[i] = width.saturating_sub(1) as u16;
707+ }
708+ for i in 0..rows.min(p.row_height_minus1.len()) {
709+ let height = if pps.uniform_spacing {
710+ ((i + 1) as u32 * ctb_rows) / rows as u32 - (i as u32 * ctb_rows) / rows as u32
711+ } else {
712+ pps.row_height_minus1.get(i).copied().unwrap_or(0) + 1
713+ };
714+ p.row_height_minus1[i] = height.saturating_sub(1) as u16;
715+ }
716+ }
717+
718+ let mut n = 0usize;
719+ for (i, pic) in dpb.iter().enumerate() {
720+ if pic.mark == Mark::Unused || n >= p.reference_frames.len() {
721+ continue;
722+ }
723+ let mut flags = 0;
724+ if pic.mark == Mark::LongTerm {
725+ flags |= PICTURE_LONG_TERM_REFERENCE;
726+ }
727+ if current.rps.st_curr_before.contains(&i) {
728+ flags |= PICTURE_RPS_ST_CURR_BEFORE;
729+ } else if current.rps.st_curr_after.contains(&i) {
730+ flags |= PICTURE_RPS_ST_CURR_AFTER;
731+ } else if current.rps.lt_curr.contains(&i) {
732+ flags |= PICTURE_RPS_LT_CURR;
733+ }
734+ p.reference_frames[n] = VAPictureHEVC::new(pic.surface.id(), pic.poc, flags);
735+ n += 1;
736+ }
737+ for entry in p.reference_frames.iter_mut().skip(n) {
738+ *entry = VAPictureHEVC::new(ec_va::sys::VA_INVALID_SURFACE, 0, PICTURE_INVALID);
739+ }
740+
741+ p.pic_fields = p
742+ .pic_fields
743+ .chroma_format_idc(sps.chroma_format_idc)
744+ .separate_colour_plane_flag(u32::from(sps.separate_colour_plane))
745+ .pcm_enabled_flag(u32::from(sps.pcm_enabled))
746+ .scaling_list_enabled_flag(u32::from(sps.scaling_list_enabled))
747+ .transform_skip_enabled_flag(u32::from(pps.transform_skip_enabled))
748+ .amp_enabled_flag(u32::from(sps.amp_enabled))
749+ .strong_intra_smoothing_enabled_flag(u32::from(sps.strong_intra_smoothing))
750+ .sign_data_hiding_enabled_flag(u32::from(pps.sign_data_hiding_enabled))
751+ .constrained_intra_pred_flag(u32::from(pps.constrained_intra_pred))
752+ .cu_qp_delta_enabled_flag(u32::from(pps.cu_qp_delta_enabled))
753+ .weighted_pred_flag(u32::from(pps.weighted_pred))
754+ .weighted_bipred_flag(u32::from(pps.weighted_bipred))
755+ .transquant_bypass_enabled_flag(u32::from(pps.transquant_bypass_enabled))
756+ .tiles_enabled_flag(u32::from(pps.tiles_enabled))
757+ .entropy_coding_sync_enabled_flag(u32::from(pps.entropy_coding_sync_enabled))
758+ .pps_loop_filter_across_slices_enabled_flag(u32::from(
759+ pps.loop_filter_across_slices_enabled,
760+ ))
761+ .loop_filter_across_tiles_enabled_flag(u32::from(pps.loop_filter_across_tiles_enabled))
762+ .pcm_loop_filter_disabled_flag(u32::from(sps.pcm.map(|p| p.4).unwrap_or(false)))
763+ .no_pic_reordering_flag(u32::from(sps.max_num_reorder_pics == 0))
764+ .no_bi_pred_flag(u32::from(sh.slice_type != SliceType::B));
765+
766+ p.slice_parsing_fields = p
767+ .slice_parsing_fields
768+ .lists_modification_present_flag(u32::from(pps.lists_modification_present))
769+ .long_term_ref_pics_present_flag(u32::from(sps.long_term_ref_pics_present))
770+ .sps_temporal_mvp_enabled_flag(u32::from(sps.temporal_mvp_enabled))
771+ .cabac_init_present_flag(u32::from(pps.cabac_init_present))
772+ .output_flag_present_flag(u32::from(pps.output_flag_present))
773+ .dependent_slice_segments_enabled_flag(u32::from(pps.dependent_slice_segments_enabled))
774+ .pps_slice_chroma_qp_offsets_present_flag(u32::from(pps.slice_chroma_qp_offsets_present))
775+ .sample_adaptive_offset_enabled_flag(u32::from(sps.sao_enabled))
776+ .deblocking_filter_override_enabled_flag(u32::from(pps.deblocking_filter_override_enabled))
777+ .pps_disable_deblocking_filter_flag(u32::from(pps.deblocking_filter_disabled))
778+ .slice_segment_header_extension_present_flag(u32::from(
779+ pps.slice_segment_header_extension_present,
780+ ))
781+ .rap_pic_flag(u32::from(nal_type.is_irap()))
782+ .idr_pic_flag(u32::from(nal_type.is_idr()))
783+ .intra_pic_flag(u32::from(sh.slice_type == SliceType::I));
784+ p
785+}
786+
787+/// Copy the parsed `pred_weight_table()` into the slice parameter buffer.
788+fn write_weights(s: &mut SliceParameterBufferHEVC, sh: &SliceHeader) {
789+ let Some(w) = sh.pred_weight_table.as_ref() else {
790+ return;
791+ };
792+ s.luma_log2_weight_denom = w.luma_log2_weight_denom as u8;
793+ s.delta_chroma_log2_weight_denom = w.delta_chroma_log2_weight_denom as i8;
794+ for (list, entries) in [(0usize, &w.l0), (1usize, &w.l1)] {
795+ let (dlw, lo, dcw, co) = if list == 0 {
796+ (
797+ &mut s.delta_luma_weight_l0,
798+ &mut s.luma_offset_l0,
799+ &mut s.delta_chroma_weight_l0,
800+ &mut s.chroma_offset_l0,
801+ )
802+ } else {
803+ (
804+ &mut s.delta_luma_weight_l1,
805+ &mut s.luma_offset_l1,
806+ &mut s.delta_chroma_weight_l1,
807+ &mut s.chroma_offset_l1,
808+ )
809+ };
810+ for (i, entry) in entries.iter().take(15).enumerate() {
811+ if let Some((weight, offset)) = entry.luma {
812+ dlw[i] = weight as i8;
813+ lo[i] = offset as i8;
814+ }
815+ if let Some(pair) = entry.chroma {
816+ for c in 0..2 {
817+ dcw[i][c] = pair[c].0 as i8;
818+ co[i][c] = pair[c].1 as i8;
819+ }
820+ }
821+ }
822+ }
823+}
crates/ec-hw/src/dec/mod.rsadded+307 -0
@@ -0,0 +1,307 @@
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+
20+use std::collections::VecDeque;
21+use std::sync::Arc;
22+
23+use ec_va::caps::{Entrypoint, Profile};
24+use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, sys};
25+
26+use crate::error::{Error, Result};
27+use crate::frame::Frame;
28+use crate::pool::SurfacePool;
29+
30+mod av1;
31+mod dpb264;
32+mod h264;
33+mod hevc;
34+mod vp9;
35+
36+pub use av1::Av1Decoder;
37+pub use h264::H264Decoder;
38+pub use hevc::HevcDecoder;
39+pub use vp9::Vp9Decoder;
40+
41+/// The codecs this crate decodes in hardware.
42+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43+pub 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)]
56+pub 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.
70+pub struct Decoder {
71+ inner: Inner,
72+}
73+
74+enum Inner {
75+ H264(Box<H264Decoder>),
76+ H265(Box<HevcDecoder>),
77+ Vp9(Box<Vp9Decoder>),
78+ Av1(Box<Av1Decoder>),
79+}
80+
81+impl 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+/// The queue is the frame-out design `cros-codecs` uses (a decode call produces
162+/// events rather than returning a picture), minus the event fd: nothing in this
163+/// family polls a decoder from an event loop, and adding a `eventfd(2)` here
164+/// would mean a second FFI surface in a crate whose whole unsafe budget is
165+/// meant to be libva.
166+#[derive(Debug, Default)]
167+pub(crate) struct ReadyFrames {
168+ queue: VecDeque<Frame>,
169+}
170+
171+impl 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+
185+/// The GPU-side state one decoded stream needs: config, context, surfaces.
186+pub(crate) struct Session {
187+ pub(crate) context: Arc<Context>,
188+ /// The readback image every frame of this stream reuses.
189+ pub(crate) images: crate::frame::ImageCache,
190+ pub(crate) pool: SurfacePool,
191+ pub(crate) coded_size: (u32, u32),
192+ pub(crate) display_size: (u32, u32),
193+ pub(crate) bit_depth: u8,
194+ pub(crate) profile: Profile,
195+}
196+
197+impl Session {
198+ /// Create a decode session, deriving the surface format from the *stream's*
199+ /// bit depth.
200+ ///
201+ /// The bit depth is the whole point of this signature. An 8-bit context on
202+ /// a 10-bit stream is the incumbent defect this crate exists to not repeat:
203+ /// the driver either refuses the config or silently decodes to NV12 and
204+ /// throws away two bits per sample.
205+ pub(crate) fn new(
206+ display: &Arc<Display>,
207+ profile: Profile,
208+ coded_size: (u32, u32),
209+ display_size: (u32, u32),
210+ bit_depth: u8,
211+ num_surfaces: usize,
212+ ) -> Result<Session> {
213+ let caps = CapReport::probe(display)?;
214+ let entry = caps.entry(profile, Entrypoint::VLD).ok_or_else(|| {
215+ Error::unsupported(
216+ format!("{profile:?} decode"),
217+ "the driver advertises no VLD entrypoint for this profile",
218+ )
219+ })?;
220+
221+ let rt_format = if bit_depth > 8 {
222+ sys::VA_RT_FORMAT_YUV420_10
223+ } else {
224+ sys::VA_RT_FORMAT_YUV420
225+ };
226+ if !entry.supports_rt_format(rt_format) {
227+ return Err(Error::unsupported(
228+ format!("{bit_depth}-bit {profile:?} decode"),
229+ format!(
230+ "the driver's RT format mask for this profile is {:#x}",
231+ entry.rt_formats
232+ ),
233+ ));
234+ }
235+
236+ let (w, h) = coded_size;
237+ if let Some(surfaces) = &entry.surfaces
238+ && !surfaces.allows(w, h)
239+ {
240+ return Err(Error::unsupported(
241+ format!("{w}x{h} {profile:?} decode"),
242+ format!(
243+ "the driver accepts {:?}..{:?} x {:?}..{:?}",
244+ surfaces.min_width,
245+ surfaces.max_width,
246+ surfaces.min_height,
247+ surfaces.max_height
248+ ),
249+ ));
250+ }
251+
252+ let config = Config::new(
253+ display,
254+ profile,
255+ Entrypoint::VLD,
256+ &[ConfigAttrib::rt_format(rt_format)],
257+ )?;
258+
259+ let spec = if bit_depth > 8 {
260+ SurfaceSpec::p010(w, h)
261+ } else {
262+ SurfaceSpec::nv12(w, h)
263+ }
264+ .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_DECODER);
265+ let pool = SurfacePool::new(display, &spec, num_surfaces)?;
266+ let context = Context::new(&config, w, h, sys::VA_PROGRESSIVE, pool.targets())?;
267+
268+ Ok(Session {
269+ context,
270+ images: crate::frame::ImageCache::default(),
271+ pool,
272+ coded_size,
273+ display_size,
274+ bit_depth,
275+ profile,
276+ })
277+ }
278+
279+ /// Submit one picture: begin, render every buffer, end. No sync — the
280+ /// driver keeps submissions in order within a context, and the wait belongs
281+ /// where the pixels are actually read.
282+ pub(crate) fn submit(&self, target: &Arc<Surface>, buffers: Vec<ec_va::Buffer>) -> Result<()> {
283+ if buffers.is_empty() {
284+ // radeonsi answers an empty submission with INVALID_CONTEXT, which
285+ // reads like a driver bug report rather than what it is: a picture
286+ // with no slices, i.e. a stream that lost its data.
287+ return Err(Error::config(
288+ "refusing to submit a picture with no parameter buffers",
289+ ));
290+ }
291+ ec_va::Picture::new(&self.context, Arc::clone(target))
292+ .begin()?
293+ .render_all(buffers)?
294+ .end()?;
295+ Ok(())
296+ }
297+
298+ pub(crate) fn info(&self) -> StreamInfo {
299+ StreamInfo {
300+ coded_size: self.coded_size,
301+ display_size: self.display_size,
302+ bit_depth: self.bit_depth,
303+ profile: self.profile,
304+ num_surfaces: self.pool.len(),
305+ }
306+ }
307+}
crates/ec-hw/src/dec/vp9.rsadded+262 -0
@@ -0,0 +1,262 @@
1+//! Stateless VP9 decoding.
2+
3+use std::sync::Arc;
4+
5+use ec_va::caps::Profile;
6+use ec_va::{Buffer, Display, sys};
7+use ec_vp9_syntax::{
8+ FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, SEG_LVL_REF_FRAME, SEG_LVL_SKIP,
9+ Vp9Parser, superframe,
10+};
11+
12+use super::{ReadyFrames, Session, StreamInfo};
13+use crate::error::{Error, Result};
14+use crate::frame::Frame;
15+use crate::params::param_buffer;
16+use crate::params::vp9::{PictureParameterBufferVP9, SegmentParameterVP9, SliceParameterBufferVP9};
17+use crate::pool::PooledSurface;
18+
19+/// Reference slots plus the picture being decoded plus caller-held frames.
20+const EXTRA_SURFACES: usize = 6;
21+
22+/// A stateless VP9 decoder.
23+pub struct Vp9Decoder {
24+ display: Arc<Display>,
25+ parser: Vp9Parser,
26+ session: Option<Session>,
27+ /// The eight reference slots, as surfaces.
28+ refs: [Option<Arc<PooledSurface>>; NUM_REF_FRAMES],
29+ ready: ReadyFrames,
30+}
31+
32+impl Vp9Decoder {
33+ /// A decoder with no stream state.
34+ pub fn new(display: &Arc<Display>) -> Vp9Decoder {
35+ Vp9Decoder {
36+ display: Arc::clone(display),
37+ parser: Vp9Parser::new(),
38+ session: None,
39+ refs: [const { None }; NUM_REF_FRAMES],
40+ ready: ReadyFrames::default(),
41+ }
42+ }
43+
44+ /// Decode one chunk, which may be a superframe holding several frames.
45+ pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
46+ if data.is_empty() {
47+ return Ok(());
48+ }
49+ // A superframe packs a hidden ALTREF and the frame that shows it into
50+ // one chunk; the driver is handed each frame separately, and the offsets
51+ // matter because the picture parameters describe one frame at a time.
52+ let frames = superframe::split(data)?;
53+ for frame in frames {
54+ self.decode_frame(frame, timestamp)?;
55+ }
56+ Ok(())
57+ }
58+
59+ /// The next frame in display order (VP9 codes in display order).
60+ pub fn next_frame(&mut self) -> Option<Frame> {
61+ self.ready.pop()
62+ }
63+
64+ /// Nothing is buffered beyond the reference slots, so this is a no-op.
65+ pub fn flush(&mut self) {}
66+
67+ /// Drop reference state after a seek.
68+ pub fn reset(&mut self) {
69+ self.parser = Vp9Parser::new();
70+ self.refs = [const { None }; NUM_REF_FRAMES];
71+ self.ready.clear();
72+ }
73+
74+ /// What the stream turned out to be.
75+ pub fn stream_info(&self) -> Option<StreamInfo> {
76+ self.session.as_ref().map(Session::info)
77+ }
78+
79+ fn decode_frame(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
80+ let header = self.parser.parse_frame(data)?;
81+
82+ if header.show_existing_frame {
83+ // No decode: the frame in that slot is shown again. It keeps its
84+ // slot as well, so the surface is shared, not moved.
85+ let slot = usize::from(header.frame_to_show_map_idx);
86+ let (Some(surface), Some(session)) = (
87+ self.refs.get(slot).and_then(|s| s.clone()),
88+ self.session.as_ref(),
89+ ) else {
90+ return Err(Error::Stream(ec_core::Error::corrupt(
91+ "VP9 show_existing_frame names an empty reference slot",
92+ )));
93+ };
94+ self.ready.push(Frame::new(
95+ surface,
96+ Arc::clone(&session.images),
97+ timestamp,
98+ (header.width, header.height),
99+ session.coded_size,
100+ session.bit_depth,
101+ ));
102+ return Ok(());
103+ }
104+
105+ self.ensure_session(&header)?;
106+ let session = self
107+ .session
108+ .as_ref()
109+ .ok_or_else(|| Error::config("VP9 frame before any session"))?;
110+ let surface = session
111+ .pool
112+ .acquire()
113+ .ok_or_else(|| Error::config("VP9 decode: every surface is still in use"))?;
114+
115+ let pic_param = self.picture_parameters(&header);
116+ let slice_param = slice_parameters(&header, data.len());
117+ let buffers = vec![
118+ param_buffer(&session.context, &pic_param)?,
119+ param_buffer(&session.context, &slice_param)?,
120+ Buffer::from_bytes(&session.context, sys::VASliceDataBufferType, data)?,
121+ ];
122+ session.submit(&surface, buffers)?;
123+
124+ // Reference slot refresh (spec 8.10), after the submission that used
125+ // the old contents.
126+ for slot in 0..NUM_REF_FRAMES {
127+ if header.refresh_frame_flags & (1 << slot) != 0 {
128+ self.refs[slot] = Some(Arc::clone(&surface));
129+ }
130+ }
131+
132+ if header.show_frame {
133+ self.ready.push(Frame::new(
134+ surface,
135+ Arc::clone(&session.images),
136+ timestamp,
137+ (header.width, header.height),
138+ session.coded_size,
139+ session.bit_depth,
140+ ));
141+ }
142+ Ok(())
143+ }
144+
145+ fn ensure_session(&mut self, header: &FrameHeader) -> Result<()> {
146+ let profile = match header.profile {
147+ 0 => Profile::VP9Profile0,
148+ 2 => Profile::VP9Profile2,
149+ other => {
150+ return Err(Error::unsupported(
151+ format!("VP9 profile {other}"),
152+ "only the 4:2:0 profiles 0 and 2 are decoded in hardware",
153+ ));
154+ }
155+ };
156+ // VP9 codes in 64x64 superblocks; a surface has to hold whole ones.
157+ let coded = (
158+ header.width.next_multiple_of(64).max(64),
159+ header.height.next_multiple_of(64).max(64),
160+ );
161+ if let Some(session) = &self.session
162+ && session.coded_size.0 >= coded.0
163+ && session.coded_size.1 >= coded.1
164+ && session.bit_depth == header.bit_depth
165+ && session.profile == profile
166+ {
167+ return Ok(());
168+ }
169+ self.refs = [const { None }; NUM_REF_FRAMES];
170+ self.session = Some(Session::new(
171+ &self.display,
172+ profile,
173+ coded,
174+ (header.width, header.height),
175+ header.bit_depth,
176+ NUM_REF_FRAMES + EXTRA_SURFACES,
177+ )?);
178+ Ok(())
179+ }
180+
181+ fn picture_parameters(&self, h: &FrameHeader) -> PictureParameterBufferVP9 {
182+ let mut p = PictureParameterBufferVP9 {
183+ frame_width: h.width as u16,
184+ frame_height: h.height as u16,
185+ filter_level: h.loop_filter.level,
186+ sharpness_level: h.loop_filter.sharpness,
187+ log2_tile_rows: h.tile_info.rows_log2,
188+ log2_tile_columns: h.tile_info.cols_log2,
189+ frame_header_length_in_bytes: h.uncompressed_header_size,
190+ first_partition_size: h.header_size_in_bytes,
191+ mb_segment_tree_probs: h.segmentation.tree_probs,
192+ segment_pred_probs: h.segmentation.pred_probs,
193+ profile: h.profile,
194+ bit_depth: h.bit_depth,
195+ ..PictureParameterBufferVP9::default()
196+ };
197+ for (slot, surface) in self.refs.iter().enumerate() {
198+ if let Some(surface) = surface {
199+ p.reference_frames[slot] = surface.id();
200+ }
201+ }
202+ p.pic_fields = p
203+ .pic_fields
204+ .subsampling_x(u32::from(h.subsampling_x))
205+ .subsampling_y(u32::from(h.subsampling_y))
206+ .frame_type(u32::from(h.frame_type == FrameType::Inter))
207+ .show_frame(u32::from(h.show_frame))
208+ .error_resilient_mode(u32::from(h.error_resilient_mode))
209+ .intra_only(u32::from(h.intra_only))
210+ .allow_high_precision_mv(u32::from(h.allow_high_precision_mv))
211+ .mcomp_filter_type(h.interpolation_filter as u32)
212+ .frame_parallel_decoding_mode(u32::from(h.frame_parallel_decoding_mode))
213+ .reset_frame_context(u32::from(h.reset_frame_context))
214+ .refresh_frame_context(u32::from(h.refresh_frame_context))
215+ .frame_context_idx(u32::from(h.frame_context_idx))
216+ .segmentation_enabled(u32::from(h.segmentation.enabled))
217+ .segmentation_temporal_update(u32::from(h.segmentation.temporal_update))
218+ .segmentation_update_map(u32::from(h.segmentation.update_map))
219+ .last_ref_frame(u32::from(h.ref_frame_idx[0]))
220+ .last_ref_frame_sign_bias(u32::from(h.ref_frame_sign_bias[0]))
221+ .golden_ref_frame(u32::from(h.ref_frame_idx[1]))
222+ .golden_ref_frame_sign_bias(u32::from(h.ref_frame_sign_bias[1]))
223+ .alt_ref_frame(u32::from(h.ref_frame_idx[2]))
224+ .alt_ref_frame_sign_bias(u32::from(h.ref_frame_sign_bias[2]))
225+ .lossless_flag(u32::from(h.quantization.lossless()));
226+ p
227+ }
228+}
229+
230+/// The slice (whole-frame) parameters, including all eight segments.
231+///
232+/// Every segment is filled whether or not segmentation is enabled: with it off,
233+/// segment 0 is the one the driver uses, and the other seven are harmless — but
234+/// leaving them zeroed would hand the driver a quantiser scale of zero.
235+fn slice_parameters(h: &FrameHeader, size: usize) -> SliceParameterBufferVP9 {
236+ let mut s = SliceParameterBufferVP9 {
237+ slice_data_size: size as u32,
238+ slice_data_offset: 0,
239+ slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL
240+ ..SliceParameterBufferVP9::default()
241+ };
242+ for segment in 0..MAX_SEGMENTS {
243+ let dequant = h.segment_dequant(segment);
244+ let levels = h.loop_filter_levels(segment);
245+ let seg = &mut s.seg_param[segment];
246+ seg.filter_level = levels;
247+ seg.luma_ac_quant_scale = dequant.luma_ac;
248+ seg.luma_dc_quant_scale = dequant.luma_dc;
249+ seg.chroma_ac_quant_scale = dequant.chroma_ac;
250+ seg.chroma_dc_quant_scale = dequant.chroma_dc;
251+ seg.segment_flags = SegmentParameterVP9::default()
252+ .segment_flags
253+ .segment_reference_enabled(u16::from(
254+ h.segmentation.feature_enabled[segment][SEG_LVL_REF_FRAME],
255+ ))
256+ .segment_reference(h.segmentation.feature_data[segment][SEG_LVL_REF_FRAME] as u16)
257+ .segment_reference_skipped(u16::from(
258+ h.segmentation.feature_enabled[segment][SEG_LVL_SKIP],
259+ ));
260+ }
261+ s
262+}