//! AV1 decoding over Vulkan Video: the reference slots over DPB slot indices. use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use ec_av1::encode::Picture; use ec_av1_syntax::{ Av1Parser, ChromaSamplePosition, ColorConfig, FilmGrainParams, FrameHeader, FrameType, InterpolationFilter, NUM_REF_FRAMES, ObuKind, REFS_PER_FRAME, RestorationType, SequenceHeader, Tile, TxMode, WarpModel, }; use ec_vk::{ Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation, Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, }; use crate::ref_slots::RefSlots; use crate::error::{Error, Result}; use ec_core::color::{ColorDescription, Tags}; use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; use crate::picture::{I420, I420_16}; const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; struct Session { av1: Rc>, ring: Rc>, bit_depth: u8, width: u32, height: u32, sequence: Option, } struct Reference { state: Av1RefSlot, picture: VkPicture, } /// AV1 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots. pub(crate) struct VkAv1Decoder { gpu: ec_vk::Gpu, parser: Av1Parser, session: Option, refs: RefSlots>, ready: VecDeque, } impl VkAv1Decoder { pub(crate) fn new() -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?; Ok(VkAv1Decoder { gpu, parser: Av1Parser::new(), session: None, refs: RefSlots::new(), ready: VecDeque::new(), }) } pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { let mut pending: Option> = None; for obu in self.parser.parse_temporal_unit(data)? { match obu.kind { ObuKind::FrameHeader(header) if header.show_existing_frame => { self.show_existing(&header, timestamp)?; } ObuKind::FrameHeader(header) => pending = Some(header), ObuKind::TileGroup(tiles) => { if let Some(header) = pending.take() { self.decode_frame(&header, &tiles, data, timestamp)?; } } ObuKind::Frame(header, _) if header.show_existing_frame => { self.show_existing(&header, timestamp)?; } ObuKind::Frame(header, tiles) => { self.decode_frame(&header, &tiles, data, timestamp)?; } _ => {} } } Ok(()) } pub(crate) fn next_frame(&mut self) -> Option { self.ready.pop_front() } pub(crate) fn reset(&mut self) { self.parser = Av1Parser::new(); self.refs = RefSlots::new(); self.ready.clear(); } pub(crate) fn flush(&mut self) -> Result<()> { Ok(()) } fn show_existing(&mut self, header: &FrameHeader, timestamp: i64) -> Result<()> { let reference = self .refs .get(usize::from(header.frame_to_show_map_idx)) .cloned() .ok_or_else(|| { Error::Stream(ec_core::Error::corrupt( "AV1 show_existing_frame names an empty reference slot", )) })?; let seq = self .parser .sequence_header() .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?; let shown = reference.picture.with_grain(&header.film_grain, seq); self.ready.push_back(HwPicture::vk(timestamp, shown)); if header.frame_type == FrameType::Key { self.refs.refresh(u8::MAX, Some(reference)); } Ok(()) } fn decode_frame( &mut self, header: &FrameHeader, tiles: &[Tile], data: &[u8], timestamp: i64, ) -> Result<()> { let seq = self .parser .sequence_header() .cloned() .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?; check_supported(&seq)?; let (width, height) = (header.upscaled_width, header.frame_height); self.ensure_session(&seq, width, height)?; let mut ref_frame_slot = [-1i32; REFS_PER_FRAME]; let mut refs: Vec = Vec::new(); if matches!(header.frame_type, FrameType::Inter | FrameType::Switch) { for (name, &index) in header.ref_frame_idx.iter().enumerate() { let reference = self.refs.get(usize::from(index)).ok_or_else(|| { Error::Stream(ec_core::Error::corrupt(format!( "AV1 inter frame names reference slot {index} (ref {name}), \ which no decoded frame has filled" ))) })?; ref_frame_slot[name] = reference.state.slot as i32; if !refs.iter().any(|r| r.slot == reference.state.slot) { refs.push(reference.state); } } } let setup_slot = self.free_slot()?; let frame = frame_header(header, &seq); let offsets: Vec = tiles.iter().map(|t| t.offset as u32).collect(); let sizes: Vec = tiles.iter().map(|t| t.size as u32).collect(); let picture = Av1DecodePicture { header: &frame, setup_slot, ref_frame_slot, refs: &refs, tile_data: data, tile_offsets: &offsets, tile_sizes: &sizes, }; let session = self .session .as_mut() .ok_or_else(|| Error::config("AV1 picture before any session"))?; session.av1.borrow_mut().decode(&picture)?; if !(header.show_frame || header.refresh_frame_flags != 0) { return Ok(()); } let slot = session .ring .borrow_mut() .take(|| Ok(session.av1.borrow_mut().add_ring_slot()?))?; session.av1.borrow_mut().store_output( slot.index(), (0, 0, width.next_multiple_of(2), height.next_multiple_of(2)), )?; let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0); let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; let decoded = VkPicture::new( Surfaces::Av1(session.av1.clone()), slot, (width, height), session.bit_depth, matrix, ) .with_ring(session.ring.clone()); let state = Av1RefSlot { slot: setup_slot, frame_type: av1_frame_type(header.frame_type), order_hint: header.order_hint as u8, ref_order_hints: saved_order_hints(&header.order_hints), sign_bias: sign_bias(&header.ref_frame_sign_bias), disable_frame_end_update_cdf: header.disable_frame_end_update_cdf, segmentation_enabled: header.segmentation.enabled, extent: (width, height), }; if header.show_frame { let shown = decoded.with_grain(&header.film_grain, &seq); self.ready.push_back(HwPicture::vk(timestamp, shown)); } if header.refresh_frame_flags != 0 { let reference = Rc::new(Reference { state, picture: decoded, }); self.refs .refresh(header.refresh_frame_flags, Some(reference)); } Ok(()) } fn ensure_session(&mut self, seq: &SequenceHeader, width: u32, height: u32) -> Result<()> { let bit_depth = seq.color_config.bit_depth; let width = seq.max_frame_width.max(width); let height = seq.max_frame_height.max(height); let mut session = match self.session.take() { Some(s) if s.bit_depth == bit_depth && s.width == width && s.height == height => s, _ => { self.refs = RefSlots::new(); let av1 = Av1DecodeSession::new( &self.gpu, &Av1DecodeConfig { max_width: width, max_height: height, max_dpb_slots: DPB_SLOTS, bit_depth, }, )?; let ring = Ring::new(av1.ring_len()); Session { av1: Rc::new(RefCell::new(av1)), ring: Rc::new(RefCell::new(ring)), bit_depth, width, height, sequence: None, } } }; if session.sequence.as_ref() != Some(seq) { session .av1 .borrow_mut() .set_sequence_header(&av1_sequence(seq))?; session.sequence = Some(seq.clone()); } self.session = Some(session); Ok(()) } fn free_slot(&self) -> Result { (0..DPB_SLOTS) .find(|slot| self.refs.filled().all(|r| r.state.slot != *slot)) .ok_or_else(|| Error::config("AV1 Vulkan decode: every DPB slot is in use")) } } fn check_supported(seq: &SequenceHeader) -> Result<()> { let c = &seq.color_config; if seq.seq_profile != 0 || !matches!(c.bit_depth, 8 | 10) || c.mono_chrome || c.subsampling_x != 1 || c.subsampling_y != 1 { return Err(Error::unsupported( "Vulkan AV1 decode", "only Main 8- and 10-bit 4:2:0", )); } Ok(()) } pub(crate) fn synthesize16(frame: I420_16, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420_16 { let bit_depth = u32::from(seq.color_config.bit_depth); let shift = if bit_depth == 8 { 2 } else { 0 }; let narrow = |p: &[u16]| p.iter().map(|&s| s >> shift).collect::>(); let clean = Picture { width: frame.width as usize, height: frame.height as usize, y: narrow(&frame.y), u: narrow(&frame.u), v: narrow(&frame.v), }; let out = ec_av1::apply_film_grain( &clean, grain, seq.color_config.matrix_coefficients == 0, bit_depth, ); let widen = |p: &[u16]| p.iter().map(|&s| s << shift).collect::>(); I420_16 { y: widen(&out.y), u: widen(&out.u), v: widen(&out.v), width: frame.width, height: frame.height, bit_depth: 10, } } pub(crate) fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 { let wide = |p: &[u8]| p.iter().map(|&s| u16::from(s)).collect::>(); let clean = Picture { width: frame.width as usize, height: frame.height as usize, y: wide(&frame.y), u: wide(&frame.u), v: wide(&frame.v), }; let out = ec_av1::apply_film_grain( &clean, grain, seq.color_config.matrix_coefficients == 0, u32::from(seq.color_config.bit_depth), ); let narrow = |p: &[u16]| p.iter().map(|&s| s as u8).collect::>(); I420 { y: narrow(&out.y), u: narrow(&out.u), v: narrow(&out.v), width: frame.width, height: frame.height, } } fn av1_frame_type(t: FrameType) -> Av1FrameType { match t { FrameType::Key => Av1FrameType::Key, FrameType::Inter => Av1FrameType::Inter, FrameType::IntraOnly => Av1FrameType::IntraOnly, FrameType::Switch => Av1FrameType::Switch, } } /// `RefFrameSignBias` as a mask: bit `n` set when reference name `n` (LAST = 1) is a future frame. fn sign_bias(bias: &[bool; REFS_PER_FRAME]) -> u8 { bias.iter() .enumerate() .filter(|(_, set)| **set) .fold(0u8, |mask, (name, _)| mask | 1 << (name + 1)) } /// `SavedOrderHints` indexed by reference name, index 0 (INTRA_FRAME) unused. fn saved_order_hints(hints: &[u32; REFS_PER_FRAME]) -> [u8; NUM_REF_FRAMES] { let mut out = [0u8; NUM_REF_FRAMES]; for (name, &hint) in hints.iter().enumerate() { out[name + 1] = hint as u8; } out } fn color(c: &ColorConfig) -> Av1ColorConfig { Av1ColorConfig { bit_depth: c.bit_depth, mono_chrome: c.mono_chrome, color_range: c.color_range, separate_uv_delta_q: c.separate_uv_delta_q, subsampling_x: c.subsampling_x, subsampling_y: c.subsampling_y, color_primaries: c.color_primaries, transfer_characteristics: c.transfer_characteristics, matrix_coefficients: c.matrix_coefficients, chroma_sample_position: match c.chroma_sample_position { ChromaSamplePosition::Unknown => 0, ChromaSamplePosition::Vertical => 1, ChromaSamplePosition::Colocated => 2, ChromaSamplePosition::Reserved => 3, }, } } fn av1_sequence(s: &SequenceHeader) -> Av1SequenceHeader { Av1SequenceHeader { seq_profile: s.seq_profile, still_picture: s.still_picture, reduced_still_picture_header: s.reduced_still_picture_header, timing_info: s.timing_info.map(|t| Av1TimingInfo { equal_picture_interval: t.equal_picture_interval, num_units_in_display_tick: t.num_units_in_display_tick, time_scale: t.time_scale, num_ticks_per_picture_minus_1: t.num_ticks_per_picture.saturating_sub(1), }), initial_display_delay_present: s.initial_display_delay_present_flag, frame_width_bits_minus_1: (s.frame_width_bits - 1) as u8, frame_height_bits_minus_1: (s.frame_height_bits - 1) as u8, max_frame_width_minus_1: (s.max_frame_width - 1) as u16, max_frame_height_minus_1: (s.max_frame_height - 1) as u16, frame_id_numbers_present: s.frame_id_numbers_present_flag, delta_frame_id_length_minus_2: s.delta_frame_id_length.saturating_sub(2) as u8, additional_frame_id_length_minus_1: s.additional_frame_id_length.saturating_sub(1) as u8, order_hint_bits_minus_1: s.order_hint_bits.saturating_sub(1) as u8, seq_force_integer_mv: s.seq_force_integer_mv, seq_force_screen_content_tools: s.seq_force_screen_content_tools, use_128x128_superblock: s.use_128x128_superblock, enable_filter_intra: s.enable_filter_intra, enable_intra_edge_filter: s.enable_intra_edge_filter, enable_interintra_compound: s.enable_interintra_compound, enable_masked_compound: s.enable_masked_compound, enable_warped_motion: s.enable_warped_motion, enable_dual_filter: s.enable_dual_filter, enable_order_hint: s.enable_order_hint, enable_jnt_comp: s.enable_jnt_comp, enable_ref_frame_mvs: s.enable_ref_frame_mvs, enable_superres: s.enable_superres, enable_cdef: s.enable_cdef, enable_restoration: s.enable_restoration, color_config: color(&s.color_config), film_grain_params_present: s.film_grain_params_present, } } fn restoration(r: RestorationType) -> Av1Restoration { match r { RestorationType::None => Av1Restoration::None, RestorationType::Wiener => Av1Restoration::Wiener, RestorationType::Sgrproj => Av1Restoration::Sgrproj, RestorationType::Switchable => Av1Restoration::Switchable, } } fn frame_header(h: &FrameHeader, s: &SequenceHeader) -> Av1FrameHeader { let sb_shift = s.sb_shift(); let mut global_motion = [Av1GlobalMotion::default(); 8]; let mut order_hints = [0u8; 8]; for i in 0..REFS_PER_FRAME { global_motion[i + 1] = Av1GlobalMotion { model: match h.global_motion[i].model { WarpModel::Identity => Av1WarpModel::Identity, WarpModel::Translation => Av1WarpModel::Translation, WarpModel::Rotzoom => Av1WarpModel::Rotzoom, WarpModel::Affine => Av1WarpModel::Affine, }, params: h.global_motion[i].params, }; order_hints[i + 1] = h.order_hints[i] as u8; } Av1FrameHeader { frame_type: av1_frame_type(h.frame_type), show_frame: h.show_frame, showable_frame: h.showable_frame, error_resilient_mode: h.error_resilient_mode, disable_cdf_update: h.disable_cdf_update, allow_screen_content_tools: h.allow_screen_content_tools, force_integer_mv: h.force_integer_mv, current_frame_id: h.current_frame_id, frame_size_override_flag: h.frame_size_override_flag, order_hint: h.order_hint as u8, primary_ref_frame: h.primary_ref_frame, refresh_frame_flags: h.refresh_frame_flags, frame_width: h.frame_width, frame_height: h.frame_height, upscaled_width: h.upscaled_width, render_width: h.render_width, render_height: h.render_height, use_superres: h.use_superres, superres_denom: h.superres_denom, allow_intrabc: h.allow_intrabc, allow_high_precision_mv: h.allow_high_precision_mv, is_motion_mode_switchable: h.is_motion_mode_switchable, use_ref_frame_mvs: h.use_ref_frame_mvs, frame_refs_short_signaling: h.frame_refs_short_signaling, disable_frame_end_update_cdf: h.disable_frame_end_update_cdf, reference_select: h.reference_select, skip_mode_present: h.skip_mode_present, allow_warped_motion: h.allow_warped_motion, reduced_tx_set: h.reduced_tx_set, interpolation_filter: match h.interpolation_filter { InterpolationFilter::Eighttap => Av1InterpolationFilter::EightTap, InterpolationFilter::EighttapSmooth => Av1InterpolationFilter::EightTapSmooth, InterpolationFilter::EighttapSharp => Av1InterpolationFilter::EightTapSharp, InterpolationFilter::Bilinear => Av1InterpolationFilter::Bilinear, InterpolationFilter::Switchable => Av1InterpolationFilter::Switchable, }, tx_mode: match h.tx_mode { TxMode::Only4x4 => Av1TxMode::Only4x4, TxMode::Largest => Av1TxMode::Largest, TxMode::Select => Av1TxMode::Select, }, tile_info: Av1TileInfo { uniform_spacing: h.tile_info.uniform_spacing, cols: h.tile_info.cols as u8, rows: h.tile_info.rows as u8, mi_col_starts: h .tile_info .mi_col_starts .iter() .map(|&v| v as u16) .collect(), mi_row_starts: h .tile_info .mi_row_starts .iter() .map(|&v| v as u16) .collect(), width_in_sbs_minus_1: h.tile_info.width_in_sbs_minus_1(sb_shift), height_in_sbs_minus_1: h.tile_info.height_in_sbs_minus_1(sb_shift), context_update_tile_id: h.tile_info.context_update_tile_id as u16, tile_size_bytes_minus_1: h.tile_info.tile_size_bytes.saturating_sub(1) as u8, }, quantization: Av1Quantization { base_q_idx: h.quantization.base_q_idx, delta_q_y_dc: h.quantization.delta_q_y_dc, delta_q_u_dc: h.quantization.delta_q_u_dc, delta_q_u_ac: h.quantization.delta_q_u_ac, delta_q_v_dc: h.quantization.delta_q_v_dc, delta_q_v_ac: h.quantization.delta_q_v_ac, using_qmatrix: h.quantization.using_qmatrix, qm_y: h.quantization.qm_y, qm_u: h.quantization.qm_u, qm_v: h.quantization.qm_v, }, segmentation: Av1Segmentation { enabled: h.segmentation.enabled, update_map: h.segmentation.update_map, temporal_update: h.segmentation.temporal_update, update_data: h.segmentation.update_data, feature_enabled: h.segmentation.feature_enabled, feature_data: h.segmentation.feature_data, }, delta: Av1DeltaParams { q_present: h.delta.q_present, q_res: h.delta.q_res, lf_present: h.delta.lf_present, lf_res: h.delta.lf_res, lf_multi: h.delta.lf_multi, }, loop_filter: Av1LoopFilter { level: h.loop_filter.level, sharpness: h.loop_filter.sharpness, delta_enabled: h.loop_filter.delta_enabled, delta_update: h.loop_filter.delta_update, ref_deltas: h.loop_filter.ref_deltas, mode_deltas: h.loop_filter.mode_deltas, }, cdef: Av1Cdef { damping_minus_3: h.cdef.damping.saturating_sub(3), bits: h.cdef.bits, y_pri: h.cdef.y_pri_strength, y_sec: h.cdef.y_sec_strength, uv_pri: h.cdef.uv_pri_strength, uv_sec: h.cdef.uv_sec_strength, }, loop_restoration: Av1LoopRestoration { frame_restoration_type: h.loop_restoration.frame_restoration_type.map(restoration), loop_restoration_size: h .loop_restoration .loop_restoration_size .map(|v| v as u16), }, global_motion, order_hints, skip_mode_frame: h.skip_mode_frame, expected_frame_id: [0; 8], apply_grain: false, } }