diff --git a/Cargo.lock b/Cargo.lock index 4eaecbc8..1a7d9b58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1895,6 +1895,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" name = "vk-video-ffi" version = "0.1.0" dependencies = [ + "ec-av1-syntax", "ec-h264-syntax", "ec-h265-syntax", "vulkanalia", diff --git a/crates/ec-vk/src/lib.rs b/crates/ec-vk/src/lib.rs index 1f920297..a9c035a0 100644 --- a/crates/ec-vk/src/lib.rs +++ b/crates/ec-vk/src/lib.rs @@ -10,8 +10,12 @@ mod h265; pub use av1::{Av1Encoder, Av1EncoderConfig}; pub use h265::{H265Encoder, H265EncoderConfig}; pub use vk_video_ffi::{ - Codec, Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, - H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, + Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, + Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, + Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation, + Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Direction, + Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, + H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, }; diff --git a/shims/vk-video-ffi/Cargo.toml b/shims/vk-video-ffi/Cargo.toml index 1fc5d632..cf368631 100644 --- a/shims/vk-video-ffi/Cargo.toml +++ b/shims/vk-video-ffi/Cargo.toml @@ -9,5 +9,6 @@ authors.workspace = true vulkanalia = { version = "0.35", features = ["libloading"] } [dev-dependencies] +ec-av1-syntax.workspace = true ec-h264-syntax.workspace = true ec-h265-syntax.workspace = true diff --git a/shims/vk-video-ffi/examples/av1_decode_smoke.rs b/shims/vk-video-ffi/examples/av1_decode_smoke.rs new file mode 100644 index 00000000..4f70a952 --- /dev/null +++ b/shims/vk-video-ffi/examples/av1_decode_smoke.rs @@ -0,0 +1,318 @@ +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +use ec_av1_syntax::{ + Av1Parser, ChromaSamplePosition, ColorConfig, FrameHeader, FrameType, InterpolationFilter, + ObuKind, RestorationType, SequenceHeader, TxMode, WarpModel, +}; +use vk_video_ffi::{ + Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, + Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, + Av1LoopRestoration, Av1Quantization, Av1Restoration, Av1Segmentation, Av1SequenceHeader, + Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Gpu, +}; + +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 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(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..7 { + 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: match h.frame_type { + FrameType::Key => Av1FrameType::Key, + FrameType::Inter => Av1FrameType::Inter, + FrameType::IntraOnly => Av1FrameType::IntraOnly, + FrameType::Switch => Av1FrameType::Switch, + }, + 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: h.film_grain.apply_grain, + } +} + +fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { + a.iter() + .zip(b) + .map(|(&x, &y)| (f64::from(x) - f64::from(y)).abs()) + .sum::() + / a.len() as f64 +} + +fn main() { + let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); + let stream = dir.join("key.ivf"); + let reference = dir.join("av1_ref.yuv"); + let status = Command::new("ffmpeg") + .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"]) + .arg("testsrc2=size=320x240:rate=30") + .args(["-frames:v", "1", "-c:v", "libsvtav1", "-f", "ivf"]) + .arg(&stream) + .status() + .expect("run ffmpeg"); + assert!(status.success()); + let status = Command::new("ffmpeg") + .args(["-y", "-loglevel", "error", "-i"]) + .arg(&stream) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) + .arg(&reference) + .status() + .expect("run ffmpeg"); + assert!(status.success()); + + let ivf = fs::read(&stream).expect("read ivf"); + let header_len = u16::from_le_bytes([ivf[6], ivf[7]]) as usize; + let frame_len = + u32::from_le_bytes(ivf[header_len..header_len + 4].try_into().unwrap()) as usize; + let data = &ivf[header_len + 12..header_len + 12 + frame_len]; + + let mut parser = Av1Parser::new(); + let obus = parser + .parse_temporal_unit(data) + .expect("parse temporal unit"); + let mut seq = None; + let mut frame_obu = None; + for obu in obus { + match obu.kind { + ObuKind::SequenceHeader(s) => seq = Some(*s), + ObuKind::Frame(h, tiles) => frame_obu = Some((*h, tiles)), + _ => {} + } + } + let seq = seq.expect("sequence header"); + let (header, tiles) = frame_obu.expect("frame OBU"); + assert_eq!(header.frame_type, FrameType::Key); + + 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 plain_seq = sequence(&seq); + let plain_frame = frame(&header, &seq); + let (w, h) = (header.upscaled_width, header.frame_height); + + let gpu = Gpu::open().expect("open GPU"); + println!("device: {}", gpu.device_name()); + let cfg = Av1DecodeConfig { + max_width: w, + max_height: h, + max_dpb_slots: 9, + }; + let mut session = Av1DecodeSession::new(&gpu, &cfg).expect("decode session"); + session + .set_sequence_header(&plain_seq) + .expect("sequence header"); + let pic = Av1DecodePicture { + header: &plain_frame, + setup_slot: 0, + ref_frame_slot: [-1; 7], + refs: &[], + tile_data: data, + tile_offsets: &offsets, + tile_sizes: &sizes, + }; + session.decode(&pic).expect("decode"); + let (y, uv) = session.read_output(w, h).expect("read output"); + + let reference = fs::read(&reference).expect("read reference"); + let luma = (w * h) as usize; + let chroma = luma / 4; + let ref_uv: Vec = reference[luma..luma + chroma] + .iter() + .zip(&reference[luma + chroma..luma + 2 * chroma]) + .flat_map(|(&u, &v)| [u, v]) + .collect(); + println!( + "mean abs diff Y: {:.6}", + mean_abs_diff(&y, &reference[..luma]) + ); + println!("mean abs diff UV: {:.6}", mean_abs_diff(&uv, &ref_uv)); +} diff --git a/shims/vk-video-ffi/src/av1_decode.rs b/shims/vk-video-ffi/src/av1_decode.rs new file mode 100644 index 00000000..e2bf9383 --- /dev/null +++ b/shims/vk-video-ffi/src/av1_decode.rs @@ -0,0 +1,1405 @@ +use std::ffi::c_void; + +use vulkanalia::prelude::v1_3::*; +use vulkanalia::vk::{ + KhrVideoDecodeQueueExtensionDeviceCommands, KhrVideoQueueExtensionDeviceCommands, + KhrVideoQueueExtensionInstanceCommands, +}; + +use crate::h264_decode::{Buffer, Image, align_u64, allocate, new_buffer, new_image, submit}; +use crate::h264_encode::{ + NV12, PLANE_0, PLANE_1, align, alloc_cb, barrier, copy_region, create_pool, picture_resource, + vk, zeroed, +}; +use crate::{Error, Gpu}; + +/// Settings fixed for the life of a decode session. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1DecodeConfig { + /// 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, +} + +/// Frame type, values as in the spec and `StdVideoAV1FrameType`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Av1FrameType { + /// KEY_FRAME. + Key = 0, + /// INTER_FRAME. + Inter = 1, + /// INTRA_ONLY_FRAME. + IntraOnly = 2, + /// SWITCH_FRAME. + Switch = 3, +} + +/// Sub-pixel interpolation filter, as `StdVideoAV1InterpolationFilter`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Av1InterpolationFilter { + /// EIGHTTAP. + EightTap = 0, + /// EIGHTTAP_SMOOTH. + EightTapSmooth = 1, + /// EIGHTTAP_SHARP. + EightTapSharp = 2, + /// BILINEAR. + Bilinear = 3, + /// SWITCHABLE. + Switchable = 4, +} + +/// Transform size mode, as `StdVideoAV1TxMode`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Av1TxMode { + /// ONLY_4X4. + Only4x4 = 0, + /// TX_MODE_LARGEST. + Largest = 1, + /// TX_MODE_SELECT. + Select = 2, +} + +/// Loop restoration type of one plane, as `StdVideoAV1FrameRestorationType`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Av1Restoration { + /// RESTORE_NONE. + None = 0, + /// RESTORE_WIENER. + Wiener = 1, + /// RESTORE_SGRPROJ. + Sgrproj = 2, + /// RESTORE_SWITCHABLE. + Switchable = 3, +} + +/// Global motion model, as `GmType`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[repr(u8)] +pub enum Av1WarpModel { + /// IDENTITY. + #[default] + Identity = 0, + /// TRANSLATION. + Translation = 1, + /// ROTZOOM. + Rotzoom = 2, + /// AFFINE. + Affine = 3, +} + +/// Color configuration of a sequence header (spec 5.5.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1ColorConfig { + /// BitDepth, 8 for this decoder. + pub bit_depth: u8, + /// mono_chrome, false for this decoder. + pub mono_chrome: bool, + /// color_range. + pub color_range: bool, + /// separate_uv_delta_q. + pub separate_uv_delta_q: bool, + /// subsampling_x, 1 for this decoder. + pub subsampling_x: u8, + /// subsampling_y, 1 for this decoder. + pub subsampling_y: u8, + /// color_primaries (H.273 code point). + pub color_primaries: u8, + /// transfer_characteristics (H.273 code point). + pub transfer_characteristics: u8, + /// matrix_coefficients (H.273 code point). + pub matrix_coefficients: u8, + /// chroma_sample_position. + pub chroma_sample_position: u8, +} + +/// Timing info of a sequence header (spec 5.5.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1TimingInfo { + /// equal_picture_interval. + pub equal_picture_interval: bool, + /// num_units_in_display_tick. + pub num_units_in_display_tick: u32, + /// time_scale. + pub time_scale: u32, + /// num_ticks_per_picture_minus_1. + pub num_ticks_per_picture_minus_1: u32, +} + +/// Sequence header fields a decoder needs (names follow `StdVideoAV1SequenceHeader`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1SequenceHeader { + /// seq_profile, 0 for this decoder. + pub seq_profile: u8, + /// still_picture. + pub still_picture: bool, + /// reduced_still_picture_header. + pub reduced_still_picture_header: bool, + /// timing_info when present. + pub timing_info: Option, + /// initial_display_delay_present_flag. + pub initial_display_delay_present: bool, + /// frame_width_bits_minus_1. + pub frame_width_bits_minus_1: u8, + /// frame_height_bits_minus_1. + pub frame_height_bits_minus_1: u8, + /// max_frame_width_minus_1. + pub max_frame_width_minus_1: u16, + /// max_frame_height_minus_1. + pub max_frame_height_minus_1: u16, + /// frame_id_numbers_present_flag. + pub frame_id_numbers_present: bool, + /// delta_frame_id_length_minus_2. + pub delta_frame_id_length_minus_2: u8, + /// additional_frame_id_length_minus_1. + pub additional_frame_id_length_minus_1: u8, + /// order_hint_bits_minus_1. + pub order_hint_bits_minus_1: u8, + /// seq_force_integer_mv. + pub seq_force_integer_mv: u8, + /// seq_force_screen_content_tools. + pub seq_force_screen_content_tools: u8, + /// use_128x128_superblock. + pub use_128x128_superblock: bool, + /// enable_filter_intra. + pub enable_filter_intra: bool, + /// enable_intra_edge_filter. + pub enable_intra_edge_filter: bool, + /// enable_interintra_compound. + pub enable_interintra_compound: bool, + /// enable_masked_compound. + pub enable_masked_compound: bool, + /// enable_warped_motion. + pub enable_warped_motion: bool, + /// enable_dual_filter. + pub enable_dual_filter: bool, + /// enable_order_hint. + pub enable_order_hint: bool, + /// enable_jnt_comp. + pub enable_jnt_comp: bool, + /// enable_ref_frame_mvs. + pub enable_ref_frame_mvs: bool, + /// enable_superres. + pub enable_superres: bool, + /// enable_cdef. + pub enable_cdef: bool, + /// enable_restoration. + pub enable_restoration: bool, + /// Color configuration. + pub color_config: Av1ColorConfig, + /// film_grain_params_present. + pub film_grain_params_present: bool, +} + +/// Tile layout of a frame (names follow `StdVideoAV1TileInfo`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Av1TileInfo { + /// uniform_tile_spacing_flag. + pub uniform_spacing: bool, + /// TileCols. + pub cols: u8, + /// TileRows. + pub rows: u8, + /// MiColStarts, TileCols + 1 entries, in mi units. + pub mi_col_starts: Vec, + /// MiRowStarts, TileRows + 1 entries, in mi units. + pub mi_row_starts: Vec, + /// width_in_sbs_minus_1 per tile column, TileCols entries. + pub width_in_sbs_minus_1: Vec, + /// height_in_sbs_minus_1 per tile row, TileRows entries. + pub height_in_sbs_minus_1: Vec, + /// context_update_tile_id. + pub context_update_tile_id: u16, + /// tile_size_bytes_minus_1. + pub tile_size_bytes_minus_1: u8, +} + +/// Quantizer parameters of a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1Quantization { + /// base_q_idx. + pub base_q_idx: u8, + /// DeltaQYDc. + pub delta_q_y_dc: i8, + /// DeltaQUDc. + pub delta_q_u_dc: i8, + /// DeltaQUAc. + pub delta_q_u_ac: i8, + /// DeltaQVDc. + pub delta_q_v_dc: i8, + /// DeltaQVAc. + pub delta_q_v_ac: i8, + /// using_qmatrix. + pub using_qmatrix: bool, + /// qm_y. + pub qm_y: u8, + /// qm_u. + pub qm_u: u8, + /// qm_v. + pub qm_v: u8, +} + +/// Segmentation parameters of a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1Segmentation { + /// 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, + /// FeatureEnabled[segment][feature]. + pub feature_enabled: [[bool; 8]; 8], + /// FeatureData[segment][feature]. + pub feature_data: [[i16; 8]; 8], +} + +/// Delta quantizer and delta loop filter parameters of a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1DeltaParams { + /// delta_q_present. + pub q_present: bool, + /// delta_q_res, as coded (log2). + pub q_res: u8, + /// delta_lf_present. + pub lf_present: bool, + /// delta_lf_res, as coded (log2). + pub lf_res: u8, + /// delta_lf_multi. + pub lf_multi: bool, +} + +/// Loop filter parameters of a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1LoopFilter { + /// loop_filter_level[4]. + pub level: [u8; 4], + /// 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, indexed by reference name (0 intra .. 7 ALTREF). + pub ref_deltas: [i8; 8], + /// loop_filter_mode_deltas. + pub mode_deltas: [i8; 2], +} + +/// CDEF parameters of a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1Cdef { + /// cdef_damping_minus_3. + pub damping_minus_3: u8, + /// cdef_bits. + pub bits: u8, + /// cdef_y_pri_strength. + pub y_pri: [u8; 8], + /// cdef_y_sec_strength, after the 3 becomes 4 adjustment. + pub y_sec: [u8; 8], + /// cdef_uv_pri_strength. + pub uv_pri: [u8; 8], + /// cdef_uv_sec_strength, after the 3 becomes 4 adjustment. + pub uv_sec: [u8; 8], +} + +/// Loop restoration parameters of a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1LoopRestoration { + /// FrameRestorationType per plane. + pub frame_restoration_type: [Av1Restoration; 3], + /// LoopRestorationSize per plane, in samples. + pub loop_restoration_size: [u16; 3], +} + +/// Global motion of one reference. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Av1GlobalMotion { + /// GmType. + pub model: Av1WarpModel, + /// gm_params[6]. + pub params: [i32; 6], +} + +/// Frame header fields a decoder needs (names follow `StdVideoDecodeAV1PictureInfo`). +/// +/// Arrays indexed by reference name use index 0 for INTRA_FRAME and 1 to 7 for LAST to ALTREF. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Av1FrameHeader { + /// frame_type. + pub frame_type: Av1FrameType, + /// show_frame. + pub show_frame: bool, + /// showable_frame. + pub showable_frame: bool, + /// error_resilient_mode. + pub error_resilient_mode: bool, + /// disable_cdf_update. + pub disable_cdf_update: bool, + /// allow_screen_content_tools. + pub allow_screen_content_tools: bool, + /// force_integer_mv. + pub force_integer_mv: bool, + /// current_frame_id. + pub current_frame_id: u32, + /// frame_size_override_flag. + pub frame_size_override_flag: bool, + /// OrderHint. + pub order_hint: u8, + /// primary_ref_frame. + pub primary_ref_frame: u8, + /// refresh_frame_flags. + pub refresh_frame_flags: u8, + /// FrameWidth, after superres downscaling. + pub frame_width: u32, + /// FrameHeight. + pub frame_height: u32, + /// UpscaledWidth. + pub upscaled_width: u32, + /// RenderWidth. + pub render_width: u32, + /// RenderHeight. + pub render_height: u32, + /// use_superres. + pub use_superres: bool, + /// SuperresDenom, 8 to 16. + pub superres_denom: u8, + /// allow_intrabc. + pub allow_intrabc: bool, + /// allow_high_precision_mv. + pub allow_high_precision_mv: bool, + /// is_motion_mode_switchable. + pub is_motion_mode_switchable: bool, + /// use_ref_frame_mvs. + pub use_ref_frame_mvs: bool, + /// frame_refs_short_signaling. + pub frame_refs_short_signaling: bool, + /// disable_frame_end_update_cdf. + pub disable_frame_end_update_cdf: bool, + /// reference_select. + pub reference_select: bool, + /// skip_mode_present. + pub skip_mode_present: bool, + /// allow_warped_motion. + pub allow_warped_motion: bool, + /// reduced_tx_set. + pub reduced_tx_set: bool, + /// interpolation_filter. + pub interpolation_filter: Av1InterpolationFilter, + /// TxMode. + pub tx_mode: Av1TxMode, + /// Tile layout. + pub tile_info: Av1TileInfo, + /// Quantizer parameters. + pub quantization: Av1Quantization, + /// Segmentation parameters. + pub segmentation: Av1Segmentation, + /// Delta quantizer and delta loop filter parameters. + pub delta: Av1DeltaParams, + /// Loop filter parameters. + pub loop_filter: Av1LoopFilter, + /// CDEF parameters. + pub cdef: Av1Cdef, + /// Loop restoration parameters. + pub loop_restoration: Av1LoopRestoration, + /// Global motion per reference name. + pub global_motion: [Av1GlobalMotion; 8], + /// OrderHints per reference name. + pub order_hints: [u8; 8], + /// SkipModeFrame[2]. + pub skip_mode_frame: [u8; 2], + /// expectedFrameId per reference name, used with frame_id_numbers_present. + pub expected_frame_id: [u32; 8], + /// apply_grain, unsupported by this decoder. + pub apply_grain: bool, +} + +/// A DPB slot holding a reference picture, with the state AV1 keeps per reference. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Av1RefSlot { + /// DPB slot index. + pub slot: u32, + /// Frame type of the picture in the slot. + pub frame_type: Av1FrameType, + /// OrderHint of the picture in the slot. + pub order_hint: u8, + /// SavedOrderHints of the picture in the slot, per reference name. + pub ref_order_hints: [u8; 8], + /// RefFrameSignBias mask recorded when the picture was decoded. + pub sign_bias: u8, + /// disable_frame_end_update_cdf of the picture in the slot. + pub disable_frame_end_update_cdf: bool, + /// segmentation_enabled of the picture in the slot. + pub segmentation_enabled: bool, +} + +/// One frame to decode, with the tile data as one buffer. +#[derive(Debug, Clone, Copy)] +pub struct Av1DecodePicture<'a> { + /// Frame header. + pub header: &'a Av1FrameHeader, + /// DPB slot the picture is decoded into. + pub setup_slot: u32, + /// Slot of each reference name LAST to ALTREF, -1 when unused. + pub ref_frame_slot: [i32; 7], + /// Reference slots, each with a distinct slot index. + pub refs: &'a [Av1RefSlot], + /// Tile data, all tile groups concatenated. + pub tile_data: &'a [u8], + /// Byte offset of each tile in tile_data. + pub tile_offsets: &'a [u32], + /// Byte size of each tile. + pub tile_sizes: &'a [u32], +} + +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, + av1: vk::VideoDecodeAV1ProfileInfoKHR, +} + +impl Profile { + fn new() -> Box { + let mut p = Box::new(Profile { + info: vk::VideoProfileInfoKHR::builder() + .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_AV1) + .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) + .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .build(), + av1: vk::VideoDecodeAV1ProfileInfoKHR::builder() + .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN) + .film_grain_support(false) + .build(), + }); + p.info.next = &p.av1 as *const _ as *const c_void; + p + } +} + +/// An AV1 Main 8-bit 4:2:0 Vulkan Video decode session: NV12 DPB images per slot and a separate NV12 output image. +pub struct Av1DecodeSession { + gpu: Gpu, + family: u32, + queue: vk::Queue, + graphics: u32, + graphics_queue: vk::Queue, + video_session: vk::VideoSessionKHR, + session_memories: Vec, + params: Option, + sequence: Option, + max_extent: vk::Extent2D, + max_dpb_slots: u32, + max_active_refs: u32, + size_align: u64, + dpb: Vec, + output: Image, + bitstream: Buffer, + readback: Buffer, + decode_pool: vk::CommandPool, + decode_cb: vk::CommandBuffer, + graphics_pool: vk::CommandPool, + graphics_cb: vk::CommandBuffer, + fence: vk::Fence, + coded: bool, +} + +impl Av1DecodeSession { + /// Creates a session with its DPB, bitstream and readback buffers. + pub fn new(gpu: &Gpu, cfg: &Av1DecodeConfig) -> 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(), + )); + } + let family = gpu + .decode_family() + .ok_or_else(|| Error::Unsupported("AV1 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_AV1_EXTENSION.name) + { + return Err(Error::Unsupported("AV1 decode".into())); + } + let width = align(cfg.max_width, 16); + let height = align(cfg.max_height, 16); + let profile = Profile::new(); + 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!("AV1 decode {width}x{height}"))); + } + if !caps.distinct { + return Err(Error::Unsupported( + "AV1 decode with DPB and output in one image".into(), + )); + } + let max_active = caps.max_active_refs.min(cfg.max_dpb_slots); + + let queue = unsafe { gpu.device().get_device_queue(family, 0) }; + let graphics_queue = unsafe { gpu.device().get_device_queue(graphics, 0) }; + let mut s = Av1DecodeSession { + gpu: gpu.clone(), + family, + queue, + graphics, + graphics_queue, + video_session: Default::default(), + session_memories: Vec::new(), + params: None, + sequence: None, + max_extent: vk::Extent2D { width, height }, + max_dpb_slots: cfg.max_dpb_slots, + max_active_refs: max_active, + size_align: caps.size_align, + dpb: Vec::new(), + output: Default::default(), + bitstream: Default::default(), + readback: Default::default(), + decode_pool: Default::default(), + decode_cb: Default::default(), + graphics_pool: Default::default(), + graphics_cb: Default::default(), + fence: Default::default(), + coded: false, + }; + s.create_session(&profile, &caps, max_active)?; + s.create_resources(&profile, &caps)?; + s.init_dpb()?; + Ok(s) + } + + /// Replaces the session parameters with the given sequence header. + pub fn set_sequence_header(&mut self, seq: &Av1SequenceHeader) -> Result<(), Error> { + let c = &seq.color_config; + if seq.seq_profile != 0 + || c.bit_depth != 8 + || c.mono_chrome + || c.subsampling_x != 1 + || c.subsampling_y != 1 + { + return Err(Error::Unsupported( + "AV1 sequence other than Main 8-bit 4:2:0".into(), + )); + } + let gpu = self.gpu.clone(); + let d = gpu.device(); + let color = std_color(c); + let timing = seq.timing_info.as_ref().map(std_timing); + + let mut flags = zeroed::(); + flags.set_still_picture(u32::from(seq.still_picture)); + flags.set_reduced_still_picture_header(u32::from(seq.reduced_still_picture_header)); + flags.set_use_128x128_superblock(u32::from(seq.use_128x128_superblock)); + flags.set_enable_filter_intra(u32::from(seq.enable_filter_intra)); + flags.set_enable_intra_edge_filter(u32::from(seq.enable_intra_edge_filter)); + flags.set_enable_interintra_compound(u32::from(seq.enable_interintra_compound)); + flags.set_enable_masked_compound(u32::from(seq.enable_masked_compound)); + flags.set_enable_warped_motion(u32::from(seq.enable_warped_motion)); + flags.set_enable_dual_filter(u32::from(seq.enable_dual_filter)); + flags.set_enable_order_hint(u32::from(seq.enable_order_hint)); + flags.set_enable_jnt_comp(u32::from(seq.enable_jnt_comp)); + flags.set_enable_ref_frame_mvs(u32::from(seq.enable_ref_frame_mvs)); + flags.set_frame_id_numbers_present_flag(u32::from(seq.frame_id_numbers_present)); + flags.set_enable_superres(u32::from(seq.enable_superres)); + flags.set_enable_cdef(u32::from(seq.enable_cdef)); + flags.set_enable_restoration(u32::from(seq.enable_restoration)); + flags.set_film_grain_params_present(u32::from(seq.film_grain_params_present)); + flags.set_timing_info_present_flag(u32::from(timing.is_some())); + flags.set_initial_display_delay_present_flag(u32::from(seq.initial_display_delay_present)); + let std_seq = vk::video::StdVideoAV1SequenceHeader { + flags, + seq_profile: vk::video::STD_VIDEO_AV1_PROFILE_MAIN, + frame_width_bits_minus_1: seq.frame_width_bits_minus_1, + frame_height_bits_minus_1: seq.frame_height_bits_minus_1, + max_frame_width_minus_1: seq.max_frame_width_minus_1, + max_frame_height_minus_1: seq.max_frame_height_minus_1, + delta_frame_id_length_minus_2: seq.delta_frame_id_length_minus_2, + additional_frame_id_length_minus_1: seq.additional_frame_id_length_minus_1, + order_hint_bits_minus_1: seq.order_hint_bits_minus_1, + seq_force_integer_mv: seq.seq_force_integer_mv, + seq_force_screen_content_tools: seq.seq_force_screen_content_tools, + reserved1: [0; 5], + pColorConfig: &color, + pTimingInfo: timing.as_ref().map_or(std::ptr::null(), |t| t as *const _), + }; + + let mut av1 = vk::VideoDecodeAV1SessionParametersCreateInfoKHR::builder() + .std_sequence_header(&std_seq) + .build(); + let info = vk::VideoSessionParametersCreateInfoKHR::builder() + .video_session(self.video_session) + .push_next(&mut av1) + .build(); + let params = unsafe { + vk( + d.create_video_session_parameters_khr(&info, None), + "vkCreateVideoSessionParametersKHR", + )? + }; + if let Some(old) = self.params.replace(params) { + unsafe { d.destroy_video_session_parameters_khr(old, None) }; + } + self.sequence = Some(*seq); + Ok(()) + } + + /// Decodes one frame into its setup slot, referencing the given DPB slots. + pub fn decode(&mut self, pic: &Av1DecodePicture) -> Result<(), Error> { + let params = self + .params + .ok_or_else(|| Error::Invalid("sequence header not set".into()))?; + let seq = self + .sequence + .ok_or_else(|| Error::Invalid("sequence header not set".into()))?; + let h = pic.header; + if h.apply_grain { + return Err(Error::Unsupported("AV1 film grain".into())); + } + let extent = vk::Extent2D { + width: h.upscaled_width, + height: h.frame_height, + }; + if extent.width == 0 + || extent.height == 0 + || extent.width > self.max_extent.width + || extent.height > self.max_extent.height + { + return Err(Error::Invalid("frame size".into())); + } + let tiles = &h.tile_info; + let cols = tiles.cols as usize; + let rows = tiles.rows as usize; + let count = cols * rows; + if count == 0 + || pic.tile_offsets.len() != count + || pic.tile_sizes.len() != count + || tiles.mi_col_starts.len() != cols + 1 + || tiles.mi_row_starts.len() != rows + 1 + || tiles.width_in_sbs_minus_1.len() != cols + || tiles.height_in_sbs_minus_1.len() != rows + { + return Err(Error::Invalid("tile layout".into())); + } + if pic + .tile_offsets + .iter() + .zip(pic.tile_sizes) + .any(|(&o, &s)| u64::from(o) + u64::from(s) > pic.tile_data.len() as u64) + { + return Err(Error::Invalid("tile outside tile data".into())); + } + if pic.tile_data.len() as u64 > self.bitstream.size { + return Err(Error::Invalid( + "tile data larger than bitstream buffer".into(), + )); + } + if pic.setup_slot >= self.max_dpb_slots { + return Err(Error::Invalid("setup DPB slot".into())); + } + if pic.refs.len() > self.max_active_refs as usize { + return Err(Error::Invalid("too many reference pictures".into())); + } + for (i, r) in pic.refs.iter().enumerate() { + if r.slot >= self.max_dpb_slots + || r.slot == pic.setup_slot + || pic.refs[..i].iter().any(|o| o.slot == r.slot) + { + return Err(Error::Invalid("reference DPB slot".into())); + } + } + if pic + .ref_frame_slot + .iter() + .any(|&s| s >= 0 && !pic.refs.iter().any(|r| i32::try_from(r.slot) == Ok(s))) + { + return Err(Error::Invalid( + "reference name without a reference slot".into(), + )); + } + + let ptr = self + .bitstream + .ptr + .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?; + let buf = unsafe { std::slice::from_raw_parts_mut(ptr, self.bitstream.size as usize) }; + buf[..pic.tile_data.len()].copy_from_slice(pic.tile_data); + let range = align_u64(pic.tile_data.len() as u64, self.size_align); + + let gpu = self.gpu.clone(); + let d = gpu.device(); + let cb = self.decode_cb; + let pr: Vec = self + .dpb + .iter() + .map(|i| picture_resource(i.view, extent)) + .collect(); + + let setup_std = ref_info( + h.frame_type, + h.order_hint, + sign_bias_mask(&seq, h.order_hint, &h.order_hints), + h.order_hints, + h.disable_frame_end_update_cdf, + h.segmentation.enabled, + ); + let mut setup_dpb = vk::VideoDecodeAV1DpbSlotInfoKHR::builder() + .std_reference_info(&setup_std) + .build(); + let setup = vk::VideoReferenceSlotInfoKHR::builder() + .slot_index(pic.setup_slot as i32) + .picture_resource(&pr[pic.setup_slot as usize]) + .push_next(&mut setup_dpb) + .build(); + + let ref_std: Vec = pic + .refs + .iter() + .map(|r| { + ref_info( + r.frame_type, + r.order_hint, + r.sign_bias, + r.ref_order_hints, + r.disable_frame_end_update_cdf, + r.segmentation_enabled, + ) + }) + .collect(); + let mut ref_dpb: Vec = ref_std + .iter() + .map(|s| { + vk::VideoDecodeAV1DpbSlotInfoKHR::builder() + .std_reference_info(s) + .build() + }) + .collect(); + let refs: Vec = pic + .refs + .iter() + .zip(ref_dpb.iter_mut()) + .map(|(r, dpb)| { + vk::VideoReferenceSlotInfoKHR::builder() + .slot_index(r.slot as i32) + .picture_resource(&pr[r.slot as usize]) + .push_next(dpb) + .build() + }) + .collect(); + + let mut begin: Vec = vec![ + vk::VideoReferenceSlotInfoKHR::builder() + .slot_index(-1) + .picture_resource(&pr[pic.setup_slot as usize]) + .build(), + ]; + begin.extend(pic.refs.iter().map(|r| { + vk::VideoReferenceSlotInfoKHR::builder() + .slot_index(r.slot as i32) + .picture_resource(&pr[r.slot as usize]) + .build() + })); + + let tile = std_tile(tiles); + let quant = std_quant(&h.quantization); + let seg = std_segmentation(&h.segmentation); + let lf = std_loop_filter(&h.loop_filter); + let cdef = std_cdef(&h.cdef); + let lr = std_loop_restoration(&h.loop_restoration); + let gm = std_global_motion(&h.global_motion); + + let mut std_pic = zeroed::(); + std_pic.flags = picture_flags(h); + std_pic.frame_type = std_frame_type(h.frame_type); + std_pic.current_frame_id = h.current_frame_id; + std_pic.OrderHint = h.order_hint; + std_pic.primary_ref_frame = h.primary_ref_frame; + std_pic.refresh_frame_flags = h.refresh_frame_flags; + std_pic.interpolation_filter = std_interpolation(h.interpolation_filter); + std_pic.TxMode = std_tx_mode(h.tx_mode); + std_pic.delta_q_res = h.delta.q_res; + std_pic.delta_lf_res = h.delta.lf_res; + std_pic.SkipModeFrame = h.skip_mode_frame; + std_pic.coded_denom = if h.use_superres { + h.superres_denom.saturating_sub(9) + } else { + 0 + }; + std_pic.OrderHints = h.order_hints; + std_pic.expectedFrameId = h.expected_frame_id; + std_pic.pTileInfo = &tile; + std_pic.pQuantization = &quant; + std_pic.pSegmentation = &seg; + std_pic.pLoopFilter = &lf; + std_pic.pCDEF = &cdef; + std_pic.pLoopRestoration = &lr; + std_pic.pGlobalMotion = &gm; + + let mut av1 = vk::VideoDecodeAV1PictureInfoKHR { + std_picture_info: &std_pic, + reference_name_slot_indices: pic.ref_frame_slot, + frame_header_offset: 0, + tile_count: count as u32, + tile_offsets: pic.tile_offsets.as_ptr(), + tile_sizes: pic.tile_sizes.as_ptr(), + ..Default::default() + }; + let decode = vk::VideoDecodeInfoKHR::builder() + .src_buffer(self.bitstream.buffer) + .src_buffer_offset(0) + .src_buffer_range(range) + .dst_picture_resource(picture_resource(self.output.view, extent)) + .setup_reference_slot(&setup) + .reference_slots(&refs) + .push_next(&mut av1) + .build(); + let begin_info = vk::VideoBeginCodingInfoKHR::builder() + .video_session(self.video_session) + .video_session_parameters(params) + .reference_slots(&begin) + .build(); + let reset = !self.coded; + + unsafe { + let info = vk::CommandBufferBeginInfo::builder() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + vk(d.begin_command_buffer(cb, &info), "vkBeginCommandBuffer")?; + barrier( + d, + cb, + self.output.image, + ( + vk::ImageLayout::UNDEFINED, + vk::PipelineStageFlags2::NONE, + vk::AccessFlags2::NONE, + ), + ( + vk::ImageLayout::VIDEO_DECODE_DST_KHR, + vk::PipelineStageFlags2::ALL_COMMANDS, + vk::AccessFlags2::NONE, + ), + ); + d.cmd_begin_video_coding_khr(cb, &begin_info); + if reset { + let control = vk::VideoCodingControlInfoKHR::builder() + .flags(vk::VideoCodingControlFlagsKHR::RESET) + .build(); + d.cmd_control_video_coding_khr(cb, &control); + } + d.cmd_decode_video_khr(cb, &decode); + let end = vk::VideoEndCodingInfoKHR::builder().build(); + d.cmd_end_video_coding_khr(cb, &end); + vk(d.end_command_buffer(cb), "vkEndCommandBuffer")?; + } + submit(d, self.fence, self.queue, cb)?; + self.coded = true; + Ok(()) + } + + /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV). + pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { + if !self.coded { + return Err(Error::Invalid("nothing decoded".into())); + } + if width == 0 + || height == 0 + || width % 2 != 0 + || height % 2 != 0 + || width > self.max_extent.width + || height > self.max_extent.height + { + return Err(Error::Invalid("readback size".into())); + } + let gpu = self.gpu.clone(); + let d = gpu.device(); + let cb = self.graphics_cb; + let image = self.output.image; + let luma = width as usize * height as usize; + let copies = [ + copy_region(0, PLANE_0, width, height), + copy_region(luma as u64, PLANE_1, width / 2, height / 2), + ]; + unsafe { + let info = vk::CommandBufferBeginInfo::builder() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + vk(d.begin_command_buffer(cb, &info), "vkBeginCommandBuffer")?; + barrier( + d, + cb, + image, + ( + vk::ImageLayout::VIDEO_DECODE_DST_KHR, + vk::PipelineStageFlags2::ALL_COMMANDS, + vk::AccessFlags2::NONE, + ), + ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_READ, + ), + ); + d.cmd_copy_image_to_buffer( + cb, + image, + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + self.readback.buffer, + &copies, + ); + barrier( + d, + cb, + image, + ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_READ, + ), + ( + vk::ImageLayout::VIDEO_DECODE_DST_KHR, + vk::PipelineStageFlags2::ALL_COMMANDS, + vk::AccessFlags2::NONE, + ), + ); + vk(d.end_command_buffer(cb), "vkEndCommandBuffer")?; + } + submit(d, self.fence, self.graphics_queue, cb)?; + let ptr = self + .readback + .ptr + .ok_or_else(|| Error::Invalid("readback buffer not mapped".into()))?; + let bytes = unsafe { std::slice::from_raw_parts(ptr, luma * 3 / 2) }; + Ok((bytes[..luma].to_vec(), bytes[luma..].to_vec())) + } + + fn create_session(&mut self, profile: &Profile, caps: &Caps, active: u32) -> Result<(), Error> { + let gpu = self.gpu.clone(); + let d = gpu.device(); + let info = vk::VideoSessionCreateInfoKHR::builder() + .queue_family_index(self.family) + .video_profile(&profile.info) + .picture_format(NV12) + .max_coded_extent(self.max_extent) + .reference_picture_format(NV12) + .max_dpb_slots(self.max_dpb_slots) + .max_active_reference_pictures(active) + .std_header_version(&caps.std_header_version) + .build(); + self.video_session = unsafe { + vk( + d.create_video_session_khr(&info, None), + "vkCreateVideoSessionKHR", + )? + }; + let reqs = unsafe { + vk( + d.get_video_session_memory_requirements_khr(self.video_session), + "vkGetVideoSessionMemoryRequirementsKHR", + )? + }; + let mut binds = Vec::new(); + for r in &reqs { + let mem = allocate( + &gpu, + r.memory_requirements, + vk::MemoryPropertyFlags::DEVICE_LOCAL, + )?; + self.session_memories.push(mem); + binds.push( + vk::BindVideoSessionMemoryInfoKHR::builder() + .memory_bind_index(r.memory_bind_index) + .memory(mem) + .memory_size(r.memory_requirements.size) + .build(), + ); + } + unsafe { + vk( + d.bind_video_session_memory_khr(self.video_session, &binds), + "vkBindVideoSessionMemoryKHR", + ) + } + } + + fn create_resources(&mut self, profile: &Profile, caps: &Caps) -> Result<(), Error> { + let gpu = self.gpu.clone(); + let d = gpu.device(); + let mut list = vk::VideoProfileListInfoKHR::builder() + .profiles(std::slice::from_ref(&profile.info)) + .build(); + let width = self.max_extent.width; + let height = self.max_extent.height; + let families = if self.family == self.graphics { + vec![self.family] + } else { + vec![self.family, self.graphics] + }; + let dpb = vk::ImageUsageFlags::VIDEO_DECODE_DPB_KHR; + for _ in 0..self.max_dpb_slots { + let image = new_image(&gpu, width, height, dpb, dpb, &[self.family], &mut list)?; + self.dpb.push(image); + } + let output = vk::ImageUsageFlags::VIDEO_DECODE_DST_KHR | vk::ImageUsageFlags::TRANSFER_SRC; + self.output = new_image( + &gpu, + width, + height, + output, + vk::ImageUsageFlags::VIDEO_DECODE_DST_KHR, + &families, + &mut list, + )?; + + let bitstream_size = align_u64(width as u64 * height as u64 * 3 + 65536, caps.size_align); + self.bitstream = new_buffer( + &gpu, + bitstream_size, + vk::BufferUsageFlags::VIDEO_DECODE_SRC_KHR, + vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, + Some(&mut list), + )?; + self.readback = new_buffer( + &gpu, + width as u64 * height as u64 * 3 / 2, + vk::BufferUsageFlags::TRANSFER_DST, + vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, + None, + )?; + + self.decode_pool = create_pool(d, self.family)?; + self.decode_cb = alloc_cb(d, self.decode_pool)?; + self.graphics_pool = create_pool(d, self.graphics)?; + self.graphics_cb = alloc_cb(d, self.graphics_pool)?; + self.fence = unsafe { + vk( + d.create_fence(&vk::FenceCreateInfo::builder().build(), None), + "vkCreateFence", + )? + }; + Ok(()) + } + + fn init_dpb(&mut self) -> Result<(), Error> { + let gpu = self.gpu.clone(); + let d = gpu.device(); + let cb = self.decode_cb; + unsafe { + let info = vk::CommandBufferBeginInfo::builder() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + vk(d.begin_command_buffer(cb, &info), "vkBeginCommandBuffer")?; + for img in &self.dpb { + barrier( + d, + cb, + img.image, + ( + vk::ImageLayout::UNDEFINED, + vk::PipelineStageFlags2::NONE, + vk::AccessFlags2::NONE, + ), + ( + vk::ImageLayout::VIDEO_DECODE_DPB_KHR, + vk::PipelineStageFlags2::ALL_COMMANDS, + vk::AccessFlags2::NONE, + ), + ); + } + vk(d.end_command_buffer(cb), "vkEndCommandBuffer")?; + } + submit(d, self.fence, self.queue, cb) + } +} + +impl Drop for Av1DecodeSession { + fn drop(&mut self) { + let gpu = self.gpu.clone(); + let d = gpu.device(); + unsafe { + let _ = d.device_wait_idle(); + d.destroy_fence(self.fence, None); + d.destroy_command_pool(self.decode_pool, None); + d.destroy_command_pool(self.graphics_pool, None); + for img in self.dpb.iter().chain(std::iter::once(&self.output)) { + d.destroy_image_view(img.view, None); + d.destroy_image(img.image, None); + d.free_memory(img.memory, None); + } + for buf in [&self.bitstream, &self.readback] { + d.destroy_buffer(buf.buffer, None); + d.free_memory(buf.memory, None); + } + if let Some(params) = self.params { + d.destroy_video_session_parameters_khr(params, None); + } + d.destroy_video_session_khr(self.video_session, None); + for m in &self.session_memories { + d.free_memory(*m, None); + } + } + } +} + +fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result { + let mut av1 = vk::VideoDecodeAV1CapabilitiesKHR::builder(); + let mut decode = vk::VideoDecodeCapabilitiesKHR::builder(); + let mut caps = vk::VideoCapabilitiesKHR::builder() + .push_next(&mut av1) + .push_next(&mut decode); + unsafe { + vk( + gpu.instance().get_physical_device_video_capabilities_khr( + gpu.physical(), + profile, + &mut caps, + ), + "vkGetPhysicalDeviceVideoCapabilitiesKHR", + )?; + } + 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 relative_dist(a: u8, b: u8, bits: u32) -> i32 { + let diff = i32::from(a) - i32::from(b); + let m: i32 = 1 << (bits - 1); + (diff & (m - 1)) - (diff & m) +} + +fn sign_bias_mask(seq: &Av1SequenceHeader, hint: u8, hints: &[u8; 8]) -> u8 { + if !seq.enable_order_hint { + return 0; + } + let bits = u32::from(seq.order_hint_bits_minus_1) + 1; + (1..8) + .filter(|&n| relative_dist(hints[n], hint, bits) > 0) + .fold(0u8, |mask, n| mask | (1 << n)) +} + +fn ref_info( + frame_type: Av1FrameType, + order_hint: u8, + sign_bias: u8, + saved_order_hints: [u8; 8], + disable_frame_end_update_cdf: bool, + segmentation_enabled: bool, +) -> vk::video::StdVideoDecodeAV1ReferenceInfo { + let mut info = zeroed::(); + info.flags + .set_disable_frame_end_update_cdf(u32::from(disable_frame_end_update_cdf)); + info.flags + .set_segmentation_enabled(u32::from(segmentation_enabled)); + info.frame_type = frame_type as u8; + info.RefFrameSignBias = sign_bias; + info.OrderHint = order_hint; + info.SavedOrderHints = saved_order_hints; + info +} + +fn std_color(c: &Av1ColorConfig) -> vk::video::StdVideoAV1ColorConfig { + let mut flags = zeroed::(); + flags.set_mono_chrome(u32::from(c.mono_chrome)); + flags.set_color_range(u32::from(c.color_range)); + flags.set_separate_uv_delta_q(u32::from(c.separate_uv_delta_q)); + vk::video::StdVideoAV1ColorConfig { + flags, + BitDepth: c.bit_depth, + subsampling_x: c.subsampling_x, + subsampling_y: c.subsampling_y, + reserved1: 0, + color_primaries: vk::video::StdVideoAV1ColorPrimaries(i32::from(c.color_primaries)), + transfer_characteristics: vk::video::StdVideoAV1TransferCharacteristics(i32::from( + c.transfer_characteristics, + )), + matrix_coefficients: vk::video::StdVideoAV1MatrixCoefficients(i32::from( + c.matrix_coefficients, + )), + chroma_sample_position: vk::video::StdVideoAV1ChromaSamplePosition(i32::from( + c.chroma_sample_position, + )), + } +} + +fn std_timing(t: &Av1TimingInfo) -> vk::video::StdVideoAV1TimingInfo { + let mut flags = zeroed::(); + flags.set_equal_picture_interval(u32::from(t.equal_picture_interval)); + vk::video::StdVideoAV1TimingInfo { + flags, + 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_minus_1, + } +} + +fn std_tile(t: &Av1TileInfo) -> vk::video::StdVideoAV1TileInfo { + let mut flags = zeroed::(); + flags.set_uniform_tile_spacing_flag(u32::from(t.uniform_spacing)); + vk::video::StdVideoAV1TileInfo { + flags, + TileCols: t.cols, + TileRows: t.rows, + context_update_tile_id: t.context_update_tile_id, + tile_size_bytes_minus_1: t.tile_size_bytes_minus_1, + reserved1: [0; 7], + pMiColStarts: t.mi_col_starts.as_ptr(), + pMiRowStarts: t.mi_row_starts.as_ptr(), + pWidthInSbsMinus1: t.width_in_sbs_minus_1.as_ptr(), + pHeightInSbsMinus1: t.height_in_sbs_minus_1.as_ptr(), + } +} + +fn std_quant(q: &Av1Quantization) -> vk::video::StdVideoAV1Quantization { + let mut flags = zeroed::(); + flags.set_using_qmatrix(u32::from(q.using_qmatrix)); + vk::video::StdVideoAV1Quantization { + flags, + base_q_idx: q.base_q_idx, + DeltaQYDc: q.delta_q_y_dc, + DeltaQUDc: q.delta_q_u_dc, + DeltaQUAc: q.delta_q_u_ac, + DeltaQVDc: q.delta_q_v_dc, + DeltaQVAc: q.delta_q_v_ac, + qm_y: q.qm_y, + qm_u: q.qm_u, + qm_v: q.qm_v, + } +} + +fn std_segmentation(s: &Av1Segmentation) -> vk::video::StdVideoAV1Segmentation { + let mut out = zeroed::(); + for segment in 0..8 { + for feature in 0..8 { + if s.feature_enabled[segment][feature] { + out.FeatureEnabled[segment] |= 1 << feature; + } + } + out.FeatureData[segment] = s.feature_data[segment]; + } + out +} + +fn std_loop_filter(l: &Av1LoopFilter) -> vk::video::StdVideoAV1LoopFilter { + 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::StdVideoAV1LoopFilter { + flags, + loop_filter_level: l.level, + loop_filter_sharpness: l.sharpness, + update_ref_delta: 0, + loop_filter_ref_deltas: l.ref_deltas, + update_mode_delta: 0, + loop_filter_mode_deltas: l.mode_deltas, + } +} + +fn std_cdef(c: &Av1Cdef) -> vk::video::StdVideoAV1CDEF { + vk::video::StdVideoAV1CDEF { + cdef_damping_minus_3: c.damping_minus_3, + cdef_bits: c.bits, + cdef_y_pri_strength: c.y_pri, + cdef_y_sec_strength: c.y_sec, + cdef_uv_pri_strength: c.uv_pri, + cdef_uv_sec_strength: c.uv_sec, + } +} + +fn std_loop_restoration(l: &Av1LoopRestoration) -> vk::video::StdVideoAV1LoopRestoration { + vk::video::StdVideoAV1LoopRestoration { + FrameRestorationType: l.frame_restoration_type.map(std_restoration), + LoopRestorationSize: l.loop_restoration_size, + } +} + +fn std_global_motion(g: &[Av1GlobalMotion; 8]) -> vk::video::StdVideoAV1GlobalMotion { + vk::video::StdVideoAV1GlobalMotion { + GmType: g.map(|m| m.model as u8), + gm_params: g.map(|m| m.params), + } +} + +fn picture_flags(h: &Av1FrameHeader) -> vk::video::StdVideoDecodeAV1PictureInfoFlags { + let lr = h.loop_restoration.frame_restoration_type; + let mut f = zeroed::(); + f.set_error_resilient_mode(u32::from(h.error_resilient_mode)); + f.set_disable_cdf_update(u32::from(h.disable_cdf_update)); + f.set_use_superres(u32::from(h.use_superres)); + f.set_render_and_frame_size_different(u32::from( + h.render_width != h.upscaled_width || h.render_height != h.frame_height, + )); + f.set_allow_screen_content_tools(u32::from(h.allow_screen_content_tools)); + f.set_is_filter_switchable(u32::from( + h.interpolation_filter == Av1InterpolationFilter::Switchable, + )); + f.set_force_integer_mv(u32::from(h.force_integer_mv)); + f.set_frame_size_override_flag(u32::from(h.frame_size_override_flag)); + f.set_allow_intrabc(u32::from(h.allow_intrabc)); + f.set_frame_refs_short_signaling(u32::from(h.frame_refs_short_signaling)); + f.set_allow_high_precision_mv(u32::from(h.allow_high_precision_mv)); + f.set_is_motion_mode_switchable(u32::from(h.is_motion_mode_switchable)); + f.set_use_ref_frame_mvs(u32::from(h.use_ref_frame_mvs)); + f.set_disable_frame_end_update_cdf(u32::from(h.disable_frame_end_update_cdf)); + f.set_allow_warped_motion(u32::from(h.allow_warped_motion)); + f.set_reduced_tx_set(u32::from(h.reduced_tx_set)); + f.set_reference_select(u32::from(h.reference_select)); + f.set_skip_mode_present(u32::from(h.skip_mode_present)); + f.set_delta_q_present(u32::from(h.delta.q_present)); + f.set_delta_lf_present(u32::from(h.delta.lf_present)); + f.set_delta_lf_multi(u32::from(h.delta.lf_multi)); + f.set_segmentation_enabled(u32::from(h.segmentation.enabled)); + f.set_segmentation_update_map(u32::from(h.segmentation.update_map)); + f.set_segmentation_temporal_update(u32::from(h.segmentation.temporal_update)); + f.set_segmentation_update_data(u32::from(h.segmentation.update_data)); + f.set_UsesLr(u32::from(lr.iter().any(|&t| t != Av1Restoration::None))); + f.set_usesChromaLr(u32::from( + lr[1..].iter().any(|&t| t != Av1Restoration::None), + )); + f +} + +fn std_frame_type(t: Av1FrameType) -> vk::video::StdVideoAV1FrameType { + vk::video::StdVideoAV1FrameType(i32::from(t as u8)) +} + +fn std_interpolation(f: Av1InterpolationFilter) -> vk::video::StdVideoAV1InterpolationFilter { + vk::video::StdVideoAV1InterpolationFilter(i32::from(f as u8)) +} + +fn std_tx_mode(m: Av1TxMode) -> vk::video::StdVideoAV1TxMode { + vk::video::StdVideoAV1TxMode(i32::from(m as u8)) +} + +fn std_restoration(r: Av1Restoration) -> vk::video::StdVideoAV1FrameRestorationType { + vk::video::StdVideoAV1FrameRestorationType(i32::from(r as u8)) +} diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index 7bbc4768..cb3c7502 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -6,6 +6,7 @@ use std::ffi::c_char; use std::fmt; use std::sync::Arc; +mod av1_decode; mod av1_encode; mod h264_decode; mod h264_encode; @@ -13,6 +14,12 @@ mod h265_decode; mod h265_encode; mod rgb_convert; +pub use av1_decode::{ + Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, + Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, + Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation, + Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, +}; pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref}; pub use h264_decode::{ H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,