diff --git a/crates/ec-hw/src/dec/av1.rs b/crates/ec-hw/src/dec/av1.rs new file mode 100644 index 00000000..2c5ad2d3 --- /dev/null +++ b/crates/ec-hw/src/dec/av1.rs @@ -0,0 +1,402 @@ +//! Stateless AV1 decoding. + +use std::sync::Arc; + +use ec_av1_syntax::{ + Av1Parser, FrameHeader, FrameType, NUM_REF_FRAMES, ObuKind, REFS_PER_FRAME, SequenceHeader, + Tile, +}; +use ec_va::caps::Profile; +use ec_va::{Buffer, Display, sys}; + +use super::{ReadyFrames, Session, StreamInfo}; +use crate::error::{Error, Result}; +use crate::frame::Frame; +use crate::params::av1::{ + PictureParameterBufferAV1, SliceParameterBufferAV1, WarpedMotionParamsAV1, +}; +use crate::params::param_buffer; +use crate::pool::PooledSurface; + +/// Reference slots plus the picture being decoded plus caller-held frames. +const EXTRA_SURFACES: usize = 6; + +/// A stateless AV1 decoder. +pub struct Av1Decoder { + display: Arc, + parser: Av1Parser, + session: Option, + refs: [Option>; NUM_REF_FRAMES], + ready: ReadyFrames, +} + +impl Av1Decoder { + /// A decoder with no stream state. + pub fn new(display: &Arc) -> Av1Decoder { + Av1Decoder { + display: Arc::clone(display), + parser: Av1Parser::new(), + session: None, + refs: [const { None }; NUM_REF_FRAMES], + ready: ReadyFrames::default(), + } + } + + /// Decode one temporal unit — every OBU of it, in order. + pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + if data.is_empty() { + return Ok(()); + } + // Tile offsets in the parse result are relative to `data`, and `data` + // is what the driver is handed, so no rebasing is needed anywhere. + let obus = self.parser.parse_temporal_unit(data)?; + let mut pending: Option> = None; + for obu in obus { + match obu.kind { + ObuKind::FrameHeader(header) => { + if header.show_existing_frame { + self.show_existing(&header, timestamp)?; + } else { + pending = Some(header); + } + } + ObuKind::TileGroup(tiles) => { + if let Some(header) = pending.take() { + self.decode_frame(&header, &tiles, data, timestamp)?; + } + } + ObuKind::Frame(header, tiles) => { + if header.show_existing_frame { + self.show_existing(&header, timestamp)?; + } else { + self.decode_frame(&header, &tiles, data, timestamp)?; + } + } + _ => {} + } + } + Ok(()) + } + + /// The next frame to show. + pub fn next_frame(&mut self) -> Option { + self.ready.pop() + } + + /// Nothing is buffered beyond the reference slots. + pub fn flush(&mut self) {} + + /// Drop reference state after a seek. + pub fn reset(&mut self) { + self.parser = Av1Parser::new(); + self.refs = [const { None }; NUM_REF_FRAMES]; + self.ready.clear(); + } + + /// What the stream turned out to be. + pub fn stream_info(&self) -> Option { + self.session.as_ref().map(Session::info) + } + + fn show_existing(&mut self, header: &FrameHeader, timestamp: i64) -> Result<()> { + let slot = usize::from(header.frame_to_show_map_idx); + let (Some(surface), Some(session)) = ( + self.refs.get(slot).and_then(|s| s.clone()), + self.session.as_ref(), + ) else { + return Err(Error::Stream(ec_core::Error::corrupt( + "AV1 show_existing_frame names an empty reference slot", + ))); + }; + self.ready.push(Frame::new( + Arc::clone(&surface), + Arc::clone(&session.images), + timestamp, + (header.render_width, header.render_height), + session.coded_size, + session.bit_depth, + )); + // 7.21: showing a KEY frame again refreshes every reference slot with + // it, which the reference *surfaces* have to follow too. + if header.frame_type == FrameType::Key { + for entry in &mut self.refs { + *entry = Some(Arc::clone(&surface)); + } + } + Ok(()) + } + + fn decode_frame( + &mut self, + header: &FrameHeader, + tiles: &[Tile], + data: &[u8], + timestamp: i64, + ) -> Result<()> { + let sequence = self + .parser + .sequence_header() + .cloned() + .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?; + self.ensure_session(&sequence, header)?; + let session = self + .session + .as_ref() + .ok_or_else(|| Error::config("AV1 frame before any session"))?; + let surface = session + .pool + .acquire() + .ok_or_else(|| Error::config("AV1 decode: every surface is still in use"))?; + + let pic_param = self.picture_parameters(&sequence, header, surface.id()); + let mut buffers = Vec::with_capacity(tiles.len() + 2); + buffers.push(param_buffer(&session.context, &pic_param)?); + for tile in tiles { + let slice = SliceParameterBufferAV1 { + slice_data_size: tile.size as u32, + slice_data_offset: tile.offset as u32, + slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL + tile_row: tile.row as u16, + tile_column: tile.column as u16, + ..SliceParameterBufferAV1::default() + }; + buffers.push(param_buffer(&session.context, &slice)?); + } + buffers.push(Buffer::from_bytes( + &session.context, + sys::VASliceDataBufferType, + data, + )?); + session.submit(&surface, buffers)?; + + for slot in 0..NUM_REF_FRAMES { + if header.refresh_frame_flags & (1 << slot) != 0 { + self.refs[slot] = Some(Arc::clone(&surface)); + } + } + + if header.show_frame { + self.ready.push(Frame::new( + surface, + Arc::clone(&session.images), + timestamp, + (header.render_width, header.render_height), + session.coded_size, + session.bit_depth, + )); + } + Ok(()) + } + + fn ensure_session(&mut self, seq: &SequenceHeader, header: &FrameHeader) -> Result<()> { + let bit_depth = seq.color_config.bit_depth; + let profile = match (seq.seq_profile, bit_depth) { + (0, _) => Profile::AV1Profile0, + (2, _) => Profile::AV1Profile2, + (other, _) => { + return Err(Error::unsupported( + format!("AV1 profile {other}"), + "only the 4:2:0 profiles 0 and 2 are decoded in hardware", + )); + } + }; + // Superblocks are 64x64 or 128x128; a surface holds whole ones. + let sb = if seq.use_128x128_superblock { 128 } else { 64 }; + let coded = ( + header.upscaled_width.next_multiple_of(sb).max(sb), + header.frame_height.next_multiple_of(sb).max(sb), + ); + if let Some(session) = &self.session + && session.coded_size.0 >= coded.0 + && session.coded_size.1 >= coded.1 + && session.bit_depth == bit_depth + && session.profile == profile + { + return Ok(()); + } + self.refs = [const { None }; NUM_REF_FRAMES]; + self.session = Some(Session::new( + &self.display, + profile, + coded, + (header.render_width, header.render_height), + bit_depth, + NUM_REF_FRAMES + EXTRA_SURFACES, + )?); + Ok(()) + } + + fn picture_parameters( + &self, + seq: &SequenceHeader, + h: &FrameHeader, + current: sys::VASurfaceID, + ) -> PictureParameterBufferAV1 { + let sb_shift = if seq.use_128x128_superblock { 5 } else { 4 }; + let mut p = PictureParameterBufferAV1 { + profile: seq.seq_profile, + order_hint_bits_minus_1: seq.order_hint_bits.saturating_sub(1) as u8, + bit_depth_idx: match seq.color_config.bit_depth { + 8 => 0, + 10 => 1, + _ => 2, + }, + matrix_coefficients: seq.color_config.matrix_coefficients, + current_frame: current, + current_display_picture: current, + frame_width_minus1: (h.upscaled_width.max(1) - 1) as u16, + frame_height_minus1: (h.frame_height.max(1) - 1) as u16, + primary_ref_frame: h.primary_ref_frame, + order_hint: h.order_hint as u8, + tile_cols: h.tile_info.cols.min(255) as u8, + tile_rows: h.tile_info.rows.min(255) as u8, + tile_count_minus_1: (h.tile_info.cols * h.tile_info.rows).max(1) as u16 - 1, + context_update_tile_id: h.tile_info.context_update_tile_id as u16, + superres_scale_denominator: h.superres_denom, + interp_filter: h.interpolation_filter as u8, + filter_level: [h.loop_filter.level[0], h.loop_filter.level[1]], + filter_level_u: h.loop_filter.level[2], + filter_level_v: h.loop_filter.level[3], + ref_deltas: h.loop_filter.ref_deltas, + mode_deltas: h.loop_filter.mode_deltas, + base_qindex: h.quantization.base_q_idx, + y_dc_delta_q: h.quantization.delta_q_y_dc, + u_dc_delta_q: h.quantization.delta_q_u_dc, + u_ac_delta_q: h.quantization.delta_q_u_ac, + v_dc_delta_q: h.quantization.delta_q_v_dc, + v_ac_delta_q: h.quantization.delta_q_v_ac, + cdef_damping_minus_3: h.cdef.damping.saturating_sub(3), + cdef_bits: h.cdef.bits, + cdef_y_strengths: h.cdef.y_strengths(), + cdef_uv_strengths: h.cdef.uv_strengths(), + ..PictureParameterBufferAV1::default() + }; + + for (slot, surface) in self.refs.iter().enumerate() { + if let Some(surface) = surface { + p.ref_frame_map[slot] = surface.id(); + } + } + for i in 0..REFS_PER_FRAME { + p.ref_frame_idx[i] = h.ref_frame_idx[i]; + } + + for (i, sbs) in h + .tile_info + .width_in_sbs_minus_1(sb_shift) + .into_iter() + .take(p.width_in_sbs_minus_1.len()) + .enumerate() + { + p.width_in_sbs_minus_1[i] = sbs; + } + for (i, sbs) in h + .tile_info + .height_in_sbs_minus_1(sb_shift) + .into_iter() + .take(p.height_in_sbs_minus_1.len()) + .enumerate() + { + p.height_in_sbs_minus_1[i] = sbs; + } + + p.seq_info_fields = p + .seq_info_fields + .still_picture(u32::from(seq.still_picture)) + .use_128x128_superblock(u32::from(seq.use_128x128_superblock)) + .enable_filter_intra(u32::from(seq.enable_filter_intra)) + .enable_intra_edge_filter(u32::from(seq.enable_intra_edge_filter)) + .enable_interintra_compound(u32::from(seq.enable_interintra_compound)) + .enable_masked_compound(u32::from(seq.enable_masked_compound)) + .enable_dual_filter(u32::from(seq.enable_dual_filter)) + .enable_order_hint(u32::from(seq.enable_order_hint)) + .enable_jnt_comp(u32::from(seq.enable_jnt_comp)) + .enable_cdef(u32::from(seq.enable_cdef)) + .mono_chrome(u32::from(seq.color_config.mono_chrome)) + .color_range(u32::from(seq.color_config.color_range)) + .subsampling_x(u32::from(seq.color_config.subsampling_x)) + .subsampling_y(u32::from(seq.color_config.subsampling_y)) + .film_grain_params_present(u32::from(seq.film_grain_params_present)); + + p.pic_info_fields = p + .pic_info_fields + .frame_type(h.frame_type as u32) + .show_frame(u32::from(h.show_frame)) + .showable_frame(u32::from(h.showable_frame)) + .error_resilient_mode(u32::from(h.error_resilient_mode)) + .disable_cdf_update(u32::from(h.disable_cdf_update)) + .allow_screen_content_tools(u32::from(h.allow_screen_content_tools)) + .force_integer_mv(u32::from(h.force_integer_mv)) + .allow_intrabc(u32::from(h.allow_intrabc)) + .use_superres(u32::from(h.use_superres)) + .allow_high_precision_mv(u32::from(h.allow_high_precision_mv)) + .is_motion_mode_switchable(u32::from(h.is_motion_mode_switchable)) + .use_ref_frame_mvs(u32::from(h.use_ref_frame_mvs)) + .disable_frame_end_update_cdf(u32::from(h.disable_frame_end_update_cdf)) + .uniform_tile_spacing_flag(u32::from(h.tile_info.uniform_spacing)) + .allow_warped_motion(u32::from(h.allow_warped_motion)); + + p.loop_filter_info_fields = p + .loop_filter_info_fields + .sharpness_level(h.loop_filter.sharpness) + .mode_ref_delta_enabled(u8::from(h.loop_filter.delta_enabled)) + .mode_ref_delta_update(u8::from(h.loop_filter.delta_update)); + + p.qmatrix_fields = p + .qmatrix_fields + .using_qmatrix(u16::from(h.quantization.using_qmatrix)) + .qm_y(u16::from(h.quantization.qm_y)) + .qm_u(u16::from(h.quantization.qm_u)) + .qm_v(u16::from(h.quantization.qm_v)); + + p.mode_control_fields = p + .mode_control_fields + .delta_q_present_flag(u32::from(h.delta.q_present)) + .log2_delta_q_res(u32::from(h.delta.q_res)) + .delta_lf_present_flag(u32::from(h.delta.lf_present)) + .log2_delta_lf_res(u32::from(h.delta.lf_res)) + .delta_lf_multi(u32::from(h.delta.lf_multi)) + .tx_mode(h.tx_mode as u32) + .reference_select(u32::from(h.reference_select)) + .reduced_tx_set_used(u32::from(h.reduced_tx_set)) + .skip_mode_present(u32::from(h.skip_mode_present)); + + p.loop_restoration_fields = p + .loop_restoration_fields + .yframe_restoration_type(h.loop_restoration.frame_restoration_type[0] as u16) + .cbframe_restoration_type(h.loop_restoration.frame_restoration_type[1] as u16) + .crframe_restoration_type(h.loop_restoration.frame_restoration_type[2] as u16) + .lr_unit_shift(u16::from(h.loop_restoration.lr_unit_shift)) + .lr_uv_shift(u16::from(h.loop_restoration.lr_uv_shift)); + + p.seg_info.segment_info_fields = p + .seg_info + .segment_info_fields + .enabled(u32::from(h.segmentation.enabled)) + .update_map(u32::from(h.segmentation.update_map)) + .temporal_update(u32::from(h.segmentation.temporal_update)) + .update_data(u32::from(h.segmentation.update_data)); + for segment in 0..ec_av1_syntax::MAX_SEGMENTS { + p.seg_info.feature_data[segment] = h.segmentation.feature_data[segment]; + p.seg_info.feature_mask[segment] = h.segmentation.feature_mask(segment); + } + + for i in 0..REFS_PER_FRAME { + let warp = &h.global_motion[i]; + let mut wm = WarpedMotionParamsAV1 { + wmtype: warp.model as i32, + invalid: u8::from(warp.invalid), + ..WarpedMotionParamsAV1::default() + }; + wm.wmmat[..6].copy_from_slice(&warp.params); + p.wm[i] = wm; + } + + // Film grain is a display-side effect, and edith wants the ungrained + // reconstruction to grade and scale; the parameters are still carried + // so a caller that wants grain has them. + p.film_grain_info.film_grain_info_fields = + p.film_grain_info.film_grain_info_fields.apply_grain(0); + p + } +} diff --git a/crates/ec-hw/src/dec/dpb264.rs b/crates/ec-hw/src/dec/dpb264.rs new file mode 100644 index 00000000..56c30652 --- /dev/null +++ b/crates/ec-hw/src/dec/dpb264.rs @@ -0,0 +1,960 @@ +//! The H.264 decoded picture buffer, clause 8.2, over surfaces. +//! +//! Same clauses as `ec-h264`'s software DPB — picture order count (8.2.1), +//! reference numbering (8.2.4.1), list initialisation and modification +//! (8.2.4.2/8.2.4.3), marking (8.2.5) and bumping (C.4.5.3) — but a stored +//! picture here is a *surface*, not a plane of samples. A stateless driver is +//! told the whole buffer on every picture, so these lists are the parameter +//! buffer's contents rather than an internal detail. + +use std::sync::Arc; + +use ec_h264_syntax::{DecRefPicMarking, RefPicListMod, SliceType, Sps}; + +use crate::error::{Error, Result}; +use crate::pool::PooledSurface; + +/// Maximum pictures held at once (Annex A caps the DPB at 16 frames; the extra +/// slot is the picture being decoded). +pub(crate) const MAX_STORED: usize = 17; + +/// How a stored picture is marked for reference (8.2.5.1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Mark { + /// Not used for reference. + Unused, + /// Used for short-term reference. + Short, + /// Used for long-term reference. + Long, +} + +/// One picture in the buffer. +pub(crate) struct Picture { + /// Identity, so "the picture just stored" survives reordering. + pub id: i32, + /// The surface it decoded into. + pub surface: Arc, + /// Presentation timestamp of the access unit it came from. + pub timestamp: i64, + /// `frame_num`. + pub frame_num: u32, + /// `FrameNumWrap` (8.2.4.1). + pub frame_num_wrap: i32, + /// `PicNum` for short-term, `LongTermPicNum` for long-term pictures. + pub pic_num: i32, + /// `LongTermFrameIdx`. + pub long_term_frame_idx: u32, + /// `PicOrderCnt()`. + pub poc: i32, + /// `PicOrderCntMsb`, predicted from by the next picture. + pub poc_msb: i32, + /// `pic_order_cnt_lsb`. + pub poc_lsb: i32, + /// `FrameNumOffset`. + pub frame_num_offset: i32, + /// Reference marking. + pub mark: Mark, + /// Inferred for a `frame_num` gap (8.2.5.2): a legal P reference with + /// unspecified samples, never output. + pub non_existing: bool, + /// Still waiting to be handed to the caller. + pub output: bool, +} + +impl Picture { + fn stored(&self) -> bool { + self.output || self.mark != Mark::Unused + } +} + +/// One reference picture list (`RefPicList0` / `RefPicList1`), as DPB indices. +#[derive(Clone, Copy, Debug)] +pub(crate) struct RefList { + entries: [u8; 33], + len: usize, +} + +impl Default for RefList { + fn default() -> RefList { + RefList { + entries: [0; 33], + len: 0, + } + } +} + +impl RefList { + pub(crate) fn len(&self) -> usize { + self.len + } + + /// The DPB index of `RefPicListX[idx]`, `None` past the end. + pub(crate) fn get(&self, idx: usize) -> Option { + (idx < self.len).then(|| usize::from(self.entries[idx])) + } + + fn push(&mut self, idx: usize) { + if self.len < self.entries.len() { + self.entries[self.len] = idx as u8; + self.len += 1; + } + } +} + +/// Output of the picture order count derivation (8.2.1). +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Poc { + pub value: i32, + pub frame_num_offset: i32, + pub msb: i32, + pub lsb: i32, +} + +/// What the DPB needs to know about the picture being decoded, taken from its +/// first slice header. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PicInfo { + pub is_idr: bool, + pub is_reference: bool, + pub frame_num: u32, + pub pic_order_cnt_lsb: u32, + pub delta_pic_order_cnt_bottom: i32, + pub delta_pic_order_cnt: [i32; 2], +} + +/// The decoded picture buffer and the cross-picture state of clause 8.2. +pub(crate) struct Dpb { + pub frames: Vec, + next_id: i32, + max_frames: usize, + max_reorder: usize, + max_long_term_idx: Option, + prev_poc_msb: i32, + prev_poc_lsb: i32, + prev_frame_num: u32, + prev_frame_num_offset: i32, + prev_has_mmco5: bool, + prev_ref_frame_num: u32, + started: bool, + pending_flush: bool, + last_id: i32, +} + +impl Default for Dpb { + fn default() -> Dpb { + Dpb { + frames: Vec::new(), + next_id: 0, + max_frames: 16, + max_reorder: 16, + max_long_term_idx: None, + prev_poc_msb: 0, + prev_poc_lsb: 0, + prev_frame_num: 0, + prev_frame_num_offset: 0, + prev_has_mmco5: false, + prev_ref_frame_num: 0, + started: false, + pending_flush: false, + last_id: -1, + } + } +} + +impl Dpb { + /// Adopt the buffer limits of `sps` (Annex A / VUI). + pub(crate) fn configure(&mut self, sps: &Sps) { + let level_frames = max_dpb_frames(sps); + let (buffering, reorder) = match sps.vui.as_ref().and_then(|v| v.bitstream_restriction) { + Some(r) => ( + (r.max_dec_frame_buffering as usize).min(MAX_STORED - 1), + (r.max_num_reorder_frames as usize).min(MAX_STORED - 1), + ), + None => (level_frames, level_frames), + }; + self.max_frames = buffering.max(sps.max_num_ref_frames as usize).max(1); + self.max_reorder = reorder.min(self.max_frames); + } + + /// How many frames the level allows, for sizing the surface pool. + pub(crate) fn capacity(&self) -> usize { + self.max_frames + } + + pub(crate) fn next_id(&mut self) -> i32 { + let id = self.next_id; + self.next_id = self.next_id.wrapping_add(1); + id + } + + /// Drop every stored picture (seek or stream discontinuity). + pub(crate) fn clear(&mut self) { + self.frames.clear(); + self.max_long_term_idx = None; + self.prev_poc_msb = 0; + self.prev_poc_lsb = 0; + self.prev_frame_num = 0; + self.prev_frame_num_offset = 0; + self.prev_has_mmco5 = false; + self.prev_ref_frame_num = 0; + self.started = false; + self.pending_flush = false; + self.last_id = -1; + } + + /// `PicOrderCnt()` of the picture about to be decoded (8.2.1). + pub(crate) fn picture_order_count(&self, sps: &Sps, info: &PicInfo) -> Result { + match sps.pic_order_cnt_type { + 0 => { + let max_lsb = 1i32 << sps.log2_max_pic_order_cnt_lsb; + let (prev_msb, prev_lsb) = if info.is_idr { + (0, 0) + } else { + (self.prev_poc_msb, self.prev_poc_lsb) + }; + let lsb = info.pic_order_cnt_lsb as i32; + let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { + prev_msb + max_lsb + } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { + prev_msb - max_lsb + } else { + prev_msb + }; + let top = msb + lsb; + let bottom = top + info.delta_pic_order_cnt_bottom; + Ok(Poc { + value: top.min(bottom), + frame_num_offset: 0, + msb, + lsb, + }) + } + 1 => { + let max_frame_num = 1i32 << sps.log2_max_frame_num; + let offset = self.frame_num_offset(info, max_frame_num); + let cycle_len = sps.offsets_for_ref_frame.len() as i32; + let mut abs_frame_num = if cycle_len != 0 { + offset + info.frame_num as i32 + } else { + 0 + }; + if !info.is_reference && abs_frame_num > 0 { + abs_frame_num -= 1; + } + let mut expected = 0i32; + if abs_frame_num > 0 { + let expected_delta: i32 = sps.offsets_for_ref_frame.iter().sum(); + let cycle_cnt = (abs_frame_num - 1) / cycle_len; + let in_cycle = (abs_frame_num - 1) % cycle_len; + expected = cycle_cnt.wrapping_mul(expected_delta); + for i in 0..=in_cycle as usize { + expected = expected.wrapping_add(sps.offsets_for_ref_frame[i]); + } + } + if !info.is_reference { + expected = expected.wrapping_add(sps.offset_for_non_ref_pic); + } + let top = expected.wrapping_add(info.delta_pic_order_cnt[0]); + let bottom = top + .wrapping_add(sps.offset_for_top_to_bottom_field) + .wrapping_add(info.delta_pic_order_cnt[1]); + Ok(Poc { + value: top.min(bottom), + frame_num_offset: offset, + msb: 0, + lsb: 0, + }) + } + 2 => { + let max_frame_num = 1i32 << sps.log2_max_frame_num; + let offset = self.frame_num_offset(info, max_frame_num); + let poc = if info.is_idr { + 0 + } else if !info.is_reference { + 2 * (offset + info.frame_num as i32) - 1 + } else { + 2 * (offset + info.frame_num as i32) + }; + Ok(Poc { + value: poc, + frame_num_offset: offset, + msb: 0, + lsb: 0, + }) + } + other => Err(Error::Stream(ec_core::Error::corrupt(format!( + "H.264 pic_order_cnt_type {other}" + )))), + } + } + + /// `FrameNumOffset` (8-6, 8-11). + fn frame_num_offset(&self, info: &PicInfo, max_frame_num: i32) -> i32 { + if info.is_idr { + return 0; + } + let prev = if self.prev_has_mmco5 { + 0 + } else { + self.prev_frame_num_offset + }; + if self.prev_frame_num > info.frame_num { + prev + max_frame_num + } else { + prev + } + } + + /// True when `frame_num` skips values (8.2.5.2). + /// + /// This is a *normal* condition — an editor seek or a lossy transport + /// produces it — and treating it as corruption is what used to knock a + /// hardware session back to software mid-timeline. + pub(crate) fn frame_num_gap(&self, sps: &Sps, frame_num: u32) -> bool { + let max = 1u32 << sps.log2_max_frame_num; + self.started + && frame_num != self.prev_ref_frame_num + && frame_num != (self.prev_ref_frame_num + 1) % max + } + + /// Insert the "non-existing" frames of 8.2.5.2 so that reference numbering + /// stays aligned with the encoder's. + /// + /// The inferred frames share the newest reference picture's surface. Their + /// samples are unspecified by the spec, and the previous reference is both + /// a better guess than grey and the only choice this driver accepts: a + /// reference surface it has never decoded into makes `vaEndPicture` fail + /// with `operation failed` (measured on radeonsi with a two-picture gap). + pub(crate) fn fill_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> Result { + let max = 1u32 << sps.log2_max_frame_num; + let mut unused = (self.prev_ref_frame_num + 1) % max; + let mut budget = MAX_STORED; + let mut filled = 0; + while unused != frame_num && budget > 0 { + budget -= 1; + let Some(surface) = self + .frames + .iter() + .max_by_key(|p| p.frame_num_wrap) + .map(|p| Arc::clone(&p.surface)) + else { + // Nothing decoded yet: there is no picture to stand in for the + // missing ones, and the next IDR will resynchronise anyway. + break; + }; + let info = PicInfo { + is_idr: false, + is_reference: true, + frame_num: unused, + pic_order_cnt_lsb: 0, + delta_pic_order_cnt_bottom: 0, + delta_pic_order_cnt: [0; 2], + }; + // 8.2.5.2: a non-existing frame gets a picture order count only + // when pic_order_cnt_type is not 0; under type 0 it has no output + // order, and 8.2.4.2.3 keeps it out of the B lists. + let poc = if sps.pic_order_cnt_type == 0 { + Poc::default() + } else { + self.picture_order_count(sps, &info)? + }; + self.number_short_term(unused, sps); + self.sliding_window(sps); + let id = self.next_id(); + self.frames.push(Picture { + id, + surface, + timestamp: 0, + frame_num: unused, + frame_num_wrap: unused as i32, + pic_num: unused as i32, + long_term_frame_idx: 0, + poc: poc.value, + poc_msb: poc.msb, + poc_lsb: poc.lsb, + frame_num_offset: poc.frame_num_offset, + mark: Mark::Short, + non_existing: true, + output: false, + }); + self.prev_frame_num = unused; + self.prev_frame_num_offset = poc.frame_num_offset; + self.prev_has_mmco5 = false; + self.prev_ref_frame_num = unused; + unused = (unused + 1) % max; + filled += 1; + } + Ok(filled) + } + + /// Recompute `FrameNumWrap` and `PicNum` against the current `frame_num` + /// (8.2.4.1). + pub(crate) fn number_short_term(&mut self, frame_num: u32, sps: &Sps) { + let max_frame_num = 1i32 << sps.log2_max_frame_num; + for pic in &mut self.frames { + match pic.mark { + Mark::Short => { + pic.frame_num_wrap = if pic.frame_num > frame_num { + pic.frame_num as i32 - max_frame_num + } else { + pic.frame_num as i32 + }; + pic.pic_num = pic.frame_num_wrap; + } + Mark::Long => pic.pic_num = pic.long_term_frame_idx as i32, + Mark::Unused => {} + } + } + } + + /// Build `RefPicList0`/`RefPicList1` for one slice: initialisation + /// (8.2.4.2.1 / 8.2.4.2.3) then modification (8.2.4.3). + #[allow(clippy::too_many_arguments)] + pub(crate) fn build_ref_lists( + &self, + slice_type: SliceType, + curr_poc: i32, + curr_pic_num: i32, + max_pic_num: i32, + num_l0: usize, + num_l1: usize, + mods: (&[RefPicListMod], &[RefPicListMod]), + ) -> Result<[RefList; 2]> { + let mut lists = [RefList::default(), RefList::default()]; + let mut short: [usize; MAX_STORED] = [0; MAX_STORED]; + let mut n_short = 0usize; + let mut long: [usize; MAX_STORED] = [0; MAX_STORED]; + let mut n_long = 0usize; + for (i, pic) in self.frames.iter().enumerate() { + if pic.non_existing && slice_type == SliceType::B { + continue; + } + match pic.mark { + Mark::Short if n_short < MAX_STORED => { + short[n_short] = i; + n_short += 1; + } + Mark::Long if n_long < MAX_STORED => { + long[n_long] = i; + n_long += 1; + } + _ => {} + } + } + let long = &mut long[..n_long]; + long.sort_unstable_by_key(|&i| self.frames[i].long_term_frame_idx); + + if slice_type == SliceType::B { + let short = &mut short[..n_short]; + short.sort_unstable_by_key(|&i| { + let poc = self.frames[i].poc; + if poc < curr_poc { + (0i32, -poc) + } else { + (1, poc) + } + }); + for &i in short.iter() { + lists[0].push(i); + } + for &i in long.iter() { + lists[0].push(i); + } + short.sort_unstable_by_key(|&i| { + let poc = self.frames[i].poc; + if poc > curr_poc { + (0i32, poc) + } else { + (1, -poc) + } + }); + for &i in short.iter() { + lists[1].push(i); + } + for &i in long.iter() { + lists[1].push(i); + } + // 8.2.4.2.3 step 3. + if lists[1].len > 1 + && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len] + { + lists[1].entries.swap(0, 1); + } + } else { + let short = &mut short[..n_short]; + short.sort_unstable_by_key(|&i| -self.frames[i].pic_num); + for &i in short.iter() { + lists[0].push(i); + } + for &i in long.iter() { + lists[0].push(i); + } + } + + let wanted = [num_l0, num_l1]; + let mods = [mods.0, mods.1]; + for x in 0..2 { + if x == 1 && slice_type != SliceType::B { + lists[1].len = 0; + continue; + } + if lists[x].len == 0 { + return Err(Error::Stream(ec_core::Error::corrupt( + "H.264 inter slice with an empty reference list", + ))); + } + let first = lists[x].entries[0]; + while lists[x].len < wanted[x] { + lists[x].push(usize::from(first)); + } + lists[x].len = wanted[x]; + self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num); + } + Ok(lists) + } + + /// Reference picture list modification (8.2.4.3), by the insert-and-compact + /// of equations 8-37 and 8-38. + fn modify_list( + &self, + list: &mut RefList, + mods: &[RefPicListMod], + curr_pic_num: i32, + max_pic_num: i32, + ) { + if mods.is_empty() { + return; + } + let active = list.len; + let mut tmp = [0u8; 34]; + tmp[..active].copy_from_slice(&list.entries[..active]); + let mut pred = curr_pic_num; + let mut ref_idx = 0usize; + for op in mods { + let target = match *op { + RefPicListMod::ShortTerm { + abs_diff_pic_num_minus1, + add, + } => { + let diff = abs_diff_pic_num_minus1 as i32 + 1; + let no_wrap = if add { + if pred + diff >= max_pic_num { + pred + diff - max_pic_num + } else { + pred + diff + } + } else if pred - diff < 0 { + pred - diff + max_pic_num + } else { + pred - diff + }; + pred = no_wrap; + let pic_num = if no_wrap > curr_pic_num { + no_wrap - max_pic_num + } else { + no_wrap + }; + self.frames + .iter() + .position(|p| p.mark == Mark::Short && p.pic_num == pic_num) + } + RefPicListMod::LongTerm(num) => self + .frames + .iter() + .position(|p| p.mark == Mark::Long && p.pic_num == num as i32), + }; + // A modification naming a picture the buffer never received points + // at something that was lost; keeping the initial entry decodes a + // seek or a dropped packet instead of failing the slice. + let Some(target) = target else { continue }; + if ref_idx >= active { + break; + } + for c in (ref_idx + 1..=active).rev() { + tmp[c] = tmp[c - 1]; + } + tmp[ref_idx] = target as u8; + ref_idx += 1; + let mut n = ref_idx; + for c in ref_idx..=active { + if usize::from(tmp[c]) != target { + tmp[n] = tmp[c]; + n += 1; + } + } + } + list.entries[..active].copy_from_slice(&tmp[..active]); + list.len = active; + } + + /// Store a decoded picture and apply the reference marking of 8.2.5. + pub(crate) fn store( + &mut self, + mut pic: Picture, + sps: &Sps, + info: &PicInfo, + marking: Option<&DecRefPicMarking>, + ) -> Result<()> { + let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5)); + pic.output = true; + self.number_short_term(info.frame_num, sps); + pic.frame_num_wrap = pic.frame_num as i32; + pic.pic_num = pic.frame_num as i32; + + if info.is_idr { + let no_output = marking.is_some_and(|m| m.no_output_of_prior_pics); + self.drain_prior(no_output); + pic.mark = Mark::Short; + if marking.is_some_and(|m| m.long_term_reference) { + pic.mark = Mark::Long; + pic.long_term_frame_idx = 0; + self.max_long_term_idx = Some(0); + } else { + self.max_long_term_idx = None; + } + } else if info.is_reference { + pic.mark = Mark::Short; + match marking { + Some(m) if m.adaptive => self.apply_mmco(&mut pic, m, info)?, + _ => self.sliding_window(sps), + } + } + + if has_mmco5 { + // 8.2.1: MMCO 5 restarts frame_num and picture order count here. + pic.poc = 0; + pic.frame_num = 0; + pic.frame_num_offset = 0; + pic.poc_msb = 0; + pic.poc_lsb = 0; + } + + self.prev_frame_num = pic.frame_num; + self.prev_frame_num_offset = pic.frame_num_offset; + self.prev_has_mmco5 = has_mmco5; + if info.is_reference { + self.prev_ref_frame_num = pic.frame_num; + self.prev_poc_msb = pic.poc_msb; + self.prev_poc_lsb = pic.poc_lsb; + } + self.started = true; + if (info.is_idr || has_mmco5) && self.frames.iter().any(|p| p.output) { + self.pending_flush = true; + } + self.last_id = pic.id; + + if self.frames.len() >= MAX_STORED { + return Err(Error::Stream(ec_core::Error::corrupt( + "H.264 decoded picture buffer overflow", + ))); + } + self.frames.push(pic); + Ok(()) + } + + /// Output and release every stored picture (IDR boundary or MMCO 5). + fn drain_prior(&mut self, discard: bool) { + for pic in &mut self.frames { + pic.mark = Mark::Unused; + if discard { + pic.output = false; + } + } + } + + /// Sliding window marking (8.2.5.3). + fn sliding_window(&mut self, sps: &Sps) { + let max_refs = (sps.max_num_ref_frames as usize).max(1); + loop { + let n = self + .frames + .iter() + .filter(|p| p.mark != Mark::Unused) + .count(); + if n < max_refs { + return; + } + let Some(oldest) = self + .frames + .iter_mut() + .filter(|p| p.mark == Mark::Short) + .min_by_key(|p| p.frame_num_wrap) + else { + // Only long-term references left: the stream must free one by + // MMCO, and refusing here would break a conformant stream. + return; + }; + oldest.mark = Mark::Unused; + } + } + + /// Adaptive marking (8.2.5.4). + fn apply_mmco( + &mut self, + pic: &mut Picture, + m: &DecRefPicMarking, + info: &PicInfo, + ) -> Result<()> { + let curr_pic_num = info.frame_num as i32; + for op in &m.mmcos { + match op.op { + 1 => { + let target = curr_pic_num - (op.arg1 as i32 + 1); + if let Some(p) = self + .frames + .iter_mut() + .find(|p| p.mark == Mark::Short && p.pic_num == target) + { + p.mark = Mark::Unused; + } + } + 2 => { + if let Some(p) = self + .frames + .iter_mut() + .find(|p| p.mark == Mark::Long && p.pic_num == op.arg1 as i32) + { + p.mark = Mark::Unused; + } + } + 3 => { + let target = curr_pic_num - (op.arg1 as i32 + 1); + let idx = op.arg2; + for p in &mut self.frames { + if p.mark == Mark::Long && p.long_term_frame_idx == idx { + p.mark = Mark::Unused; + } + } + if let Some(p) = self + .frames + .iter_mut() + .find(|p| p.mark == Mark::Short && p.pic_num == target) + { + p.mark = Mark::Long; + p.long_term_frame_idx = idx; + p.pic_num = idx as i32; + } + } + 4 => { + self.max_long_term_idx = op.arg1.checked_sub(1); + let limit = self.max_long_term_idx; + for p in &mut self.frames { + if p.mark == Mark::Long + && limit.is_none_or(|max| p.long_term_frame_idx > max) + { + p.mark = Mark::Unused; + } + } + } + 5 => { + for p in &mut self.frames { + p.mark = Mark::Unused; + } + self.max_long_term_idx = None; + } + 6 => { + let idx = op.arg1; + for p in &mut self.frames { + if p.mark == Mark::Long && p.long_term_frame_idx == idx { + p.mark = Mark::Unused; + } + } + pic.mark = Mark::Long; + pic.long_term_frame_idx = idx; + pic.pic_num = idx as i32; + } + other => { + return Err(Error::Stream(ec_core::Error::corrupt(format!( + "H.264 memory_management_control_operation {other}" + )))); + } + } + } + Ok(()) + } + + /// The next picture to output, or `None` while the buffer is still within + /// its reordering and storage limits (bumping, C.4.5.3). + pub(crate) fn next_output(&mut self, flush: bool) -> Option { + if self.pending_flush { + let last = self.last_id; + let best = self + .frames + .iter() + .enumerate() + .filter(|(_, p)| p.output && p.id != last) + .min_by_key(|(_, p)| p.poc) + .map(|(i, _)| i); + if best.is_some() { + return best; + } + self.pending_flush = false; + } + let pending = self.frames.iter().filter(|p| p.output).count(); + let stored = self.frames.iter().filter(|p| p.stored()).count(); + if !flush && pending <= self.max_reorder && stored <= self.max_frames { + return None; + } + let mut best: Option = None; + for (i, pic) in self.frames.iter().enumerate() { + if !pic.output || pic.non_existing { + continue; + } + if best.is_none_or(|b| pic.poc < self.frames[b].poc) { + best = Some(i); + } + } + best + } + + /// Mark picture `idx` as output and drop every slot that is now free. + /// + /// Dropping is what releases the surface back to the pool: nothing else + /// holds it once the buffer and the caller are done, which is the leak this + /// design makes structurally impossible. + pub(crate) fn released(&mut self, idx: usize) { + self.frames[idx].output = false; + self.frames.retain(|p| p.stored()); + } +} + +/// `MaxDpbFrames` from the level limits of Annex A, Table A-1. +fn max_dpb_frames(sps: &Sps) -> usize { + // MaxDpbMbs per level, in the level_idc order of Table A-1. + const LIMITS: [(u8, u32); 17] = [ + (10, 396), + (11, 900), + (12, 2376), + (13, 2376), + (20, 2376), + (21, 4752), + (22, 8100), + (30, 8100), + (31, 18000), + (32, 20480), + (40, 32768), + (41, 32768), + (42, 34816), + (50, 110400), + (51, 184320), + (52, 184320), + (60, 696320), + ]; + let mbs = sps.mbs_per_picture().max(1); + let max_dpb_mbs = LIMITS + .iter() + .find(|(level, _)| *level >= sps.level_idc) + .map(|(_, mbs)| *mbs) + .unwrap_or(696_320); + ((max_dpb_mbs / mbs) as usize).clamp(1, 16) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sps_for(poc_type: u8) -> Sps { + let mut sps = Sps { + profile_idc: 100, + constraint_flags: 0, + level_idc: 40, + id: 0, + chroma_format_idc: 1, + separate_colour_plane: false, + bit_depth_luma: 8, + bit_depth_chroma: 8, + transform_bypass: false, + scaling_lists: None, + log2_max_frame_num: 4, + pic_order_cnt_type: poc_type, + log2_max_pic_order_cnt_lsb: 4, + delta_pic_order_always_zero: false, + offset_for_non_ref_pic: 0, + offset_for_top_to_bottom_field: 0, + offsets_for_ref_frame: Vec::new(), + max_num_ref_frames: 4, + gaps_in_frame_num_allowed: true, + frame_mbs_only: true, + mb_adaptive_frame_field: false, + direct_8x8_inference: true, + crop: (0, 0, 0, 0), + vui: None, + mb_width: 120, + mb_height: 68, + coded_width: 1920, + coded_height: 1088, + width: 1920, + height: 1088, + }; + if poc_type == 1 { + sps.offsets_for_ref_frame = vec![2, -2]; + } + sps + } + + fn info(frame_num: u32, lsb: u32, is_ref: bool, is_idr: bool) -> PicInfo { + PicInfo { + is_idr, + is_reference: is_ref, + frame_num, + pic_order_cnt_lsb: lsb, + delta_pic_order_cnt_bottom: 0, + delta_pic_order_cnt: [0; 2], + } + } + + #[test] + fn poc_type_0_tracks_the_msb_across_a_wrap() { + let sps = sps_for(0); + let mut dpb = Dpb::default(); + let poc = dpb + .picture_order_count(&sps, &info(0, 0, true, true)) + .unwrap(); + assert_eq!(poc.value, 0); + dpb.prev_poc_msb = poc.msb; + dpb.prev_poc_lsb = poc.lsb; + + let poc = dpb + .picture_order_count(&sps, &info(1, 14, true, false)) + .unwrap(); + assert_eq!(poc.value, 14); + dpb.prev_poc_msb = poc.msb; + dpb.prev_poc_lsb = poc.lsb; + + // lsb wraps 14 -> 2 with MaxPicOrderCntLsb 16: the msb must step up. + let poc = dpb + .picture_order_count(&sps, &info(2, 2, true, false)) + .unwrap(); + assert_eq!(poc.value, 18); + } + + #[test] + fn frame_num_gaps_are_detected_but_not_at_the_start() { + let sps = sps_for(0); + let mut dpb = Dpb::default(); + // Nothing decoded yet: a jump is a seek, not a gap. + assert!(!dpb.frame_num_gap(&sps, 7)); + dpb.started = true; + dpb.prev_ref_frame_num = 3; + assert!(!dpb.frame_num_gap(&sps, 3)); + assert!(!dpb.frame_num_gap(&sps, 4)); + assert!(dpb.frame_num_gap(&sps, 6)); + // MaxFrameNum is 16, so 15 -> 0 is contiguous, 15 -> 1 is a gap. + dpb.prev_ref_frame_num = 15; + assert!(!dpb.frame_num_gap(&sps, 0)); + assert!(dpb.frame_num_gap(&sps, 1)); + } + + #[test] + fn level_limits_size_the_buffer() { + let mut sps = sps_for(0); + let mut dpb = Dpb::default(); + dpb.configure(&sps); + // 1080p at level 4.0: 32768 / 8160 = 4 frames. + assert_eq!(dpb.capacity(), 4); + sps.level_idc = 51; + dpb.configure(&sps); + assert_eq!(dpb.capacity(), 16); + } +} diff --git a/crates/ec-hw/src/dec/h264.rs b/crates/ec-hw/src/dec/h264.rs new file mode 100644 index 00000000..31843549 --- /dev/null +++ b/crates/ec-hw/src/dec/h264.rs @@ -0,0 +1,707 @@ +//! Stateless H.264 decoding. + +use std::sync::Arc; + +use ec_h264_syntax::{ + AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader, + SliceType, Sps, unescape_rbsp, +}; +use ec_va::caps::Profile; +use ec_va::{Buffer, Display, sys}; + +use super::dpb264::{Dpb, Mark, PicInfo, Picture, Poc, RefList}; +use super::{ReadyFrames, Session, StreamInfo}; +use crate::error::{Error, Result}; +use crate::frame::Frame; +use crate::params::h264::{ + IQMatrixBufferH264, PICTURE_LONG_TERM_REFERENCE, PICTURE_SHORT_TERM_REFERENCE, + PictureParameterBufferH264, SliceParameterBufferH264, VAPictureH264, +}; +use crate::params::param_buffer; +use crate::pool::PooledSurface; + +/// Extra surfaces beyond the DPB: one being decoded, one or two in the caller's +/// hands, plus slack so a `frame_num` gap fill never starves the decoder. +const EXTRA_SURFACES: usize = 6; + +/// The picture currently being assembled from its slices. +struct Current { + surface: Arc, + id: i32, + sps_id: u8, + info: PicInfo, + poc: Poc, + timestamp: i64, + /// `dec_ref_pic_marking()` from the picture's first slice header, which is + /// what 8.2.5 applies once the whole picture is decoded. + marking: Option, + /// Parameter and data buffers submitted so far. + buffers: Vec, + slices: usize, +} + +/// A stateless H.264 decoder. +pub struct H264Decoder { + display: Arc, + sps_map: [Option; 32], + pps_map: Vec>, + session: Option, + dpb: Dpb, + ready: ReadyFrames, + current: Option, + /// Reusable unescape buffer; NAL payloads are rewritten into it in turn. + rbsp: Vec, + gap_frames: u64, +} + +impl H264Decoder { + /// A decoder with no stream state. The GPU context is created when the + /// first SPS arrives, because only then is the size and bit depth known. + pub fn new(display: &Arc) -> H264Decoder { + H264Decoder { + display: Arc::clone(display), + sps_map: [const { None }; 32], + pps_map: (0..256).map(|_| None).collect(), + session: None, + dpb: Dpb::default(), + ready: ReadyFrames::default(), + current: None, + rbsp: Vec::new(), + gap_frames: 0, + } + } + + /// Decode one Annex B access unit. + pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + for nal in AnnexBIter::new(data) { + let Some((&first, payload)) = nal.split_first() else { + continue; + }; + let header = NalHeader::parse(first)?; + match header.unit_type { + NalUnitType::Sps => { + let mut rbsp = std::mem::take(&mut self.rbsp); + unescape_rbsp(payload, &mut rbsp); + let sps = Sps::parse(&rbsp); + self.rbsp = rbsp; + let sps = sps?; + self.dpb.configure(&sps); + let id = usize::from(sps.id); + self.sps_map[id] = Some(sps); + } + NalUnitType::Pps => { + let mut rbsp = std::mem::take(&mut self.rbsp); + unescape_rbsp(payload, &mut rbsp); + let pps = Pps::parse(&rbsp, |id| self.sps_map[usize::from(id)].as_ref()); + self.rbsp = rbsp; + let pps = pps?; + let id = pps.id as usize; + if id < self.pps_map.len() { + self.pps_map[id] = Some(pps); + } + } + NalUnitType::Slice | NalUnitType::SliceIdr => { + self.slice(header, nal, payload, timestamp)?; + } + // SEI, AUD, filler and everything else carries nothing a + // stateless decode submission needs. + _ => {} + } + } + // One access unit is one picture: close it here rather than waiting for + // the next first_mb_in_slice == 0, so a caller gets its frame in the + // call that fed the data. + self.finish_picture()?; + Ok(()) + } + + /// The next frame in display order. + pub fn next_frame(&mut self) -> Option { + self.ready.pop() + } + + /// Push every buffered picture out (end of stream). + pub fn flush(&mut self) { + let _ = self.finish_picture(); + self.bump(true); + } + + /// Drop all picture state; parameter sets and the GPU session survive. + pub fn reset(&mut self) { + self.current = None; + self.dpb.clear(); + self.ready.clear(); + self.gap_frames = 0; + } + + /// What the stream turned out to be, once its first SPS was seen. + pub fn stream_info(&self) -> Option { + self.session.as_ref().map(Session::info) + } + + /// Pictures inferred for `frame_num` gaps (8.2.5.2) since the last reset. + /// + /// Exposed because it is the difference between a stream that stays on the + /// hardware and one that falls back to software: a gap is normal, and a + /// caller watching this counter can tell "the encoder skipped pictures" + /// from "the decoder is guessing". + pub fn gap_frames_synthesized(&self) -> u64 { + self.gap_frames + } + + fn slice( + &mut self, + header: NalHeader, + nal: &[u8], + payload: &[u8], + timestamp: i64, + ) -> Result<()> { + let mut rbsp = std::mem::take(&mut self.rbsp); + unescape_rbsp(payload, &mut rbsp); + let result = self.slice_rbsp(header, nal, &rbsp, timestamp); + self.rbsp = rbsp; + result + } + + fn slice_rbsp( + &mut self, + header: NalHeader, + nal: &[u8], + rbsp: &[u8], + timestamp: i64, + ) -> Result<()> { + // Two passes over the parameter sets: the slice header needs the PPS to + // parse, and the PPS names its SPS. + let pps_id = peek_pps_id(rbsp)?; + let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else { + // A slice referring to a parameter set we never received is what a + // seek into the middle of a stream looks like; skip it rather than + // failing the whole access unit. + return Ok(()); + }; + let Some(sps) = self.sps_map[usize::from(pps.sps_id)].clone() else { + return Ok(()); + }; + let sh = SliceHeader::parse(rbsp, header, &sps, &pps)?; + + if sh.first_mb_in_slice == 0 { + self.finish_picture()?; + self.start_picture(&sps, &sh, header, timestamp)?; + } + if self.current.is_none() { + // Mid-picture entry after a seek: no first slice, nothing to add to. + return Ok(()); + } + self.render_slice(&sps, &pps, &sh, nal, header) + } + + /// Create the GPU session if this stream has not had one yet. + fn ensure_session(&mut self, sps: &Sps) -> Result<()> { + let profile = profile_for(sps)?; + let coded = (sps.coded_width, sps.coded_height); + let bit_depth = sps.bit_depth_luma; + if let Some(session) = &self.session + && session.coded_size == coded + && session.bit_depth == bit_depth + && session.profile == profile + { + return Ok(()); + } + // A resolution change starts a new session; the old one drops with its + // surfaces once the frames still out there are released. + self.current = None; + self.dpb.clear(); + let surfaces = self.dpb.capacity() + EXTRA_SURFACES; + self.session = Some(Session::new( + &self.display, + profile, + coded, + (sps.width, sps.height), + bit_depth, + surfaces, + )?); + Ok(()) + } + + fn start_picture( + &mut self, + sps: &Sps, + sh: &SliceHeader, + header: NalHeader, + timestamp: i64, + ) -> Result<()> { + self.ensure_session(sps)?; + let info = PicInfo { + is_idr: header.is_idr(), + is_reference: header.ref_idc != 0, + frame_num: sh.frame_num, + pic_order_cnt_lsb: sh.pic_order_cnt_lsb, + delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom, + delta_pic_order_cnt: sh.delta_pic_order_cnt, + }; + + // 8.2.5.2: missing frame_num values are normal (a seek, a dropped + // packet, an encoder that skipped a picture). Synthesising the frames + // keeps the reference numbering aligned, which is the difference + // between decoding the rest of the GOP and falling back to software. + if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) { + self.gap_frames += self.dpb.fill_frame_num_gap(sps, sh.frame_num)? as u64; + } + + let poc = self.dpb.picture_order_count(sps, &info)?; + let session = self + .session + .as_ref() + .ok_or_else(|| Error::config("H.264 picture before any SPS"))?; + let surface = session + .pool + .acquire() + .ok_or_else(|| Error::config("H.264 decode: every surface is still in use"))?; + let id = self.dpb.next_id(); + self.current = Some(Current { + surface, + id, + sps_id: sps.id, + info, + poc, + timestamp, + marking: sh.dec_ref_pic_marking.clone(), + buffers: Vec::new(), + slices: 0, + }); + Ok(()) + } + + fn render_slice( + &mut self, + sps: &Sps, + pps: &Pps, + sh: &SliceHeader, + nal: &[u8], + header: NalHeader, + ) -> Result<()> { + let (Some(current), Some(session)) = (self.current.as_mut(), self.session.as_ref()) else { + return Ok(()); + }; + if current.sps_id != sps.id { + return Err(Error::Stream(ec_core::Error::corrupt( + "H.264 SPS changed mid-picture", + ))); + } + + // The picture parameter buffer goes in once, with the first slice: it + // describes the picture, and the DPB it names must not change under the + // driver between slices. + if current.slices == 0 { + let pic_param = picture_parameters(sps, pps, sh, header, current, &self.dpb); + current + .buffers + .push(param_buffer(&session.context, &pic_param)?); + // The matrices are sent for every picture, flat or not: a driver + // that never receives them dequantises with a zero matrix and + // hands back a uniformly grey surface (radeonsi does exactly this). + // A PPS scaling matrix overrides the SPS one (7.4.2.2). + let iq = match pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref()) { + Some(lists) => IQMatrixBufferH264 { + scaling_list_4x4: lists.list_4x4, + scaling_list_8x8: [lists.list_8x8[0], lists.list_8x8[1]], + ..IQMatrixBufferH264::default() + }, + None => IQMatrixBufferH264::default(), + }; + current.buffers.push(param_buffer(&session.context, &iq)?); + } + + let max_pic_num = 1i32 << sps.log2_max_frame_num; + let lists = if sh.slice_type.is_intra() { + [RefList::default(), RefList::default()] + } else { + self.dpb.number_short_term(sh.frame_num, sps); + self.dpb.build_ref_lists( + sh.slice_type, + current.poc.value, + sh.frame_num as i32, + max_pic_num, + sh.num_ref_idx_l0_active as usize, + sh.num_ref_idx_l1_active as usize, + (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1), + )? + }; + + let slice_param = slice_parameters(sh, pps, nal, &lists, &self.dpb); + current + .buffers + .push(param_buffer(&session.context, &slice_param)?); + current.buffers.push(Buffer::from_bytes( + &session.context, + sys::VASliceDataBufferType, + nal, + )?); + current.slices += 1; + Ok(()) + } + + fn finish_picture(&mut self) -> Result<()> { + let Some(current) = self.current.take() else { + return Ok(()); + }; + let Some(session) = self.session.as_ref() else { + return Ok(()); + }; + if current.slices == 0 { + // No slice data reached the driver, so there is nothing to submit; + // the surface returns to the pool with `current`. + return Ok(()); + } + let Some(sps) = self.sps_map[usize::from(current.sps_id)].clone() else { + return Ok(()); + }; + + session.submit(¤t.surface, current.buffers)?; + + let picture = Picture { + id: current.id, + surface: Arc::clone(¤t.surface), + timestamp: current.timestamp, + frame_num: current.info.frame_num, + frame_num_wrap: current.info.frame_num as i32, + pic_num: current.info.frame_num as i32, + long_term_frame_idx: 0, + poc: current.poc.value, + poc_msb: current.poc.msb, + poc_lsb: current.poc.lsb, + frame_num_offset: current.poc.frame_num_offset, + mark: Mark::Unused, + non_existing: false, + output: true, + }; + self.dpb + .store(picture, &sps, ¤t.info, current.marking.as_ref())?; + self.bump(false); + Ok(()) + } + + /// Move whatever the bumping process releases into the ready queue. + fn bump(&mut self, flush: bool) { + let Some(session) = self.session.as_ref() else { + return; + }; + while let Some(idx) = self.dpb.next_output(flush) { + let pic = &self.dpb.frames[idx]; + let frame = Frame::new( + Arc::clone(&pic.surface), + Arc::clone(&session.images), + pic.timestamp, + session.display_size, + session.coded_size, + session.bit_depth, + ); + self.ready.push(frame); + self.dpb.released(idx); + } + } +} + +/// The `pic_parameter_set_id` of a slice header, which is the second syntax +/// element and needs no parameter set to read. +fn peek_pps_id(rbsp: &[u8]) -> Result { + let mut r = ec_core::BitReader::new(rbsp); + r.read_ue()?; // first_mb_in_slice + r.read_ue()?; // slice_type + Ok(r.read_ue()?) +} + +/// The VA profile for a stream, from its SPS. +fn profile_for(sps: &Sps) -> Result { + Ok(match sps.profile_idc { + 66 => { + // Constrained baseline is a subset of main and every driver that + // decodes main decodes it; plain baseline (FMO/ASO) is not, and + // this crate does not implement slice groups either way. + Profile::H264ConstrainedBaseline + } + 77 | 88 => Profile::H264Main, + 100 | 110 | 122 | 244 if sps.bit_depth_luma > 8 => Profile::H264High10, + 100 => Profile::H264High, + other => { + return Err(Error::unsupported( + format!("H.264 profile_idc {other}"), + "no VA profile covers it", + )); + } + }) +} + +/// `slice_type` as the driver wants it: the modulo-5 value of Table 7-6. +fn slice_type_code(slice_type: SliceType) -> u8 { + match slice_type { + SliceType::P => 0, + SliceType::B => 1, + SliceType::I => 2, + SliceType::Sp => 3, + SliceType::Si => 4, + } +} + +/// The VA reference entry for a stored picture. +fn reference_entry(pic: &Picture) -> VAPictureH264 { + let flags = match pic.mark { + Mark::Long => PICTURE_LONG_TERM_REFERENCE, + _ => PICTURE_SHORT_TERM_REFERENCE, + }; + let frame_idx = if pic.mark == Mark::Long { + pic.long_term_frame_idx + } else { + pic.frame_num + }; + VAPictureH264::frame(pic.surface.id(), frame_idx, pic.poc, flags) +} + +fn picture_parameters( + sps: &Sps, + pps: &Pps, + sh: &SliceHeader, + header: NalHeader, + current: &Current, + dpb: &Dpb, +) -> PictureParameterBufferH264 { + let mut p = PictureParameterBufferH264 { + curr_pic: VAPictureH264::frame( + current.surface.id(), + current.info.frame_num, + current.poc.value, + if current.info.is_reference { + PICTURE_SHORT_TERM_REFERENCE + } else { + 0 + }, + ), + picture_width_in_mbs_minus1: (sps.mb_width.max(1) - 1) as u16, + picture_height_in_mbs_minus1: (sps.mb_height.max(1) - 1) as u16, + bit_depth_luma_minus8: sps.bit_depth_luma.saturating_sub(8), + bit_depth_chroma_minus8: sps.bit_depth_chroma.saturating_sub(8), + num_ref_frames: sps.max_num_ref_frames.min(255) as u8, + pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8, + pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8, + chroma_qp_index_offset: pps.chroma_qp_index_offset as i8, + second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8, + frame_num: sh.frame_num as u16, + ..PictureParameterBufferH264::default() + }; + + for (n, pic) in dpb + .frames + .iter() + .filter(|p| p.mark != Mark::Unused) + .take(p.reference_frames.len()) + .enumerate() + { + p.reference_frames[n] = reference_entry(pic); + } + + p.seq_fields = p + .seq_fields + .chroma_format_idc(u32::from(sps.chroma_format_idc)) + .residual_colour_transform_flag(u32::from(sps.separate_colour_plane)) + .gaps_in_frame_num_value_allowed_flag(u32::from(sps.gaps_in_frame_num_allowed)) + .frame_mbs_only_flag(u32::from(sps.frame_mbs_only)) + .mb_adaptive_frame_field_flag(u32::from(sps.mb_adaptive_frame_field)) + .direct_8x8_inference_flag(u32::from(sps.direct_8x8_inference)) + // A.3.3.2: 8x8 bi-prediction is restricted from level 3.1 up. + .min_luma_bipred_size8x8(u32::from(sps.level_idc >= 31)) + .log2_max_frame_num_minus4(u32::from(sps.log2_max_frame_num.saturating_sub(4))) + .pic_order_cnt_type(u32::from(sps.pic_order_cnt_type)) + .log2_max_pic_order_cnt_lsb_minus4(u32::from( + sps.log2_max_pic_order_cnt_lsb.saturating_sub(4), + )) + .delta_pic_order_always_zero_flag(u32::from(sps.delta_pic_order_always_zero)); + + p.pic_fields = p + .pic_fields + .entropy_coding_mode_flag(u32::from(pps.entropy_coding_mode)) + .weighted_pred_flag(u32::from(pps.weighted_pred)) + .weighted_bipred_idc(u32::from(pps.weighted_bipred_idc)) + .transform_8x8_mode_flag(u32::from(pps.transform_8x8_mode)) + .field_pic_flag(u32::from(sh.field_pic)) + .constrained_intra_pred_flag(u32::from(pps.constrained_intra_pred)) + .pic_order_present_flag(u32::from(pps.bottom_field_pic_order_in_frame_present)) + .deblocking_filter_control_present_flag(u32::from(pps.deblocking_filter_control_present)) + .redundant_pic_cnt_present_flag(u32::from(pps.redundant_pic_cnt_present)) + .reference_pic_flag(u32::from(header.ref_idc != 0)); + p +} + +fn slice_parameters( + sh: &SliceHeader, + pps: &Pps, + nal: &[u8], + lists: &[RefList; 2], + dpb: &Dpb, +) -> SliceParameterBufferH264 { + let mut s = SliceParameterBufferH264 { + slice_data_size: nal.len() as u32, + slice_data_offset: 0, + slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL + // "relative to and includes the NAL unit byte", counted in the + // unescaped RBSP: the syntax crate's header_bits starts *after* that + // byte, hence the 8. + slice_data_bit_offset: (sh.header_bits + 8) as u16, + first_mb_in_slice: sh.first_mb_in_slice as u16, + slice_type: slice_type_code(sh.slice_type), + direct_spatial_mv_pred_flag: u8::from(sh.direct_spatial_mv_pred), + num_ref_idx_l0_active_minus1: sh.num_ref_idx_l0_active.saturating_sub(1) as u8, + num_ref_idx_l1_active_minus1: sh.num_ref_idx_l1_active.saturating_sub(1) as u8, + cabac_init_idc: sh.cabac_init_idc as u8, + // The syntax crate resolves SliceQPY; the driver wants the delta back. + slice_qp_delta: (sh.slice_qp - pps.pic_init_qp) as i8, + disable_deblocking_filter_idc: sh.deblock.disable_idc, + slice_alpha_c0_offset_div2: (sh.deblock.alpha_c0_offset / 2) as i8, + slice_beta_offset_div2: (sh.deblock.beta_offset / 2) as i8, + ..SliceParameterBufferH264::default() + }; + + for (x, list) in lists.iter().enumerate() { + let out = if x == 0 { + &mut s.ref_pic_list0 + } else { + &mut s.ref_pic_list1 + }; + for i in 0..list.len().min(out.len()) { + if let Some(idx) = list.get(i) + && let Some(pic) = dpb.frames.get(idx) + { + out[i] = reference_entry(pic); + } + } + } + + if let Some(w) = sh.pred_weight_table.as_ref() { + write_weights(&mut s, w); + } + s +} + +/// Copy a parsed `pred_weight_table()` into the slice parameter buffer. +/// +/// The spec's default weights are `(1 << denom, 0)`, and a driver reads every +/// entry the active count names — so an absent entry has to be *written* as the +/// default rather than left at zero, which would black out the prediction. +fn write_weights(s: &mut SliceParameterBufferH264, w: &PredWeightTable) { + s.luma_log2_weight_denom = w.luma_log2_weight_denom as u8; + s.chroma_log2_weight_denom = w.chroma_log2_weight_denom as u8; + let luma_default = 1i16 << w.luma_log2_weight_denom; + let chroma_default = 1i16 << w.chroma_log2_weight_denom; + + for (list, entries) in [(0usize, &w.l0), (1usize, &w.l1)] { + let (weights, offsets, cweights, coffsets, luma_flag, chroma_flag) = if list == 0 { + ( + &mut s.luma_weight_l0, + &mut s.luma_offset_l0, + &mut s.chroma_weight_l0, + &mut s.chroma_offset_l0, + &mut s.luma_weight_l0_flag, + &mut s.chroma_weight_l0_flag, + ) + } else { + ( + &mut s.luma_weight_l1, + &mut s.luma_offset_l1, + &mut s.chroma_weight_l1, + &mut s.chroma_offset_l1, + &mut s.luma_weight_l1_flag, + &mut s.chroma_weight_l1_flag, + ) + }; + for (i, entry) in entries.iter().take(32).enumerate() { + match entry.luma { + Some((weight, offset)) => { + *luma_flag = 1; + weights[i] = weight as i16; + offsets[i] = offset as i16; + } + None => { + weights[i] = luma_default; + offsets[i] = 0; + } + } + match entry.chroma { + Some(pair) => { + *chroma_flag = 1; + for c in 0..2 { + cweights[i][c] = pair[c].0 as i16; + coffsets[i][c] = pair[c].1 as i16; + } + } + None => { + for c in 0..2 { + cweights[i][c] = chroma_default; + coffsets[i][c] = 0; + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_sps() -> Sps { + Sps { + profile_idc: 100, + constraint_flags: 0, + level_idc: 40, + id: 0, + chroma_format_idc: 1, + separate_colour_plane: false, + bit_depth_luma: 8, + bit_depth_chroma: 8, + transform_bypass: false, + scaling_lists: None, + log2_max_frame_num: 4, + pic_order_cnt_type: 0, + log2_max_pic_order_cnt_lsb: 4, + delta_pic_order_always_zero: false, + offset_for_non_ref_pic: 0, + offset_for_top_to_bottom_field: 0, + offsets_for_ref_frame: Vec::new(), + max_num_ref_frames: 4, + gaps_in_frame_num_allowed: true, + frame_mbs_only: true, + mb_adaptive_frame_field: false, + direct_8x8_inference: true, + crop: (0, 0, 0, 0), + vui: None, + mb_width: 120, + mb_height: 68, + coded_width: 1920, + coded_height: 1088, + width: 1920, + height: 1080, + } + } + + #[test] + fn slice_type_codes_match_table_7_6() { + assert_eq!(slice_type_code(SliceType::P), 0); + assert_eq!(slice_type_code(SliceType::B), 1); + assert_eq!(slice_type_code(SliceType::I), 2); + assert_eq!(slice_type_code(SliceType::Sp), 3); + assert_eq!(slice_type_code(SliceType::Si), 4); + } + + #[test] + fn profiles_follow_the_stream_bit_depth() { + let mut sps = test_sps(); + sps.profile_idc = 100; + assert_eq!(profile_for(&sps).unwrap(), Profile::H264High); + sps.bit_depth_luma = 10; + assert_eq!(profile_for(&sps).unwrap(), Profile::H264High10); + sps.profile_idc = 66; + sps.bit_depth_luma = 8; + assert_eq!(profile_for(&sps).unwrap(), Profile::H264ConstrainedBaseline); + sps.profile_idc = 244; + assert!(profile_for(&sps).is_err()); + } +} diff --git a/crates/ec-hw/src/dec/hevc.rs b/crates/ec-hw/src/dec/hevc.rs new file mode 100644 index 00000000..8d370f06 --- /dev/null +++ b/crates/ec-hw/src/dec/hevc.rs @@ -0,0 +1,823 @@ +//! Stateless HEVC decoding. +//! +//! HEVC keeps no `frame_num` and no sliding window: every picture states its +//! whole reference picture set, and anything the set does not name stops being +//! a reference there and then (8.3.2). That makes the DPB smaller than H.264's +//! but the *derivation* larger, and all of it has to happen here — a stateless +//! driver is handed `RefPicSetStCurrBefore`, `StCurrAfter` and `LtCurr` as +//! finished picture lists. + +use std::sync::Arc; + +use ec_h265_syntax::{ + NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b, + unescape_rbsp, +}; +use ec_va::caps::Profile; +use ec_va::{Buffer, Display, sys}; + +use super::{ReadyFrames, Session, StreamInfo}; +use crate::error::{Error, Result}; +use crate::frame::Frame; +use crate::params::hevc::{ + IQMatrixBufferHEVC, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR, + PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PictureParameterBufferHEVC, + SliceParameterBufferHEVC, VAPictureHEVC, +}; +use crate::params::param_buffer; +use crate::pool::PooledSurface; + +/// Beyond `sps_max_dec_pic_buffering`: the picture being decoded plus the ones +/// a caller is still holding. +const EXTRA_SURFACES: usize = 6; + +/// Reference marking of a stored picture (8.3.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mark { + Unused, + ShortTerm, + LongTerm, +} + +struct StoredPicture { + surface: Arc, + poc: i32, + timestamp: i64, + mark: Mark, + /// Still to be handed to the caller. + output: bool, +} + +impl StoredPicture { + fn stored(&self) -> bool { + self.output || self.mark != Mark::Unused + } +} + +/// The reference picture set of the picture being decoded, as DPB indices. +#[derive(Debug, Default, Clone)] +struct Rps { + st_curr_before: Vec, + st_curr_after: Vec, + lt_curr: Vec, +} + +/// The picture being assembled from its slices. +struct Current { + surface: Arc, + sps_id: u32, + poc: i32, + timestamp: i64, + is_reference: bool, + output: bool, + rps: Rps, + buffers: Vec, + slices: usize, + /// Index into `PictureParameterBufferHEVC::reference_frames` per DPB index. + va_index: Vec, +} + +/// A stateless HEVC decoder. +pub struct HevcDecoder { + display: Arc, + vps_map: Vec>, + sps_map: Vec>, + pps_map: Vec>, + session: Option, + dpb: Vec, + ready: ReadyFrames, + current: Option, + /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1. + prev_tid0_poc: i32, + /// Set once a picture has been decoded since the last reset. + started: bool, + max_reorder: usize, + max_dec_pic_buffering: usize, +} + +impl HevcDecoder { + /// A decoder with no stream state. + pub fn new(display: &Arc) -> HevcDecoder { + HevcDecoder { + display: Arc::clone(display), + vps_map: (0..16).map(|_| None).collect(), + sps_map: (0..16).map(|_| None).collect(), + pps_map: (0..64).map(|_| None).collect(), + session: None, + dpb: Vec::new(), + ready: ReadyFrames::default(), + current: None, + prev_tid0_poc: 0, + started: false, + max_reorder: 1, + max_dec_pic_buffering: 6, + } + } + + /// Decode one Annex B access unit. + pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + for nal in split_annex_b(data) { + match nal.header.nal_type { + NalUnitType::Vps => { + let vps = Vps::parse(&nal.rbsp())?; + let id = usize::from(vps.id); + if id < self.vps_map.len() { + self.vps_map[id] = Some(vps); + } + } + NalUnitType::Sps => { + let sps = Sps::parse(&nal.rbsp())?; + self.max_reorder = sps.max_num_reorder_pics as usize; + self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; + let id = sps.id as usize; + if id < self.sps_map.len() { + self.sps_map[id] = Some(sps); + } + } + NalUnitType::Pps => { + let pps = Pps::parse(&nal.rbsp())?; + let id = pps.id as usize; + if id < self.pps_map.len() { + self.pps_map[id] = Some(pps); + } + } + t if t.is_vcl() => { + self.slice(t, nal.payload, timestamp)?; + } + _ => {} + } + } + self.finish_picture()?; + Ok(()) + } + + /// The next frame in output order. + pub fn next_frame(&mut self) -> Option { + self.ready.pop() + } + + /// Push every buffered picture out (end of stream). + pub fn flush(&mut self) { + let _ = self.finish_picture(); + self.bump(true); + } + + /// Drop all picture state after a seek; parameter sets survive. + pub fn reset(&mut self) { + self.current = None; + self.dpb.clear(); + self.ready.clear(); + self.prev_tid0_poc = 0; + self.started = false; + } + + /// What the stream turned out to be. + pub fn stream_info(&self) -> Option { + self.session.as_ref().map(Session::info) + } + + fn slice(&mut self, nal_type: NalUnitType, payload: &[u8], timestamp: i64) -> Result<()> { + let rbsp = unescape_rbsp(payload); + // The header cannot be parsed without its PPS, and the PPS names the SPS. + let pps_id = peek_pps_id(&rbsp, nal_type)?; + let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else { + return Ok(()); + }; + let Some(sps) = self + .sps_map + .get(pps.sps_id as usize) + .and_then(|s| s.clone()) + else { + return Ok(()); + }; + let (sh, pos) = SliceHeader::parse(&rbsp, &sps, &pps, nal_type)?; + + if sh.first_slice_segment_in_pic { + self.finish_picture()?; + self.start_picture(&sps, &sh, nal_type, timestamp)?; + } + if self.current.is_none() { + return Ok(()); + } + self.render_slice(&sps, &pps, &sh, &pos, payload, nal_type) + } + + fn ensure_session(&mut self, sps: &Sps) -> Result<()> { + let bit_depth = (sps.bit_depth_luma_minus8 + 8) as u8; + let profile = match (sps.chroma_format_idc, bit_depth) { + (1, 8) => Profile::HEVCMain, + (1, 10) => Profile::HEVCMain10, + (chroma, depth) => { + return Err(Error::unsupported( + format!("HEVC chroma_format_idc {chroma} at {depth} bits"), + "only Main and Main10 (4:2:0, 8 or 10 bit) are decoded in hardware", + )); + } + }; + let coded = ( + sps.pic_width_in_luma_samples, + sps.pic_height_in_luma_samples, + ); + if let Some(session) = &self.session + && session.coded_size == coded + && session.bit_depth == bit_depth + && session.profile == profile + { + return Ok(()); + } + self.current = None; + self.dpb.clear(); + self.session = Some(Session::new( + &self.display, + profile, + coded, + sps.display_size(), + bit_depth, + self.max_dec_pic_buffering + EXTRA_SURFACES, + )?); + Ok(()) + } + + fn start_picture( + &mut self, + sps: &Sps, + sh: &SliceHeader, + nal_type: NalUnitType, + timestamp: i64, + ) -> Result<()> { + self.ensure_session(sps)?; + + let poc = self.picture_order_count(sps, sh, nal_type); + // 8.3.2 runs before the picture is decoded and after its POC is known: + // every stored picture the set does not name stops being a reference. + let rps = self.apply_rps(sps, sh, nal_type, poc); + + if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { + // An IRAP that restarts output order: everything ahead of it in the + // buffer belongs ahead of it on screen too. + self.bump(true); + } + + let session = self + .session + .as_ref() + .ok_or_else(|| Error::config("HEVC picture before any SPS"))?; + let surface = session + .pool + .acquire() + .ok_or_else(|| Error::config("HEVC decode: every surface is still in use"))?; + + // The driver indexes RefPicList into `reference_frames`, so the mapping + // from DPB slot to that array is fixed once, here. + let mut va_index = vec![0xffu8; self.dpb.len()]; + let mut n = 0u8; + for (i, pic) in self.dpb.iter().enumerate() { + if pic.mark != Mark::Unused && n < 15 { + va_index[i] = n; + n += 1; + } + } + + self.current = Some(Current { + surface, + sps_id: sps.id, + poc, + timestamp, + is_reference: true, + output: sh.pic_output_flag, + rps, + buffers: Vec::new(), + slices: 0, + va_index, + }); + Ok(()) + } + + /// `PicOrderCntVal` (8.3.1). + fn picture_order_count(&self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType) -> i32 { + if nal_type.is_idr() { + return 0; + } + let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); + let lsb = sh.poc_lsb as i32; + let (prev_msb, prev_lsb) = if !self.started { + (0, 0) + } else { + ( + self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)), + self.prev_tid0_poc.rem_euclid(max_lsb), + ) + }; + // An IRAP that starts a new coded video sequence has no predecessor. + if nal_type.is_irap() && !self.started { + return lsb; + } + let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { + prev_msb + max_lsb + } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { + prev_msb - max_lsb + } else { + prev_msb + }; + msb + lsb + } + + /// Reference picture set derivation and marking (8.3.2). + fn apply_rps(&mut self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType, poc: i32) -> Rps { + if nal_type.is_irap() && (nal_type.is_idr() || !self.started) { + for pic in &mut self.dpb { + pic.mark = Mark::Unused; + } + self.dpb.retain(|p| p.stored()); + return Rps::default(); + } + + let set = &sh.short_term_ref_pic_set; + let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); + let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term) + for i in 0..set.num_negative as usize { + wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false)); + } + for i in 0..set.num_positive as usize { + wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false)); + } + for lt in &sh.long_term { + // 8.3.2: a long-term entry without an MSB cycle is matched on its + // POC low bits alone, which is how a stream survives an MSB wrap. + let target = if lt.delta_poc_msb_present { + poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb) + + lt.poc_lsb_lt as i32 + } else { + lt.poc_lsb_lt as i32 + }; + wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present)); + } + + let mut rps = Rps::default(); + let mut keep = vec![false; self.dpb.len()]; + for (target, used, lsb_only) in wanted { + let found = self.dpb.iter().position(|p| { + if lsb_only { + p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb) + } else { + p.poc == target + } + }); + let Some(idx) = found else { continue }; + keep[idx] = true; + if !used { + continue; + } + // The three "current" lists are what the reference lists are built + // from, in POC order relative to the current picture. + if self.dpb[idx].mark == Mark::LongTerm || lsb_only { + rps.lt_curr.push(idx); + } else if self.dpb[idx].poc < poc { + rps.st_curr_before.push(idx); + } else { + rps.st_curr_after.push(idx); + } + } + rps.st_curr_before + .sort_by_key(|&i| std::cmp::Reverse(self.dpb[i].poc)); + rps.st_curr_after.sort_by_key(|&i| self.dpb[i].poc); + + for (i, pic) in self.dpb.iter_mut().enumerate() { + if !keep[i] { + pic.mark = Mark::Unused; + } + } + // Dropping unreferenced, already-output pictures here is what returns + // their surfaces to the pool; the indices in `rps` are recomputed after. + let mut remap = vec![usize::MAX; self.dpb.len()]; + let mut next = 0usize; + for (i, pic) in self.dpb.iter().enumerate() { + if pic.stored() { + remap[i] = next; + next += 1; + } + } + self.dpb.retain(|p| p.stored()); + for list in [ + &mut rps.st_curr_before, + &mut rps.st_curr_after, + &mut rps.lt_curr, + ] { + list.retain(|&i| remap[i] != usize::MAX); + for entry in list.iter_mut() { + *entry = remap[*entry]; + } + } + rps + } + + fn render_slice( + &mut self, + sps: &Sps, + pps: &Pps, + sh: &SliceHeader, + pos: &ParsePositions, + payload: &[u8], + nal_type: NalUnitType, + ) -> Result<()> { + let (Some(current), Some(session)) = (self.current.as_mut(), self.session.as_ref()) else { + return Ok(()); + }; + if current.sps_id != sps.id { + return Err(Error::Stream(ec_core::Error::corrupt( + "HEVC SPS changed mid-picture", + ))); + } + + if current.slices == 0 { + let pic_param = picture_parameters(sps, pps, sh, nal_type, current, &self.dpb); + current + .buffers + .push(param_buffer(&session.context, &pic_param)?); + if sps.scaling_list_enabled { + // The syntax crate refuses a stream that codes its own lists, so + // "enabled" here always means the flat default matrices. + current.buffers.push(param_buffer( + &session.context, + &IQMatrixBufferHEVC::default(), + )?); + } + } + + // The NAL unit header is part of the slice data the driver is handed, + // and every offset it is given is measured from there. + let nal_bytes = payload.len() + 2; + let mut slice_param = SliceParameterBufferHEVC { + slice_data_size: nal_bytes as u32, + slice_data_offset: 0, + slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL + slice_data_byte_offset: pos.slice_data_byte_offset(payload) as u32, + slice_segment_address: sh.segment_address, + collocated_ref_idx: if sh.temporal_mvp_enabled { + sh.collocated_ref_idx as u8 + } else { + 0xff + }, + num_ref_idx_l0_active_minus1: sh.num_ref_idx_l0_active_minus1 as u8, + num_ref_idx_l1_active_minus1: sh.num_ref_idx_l1_active_minus1 as u8, + slice_qp_delta: sh.qp_delta as i8, + slice_cb_qp_offset: sh.cb_qp_offset as i8, + slice_cr_qp_offset: sh.cr_qp_offset as i8, + slice_beta_offset_div2: sh.beta_offset_div2 as i8, + slice_tc_offset_div2: sh.tc_offset_div2 as i8, + five_minus_max_num_merge_cand: sh.five_minus_max_num_merge_cand as u8, + num_entry_point_offsets: sh.entry_point_offsets.len().min(u16::MAX as usize) as u16, + slice_data_num_emu_prevn_bytes: ec_h265_syntax::count_emulation_prevention_bytes( + payload, + ) + .min(u16::MAX as usize) as u16, + ..SliceParameterBufferHEVC::default() + }; + slice_param.long_slice_flags = slice_param + .long_slice_flags + .last_slice_of_pic(0) + .dependent_slice_segment_flag(u32::from(sh.dependent_slice_segment)) + .slice_type(sh.slice_type.code()) + .color_plane_id(u32::from(sh.colour_plane_id)) + .slice_sao_luma_flag(u32::from(sh.sao_luma)) + .slice_sao_chroma_flag(u32::from(sh.sao_chroma)) + .mvd_l1_zero_flag(u32::from(sh.mvd_l1_zero)) + .cabac_init_flag(u32::from(sh.cabac_init)) + .slice_temporal_mvp_enabled_flag(u32::from(sh.temporal_mvp_enabled)) + .slice_deblocking_filter_disabled_flag(u32::from(sh.deblocking_filter_disabled)) + .collocated_from_l0_flag(u32::from(sh.collocated_from_l0)) + .slice_loop_filter_across_slices_enabled_flag(u32::from( + sh.loop_filter_across_slices_enabled, + )); + + if sh.slice_type != SliceType::I { + let lists = reference_lists(sh, ¤t.rps); + for (x, list) in lists.iter().enumerate() { + for (i, &dpb_idx) in list.iter().take(15).enumerate() { + slice_param.ref_pic_list[x][i] = + current.va_index.get(dpb_idx).copied().unwrap_or(0xff); + } + } + } + write_weights(&mut slice_param, sh); + + current + .buffers + .push(param_buffer(&session.context, &slice_param)?); + // Rebuild the NAL unit: `split_annex_b` hands over the payload without + // its two header bytes, and the driver counts from them. + let mut nal = Vec::with_capacity(nal_bytes); + nal.extend_from_slice(&ec_h265_syntax::NalHeader::new(nal_type).to_bytes()); + nal.extend_from_slice(payload); + current.buffers.push(Buffer::from_bytes( + &session.context, + sys::VASliceDataBufferType, + &nal, + )?); + current.slices += 1; + Ok(()) + } + + fn finish_picture(&mut self) -> Result<()> { + let Some(current) = self.current.take() else { + return Ok(()); + }; + let Some(session) = self.session.as_ref() else { + return Ok(()); + }; + if current.slices == 0 { + return Ok(()); + } + session.submit(¤t.surface, current.buffers)?; + + self.dpb.push(StoredPicture { + surface: Arc::clone(¤t.surface), + poc: current.poc, + timestamp: current.timestamp, + mark: if current.is_reference { + Mark::ShortTerm + } else { + Mark::Unused + }, + output: current.output, + }); + self.prev_tid0_poc = current.poc; + self.started = true; + self.bump(false); + Ok(()) + } + + /// The bumping process (C.5.2.4): output while the buffer holds more than + /// its reordering or storage limit allows. + fn bump(&mut self, flush: bool) { + let Some(session) = self.session.as_ref() else { + return; + }; + loop { + let pending = self.dpb.iter().filter(|p| p.output).count(); + let stored = self.dpb.iter().filter(|p| p.stored()).count(); + if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering { + return; + } + let Some(idx) = self + .dpb + .iter() + .enumerate() + .filter(|(_, p)| p.output) + .min_by_key(|(_, p)| p.poc) + .map(|(i, _)| i) + else { + return; + }; + let pic = &self.dpb[idx]; + self.ready.push(Frame::new( + Arc::clone(&pic.surface), + Arc::clone(&session.images), + pic.timestamp, + session.display_size, + session.coded_size, + session.bit_depth, + )); + self.dpb[idx].output = false; + self.dpb.retain(|p| p.stored()); + } + } +} + +/// `slice_pic_parameter_set_id`, readable without any parameter set. +fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result { + let mut r = ec_core::BitReader::new(rbsp); + r.read_bit()?; // first_slice_segment_in_pic_flag + if nal_type.is_irap() { + r.read_bit()?; // no_output_of_prior_pics_flag + } + Ok(r.read_ue()?) +} + +/// Reference list construction (8.3.4), as DPB indices. +fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec; 2] { + let mut out = [Vec::new(), Vec::new()]; + let counts = [ + sh.num_ref_idx_l0_active_minus1 as usize + 1, + sh.num_ref_idx_l1_active_minus1 as usize + 1, + ]; + for x in 0..2 { + if x == 1 && sh.slice_type != SliceType::B { + continue; + } + // RefPicListTemp0 is StCurrBefore, StCurrAfter, LtCurr; list 1 swaps the + // first two, which is the whole difference between the two lists. + let mut temp: Vec = Vec::new(); + while temp.len() < counts[x] { + let before = if x == 0 { + &rps.st_curr_before + } else { + &rps.st_curr_after + }; + let after = if x == 0 { + &rps.st_curr_after + } else { + &rps.st_curr_before + }; + let round = before.len() + after.len() + rps.lt_curr.len(); + if round == 0 { + break; + } + temp.extend(before.iter().copied()); + temp.extend(after.iter().copied()); + temp.extend(rps.lt_curr.iter().copied()); + } + if temp.is_empty() { + continue; + } + for i in 0..counts[x] { + let idx = match sh.list_entry[x].get(i) { + Some(&entry) => *temp.get(entry as usize).unwrap_or(&temp[0]), + None => temp[i.min(temp.len() - 1)], + }; + out[x].push(idx); + } + } + out +} + +fn picture_parameters( + sps: &Sps, + pps: &Pps, + sh: &SliceHeader, + nal_type: NalUnitType, + current: &Current, + dpb: &[StoredPicture], +) -> PictureParameterBufferHEVC { + let mut p = PictureParameterBufferHEVC { + curr_pic: VAPictureHEVC::new(current.surface.id(), current.poc, 0), + pic_width_in_luma_samples: sps.pic_width_in_luma_samples as u16, + pic_height_in_luma_samples: sps.pic_height_in_luma_samples as u16, + sps_max_dec_pic_buffering_minus1: sps.max_dec_pic_buffering_minus1 as u8, + bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, + bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, + pcm_sample_bit_depth_luma_minus1: sps.pcm.map(|p| p.0 as u8).unwrap_or(0), + pcm_sample_bit_depth_chroma_minus1: sps.pcm.map(|p| p.1 as u8).unwrap_or(0), + log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8, + log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8, + log2_min_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, + log2_diff_max_min_transform_block_size: sps.log2_diff_max_min_tb_size as u8, + log2_min_pcm_luma_coding_block_size_minus3: sps.pcm.map(|p| p.2 as u8).unwrap_or(0), + log2_diff_max_min_pcm_luma_coding_block_size: sps.pcm.map(|p| p.3 as u8).unwrap_or(0), + max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, + max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, + init_qp_minus26: pps.init_qp_minus26 as i8, + diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, + pps_cb_qp_offset: pps.cb_qp_offset as i8, + pps_cr_qp_offset: pps.cr_qp_offset as i8, + log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, + num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, + num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, + log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, + num_short_term_ref_pic_sets: sps.num_short_term_ref_pic_sets as u8, + num_long_term_ref_pic_sps: sps.num_long_term_ref_pics_sps as u8, + num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8, + num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8, + pps_beta_offset_div2: pps.beta_offset_div2 as i8, + pps_tc_offset_div2: pps.tc_offset_div2 as i8, + num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, + // Zero when the slice took its set from the SPS, which is what the + // parser reports; the field exists so the driver can skip a set the + // header carried itself. + st_rps_bits: 0, + ..PictureParameterBufferHEVC::default() + }; + + // Tile geometry: uniform spacing is expanded here because libva wants the + // widths either way (`va_dec_hevc.h:125`). + let (cols, rows) = ( + pps.num_tile_columns_minus1 as usize + 1, + pps.num_tile_rows_minus1 as usize + 1, + ); + if pps.tiles_enabled { + let ctb_cols = sps.pic_width_in_ctbs(); + let ctb_rows = sps.pic_height_in_ctbs(); + for i in 0..cols.min(p.column_width_minus1.len()) { + let width = if pps.uniform_spacing { + ((i + 1) as u32 * ctb_cols) / cols as u32 - (i as u32 * ctb_cols) / cols as u32 + } else { + pps.column_width_minus1.get(i).copied().unwrap_or(0) + 1 + }; + p.column_width_minus1[i] = width.saturating_sub(1) as u16; + } + for i in 0..rows.min(p.row_height_minus1.len()) { + let height = if pps.uniform_spacing { + ((i + 1) as u32 * ctb_rows) / rows as u32 - (i as u32 * ctb_rows) / rows as u32 + } else { + pps.row_height_minus1.get(i).copied().unwrap_or(0) + 1 + }; + p.row_height_minus1[i] = height.saturating_sub(1) as u16; + } + } + + let mut n = 0usize; + for (i, pic) in dpb.iter().enumerate() { + if pic.mark == Mark::Unused || n >= p.reference_frames.len() { + continue; + } + let mut flags = 0; + if pic.mark == Mark::LongTerm { + flags |= PICTURE_LONG_TERM_REFERENCE; + } + if current.rps.st_curr_before.contains(&i) { + flags |= PICTURE_RPS_ST_CURR_BEFORE; + } else if current.rps.st_curr_after.contains(&i) { + flags |= PICTURE_RPS_ST_CURR_AFTER; + } else if current.rps.lt_curr.contains(&i) { + flags |= PICTURE_RPS_LT_CURR; + } + p.reference_frames[n] = VAPictureHEVC::new(pic.surface.id(), pic.poc, flags); + n += 1; + } + for entry in p.reference_frames.iter_mut().skip(n) { + *entry = VAPictureHEVC::new(ec_va::sys::VA_INVALID_SURFACE, 0, PICTURE_INVALID); + } + + p.pic_fields = p + .pic_fields + .chroma_format_idc(sps.chroma_format_idc) + .separate_colour_plane_flag(u32::from(sps.separate_colour_plane)) + .pcm_enabled_flag(u32::from(sps.pcm_enabled)) + .scaling_list_enabled_flag(u32::from(sps.scaling_list_enabled)) + .transform_skip_enabled_flag(u32::from(pps.transform_skip_enabled)) + .amp_enabled_flag(u32::from(sps.amp_enabled)) + .strong_intra_smoothing_enabled_flag(u32::from(sps.strong_intra_smoothing)) + .sign_data_hiding_enabled_flag(u32::from(pps.sign_data_hiding_enabled)) + .constrained_intra_pred_flag(u32::from(pps.constrained_intra_pred)) + .cu_qp_delta_enabled_flag(u32::from(pps.cu_qp_delta_enabled)) + .weighted_pred_flag(u32::from(pps.weighted_pred)) + .weighted_bipred_flag(u32::from(pps.weighted_bipred)) + .transquant_bypass_enabled_flag(u32::from(pps.transquant_bypass_enabled)) + .tiles_enabled_flag(u32::from(pps.tiles_enabled)) + .entropy_coding_sync_enabled_flag(u32::from(pps.entropy_coding_sync_enabled)) + .pps_loop_filter_across_slices_enabled_flag(u32::from( + pps.loop_filter_across_slices_enabled, + )) + .loop_filter_across_tiles_enabled_flag(u32::from(pps.loop_filter_across_tiles_enabled)) + .pcm_loop_filter_disabled_flag(u32::from(sps.pcm.map(|p| p.4).unwrap_or(false))) + .no_pic_reordering_flag(u32::from(sps.max_num_reorder_pics == 0)) + .no_bi_pred_flag(u32::from(sh.slice_type != SliceType::B)); + + p.slice_parsing_fields = p + .slice_parsing_fields + .lists_modification_present_flag(u32::from(pps.lists_modification_present)) + .long_term_ref_pics_present_flag(u32::from(sps.long_term_ref_pics_present)) + .sps_temporal_mvp_enabled_flag(u32::from(sps.temporal_mvp_enabled)) + .cabac_init_present_flag(u32::from(pps.cabac_init_present)) + .output_flag_present_flag(u32::from(pps.output_flag_present)) + .dependent_slice_segments_enabled_flag(u32::from(pps.dependent_slice_segments_enabled)) + .pps_slice_chroma_qp_offsets_present_flag(u32::from(pps.slice_chroma_qp_offsets_present)) + .sample_adaptive_offset_enabled_flag(u32::from(sps.sao_enabled)) + .deblocking_filter_override_enabled_flag(u32::from(pps.deblocking_filter_override_enabled)) + .pps_disable_deblocking_filter_flag(u32::from(pps.deblocking_filter_disabled)) + .slice_segment_header_extension_present_flag(u32::from( + pps.slice_segment_header_extension_present, + )) + .rap_pic_flag(u32::from(nal_type.is_irap())) + .idr_pic_flag(u32::from(nal_type.is_idr())) + .intra_pic_flag(u32::from(sh.slice_type == SliceType::I)); + p +} + +/// Copy the parsed `pred_weight_table()` into the slice parameter buffer. +fn write_weights(s: &mut SliceParameterBufferHEVC, sh: &SliceHeader) { + let Some(w) = sh.pred_weight_table.as_ref() else { + return; + }; + s.luma_log2_weight_denom = w.luma_log2_weight_denom as u8; + s.delta_chroma_log2_weight_denom = w.delta_chroma_log2_weight_denom as i8; + for (list, entries) in [(0usize, &w.l0), (1usize, &w.l1)] { + let (dlw, lo, dcw, co) = if list == 0 { + ( + &mut s.delta_luma_weight_l0, + &mut s.luma_offset_l0, + &mut s.delta_chroma_weight_l0, + &mut s.chroma_offset_l0, + ) + } else { + ( + &mut s.delta_luma_weight_l1, + &mut s.luma_offset_l1, + &mut s.delta_chroma_weight_l1, + &mut s.chroma_offset_l1, + ) + }; + for (i, entry) in entries.iter().take(15).enumerate() { + if let Some((weight, offset)) = entry.luma { + dlw[i] = weight as i8; + lo[i] = offset as i8; + } + if let Some(pair) = entry.chroma { + for c in 0..2 { + dcw[i][c] = pair[c].0 as i8; + co[i][c] = pair[c].1 as i8; + } + } + } + } +} diff --git a/crates/ec-hw/src/dec/mod.rs b/crates/ec-hw/src/dec/mod.rs new file mode 100644 index 00000000..e10249c1 --- /dev/null +++ b/crates/ec-hw/src/dec/mod.rs @@ -0,0 +1,307 @@ +//! Stateless hardware decoders, one per codec, behind one [`Decoder`]. +//! +//! # The shape of a stateless decode +//! +//! For every picture: parse the headers in Rust, fill the codec's +//! `VAPictureParameterBuffer*` from them, fill one +//! `VASliceParameterBuffer*` per slice or tile, hand the driver the original +//! (still escaped) bitstream bytes, and submit. Between pictures the decoder +//! keeps whatever the codec spreads across frames — the H.264 DPB and its +//! reference lists, HEVC's reference picture sets, VP9's and AV1's reference +//! slots — because the driver keeps nothing. +//! +//! # Output order +//! +//! Frames leave in *display* order. H.264 and HEVC reorder through their +//! decoded picture buffer (bumping, C.4.5.3); VP9 and AV1 emit in decode order +//! with `show_existing_frame` handled. A caller that wants decode order has the +//! per-frame timestamp it fed in. + +use std::collections::VecDeque; +use std::sync::Arc; + +use ec_va::caps::{Entrypoint, Profile}; +use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, sys}; + +use crate::error::{Error, Result}; +use crate::frame::Frame; +use crate::pool::SurfacePool; + +mod av1; +mod dpb264; +mod h264; +mod hevc; +mod vp9; + +pub use av1::Av1Decoder; +pub use h264::H264Decoder; +pub use hevc::HevcDecoder; +pub use vp9::Vp9Decoder; + +/// The codecs this crate decodes in hardware. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Codec { + /// H.264 / AVC, Annex B byte stream. + H264, + /// H.265 / HEVC, Annex B byte stream. + H265, + /// VP9, one frame (or superframe) per call. + Vp9, + /// AV1, one temporal unit per call. + Av1, +} + +/// What the stream turned out to be, once its first headers were parsed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StreamInfo { + /// Coded size, a multiple of the codec's block size. + pub coded_size: (u32, u32), + /// Size after cropping — what a player shows. + pub display_size: (u32, u32), + /// Luma bit depth. + pub bit_depth: u8, + /// The VA profile the context was created with. + pub profile: Profile, + /// Surfaces allocated for this stream. + pub num_surfaces: usize, +} + +/// A hardware decoder for one elementary stream. +pub struct Decoder { + inner: Inner, +} + +enum Inner { + H264(Box), + H265(Box), + Vp9(Box), + Av1(Box), +} + +impl Decoder { + /// Open a decoder for `codec` on `display`. + /// + /// Nothing is allocated on the GPU yet: the surface pool and context need + /// the stream's size and bit depth, which only its first parameter set + /// carries, so they are created on the first [`Decoder::decode`] call. + pub fn new(display: &Arc, codec: Codec) -> Result { + let inner = match codec { + Codec::H264 => Inner::H264(Box::new(H264Decoder::new(display))), + Codec::H265 => Inner::H265(Box::new(HevcDecoder::new(display))), + Codec::Vp9 => Inner::Vp9(Box::new(Vp9Decoder::new(display))), + Codec::Av1 => Inner::Av1(Box::new(Av1Decoder::new(display))), + }; + Ok(Decoder { inner }) + } + + /// Feed one access unit (H.264/HEVC: Annex B; VP9: one chunk; AV1: one + /// temporal unit) and queue whatever pictures it completed. + pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + match &mut self.inner { + Inner::H264(d) => d.decode(data, timestamp), + Inner::H265(d) => d.decode(data, timestamp), + Inner::Vp9(d) => d.decode(data, timestamp), + Inner::Av1(d) => d.decode(data, timestamp), + } + } + + /// The next frame in display order, if one is ready. + pub fn next_frame(&mut self) -> Option { + match &mut self.inner { + Inner::H264(d) => d.next_frame(), + Inner::H265(d) => d.next_frame(), + Inner::Vp9(d) => d.next_frame(), + Inner::Av1(d) => d.next_frame(), + } + } + + /// End of stream: push every buffered picture out. + pub fn flush(&mut self) -> Result<()> { + match &mut self.inner { + Inner::H264(d) => d.flush(), + Inner::H265(d) => d.flush(), + Inner::Vp9(d) => d.flush(), + Inner::Av1(d) => d.flush(), + } + Ok(()) + } + + /// Discard all state after a seek. Parameter sets are kept. + pub fn reset(&mut self) { + match &mut self.inner { + Inner::H264(d) => d.reset(), + Inner::H265(d) => d.reset(), + Inner::Vp9(d) => d.reset(), + Inner::Av1(d) => d.reset(), + } + } + + /// Pictures inferred for H.264 `frame_num` gaps (8.2.5.2); zero for the + /// other codecs, which have no such concept. + pub fn gap_frames_synthesized(&self) -> u64 { + match &self.inner { + Inner::H264(d) => d.gap_frames_synthesized(), + _ => 0, + } + } + + /// What the stream turned out to be, once a session exists. + pub fn stream_info(&self) -> Option { + match &self.inner { + Inner::H264(d) => d.stream_info(), + Inner::H265(d) => d.stream_info(), + Inner::Vp9(d) => d.stream_info(), + Inner::Av1(d) => d.stream_info(), + } + } +} + +/// Frames waiting to be collected, oldest first. +/// +/// The queue is the frame-out design `cros-codecs` uses (a decode call produces +/// events rather than returning a picture), minus the event fd: nothing in this +/// family polls a decoder from an event loop, and adding a `eventfd(2)` here +/// would mean a second FFI surface in a crate whose whole unsafe budget is +/// meant to be libva. +#[derive(Debug, Default)] +pub(crate) struct ReadyFrames { + queue: VecDeque, +} + +impl ReadyFrames { + pub(crate) fn push(&mut self, frame: Frame) { + self.queue.push_back(frame); + } + + pub(crate) fn pop(&mut self) -> Option { + self.queue.pop_front() + } + + pub(crate) fn clear(&mut self) { + self.queue.clear(); + } +} + +/// The GPU-side state one decoded stream needs: config, context, surfaces. +pub(crate) struct Session { + pub(crate) context: Arc, + /// The readback image every frame of this stream reuses. + pub(crate) images: crate::frame::ImageCache, + pub(crate) pool: SurfacePool, + pub(crate) coded_size: (u32, u32), + pub(crate) display_size: (u32, u32), + pub(crate) bit_depth: u8, + pub(crate) profile: Profile, +} + +impl Session { + /// Create a decode session, deriving the surface format from the *stream's* + /// bit depth. + /// + /// The bit depth is the whole point of this signature. An 8-bit context on + /// a 10-bit stream is the incumbent defect this crate exists to not repeat: + /// the driver either refuses the config or silently decodes to NV12 and + /// throws away two bits per sample. + pub(crate) fn new( + display: &Arc, + profile: Profile, + coded_size: (u32, u32), + display_size: (u32, u32), + bit_depth: u8, + num_surfaces: usize, + ) -> Result { + let caps = CapReport::probe(display)?; + let entry = caps.entry(profile, Entrypoint::VLD).ok_or_else(|| { + Error::unsupported( + format!("{profile:?} decode"), + "the driver advertises no VLD entrypoint for this profile", + ) + })?; + + let rt_format = if bit_depth > 8 { + sys::VA_RT_FORMAT_YUV420_10 + } else { + sys::VA_RT_FORMAT_YUV420 + }; + if !entry.supports_rt_format(rt_format) { + return Err(Error::unsupported( + format!("{bit_depth}-bit {profile:?} decode"), + format!( + "the driver's RT format mask for this profile is {:#x}", + entry.rt_formats + ), + )); + } + + let (w, h) = coded_size; + if let Some(surfaces) = &entry.surfaces + && !surfaces.allows(w, h) + { + return Err(Error::unsupported( + format!("{w}x{h} {profile:?} decode"), + format!( + "the driver accepts {:?}..{:?} x {:?}..{:?}", + surfaces.min_width, + surfaces.max_width, + surfaces.min_height, + surfaces.max_height + ), + )); + } + + let config = Config::new( + display, + profile, + Entrypoint::VLD, + &[ConfigAttrib::rt_format(rt_format)], + )?; + + let spec = if bit_depth > 8 { + SurfaceSpec::p010(w, h) + } else { + SurfaceSpec::nv12(w, h) + } + .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_DECODER); + let pool = SurfacePool::new(display, &spec, num_surfaces)?; + let context = Context::new(&config, w, h, sys::VA_PROGRESSIVE, pool.targets())?; + + Ok(Session { + context, + images: crate::frame::ImageCache::default(), + pool, + coded_size, + display_size, + bit_depth, + profile, + }) + } + + /// Submit one picture: begin, render every buffer, end. No sync — the + /// driver keeps submissions in order within a context, and the wait belongs + /// where the pixels are actually read. + pub(crate) fn submit(&self, target: &Arc, buffers: Vec) -> Result<()> { + if buffers.is_empty() { + // radeonsi answers an empty submission with INVALID_CONTEXT, which + // reads like a driver bug report rather than what it is: a picture + // with no slices, i.e. a stream that lost its data. + return Err(Error::config( + "refusing to submit a picture with no parameter buffers", + )); + } + ec_va::Picture::new(&self.context, Arc::clone(target)) + .begin()? + .render_all(buffers)? + .end()?; + Ok(()) + } + + pub(crate) fn info(&self) -> StreamInfo { + StreamInfo { + coded_size: self.coded_size, + display_size: self.display_size, + bit_depth: self.bit_depth, + profile: self.profile, + num_surfaces: self.pool.len(), + } + } +} diff --git a/crates/ec-hw/src/dec/vp9.rs b/crates/ec-hw/src/dec/vp9.rs new file mode 100644 index 00000000..15deb4d3 --- /dev/null +++ b/crates/ec-hw/src/dec/vp9.rs @@ -0,0 +1,262 @@ +//! Stateless VP9 decoding. + +use std::sync::Arc; + +use ec_va::caps::Profile; +use ec_va::{Buffer, Display, sys}; +use ec_vp9_syntax::{ + FrameHeader, FrameType, MAX_SEGMENTS, NUM_REF_FRAMES, SEG_LVL_REF_FRAME, SEG_LVL_SKIP, + Vp9Parser, superframe, +}; + +use super::{ReadyFrames, Session, StreamInfo}; +use crate::error::{Error, Result}; +use crate::frame::Frame; +use crate::params::param_buffer; +use crate::params::vp9::{PictureParameterBufferVP9, SegmentParameterVP9, SliceParameterBufferVP9}; +use crate::pool::PooledSurface; + +/// Reference slots plus the picture being decoded plus caller-held frames. +const EXTRA_SURFACES: usize = 6; + +/// A stateless VP9 decoder. +pub struct Vp9Decoder { + display: Arc, + parser: Vp9Parser, + session: Option, + /// The eight reference slots, as surfaces. + refs: [Option>; NUM_REF_FRAMES], + ready: ReadyFrames, +} + +impl Vp9Decoder { + /// A decoder with no stream state. + pub fn new(display: &Arc) -> Vp9Decoder { + Vp9Decoder { + display: Arc::clone(display), + parser: Vp9Parser::new(), + session: None, + refs: [const { None }; NUM_REF_FRAMES], + ready: ReadyFrames::default(), + } + } + + /// Decode one chunk, which may be a superframe holding several frames. + pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + if data.is_empty() { + return Ok(()); + } + // A superframe packs a hidden ALTREF and the frame that shows it into + // one chunk; the driver is handed each frame separately, and the offsets + // matter because the picture parameters describe one frame at a time. + let frames = superframe::split(data)?; + for frame in frames { + self.decode_frame(frame, timestamp)?; + } + Ok(()) + } + + /// The next frame in display order (VP9 codes in display order). + pub fn next_frame(&mut self) -> Option { + self.ready.pop() + } + + /// Nothing is buffered beyond the reference slots, so this is a no-op. + pub fn flush(&mut self) {} + + /// Drop reference state after a seek. + pub fn reset(&mut self) { + self.parser = Vp9Parser::new(); + self.refs = [const { None }; NUM_REF_FRAMES]; + self.ready.clear(); + } + + /// What the stream turned out to be. + pub fn stream_info(&self) -> Option { + self.session.as_ref().map(Session::info) + } + + fn decode_frame(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + let header = self.parser.parse_frame(data)?; + + if header.show_existing_frame { + // No decode: the frame in that slot is shown again. It keeps its + // slot as well, so the surface is shared, not moved. + let slot = usize::from(header.frame_to_show_map_idx); + let (Some(surface), Some(session)) = ( + self.refs.get(slot).and_then(|s| s.clone()), + self.session.as_ref(), + ) else { + return Err(Error::Stream(ec_core::Error::corrupt( + "VP9 show_existing_frame names an empty reference slot", + ))); + }; + self.ready.push(Frame::new( + surface, + Arc::clone(&session.images), + timestamp, + (header.width, header.height), + session.coded_size, + session.bit_depth, + )); + return Ok(()); + } + + self.ensure_session(&header)?; + let session = self + .session + .as_ref() + .ok_or_else(|| Error::config("VP9 frame before any session"))?; + let surface = session + .pool + .acquire() + .ok_or_else(|| Error::config("VP9 decode: every surface is still in use"))?; + + let pic_param = self.picture_parameters(&header); + let slice_param = slice_parameters(&header, data.len()); + let buffers = vec![ + param_buffer(&session.context, &pic_param)?, + param_buffer(&session.context, &slice_param)?, + Buffer::from_bytes(&session.context, sys::VASliceDataBufferType, data)?, + ]; + session.submit(&surface, buffers)?; + + // Reference slot refresh (spec 8.10), after the submission that used + // the old contents. + for slot in 0..NUM_REF_FRAMES { + if header.refresh_frame_flags & (1 << slot) != 0 { + self.refs[slot] = Some(Arc::clone(&surface)); + } + } + + if header.show_frame { + self.ready.push(Frame::new( + surface, + Arc::clone(&session.images), + timestamp, + (header.width, header.height), + session.coded_size, + session.bit_depth, + )); + } + Ok(()) + } + + fn ensure_session(&mut self, header: &FrameHeader) -> Result<()> { + let profile = match header.profile { + 0 => Profile::VP9Profile0, + 2 => Profile::VP9Profile2, + other => { + return Err(Error::unsupported( + format!("VP9 profile {other}"), + "only the 4:2:0 profiles 0 and 2 are decoded in hardware", + )); + } + }; + // VP9 codes in 64x64 superblocks; a surface has to hold whole ones. + let coded = ( + header.width.next_multiple_of(64).max(64), + header.height.next_multiple_of(64).max(64), + ); + if let Some(session) = &self.session + && session.coded_size.0 >= coded.0 + && session.coded_size.1 >= coded.1 + && session.bit_depth == header.bit_depth + && session.profile == profile + { + return Ok(()); + } + self.refs = [const { None }; NUM_REF_FRAMES]; + self.session = Some(Session::new( + &self.display, + profile, + coded, + (header.width, header.height), + header.bit_depth, + NUM_REF_FRAMES + EXTRA_SURFACES, + )?); + Ok(()) + } + + fn picture_parameters(&self, h: &FrameHeader) -> PictureParameterBufferVP9 { + let mut p = PictureParameterBufferVP9 { + frame_width: h.width as u16, + frame_height: h.height as u16, + filter_level: h.loop_filter.level, + sharpness_level: h.loop_filter.sharpness, + log2_tile_rows: h.tile_info.rows_log2, + log2_tile_columns: h.tile_info.cols_log2, + frame_header_length_in_bytes: h.uncompressed_header_size, + first_partition_size: h.header_size_in_bytes, + mb_segment_tree_probs: h.segmentation.tree_probs, + segment_pred_probs: h.segmentation.pred_probs, + profile: h.profile, + bit_depth: h.bit_depth, + ..PictureParameterBufferVP9::default() + }; + for (slot, surface) in self.refs.iter().enumerate() { + if let Some(surface) = surface { + p.reference_frames[slot] = surface.id(); + } + } + p.pic_fields = p + .pic_fields + .subsampling_x(u32::from(h.subsampling_x)) + .subsampling_y(u32::from(h.subsampling_y)) + .frame_type(u32::from(h.frame_type == FrameType::Inter)) + .show_frame(u32::from(h.show_frame)) + .error_resilient_mode(u32::from(h.error_resilient_mode)) + .intra_only(u32::from(h.intra_only)) + .allow_high_precision_mv(u32::from(h.allow_high_precision_mv)) + .mcomp_filter_type(h.interpolation_filter as u32) + .frame_parallel_decoding_mode(u32::from(h.frame_parallel_decoding_mode)) + .reset_frame_context(u32::from(h.reset_frame_context)) + .refresh_frame_context(u32::from(h.refresh_frame_context)) + .frame_context_idx(u32::from(h.frame_context_idx)) + .segmentation_enabled(u32::from(h.segmentation.enabled)) + .segmentation_temporal_update(u32::from(h.segmentation.temporal_update)) + .segmentation_update_map(u32::from(h.segmentation.update_map)) + .last_ref_frame(u32::from(h.ref_frame_idx[0])) + .last_ref_frame_sign_bias(u32::from(h.ref_frame_sign_bias[0])) + .golden_ref_frame(u32::from(h.ref_frame_idx[1])) + .golden_ref_frame_sign_bias(u32::from(h.ref_frame_sign_bias[1])) + .alt_ref_frame(u32::from(h.ref_frame_idx[2])) + .alt_ref_frame_sign_bias(u32::from(h.ref_frame_sign_bias[2])) + .lossless_flag(u32::from(h.quantization.lossless())); + p + } +} + +/// The slice (whole-frame) parameters, including all eight segments. +/// +/// Every segment is filled whether or not segmentation is enabled: with it off, +/// segment 0 is the one the driver uses, and the other seven are harmless — but +/// leaving them zeroed would hand the driver a quantiser scale of zero. +fn slice_parameters(h: &FrameHeader, size: usize) -> SliceParameterBufferVP9 { + let mut s = SliceParameterBufferVP9 { + slice_data_size: size as u32, + slice_data_offset: 0, + slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL + ..SliceParameterBufferVP9::default() + }; + for segment in 0..MAX_SEGMENTS { + let dequant = h.segment_dequant(segment); + let levels = h.loop_filter_levels(segment); + let seg = &mut s.seg_param[segment]; + seg.filter_level = levels; + seg.luma_ac_quant_scale = dequant.luma_ac; + seg.luma_dc_quant_scale = dequant.luma_dc; + seg.chroma_ac_quant_scale = dequant.chroma_ac; + seg.chroma_dc_quant_scale = dequant.chroma_dc; + seg.segment_flags = SegmentParameterVP9::default() + .segment_flags + .segment_reference_enabled(u16::from( + h.segmentation.feature_enabled[segment][SEG_LVL_REF_FRAME], + )) + .segment_reference(h.segmentation.feature_data[segment][SEG_LVL_REF_FRAME] as u16) + .segment_reference_skipped(u16::from( + h.segmentation.feature_enabled[segment][SEG_LVL_SKIP], + )); + } + s +}