diff --git a/crates/ec-hw/examples/hw_decode.rs b/crates/ec-hw/examples/hw_decode.rs index 89a930d1..de330fd8 100644 --- a/crates/ec-hw/examples/hw_decode.rs +++ b/crates/ec-hw/examples/hw_decode.rs @@ -1,4 +1,4 @@ -//! Decodes ffmpeg libx264, libx265, SVT-AV1 and libaom AV1 streams, plus our own Vulkan AV1 encoder's, through HwDecoder and compares luma with ffmpeg's decode, frame by frame. +//! Decodes ffmpeg libx264, libx265, libvpx VP9, SVT-AV1 and libaom AV1 streams, plus our own Vulkan AV1 encoder's, through HwDecoder and compares luma with ffmpeg's decode, frame by frame. //! The 10-bit H.265 and AV1 streams run on Vulkan and are compared with the VA-API decode of the same stream. //! //! ```text @@ -106,6 +106,57 @@ fn main() { } ten_bit(&dir); own_av1(&dir); + vp9_cases(&dir); +} + +fn vp9_cases(dir: &Path) { + vp9_case(dir, "vp9_640", "640x360", 60, &[], "yuv420p", 8); + vp9_case( + dir, + "vp9_720", + "1280x720", + 30, + &["-lag-in-frames", "0", "-deadline", "realtime"], + "yuv420p", + 8, + ); + vp9_case(dir, "vp9_10", "640x360", 30, &["-profile:v", "2"], "yuv420p10le", 10); +} + +fn vp9_case(dir: &Path, name: &str, size: &str, frames: usize, encoder: &[&str], pix_fmt: &str, bits: u32) { + let stream = dir.join(format!("{name}.ivf")); + let reference = dir.join(format!("{name}.yuv")); + let source = format!("testsrc2=size={size}:rate=30"); + let frames = frames.to_string(); + let stream_arg = stream.to_str().expect("utf-8 path"); + let reference_arg = reference.to_str().expect("utf-8 path"); + let mut encode = vec!["-f", "lavfi", "-i", source.as_str(), "-frames:v", frames.as_str(), "-c:v", "libvpx-vp9", "-pix_fmt", pix_fmt]; + encode.extend_from_slice(encoder); + encode.extend_from_slice(&["-f", "ivf", stream_arg]); + ffmpeg(&encode); + ffmpeg(&["-i", stream_arg, "-f", "rawvideo", "-pix_fmt", pix_fmt, reference_arg]); + + let data = fs::read(&stream).expect("read VP9 stream"); + let mut decoder = HwDecoder::open(Codec::Vp9).expect("open decoder"); + let backend = decoder.backend(); + assert_eq!(backend, Backend::Vk, "{name}: VP9 must decode on Vulkan"); + let mut decoded: Vec = Vec::new(); + for (pts, unit) in ivf_units(&data).into_iter().enumerate() { + decoder.decode(unit, pts as i64).expect("decode"); + drain(&mut decoder, &mut decoded); + } + decoder.flush().expect("flush"); + drain(&mut decoder, &mut decoded); + + let raw = fs::read(&reference).expect("read reference"); + let raw: Vec = if bits == 10 { + raw.chunks_exact(2) + .map(|p| (u16::from_le_bytes([p[0], p[1]]) >> 2) as u8) + .collect() + } else { + raw + }; + compare(name, Codec::Vp9, backend, dims(size), &decoded, &raw); } fn ten_bit(dir: &Path) { diff --git a/crates/ec-hw/examples/hw_decode_rgb.rs b/crates/ec-hw/examples/hw_decode_rgb.rs index ab838738..b5533679 100644 --- a/crates/ec-hw/examples/hw_decode_rgb.rs +++ b/crates/ec-hw/examples/hw_decode_rgb.rs @@ -18,13 +18,15 @@ const FILES: &[(&str, Codec)] = &[ ("h265idr720.hevc", Codec::H265), ("av1aom720.ivf", Codec::Av1), ("ten.hevc", Codec::H265), + ("vp9_640.ivf", Codec::Vp9), + ("vp9_720.ivf", Codec::Vp9), ]; fn main() { let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); for &(name, codec) in FILES { let data = fs::read(dir.join(name)).expect("read stream"); - let units = if codec == Codec::Av1 { + let units = if matches!(codec, Codec::Av1 | Codec::Vp9) { ivf_units(&data) } else { vec![data.as_slice()] diff --git a/crates/ec-hw/src/dec/av1.rs b/crates/ec-hw/src/dec/av1.rs index fb2ebd0f..77973c44 100644 --- a/crates/ec-hw/src/dec/av1.rs +++ b/crates/ec-hw/src/dec/av1.rs @@ -11,7 +11,7 @@ use ec_va::va::BufferType; use ec_va::{Display, picture}; use super::{ReadyFrames, Session, StreamInfo}; -use crate::av1_refs::RefSlots; +use crate::ref_slots::RefSlots; use crate::error::{Error, Result}; use crate::frame::Frame; use crate::params::av1::{ diff --git a/crates/ec-hw/src/dec/vp9.rs b/crates/ec-hw/src/dec/vp9.rs index 69e7afce..7bde9dd2 100644 --- a/crates/ec-hw/src/dec/vp9.rs +++ b/crates/ec-hw/src/dec/vp9.rs @@ -18,6 +18,7 @@ use crate::params::vp9::{ SliceParameterBufferVP9, }; use crate::pool::PooledSurface; +use crate::ref_slots::RefSlots; /// Reference slots plus the picture being decoded plus caller-held frames. const EXTRA_SURFACES: usize = 6; @@ -28,7 +29,7 @@ pub struct Vp9Decoder { parser: Vp9Parser, session: Option, /// The eight reference slots, as surfaces. - refs: [Option>; NUM_REF_FRAMES], + refs: RefSlots>, ready: ReadyFrames, } @@ -39,7 +40,7 @@ impl Vp9Decoder { display: Rc::clone(display), parser: Vp9Parser::new(), session: None, - refs: [const { None }; NUM_REF_FRAMES], + refs: RefSlots::new(), ready: ReadyFrames::default(), } } @@ -70,7 +71,7 @@ impl Vp9Decoder { /// Drop reference state after a seek. pub fn reset(&mut self) { self.parser = Vp9Parser::new(); - self.refs = [const { None }; NUM_REF_FRAMES]; + self.refs = RefSlots::new(); self.ready.clear(); } @@ -87,7 +88,7 @@ impl Vp9Decoder { // 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.refs.get(slot).cloned(), self.session.as_ref(), ) else { return Err(Error::Stream(ec_core::Error::corrupt( @@ -112,7 +113,7 @@ impl Vp9Decoder { // and the driver would read VA_INVALID_SURFACE: refuse the broken GOP. if header.frame_type == FrameType::Inter { for (ref_index, &slot) in header.ref_frame_idx[..3].iter().enumerate() { - if self.refs[usize::from(slot)].is_none() { + if self.refs.get(usize::from(slot)).is_none() { return Err(Error::Stream(ec_core::Error::corrupt(format!( "VP9 inter frame names reference slot {slot} (ref {ref_index}), \ which no decoded frame has filled" @@ -140,11 +141,8 @@ impl Vp9Decoder { // 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(Rc::clone(&surface)); - } - } + self.refs + .refresh(header.refresh_frame_flags, Some(Rc::clone(&surface))); if header.show_frame { self.ready.push(Frame::new( @@ -184,7 +182,7 @@ impl Vp9Decoder { { return Ok(()); } - self.refs = [const { None }; NUM_REF_FRAMES]; + self.refs = RefSlots::new(); self.session = Some(Session::new( &self.display, profile, @@ -249,8 +247,8 @@ fn picture_parameters( } /// The surface id in each reference slot, `None` for an empty one. -fn slot_ids(refs: &[Option>; NUM_REF_FRAMES]) -> [Option; NUM_REF_FRAMES] { - refs.each_ref().map(|s| s.as_ref().map(|s| s.id())) +fn slot_ids(refs: &RefSlots>) -> [Option; NUM_REF_FRAMES] { + std::array::from_fn(|slot| refs.get(slot).map(|s| s.id())) } /// Feeds a run of VP9 chunks (each a frame or a superframe, see diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index 1d84309f..248206d7 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -16,6 +16,7 @@ use crate::types::{ Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings, }; use crate::vkdec_av1::VkAv1Decoder; +use crate::vkdec_vp9::VkVp9Decoder; use crate::vkdec264::VkH264Decoder; use crate::vkdec265::VkH265Decoder; @@ -74,7 +75,7 @@ pub fn capabilities() -> Vec { || (c.direction == ec_vk::Direction::Decode && matches!( c.codec, - ec_vk::Codec::H264 | ec_vk::Codec::H265 | ec_vk::Codec::Av1 + ec_vk::Codec::H264 | ec_vk::Codec::H265 | ec_vk::Codec::Av1 | ec_vk::Codec::Vp9 )) }) { let codec = match caps.codec { @@ -540,6 +541,7 @@ enum VkDecoder { H264(VkH264Decoder), H265(VkH265Decoder), Av1(VkAv1Decoder), + Vp9(VkVp9Decoder), } impl VkDecoder { @@ -548,6 +550,7 @@ impl VkDecoder { VkDecoder::H264(d) => d.decode(data, timestamp), VkDecoder::H265(d) => d.decode(data, timestamp), VkDecoder::Av1(d) => d.decode(data, timestamp), + VkDecoder::Vp9(d) => d.decode(data, timestamp), } } @@ -556,6 +559,7 @@ impl VkDecoder { VkDecoder::H264(d) => d.next_frame(), VkDecoder::H265(d) => d.next_frame(), VkDecoder::Av1(d) => d.next_frame(), + VkDecoder::Vp9(d) => d.next_frame(), } } @@ -564,6 +568,7 @@ impl VkDecoder { VkDecoder::H264(d) => d.flush(), VkDecoder::H265(d) => d.flush(), VkDecoder::Av1(d) => d.flush(), + VkDecoder::Vp9(d) => d.flush(), } } } @@ -602,7 +607,7 @@ pub struct HwDecoder { } impl HwDecoder { - /// Open a decoder for `codec` that hands out I420. H.264, H.265 and AV1 try Vulkan Video first, then VA-API (Linux). + /// Open a decoder for `codec` that hands out I420. Every codec tries Vulkan Video first, then VA-API (Linux). pub fn open(codec: Codec) -> Result { HwDecoder::open_mode(codec, Mode::I420) } @@ -622,7 +627,7 @@ impl HwDecoder { Codec::H264 => VkH264Decoder::new(rgb).map(VkDecoder::H264), Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265), Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1), - _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")), + Codec::Vp9 => VkVp9Decoder::new(rgb).map(VkDecoder::Vp9), }; match vk { Ok(inner) => { @@ -633,10 +638,7 @@ impl HwDecoder { replay: Some(Vec::new()), }); } - Err(e) if matches!(codec, Codec::H264 | Codec::H265 | Codec::Av1) => { - reasons.push(format!("Vk: {e}")); - } - Err(_) => {} + Err(e) => reasons.push(format!("Vk: {e}")), } #[cfg(target_os = "linux")] { diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 94ff2260..70322185 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -63,7 +63,8 @@ pub mod error; pub(crate) mod dpb264; #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub(crate) mod h264_common; -pub(crate) mod av1_refs; +pub(crate) mod ref_slots; +pub(crate) mod vkdec_vp9; pub(crate) mod hevc_dpb; pub mod hw; #[cfg(target_os = "linux")] diff --git a/crates/ec-hw/src/av1_refs.rs b/crates/ec-hw/src/ref_slots.rs similarity index 91% rename from crates/ec-hw/src/av1_refs.rs rename to crates/ec-hw/src/ref_slots.rs index 149ea2c6..310cb7b4 100644 --- a/crates/ec-hw/src/av1_refs.rs +++ b/crates/ec-hw/src/ref_slots.rs @@ -1,4 +1,4 @@ -//! The eight AV1 reference slots (spec 7.20), shared by the VA-API and Vulkan decoders. +//! The eight reference slots (AV1 spec 7.20, VP9 spec 8.10), shared by the VA-API and Vulkan decoders. use ec_av1_syntax::NUM_REF_FRAMES; diff --git a/crates/ec-hw/src/vkdec_av1.rs b/crates/ec-hw/src/vkdec_av1.rs index f1ba8cc1..db4c8751 100644 --- a/crates/ec-hw/src/vkdec_av1.rs +++ b/crates/ec-hw/src/vkdec_av1.rs @@ -15,7 +15,7 @@ use ec_vk::{ Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, }; -use crate::av1_refs::RefSlots; +use crate::ref_slots::RefSlots; use crate::error::{Error, Result}; use ec_core::color::{ColorDescription, Tags}; diff --git a/crates/ec-hw/src/vkdec_vp9.rs b/crates/ec-hw/src/vkdec_vp9.rs new file mode 100644 index 00000000..3d6222e2 --- /dev/null +++ b/crates/ec-hw/src/vkdec_vp9.rs @@ -0,0 +1,345 @@ +//! VP9 decoding over Vulkan Video: the reference slots over DPB slot indices. + +use std::collections::VecDeque; +use std::rc::Rc; + +use ec_core::color::{ColorDescription, Tags}; +use ec_vk::{ + Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, + Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation, +}; +use ec_vp9_syntax::{ + ColorSpace, FrameHeader, FrameType, InterpolationFilter, NUM_REF_FRAMES, REFS_PER_FRAME, + Vp9Parser, superframe, +}; + +use crate::error::{Error, Result}; +use crate::hw::{RgbOrder, RgbOutput}; +use crate::picture::{Decoded, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb}; +use crate::ref_slots::RefSlots; + +const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; + +struct Session { + vp9: Vp9DecodeSession, + bit_depth: u8, + width: u32, + height: u32, +} + +struct Reference { + slot: u32, + picture: Decoded, +} + +/// What the next frame needs from the one before it (spec 7.2, UsePrevFrameMvs). +#[derive(Clone, Copy)] +struct PreviousFrame { + width: u32, + height: u32, + show_frame: bool, + intra_only: bool, +} + +/// VP9 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots. +pub(crate) struct VkVp9Decoder { + gpu: ec_vk::Gpu, + parser: Vp9Parser, + session: Option, + refs: RefSlots>, + previous: Option, + ready: VecDeque<(i64, Decoded)>, + rgb: Option, +} + +impl VkVp9Decoder { + pub(crate) fn new(rgb: Option) -> Result { + let gpu = crate::hw::vk_gpu() + .ok_or_else(|| Error::unsupported("Vulkan Video VP9 decode", "no Vulkan device"))?; + Ok(VkVp9Decoder { + gpu, + parser: Vp9Parser::new(), + session: None, + refs: RefSlots::new(), + previous: None, + ready: VecDeque::new(), + rgb, + }) + } + + pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + if data.is_empty() { + return Ok(()); + } + for frame in superframe::split(data)? { + self.decode_frame(frame, timestamp)?; + } + Ok(()) + } + + pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { + self.ready.pop_front() + } + + pub(crate) fn flush(&mut self) -> Result<()> { + Ok(()) + } + + fn decode_frame(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + let header = self.parser.parse_frame(data)?; + if header.show_existing_frame { + let reference = self + .refs + .get(usize::from(header.frame_to_show_map_idx)) + .cloned() + .ok_or_else(|| { + Error::Stream(ec_core::Error::corrupt( + "VP9 show_existing_frame names an empty reference slot", + )) + })?; + self.ready.push_back((timestamp, reference.picture.clone())); + if let Some(previous) = self.previous.as_mut() { + previous.show_frame = true; + } + return Ok(()); + } + check_supported(&header)?; + self.ensure_session(&header)?; + + let mut ref_name_slot = [-1i32; REFS_PER_FRAME]; + let mut refs: Vec = Vec::new(); + if !header.frame_is_intra { + 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!( + "VP9 inter frame names reference slot {index} (ref {name}), \ + which no decoded frame has filled" + ))) + })?; + ref_name_slot[name] = reference.slot as i32; + if !refs.contains(&reference.slot) { + refs.push(reference.slot); + } + } + } + + let setup_slot = self.free_slot()?; + let use_prev_frame_mvs = !header.error_resilient_mode + && self.previous.is_some_and(|p| { + p.width == header.width + && p.height == header.height + && p.show_frame + && !p.intra_only + }); + let frame = frame_header(&header, use_prev_frame_mvs); + let picture = Vp9DecodePicture { + header: &frame, + setup_slot, + ref_name_slot, + refs: &refs, + data, + }; + let session = self + .session + .as_mut() + .ok_or_else(|| Error::config("VP9 picture before any session"))?; + session.vp9.decode(&picture)?; + self.previous = Some(PreviousFrame { + width: header.width, + height: header.height, + show_frame: header.show_frame, + intra_only: header.intra_only, + }); + + if !(header.show_frame || header.refresh_frame_flags != 0) { + return Ok(()); + } + let (width, height) = (header.width, header.height); + let decoded = match self.rgb { + None => { + let (y, uv) = session.vp9.read_output(width, height)?; + Decoded::I420(semi_planar_to_i420( + session.bit_depth, + &y, + &uv, + width as usize, + (0, 0), + (width, height), + )?) + } + Some(rgb) => { + let codes = Tags::from_codes( + u64::from(header.color_space.h273().map_or(2, |c| c.2)), + 0, + 0, + ); + let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; + let (w, h) = rgb_size(width, height, rgb.max_width); + let data = session.vp9.read_output_rgb( + (0, 0, width, height), + (w, h), + rgb.order == RgbOrder::Bgra, + yuv_to_rgb(matrix).words(), + )?; + Decoded::Rgb(RgbPicture::new(data, w, h)) + } + }; + if header.show_frame { + self.ready.push_back((timestamp, decoded.clone())); + } + if header.refresh_frame_flags != 0 { + let reference = Rc::new(Reference { + slot: setup_slot, + picture: decoded, + }); + self.refs + .refresh(header.refresh_frame_flags, Some(reference)); + } + Ok(()) + } + + fn ensure_session(&mut self, header: &FrameHeader) -> Result<()> { + if let Some(s) = &self.session + && s.bit_depth == header.bit_depth + && header.width <= s.width + && header.height <= s.height + { + return Ok(()); + } + let (width, height) = match &self.session { + Some(s) if s.bit_depth == header.bit_depth => { + (header.width.max(s.width), header.height.max(s.height)) + } + _ => (header.width, header.height), + }; + self.refs = RefSlots::new(); + let vp9 = Vp9DecodeSession::new( + &self.gpu, + &Vp9DecodeConfig { + max_width: width, + max_height: height, + max_dpb_slots: DPB_SLOTS, + bit_depth: header.bit_depth, + }, + )?; + self.session = Some(Session { + vp9, + bit_depth: header.bit_depth, + width, + height, + }); + Ok(()) + } + + fn free_slot(&self) -> Result { + (0..DPB_SLOTS) + .find(|slot| self.refs.filled().all(|r| r.slot != *slot)) + .ok_or_else(|| Error::config("VP9 Vulkan decode: every DPB slot is in use")) + } +} + +fn check_supported(h: &FrameHeader) -> Result<()> { + if !matches!((h.profile, h.bit_depth), (0, 8) | (2, 10)) + || h.subsampling_x != 1 + || h.subsampling_y != 1 + { + return Err(Error::unsupported( + "Vulkan VP9 decode", + "only 4:2:0 profile 0 8-bit and profile 2 10-bit", + )); + } + if h.width % 2 != 0 || h.height % 2 != 0 { + return Err(Error::unsupported("Vulkan VP9 decode", "odd frame size")); + } + Ok(()) +} + +fn color_code(c: ColorSpace) -> u8 { + match c { + ColorSpace::Unknown => 0, + ColorSpace::Bt601 => 1, + ColorSpace::Bt709 => 2, + ColorSpace::Smpte170 => 3, + ColorSpace::Smpte240 => 4, + ColorSpace::Bt2020 => 5, + ColorSpace::Reserved => 6, + ColorSpace::Rgb => 7, + } +} + +fn interpolation(f: InterpolationFilter) -> Vp9InterpolationFilter { + match f { + InterpolationFilter::Eighttap => Vp9InterpolationFilter::EightTap, + InterpolationFilter::EighttapSmooth => Vp9InterpolationFilter::EightTapSmooth, + InterpolationFilter::EighttapSharp => Vp9InterpolationFilter::EightTapSharp, + InterpolationFilter::Bilinear => Vp9InterpolationFilter::Bilinear, + InterpolationFilter::Switchable => Vp9InterpolationFilter::Switchable, + } +} + +fn frame_header(h: &FrameHeader, use_prev_frame_mvs: bool) -> Vp9FrameHeader { + let s = &h.segmentation; + let feature_enabled = std::array::from_fn(|segment| { + (0..s.feature_enabled[segment].len()) + .filter(|&f| s.feature_enabled[segment][f]) + .fold(0u8, |mask, f| mask | 1 << f) + }); + let sign_bias = h + .ref_frame_sign_bias + .iter() + .enumerate() + .filter(|(_, set)| **set) + .fold(0u8, |mask, (name, _)| mask | 1 << (name + 1)); + let lf = &h.loop_filter; + Vp9FrameHeader { + key_frame: h.frame_type == FrameType::Key, + show_frame: h.show_frame, + error_resilient_mode: h.error_resilient_mode, + intra_only: h.intra_only, + allow_high_precision_mv: h.allow_high_precision_mv, + refresh_frame_context: h.refresh_frame_context, + frame_parallel_decoding_mode: h.frame_parallel_decoding_mode, + use_prev_frame_mvs, + frame_context_idx: h.frame_context_idx, + reset_frame_context: h.reset_frame_context, + refresh_frame_flags: h.refresh_frame_flags, + ref_frame_sign_bias_mask: sign_bias, + interpolation_filter: interpolation(h.interpolation_filter), + base_q_idx: h.quantization.base_q_idx, + delta_q_y_dc: h.quantization.delta_q_y_dc, + delta_q_uv_dc: h.quantization.delta_q_uv_dc, + delta_q_uv_ac: h.quantization.delta_q_uv_ac, + tile_cols_log2: h.tile_info.cols_log2, + tile_rows_log2: h.tile_info.rows_log2, + width: h.width, + height: h.height, + bit_depth: h.bit_depth, + color: Vp9ColorConfig { + color_space: color_code(h.color_space), + color_range: h.color_range, + subsampling_x: h.subsampling_x, + subsampling_y: h.subsampling_y, + }, + loop_filter: Vp9LoopFilter { + level: lf.level, + sharpness: lf.sharpness, + delta_enabled: lf.delta_enabled, + delta_update: lf.delta_update, + ref_deltas: lf.ref_deltas, + mode_deltas: lf.mode_deltas, + }, + segmentation: Vp9Segmentation { + enabled: s.enabled, + update_map: s.update_map, + temporal_update: s.temporal_update, + update_data: s.update_data, + abs_or_delta_update: s.abs_or_delta_update, + tree_probs: s.tree_probs, + pred_probs: s.pred_probs, + feature_enabled, + feature_data: s.feature_data, + }, + uncompressed_header_size: u32::from(h.uncompressed_header_size), + compressed_header_size: u32::from(h.header_size_in_bytes), + } +} diff --git a/crates/ec-vk/src/lib.rs b/crates/ec-vk/src/lib.rs index 629e2fca..bdac45a0 100644 --- a/crates/ec-vk/src/lib.rs +++ b/crates/ec-vk/src/lib.rs @@ -19,7 +19,9 @@ pub use vk_video_ffi::{ Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, - H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, + H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, Vp9ColorConfig, + Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, Vp9InterpolationFilter, + Vp9LoopFilter, Vp9Segmentation, }; /// Encoder settings. diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index 6a950550..9fe875f9 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -17,6 +17,7 @@ mod h265_encode; mod rgb_convert; mod rgb_decode; mod session; +mod vp9_decode; pub use av1_decode::{ Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, @@ -27,6 +28,10 @@ pub use av1_decode::{ pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref}; #[cfg(target_os = "linux")] pub use dmabuf::DmaBuf; +pub use vp9_decode::{ + Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, + Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation, +}; pub use h264_decode::{ H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps, ScalingLists, diff --git a/shims/vk-video-ffi/src/vp9_decode.rs b/shims/vk-video-ffi/src/vp9_decode.rs new file mode 100644 index 00000000..77052713 --- /dev/null +++ b/shims/vk-video-ffi/src/vp9_decode.rs @@ -0,0 +1,508 @@ +use std::ffi::c_void; + +use vulkanalia::prelude::v1_3::*; + +use crate::session::{ + Decoder, VideoSession, align, align_u64, component_bit_depth, picture_resource, video_caps, + zeroed, +}; +use crate::{Error, Gpu}; + +/// Settings fixed for the life of a VP9 decode session. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Vp9DecodeConfig { + /// Largest frame width in luma samples. + pub max_width: u32, + /// Largest frame height in luma samples. + pub max_height: u32, + /// DPB slots, including the slot the picture is decoded into. + pub max_dpb_slots: u32, + /// Luma and chroma bit depth: 8 (profile 0) or 10 (profile 2). + pub bit_depth: u8, +} + +/// Interpolation filter, as `StdVideoVP9InterpolationFilter`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Vp9InterpolationFilter { + /// EIGHTTAP. + EightTap = 0, + /// EIGHTTAP_SMOOTH. + EightTapSmooth = 1, + /// EIGHTTAP_SHARP. + EightTapSharp = 2, + /// BILINEAR. + Bilinear = 3, + /// SWITCHABLE. + Switchable = 4, +} + +/// Colour configuration of a frame (spec 6.2, `color_config`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Vp9ColorConfig { + /// color_space, the VP9 code point. + pub color_space: u8, + /// color_range. + pub color_range: bool, + /// subsampling_x. + pub subsampling_x: u8, + /// subsampling_y. + pub subsampling_y: u8, +} + +/// Loop filter parameters of a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Vp9LoopFilter { + /// loop_filter_level. + pub level: u8, + /// loop_filter_sharpness. + pub sharpness: u8, + /// loop_filter_delta_enabled. + pub delta_enabled: bool, + /// loop_filter_delta_update. + pub delta_update: bool, + /// loop_filter_ref_deltas. + pub ref_deltas: [i8; 4], + /// loop_filter_mode_deltas. + pub mode_deltas: [i8; 2], +} + +/// Segmentation parameters of a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Vp9Segmentation { + /// segmentation_enabled. + pub enabled: bool, + /// segmentation_update_map. + pub update_map: bool, + /// segmentation_temporal_update. + pub temporal_update: bool, + /// segmentation_update_data. + pub update_data: bool, + /// segmentation_abs_or_delta_update. + pub abs_or_delta_update: bool, + /// segmentation_tree_probs. + pub tree_probs: [u8; 7], + /// segmentation_pred_prob. + pub pred_probs: [u8; 3], + /// Per segment, a bit mask of the features enabled (bit n is feature n). + pub feature_enabled: [u8; 8], + /// FeatureData[segment][feature]. + pub feature_data: [[i16; 4]; 8], +} + +/// One VP9 frame's uncompressed header fields, in the shape `StdVideoDecodeVP9PictureInfo` takes them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Vp9FrameHeader { + /// True for a key frame. + pub key_frame: bool, + /// show_frame. + pub show_frame: bool, + /// error_resilient_mode. + pub error_resilient_mode: bool, + /// intra_only. + pub intra_only: bool, + /// allow_high_precision_mv. + pub allow_high_precision_mv: bool, + /// refresh_frame_context. + pub refresh_frame_context: bool, + /// frame_parallel_decoding_mode. + pub frame_parallel_decoding_mode: bool, + /// UsePrevFrameMvs, derived by the caller from the previous frame. + pub use_prev_frame_mvs: bool, + /// frame_context_idx. + pub frame_context_idx: u8, + /// reset_frame_context. + pub reset_frame_context: u8, + /// refresh_frame_flags. + pub refresh_frame_flags: u8, + /// Sign bias per reference name, bit n for reference name n (LAST = 1). + pub ref_frame_sign_bias_mask: u8, + /// interp_filter. + pub interpolation_filter: Vp9InterpolationFilter, + /// base_q_idx. + pub base_q_idx: u8, + /// DeltaQYDc. + pub delta_q_y_dc: i8, + /// DeltaQUVDc. + pub delta_q_uv_dc: i8, + /// DeltaQUVAc. + pub delta_q_uv_ac: i8, + /// tile_cols_log2. + pub tile_cols_log2: u8, + /// tile_rows_log2. + pub tile_rows_log2: u8, + /// FrameWidth. + pub width: u32, + /// FrameHeight. + pub height: u32, + /// BitDepth, 8 or 10. + pub bit_depth: u8, + /// Colour configuration. + pub color: Vp9ColorConfig, + /// Loop filter parameters. + pub loop_filter: Vp9LoopFilter, + /// Segmentation parameters. + pub segmentation: Vp9Segmentation, + /// Length of the uncompressed header in bytes, from the start of the frame. + pub uncompressed_header_size: u32, + /// Length of the compressed header in bytes, after the uncompressed header. + pub compressed_header_size: u32, +} + +/// One frame to decode; the frame data holds the uncompressed header, compressed header and tiles. +#[derive(Debug, Clone, Copy)] +pub struct Vp9DecodePicture<'a> { + /// Frame header. + pub header: &'a Vp9FrameHeader, + /// DPB slot the picture is decoded into. + pub setup_slot: u32, + /// DPB slot of each reference name LAST, GOLDEN and ALTREF, -1 when unused. + pub ref_name_slot: [i32; 3], + /// Distinct DPB slots the frame references. + pub refs: &'a [u32], + /// The whole frame, uncompressed header through the last tile. + pub data: &'a [u8], +} + +struct Caps { + std_header_version: vk::ExtensionProperties, + max_extent: vk::Extent2D, + size_align: u64, + max_dpb_slots: u32, + max_active_refs: u32, + distinct: bool, +} + +struct Profile { + info: vk::VideoProfileInfoKHR, + vp9: vk::VideoDecodeVP9ProfileInfoKHR, +} + +impl Profile { + fn new(bit_depth: u8) -> Box { + let component = component_bit_depth(bit_depth); + let std_profile = if bit_depth == 10 { + vk::video::STD_VIDEO_VP9_PROFILE_2 + } else { + vk::video::STD_VIDEO_VP9_PROFILE_0 + }; + let mut p = Box::new(Profile { + info: vk::VideoProfileInfoKHR::builder() + .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_VP9) + .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) + .luma_bit_depth(component) + .chroma_bit_depth(component) + .build(), + vp9: vk::VideoDecodeVP9ProfileInfoKHR::builder() + .std_profile(std_profile) + .build(), + }); + p.info.next = &p.vp9 as *const _ as *const c_void; + p + } +} + +/// A VP9 profile 0 or 2 Vulkan Video decode session: DPB images per slot and a separate output image. +pub struct Vp9DecodeSession { + dec: Decoder, + bit_depth: u8, +} + +impl Vp9DecodeSession { + /// Creates a session with its DPB, bitstream and readback buffers. + pub fn new(gpu: &Gpu, cfg: &Vp9DecodeConfig) -> Result { + if cfg.max_width == 0 || cfg.max_height == 0 || cfg.max_dpb_slots == 0 { + return Err(Error::Invalid( + "decode size or DPB slot count is zero".into(), + )); + } + if !matches!(cfg.bit_depth, 8 | 10) { + return Err(Error::Invalid("bit depth is not 8 or 10".into())); + } + let family = gpu + .decode_family() + .ok_or_else(|| Error::Unsupported("VP9 decode queue family".into()))?; + let graphics = gpu + .graphics_family() + .ok_or_else(|| Error::Unsupported("graphics queue family for readback".into()))?; + if !gpu + .device() + .extensions() + .contains(&vk::KHR_VIDEO_DECODE_VP9_EXTENSION.name) + { + return Err(Error::Unsupported("VP9 decode".into())); + } + let width = align(cfg.max_width, 16); + let height = align(cfg.max_height, 16); + let profile = Profile::new(cfg.bit_depth); + let caps = query_caps(gpu, &profile.info)?; + if width > caps.max_extent.width + || height > caps.max_extent.height + || cfg.max_dpb_slots > caps.max_dpb_slots + { + return Err(Error::Unsupported(format!("VP9 decode {width}x{height}"))); + } + if !caps.distinct { + return Err(Error::Unsupported( + "VP9 decode with DPB and output in one image".into(), + )); + } + let max_active = caps.max_active_refs.min(cfg.max_dpb_slots); + let max_extent = vk::Extent2D { width, height }; + let vs = VideoSession::new( + gpu, + family, + &profile.info, + &caps.std_header_version, + max_extent, + cfg.max_dpb_slots, + max_active, + )?; + let dec = Decoder::new( + vs, + &profile.info, + graphics, + max_extent, + cfg.max_dpb_slots, + max_active, + caps.size_align, + )?; + Ok(Vp9DecodeSession { + dec, + bit_depth: cfg.bit_depth, + }) + } + + /// Decodes one frame into its setup slot, referencing the given DPB slots. + pub fn decode(&mut self, pic: &Vp9DecodePicture) -> Result<(), Error> { + let h = pic.header; + if h.bit_depth != self.bit_depth { + return Err(Error::Invalid( + "frame bit depth differs from session".into(), + )); + } + let extent = vk::Extent2D { + width: h.width, + height: h.height, + }; + if extent.width == 0 + || extent.height == 0 + || extent.width > self.dec.max_extent.width + || extent.height > self.dec.max_extent.height + { + return Err(Error::Invalid("frame size".into())); + } + if pic.data.len() as u64 > self.dec.bitstream.size { + return Err(Error::Invalid("frame larger than bitstream buffer".into())); + } + let compressed_end = + u64::from(h.uncompressed_header_size) + u64::from(h.compressed_header_size); + if compressed_end > pic.data.len() as u64 { + return Err(Error::Invalid("headers outside frame data".into())); + } + if pic.setup_slot >= self.dec.max_dpb_slots { + return Err(Error::Invalid("setup DPB slot".into())); + } + if pic.refs.len() > self.dec.max_active_refs as usize { + return Err(Error::Invalid("too many reference pictures".into())); + } + for (i, &slot) in pic.refs.iter().enumerate() { + if slot >= self.dec.max_dpb_slots + || slot == pic.setup_slot + || pic.refs[..i].contains(&slot) + { + return Err(Error::Invalid("reference DPB slot".into())); + } + } + if pic + .ref_name_slot + .iter() + .any(|&s| s >= 0 && !pic.refs.iter().any(|&r| i32::try_from(r) == Ok(s))) + { + return Err(Error::Invalid( + "reference name without a reference slot".into(), + )); + } + + let ptr = self + .dec + .bitstream + .ptr + .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?; + let buf = unsafe { std::slice::from_raw_parts_mut(ptr, self.dec.bitstream.size as usize) }; + buf[..pic.data.len()].copy_from_slice(pic.data); + let range = align_u64(pic.data.len() as u64, self.dec.size_align); + + let pr: Vec = self + .dec + .dpb + .iter() + .map(|i| picture_resource(i.view, extent)) + .collect(); + let setup = vk::VideoReferenceSlotInfoKHR::builder() + .slot_index(pic.setup_slot as i32) + .picture_resource(&pr[pic.setup_slot as usize]) + .build(); + let refs: Vec = pic + .refs + .iter() + .map(|&slot| { + vk::VideoReferenceSlotInfoKHR::builder() + .slot_index(slot as i32) + .picture_resource(&pr[slot as usize]) + .build() + }) + .collect(); + let mut begin: Vec = vec![ + vk::VideoReferenceSlotInfoKHR::builder() + .slot_index(-1) + .picture_resource(&pr[pic.setup_slot as usize]) + .build(), + ]; + begin.extend(refs.iter().copied()); + + let color = std_color(h); + let lf = std_loop_filter(&h.loop_filter); + let seg = std_segmentation(&h.segmentation); + let mut std_pic = zeroed::(); + std_pic.flags = picture_flags(h); + std_pic.profile = if self.bit_depth == 10 { + vk::video::STD_VIDEO_VP9_PROFILE_2 + } else { + vk::video::STD_VIDEO_VP9_PROFILE_0 + }; + std_pic.frame_type = if h.key_frame { + vk::video::STD_VIDEO_VP9_FRAME_TYPE_KEY + } else { + vk::video::STD_VIDEO_VP9_FRAME_TYPE_NON_KEY + }; + std_pic.frame_context_idx = h.frame_context_idx; + std_pic.reset_frame_context = h.reset_frame_context; + std_pic.refresh_frame_flags = h.refresh_frame_flags; + std_pic.ref_frame_sign_bias_mask = h.ref_frame_sign_bias_mask; + std_pic.interpolation_filter = + vk::video::StdVideoVP9InterpolationFilter(i32::from(h.interpolation_filter as u8)); + std_pic.base_q_idx = h.base_q_idx; + std_pic.delta_q_y_dc = h.delta_q_y_dc; + std_pic.delta_q_uv_dc = h.delta_q_uv_dc; + std_pic.delta_q_uv_ac = h.delta_q_uv_ac; + std_pic.tile_cols_log2 = h.tile_cols_log2; + std_pic.tile_rows_log2 = h.tile_rows_log2; + std_pic.pColorConfig = &color; + std_pic.pLoopFilter = &lf; + std_pic.pSegmentation = &seg; + + let mut vp9 = vk::VideoDecodeVP9PictureInfoKHR { + std_picture_info: &std_pic, + reference_name_slot_indices: pic.ref_name_slot, + uncompressed_header_offset: 0, + compressed_header_offset: h.uncompressed_header_size, + tiles_offset: compressed_end as u32, + ..Default::default() + }; + let decode = vk::VideoDecodeInfoKHR::builder() + .src_buffer(self.dec.bitstream.buffer) + .src_buffer_offset(0) + .src_buffer_range(range) + .dst_picture_resource(picture_resource(self.dec.output.view, extent)) + .setup_reference_slot(&setup) + .reference_slots(&refs) + .push_next(&mut vp9) + .build(); + self.dec.run(&begin, &decode) + } + + /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). + pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { + self.dec.read_nv12(width, height) + } + + /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order. + pub fn read_output_rgb( + &mut self, + crop: (u32, u32, u32, u32), + out: (u32, u32), + bgra: bool, + coeffs: [i32; 5], + ) -> Result, Error> { + self.dec.read_rgb(crop, out, bgra, coeffs) + } +} + +fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result { + let mut vp9 = vk::VideoDecodeVP9CapabilitiesKHR::builder(); + let mut decode = vk::VideoDecodeCapabilitiesKHR::builder(); + let mut caps = vk::VideoCapabilitiesKHR::builder() + .push_next(&mut vp9) + .push_next(&mut decode); + video_caps(gpu, profile, &mut caps) + .map_err(|_| Error::Unsupported("VP9 decode profile".into()))?; + let caps = caps.build(); + let decode = decode.build(); + Ok(Caps { + std_header_version: caps.std_header_version, + max_extent: caps.max_coded_extent, + size_align: caps.min_bitstream_buffer_size_alignment, + max_dpb_slots: caps.max_dpb_slots, + max_active_refs: caps.max_active_reference_pictures, + distinct: decode + .flags + .contains(vk::VideoDecodeCapabilityFlagsKHR::DPB_AND_OUTPUT_DISTINCT), + }) +} + +fn std_color(h: &Vp9FrameHeader) -> vk::video::StdVideoVP9ColorConfig { + let mut flags = zeroed::(); + flags.set_color_range(u32::from(h.color.color_range)); + vk::video::StdVideoVP9ColorConfig { + flags, + BitDepth: h.bit_depth, + subsampling_x: h.color.subsampling_x, + subsampling_y: h.color.subsampling_y, + reserved1: 0, + color_space: vk::video::StdVideoVP9ColorSpace(i32::from(h.color.color_space)), + } +} + +fn std_loop_filter(l: &Vp9LoopFilter) -> vk::video::StdVideoVP9LoopFilter { + let mut flags = zeroed::(); + flags.set_loop_filter_delta_enabled(u32::from(l.delta_enabled)); + flags.set_loop_filter_delta_update(u32::from(l.delta_update)); + vk::video::StdVideoVP9LoopFilter { + flags, + loop_filter_level: l.level, + loop_filter_sharpness: l.sharpness, + update_ref_delta: u8::from(l.delta_update), + loop_filter_ref_deltas: l.ref_deltas, + update_mode_delta: u8::from(l.delta_update), + loop_filter_mode_deltas: l.mode_deltas, + } +} + +fn std_segmentation(s: &Vp9Segmentation) -> vk::video::StdVideoVP9Segmentation { + let mut flags = zeroed::(); + flags.set_segmentation_update_map(u32::from(s.update_map)); + flags.set_segmentation_temporal_update(u32::from(s.temporal_update)); + flags.set_segmentation_update_data(u32::from(s.update_data)); + flags.set_segmentation_abs_or_delta_update(u32::from(s.abs_or_delta_update)); + vk::video::StdVideoVP9Segmentation { + flags, + segmentation_tree_probs: s.tree_probs, + segmentation_pred_prob: s.pred_probs, + FeatureEnabled: s.feature_enabled, + FeatureData: s.feature_data, + } +} + +fn picture_flags(h: &Vp9FrameHeader) -> vk::video::StdVideoDecodeVP9PictureInfoFlags { + let mut f = zeroed::(); + f.set_error_resilient_mode(u32::from(h.error_resilient_mode)); + f.set_intra_only(u32::from(h.intra_only)); + f.set_allow_high_precision_mv(u32::from(h.allow_high_precision_mv)); + f.set_refresh_frame_context(u32::from(h.refresh_frame_context)); + f.set_frame_parallel_decoding_mode(u32::from(h.frame_parallel_decoding_mode)); + f.set_segmentation_enabled(u32::from(h.segmentation.enabled)); + f.set_show_frame(u32::from(h.show_frame)); + f.set_UsePrevFrameMvs(u32::from(h.use_prev_frame_mvs)); + f +}