From 6f8f2a3fff601d5dc714593d00d4d1efb7e74970 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 09:42:21 +0300 Subject: [PATCH] vk-video-ffi: H265DecodeSession (Main 8-bit, distinct DPB/output, resolved short-term RPS); smoke example bit-exact vs ffmpeg --- Cargo.lock | 1 + crates/ec-vk/src/lib.rs | 4 +- shims/vk-video-ffi/Cargo.toml | 1 + .../examples/h265_decode_smoke.rs | 282 ++++ shims/vk-video-ffi/src/h264_decode.rs | 28 +- shims/vk-video-ffi/src/h265_decode.rs | 1297 +++++++++++++++++ shims/vk-video-ffi/src/lib.rs | 6 + 7 files changed, 1604 insertions(+), 15 deletions(-) create mode 100644 shims/vk-video-ffi/examples/h265_decode_smoke.rs create mode 100644 shims/vk-video-ffi/src/h265_decode.rs diff --git a/Cargo.lock b/Cargo.lock index 7b75c2a1..4eaecbc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1896,6 +1896,7 @@ name = "vk-video-ffi" version = "0.1.0" dependencies = [ "ec-h264-syntax", + "ec-h265-syntax", "vulkanalia", ] diff --git a/crates/ec-vk/src/lib.rs b/crates/ec-vk/src/lib.rs index cfd2d23d..1f920297 100644 --- a/crates/ec-vk/src/lib.rs +++ b/crates/ec-vk/src/lib.rs @@ -11,7 +11,9 @@ 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, RateControl, ScalingLists, + H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, + H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, + H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, }; /// Encoder settings. diff --git a/shims/vk-video-ffi/Cargo.toml b/shims/vk-video-ffi/Cargo.toml index 677e4251..1fc5d632 100644 --- a/shims/vk-video-ffi/Cargo.toml +++ b/shims/vk-video-ffi/Cargo.toml @@ -10,3 +10,4 @@ vulkanalia = { version = "0.35", features = ["libloading"] } [dev-dependencies] ec-h264-syntax.workspace = true +ec-h265-syntax.workspace = true diff --git a/shims/vk-video-ffi/examples/h265_decode_smoke.rs b/shims/vk-video-ffi/examples/h265_decode_smoke.rs new file mode 100644 index 00000000..32769b0a --- /dev/null +++ b/shims/vk-video-ffi/examples/h265_decode_smoke.rs @@ -0,0 +1,282 @@ +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +use ec_h265_syntax::{ + NalUnitType, Pps, ProfileTierLevel, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps, + split_annex_b, +}; +use vk_video_ffi::{ + Gpu, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, + H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265ScalingLists, + H265ShortTermRefPicSet, H265Sps, H265Vps, +}; + +fn ptl(p: &ProfileTierLevel) -> H265ProfileTierLevel { + H265ProfileTierLevel { + tier_flag: p.tier_flag, + progressive_source: p.progressive_source, + interlaced_source: p.interlaced_source, + non_packed_constraint: p.non_packed_constraint, + frame_only_constraint: p.frame_only_constraint, + profile_idc: p.profile_idc, + level_idc: p.level_idc, + } +} + +fn dpbm( + max_latency_increase_plus1: u32, + max_dec_pic_buffering_minus1: u32, + reorder: u32, +) -> H265DecPicBufMgr { + H265DecPicBufMgr { + max_latency_increase_plus1: [max_latency_increase_plus1; 7], + max_dec_pic_buffering_minus1: [max_dec_pic_buffering_minus1 as u8; 7], + max_num_reorder_pics: [reorder as u8; 7], + } +} + +fn lists(l: &ScalingList) -> H265ScalingLists { + let c = &l.coefficients; + H265ScalingLists { + list_4x4: std::array::from_fn(|i| c[0][i][..16].try_into().unwrap()), + list_8x8: std::array::from_fn(|i| c[1][i]), + list_16x16: std::array::from_fn(|i| c[2][i]), + list_32x32: std::array::from_fn(|i| c[3][3 * i]), + dc_16x16: std::array::from_fn(|i| l.dc[2][i]), + dc_32x32: std::array::from_fn(|i| l.dc[3][3 * i]), + } +} + +fn rps(r: &ShortTermRefPicSet) -> H265ShortTermRefPicSet { + let (n0, n1) = (r.num_negative as usize, r.num_positive as usize); + H265ShortTermRefPicSet { + delta_poc_s0: r.delta_poc_s0[..n0].to_vec(), + used_by_curr_pic_s0: r.used_s0[..n0].to_vec(), + delta_poc_s1: r.delta_poc_s1[..n1].to_vec(), + used_by_curr_pic_s1: r.used_s1[..n1].to_vec(), + } +} + +fn main() { + let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); + let stream = dir.join("idr.hevc"); + let reference = dir.join("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", + "libx265", + "-x265-params", + "log-level=error", + ]) + .args(["-f", "hevc"]) + .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 data = fs::read(&stream).expect("read stream"); + let nals = split_annex_b(&data); + let mut vps_list: Vec = Vec::new(); + let mut sps_list: Vec = Vec::new(); + let mut pps_list: Vec = Vec::new(); + let mut slice_nals: Vec> = Vec::new(); + for nal in &nals { + match nal.header.nal_type { + NalUnitType::Vps => vps_list.push(Vps::parse(&nal.rbsp()).expect("VPS")), + NalUnitType::Sps => sps_list.push(Sps::parse(&nal.rbsp()).expect("SPS")), + NalUnitType::Pps => pps_list.push(Pps::parse(&nal.rbsp()).expect("PPS")), + t if t.is_vcl() => { + let mut raw = nal.header.to_bytes().to_vec(); + raw.extend_from_slice(nal.payload); + slice_nals.push(raw); + } + _ => {} + } + } + let first = nals + .iter() + .find(|n| n.header.nal_type.is_vcl()) + .expect("slice"); + let vps = &vps_list[0]; + let pps = &pps_list[0]; + let sps = sps_list + .iter() + .find(|s| s.id == pps.sps_id) + .expect("SPS for PPS"); + let (sh, pos) = + SliceHeader::parse(&first.rbsp(), sps, pps, first.header.nal_type).expect("slice header"); + + let h265_vps = H265Vps { + id: vps.id, + max_sub_layers_minus1: 0, + profile_tier_level: ptl(&vps.ptl), + dec_pic_buf_mgr: dpbm( + 0, + vps.max_dec_pic_buffering_minus1, + vps.max_num_reorder_pics, + ), + }; + let c = &sps.conf_win; + let h265_sps = H265Sps { + id: sps.id as u8, + vps_id: sps.vps_id, + max_sub_layers_minus1: 0, + profile_tier_level: ptl(&sps.ptl), + chroma_format_idc: sps.chroma_format_idc as u8, + pic_width_in_luma_samples: sps.pic_width_in_luma_samples, + pic_height_in_luma_samples: sps.pic_height_in_luma_samples, + conformance_window: [c.left, c.right, c.top, c.bottom], + bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, + bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, + log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, + log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8, + log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8, + log2_min_luma_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, + log2_diff_max_min_luma_transform_block_size: sps.log2_diff_max_min_tb_size as u8, + max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, + max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, + pcm: sps.pcm.map(|(a, b, c, d, e)| H265Pcm { + bit_depth_luma_minus1: a as u8, + bit_depth_chroma_minus1: b as u8, + log2_min_luma_coding_block_size_minus3: c as u8, + log2_diff_max_min_luma_coding_block_size: d as u8, + loop_filter_disabled: e, + }), + dec_pic_buf_mgr: dpbm( + sps.max_latency_increase_plus1, + sps.max_dec_pic_buffering_minus1, + sps.max_num_reorder_pics, + ), + scaling_list_enabled: sps.scaling_list_enabled, + scaling_lists: sps.scaling_list.as_ref().map(lists), + amp_enabled: sps.amp_enabled, + sample_adaptive_offset_enabled: sps.sao_enabled, + long_term_ref_pics_present: sps.long_term_ref_pics_present, + long_term_ref_pics_sps: sps + .long_term_ref_pics_sps + .iter() + .map(|&(poc_lsb, used_by_curr_pic)| H265LongTermRefPicSps { + poc_lsb, + used_by_curr_pic, + }) + .collect(), + temporal_mvp_enabled: sps.temporal_mvp_enabled, + strong_intra_smoothing_enabled: sps.strong_intra_smoothing, + short_term_ref_pic_sets: sps.short_term_ref_pic_sets.iter().map(rps).collect(), + }; + let h265_pps = H265Pps { + id: pps.id as u8, + sps_id: pps.sps_id as u8, + dependent_slice_segments_enabled: pps.dependent_slice_segments_enabled, + output_flag_present: pps.output_flag_present, + num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, + sign_data_hiding_enabled: pps.sign_data_hiding_enabled, + cabac_init_present: pps.cabac_init_present, + num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8, + num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8, + init_qp_minus26: pps.init_qp_minus26 as i8, + constrained_intra_pred: pps.constrained_intra_pred, + transform_skip_enabled: pps.transform_skip_enabled, + cu_qp_delta_enabled: pps.cu_qp_delta_enabled, + diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, + cb_qp_offset: pps.cb_qp_offset as i8, + cr_qp_offset: pps.cr_qp_offset as i8, + slice_chroma_qp_offsets_present: pps.slice_chroma_qp_offsets_present, + weighted_pred: pps.weighted_pred, + weighted_bipred: pps.weighted_bipred, + transquant_bypass_enabled: pps.transquant_bypass_enabled, + tiles_enabled: pps.tiles_enabled, + entropy_coding_sync_enabled: pps.entropy_coding_sync_enabled, + num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, + num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, + uniform_spacing: pps.uniform_spacing, + column_width_minus1: pps.column_width_minus1.iter().map(|&w| w as u16).collect(), + row_height_minus1: pps.row_height_minus1.iter().map(|&h| h as u16).collect(), + loop_filter_across_tiles_enabled: pps.loop_filter_across_tiles_enabled, + loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, + deblocking_filter_control_present: pps.deblocking_filter_control_present, + deblocking_filter_override_enabled: pps.deblocking_filter_override_enabled, + deblocking_filter_disabled: pps.deblocking_filter_disabled, + beta_offset_div2: pps.beta_offset_div2 as i8, + tc_offset_div2: pps.tc_offset_div2 as i8, + scaling_lists: pps.scaling_list.as_ref().map(lists), + lists_modification_present: pps.lists_modification_present, + log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, + slice_segment_header_extension_present: pps.slice_segment_header_extension_present, + }; + + let (w, h) = ( + h265_sps.pic_width_in_luma_samples, + h265_sps.pic_height_in_luma_samples, + ); + let gpu = Gpu::open().expect("open GPU"); + println!("device: {}", gpu.device_name()); + let cfg = H265DecodeConfig { + max_width: w, + max_height: h, + max_dpb_slots: 2, + }; + let mut session = H265DecodeSession::new(&gpu, &cfg).expect("decode session"); + session + .set_parameters( + std::slice::from_ref(&h265_vps), + std::slice::from_ref(&h265_sps), + std::slice::from_ref(&h265_pps), + ) + .expect("parameters"); + let slices: Vec<&[u8]> = slice_nals.iter().map(|v| v.as_slice()).collect(); + let pic = H265DecodePicture { + vps_id: sps.vps_id, + sps_id: sps.id as u8, + pps_id: pps.id as u8, + irap: first.header.nal_type.is_irap(), + idr: first.header.nal_type.is_idr(), + reference: true, + poc: 0, + setup_slot: 0, + short_term_ref_pic_set_sps: sh.short_term_ref_pic_set_sps_flag, + num_delta_pocs_of_ref_rps_idx: 0, + st_rps_bits: pos.st_rps_bits, + st_curr_before: &[], + st_curr_after: &[], + lt_curr: &[], + refs: &[], + slices: &slices, + }; + session.decode(&pic).expect("decode"); + let (y, uv) = session.read_output(w, h).expect("read slot"); + + let ref_data = fs::read(&reference).expect("read reference"); + let luma = (w * h) as usize; + let chroma = luma / 4; + let ref_y = &ref_data[..luma]; + let ref_u = &ref_data[luma..luma + chroma]; + let ref_v = &ref_data[luma + chroma..luma + 2 * chroma]; + let mad = |a: &[u8], b: &[u8]| { + a.iter() + .zip(b) + .map(|(&x, &y)| (x as f64 - y as f64).abs()) + .sum::() + / a.len() as f64 + }; + let ref_uv: Vec = ref_u + .iter() + .zip(ref_v) + .flat_map(|(&u, &v)| [u, v]) + .collect(); + println!("mean abs diff Y: {:.6}", mad(&y, ref_y)); + println!("mean abs diff UV: {:.6}", mad(&uv, &ref_uv)); +} diff --git a/shims/vk-video-ffi/src/h264_decode.rs b/shims/vk-video-ffi/src/h264_decode.rs index 7f6aabcd..11bb1b05 100644 --- a/shims/vk-video-ffi/src/h264_decode.rs +++ b/shims/vk-video-ffi/src/h264_decode.rs @@ -172,18 +172,18 @@ struct Caps { } #[derive(Default)] -struct Image { - image: vk::Image, - view: vk::ImageView, - memory: vk::DeviceMemory, +pub(crate) struct Image { + pub(crate) image: vk::Image, + pub(crate) view: vk::ImageView, + pub(crate) memory: vk::DeviceMemory, } #[derive(Default)] -struct Buffer { - buffer: vk::Buffer, - memory: vk::DeviceMemory, - ptr: Option<*mut u8>, - size: u64, +pub(crate) struct Buffer { + pub(crate) buffer: vk::Buffer, + pub(crate) memory: vk::DeviceMemory, + pub(crate) ptr: Option<*mut u8>, + pub(crate) size: u64, } struct Profile { @@ -798,7 +798,7 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result u64 { +pub(crate) fn align_u64(value: u64, to: u64) -> u64 { let to = to.max(1); value.div_ceil(to) * to } diff --git a/shims/vk-video-ffi/src/h265_decode.rs b/shims/vk-video-ffi/src/h265_decode.rs new file mode 100644 index 00000000..da8811c4 --- /dev/null +++ b/shims/vk-video-ffi/src/h265_decode.rs @@ -0,0 +1,1297 @@ +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 H265DecodeConfig { + /// Largest coded width in luma samples. + pub max_width: u32, + /// Largest coded height in luma samples. + pub max_height: u32, + /// DPB slots, including the slot the picture is decoded into. + pub max_dpb_slots: u32, +} + +/// Profile, tier and level of a parameter set. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct H265ProfileTierLevel { + /// general_tier_flag. + pub tier_flag: bool, + /// general_progressive_source_flag. + pub progressive_source: bool, + /// general_interlaced_source_flag. + pub interlaced_source: bool, + /// general_non_packed_constraint_flag. + pub non_packed_constraint: bool, + /// general_frame_only_constraint_flag. + pub frame_only_constraint: bool, + /// general_profile_idc. + pub profile_idc: u8, + /// general_level_idc, 30 x the level number. + pub level_idc: u8, +} + +/// Decoded picture buffer limits, one entry per sub-layer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct H265DecPicBufMgr { + /// sps_max_latency_increase_plus1. + pub max_latency_increase_plus1: [u32; 7], + /// sps_max_dec_pic_buffering_minus1. + pub max_dec_pic_buffering_minus1: [u8; 7], + /// sps_max_num_reorder_pics. + pub max_num_reorder_pics: [u8; 7], +} + +/// Video parameter set fields a decoder needs (names follow the spec syntax). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct H265Vps { + /// vps_video_parameter_set_id. + pub id: u8, + /// vps_max_sub_layers_minus1. + pub max_sub_layers_minus1: u8, + /// Profile, tier and level of the base layer. + pub profile_tier_level: H265ProfileTierLevel, + /// Decoded picture buffer limits. + pub dec_pic_buf_mgr: H265DecPicBufMgr, +} + +/// Scaling lists in coded (up-right diagonal) order, fall-back rules already applied. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct H265ScalingLists { + /// ScalingList4x4 for matrixId 0..6. + pub list_4x4: [[u8; 16]; 6], + /// ScalingList8x8 for matrixId 0..6. + pub list_8x8: [[u8; 64]; 6], + /// ScalingList16x16 for matrixId 0..6. + pub list_16x16: [[u8; 64]; 6], + /// ScalingList32x32 for matrixId 0 and 3. + pub list_32x32: [[u8; 64]; 2], + /// scaling_list_dc_coef_minus8 + 8 for 16x16. + pub dc_16x16: [u8; 6], + /// scaling_list_dc_coef_minus8 + 8 for 32x32. + pub dc_32x32: [u8; 2], +} + +/// PCM parameters, present when pcm_enabled_flag is set. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct H265Pcm { + /// pcm_sample_bit_depth_luma_minus1. + pub bit_depth_luma_minus1: u8, + /// pcm_sample_bit_depth_chroma_minus1. + pub bit_depth_chroma_minus1: u8, + /// log2_min_pcm_luma_coding_block_size_minus3. + pub log2_min_luma_coding_block_size_minus3: u8, + /// log2_diff_max_min_pcm_luma_coding_block_size. + pub log2_diff_max_min_luma_coding_block_size: u8, + /// pcm_loop_filter_disabled_flag. + pub loop_filter_disabled: bool, +} + +/// One SPS long-term reference picture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct H265LongTermRefPicSps { + /// lt_ref_pic_poc_lsb_sps. + pub poc_lsb: u32, + /// used_by_curr_pic_lt_sps_flag. + pub used_by_curr_pic: bool, +} + +/// An explicit short-term reference picture set, resolved to POC deltas. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct H265ShortTermRefPicSet { + /// DeltaPocS0, negative and decreasing. + pub delta_poc_s0: Vec, + /// UsedByCurrPicS0. + pub used_by_curr_pic_s0: Vec, + /// DeltaPocS1, positive and increasing. + pub delta_poc_s1: Vec, + /// UsedByCurrPicS1. + pub used_by_curr_pic_s1: Vec, +} + +/// Sequence parameter set fields a decoder needs (names follow the spec syntax). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct H265Sps { + /// seq_parameter_set_id. + pub id: u8, + /// sps_video_parameter_set_id. + pub vps_id: u8, + /// sps_max_sub_layers_minus1. + pub max_sub_layers_minus1: u8, + /// Profile, tier and level of the base layer. + pub profile_tier_level: H265ProfileTierLevel, + /// chroma_format_idc, 1 for 4:2:0. + pub chroma_format_idc: u8, + /// pic_width_in_luma_samples. + pub pic_width_in_luma_samples: u32, + /// pic_height_in_luma_samples. + pub pic_height_in_luma_samples: u32, + /// Conformance window left, right, top and bottom offsets in chroma units. + pub conformance_window: [u32; 4], + /// bit_depth_luma_minus8. + pub bit_depth_luma_minus8: u8, + /// bit_depth_chroma_minus8. + pub bit_depth_chroma_minus8: u8, + /// log2_max_pic_order_cnt_lsb_minus4. + pub log2_max_pic_order_cnt_lsb_minus4: u8, + /// log2_min_luma_coding_block_size_minus3. + pub log2_min_luma_coding_block_size_minus3: u8, + /// log2_diff_max_min_luma_coding_block_size. + pub log2_diff_max_min_luma_coding_block_size: u8, + /// log2_min_luma_transform_block_size_minus2. + pub log2_min_luma_transform_block_size_minus2: u8, + /// log2_diff_max_min_luma_transform_block_size. + pub log2_diff_max_min_luma_transform_block_size: u8, + /// max_transform_hierarchy_depth_inter. + pub max_transform_hierarchy_depth_inter: u8, + /// max_transform_hierarchy_depth_intra. + pub max_transform_hierarchy_depth_intra: u8, + /// PCM parameters when pcm_enabled_flag is set. + pub pcm: Option, + /// Decoded picture buffer limits. + pub dec_pic_buf_mgr: H265DecPicBufMgr, + /// scaling_list_enabled_flag. + pub scaling_list_enabled: bool, + /// Explicit scaling lists when sps_scaling_list_data_present_flag is set. + pub scaling_lists: Option, + /// amp_enabled_flag. + pub amp_enabled: bool, + /// sample_adaptive_offset_enabled_flag. + pub sample_adaptive_offset_enabled: bool, + /// long_term_ref_pics_present_flag. + pub long_term_ref_pics_present: bool, + /// SPS long-term reference pictures. + pub long_term_ref_pics_sps: Vec, + /// sps_temporal_mvp_enabled_flag. + pub temporal_mvp_enabled: bool, + /// strong_intra_smoothing_enabled_flag. + pub strong_intra_smoothing_enabled: bool, + /// Short-term reference picture sets in the SPS. + pub short_term_ref_pic_sets: Vec, +} + +/// Picture parameter set fields a decoder needs (names follow the spec syntax). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct H265Pps { + /// pic_parameter_set_id. + pub id: u8, + /// seq_parameter_set_id. + pub sps_id: u8, + /// dependent_slice_segments_enabled_flag. + pub dependent_slice_segments_enabled: bool, + /// output_flag_present_flag. + pub output_flag_present: bool, + /// num_extra_slice_header_bits. + pub num_extra_slice_header_bits: u8, + /// sign_data_hiding_enabled_flag. + pub sign_data_hiding_enabled: bool, + /// cabac_init_present_flag. + pub cabac_init_present: bool, + /// num_ref_idx_l0_default_active_minus1. + pub num_ref_idx_l0_default_active_minus1: u8, + /// num_ref_idx_l1_default_active_minus1. + pub num_ref_idx_l1_default_active_minus1: u8, + /// init_qp_minus26. + pub init_qp_minus26: i8, + /// constrained_intra_pred_flag. + pub constrained_intra_pred: bool, + /// transform_skip_enabled_flag. + pub transform_skip_enabled: bool, + /// cu_qp_delta_enabled_flag. + pub cu_qp_delta_enabled: bool, + /// diff_cu_qp_delta_depth. + pub diff_cu_qp_delta_depth: u8, + /// pps_cb_qp_offset. + pub cb_qp_offset: i8, + /// pps_cr_qp_offset. + pub cr_qp_offset: i8, + /// pps_slice_chroma_qp_offsets_present_flag. + pub slice_chroma_qp_offsets_present: bool, + /// weighted_pred_flag. + pub weighted_pred: bool, + /// weighted_bipred_flag. + pub weighted_bipred: bool, + /// transquant_bypass_enabled_flag. + pub transquant_bypass_enabled: bool, + /// tiles_enabled_flag. + pub tiles_enabled: bool, + /// entropy_coding_sync_enabled_flag. + pub entropy_coding_sync_enabled: bool, + /// num_tile_columns_minus1. + pub num_tile_columns_minus1: u8, + /// num_tile_rows_minus1. + pub num_tile_rows_minus1: u8, + /// uniform_spacing_flag. + pub uniform_spacing: bool, + /// column_width_minus1 when the spacing is not uniform. + pub column_width_minus1: Vec, + /// row_height_minus1 when the spacing is not uniform. + pub row_height_minus1: Vec, + /// loop_filter_across_tiles_enabled_flag. + pub loop_filter_across_tiles_enabled: bool, + /// pps_loop_filter_across_slices_enabled_flag. + pub loop_filter_across_slices_enabled: bool, + /// deblocking_filter_control_present_flag. + pub deblocking_filter_control_present: bool, + /// deblocking_filter_override_enabled_flag. + pub deblocking_filter_override_enabled: bool, + /// pps_deblocking_filter_disabled_flag. + pub deblocking_filter_disabled: bool, + /// pps_beta_offset_div2. + pub beta_offset_div2: i8, + /// pps_tc_offset_div2. + pub tc_offset_div2: i8, + /// Explicit scaling lists when pps_scaling_list_data_present_flag is set. + pub scaling_lists: Option, + /// lists_modification_present_flag. + pub lists_modification_present: bool, + /// log2_parallel_merge_level_minus2. + pub log2_parallel_merge_level_minus2: u8, + /// slice_segment_header_extension_present_flag. + pub slice_segment_header_extension_present: bool, +} + +/// A picture held in a DPB slot, used as reference. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct H265RefSlot { + /// DPB slot index. + pub slot: u32, + /// PicOrderCntVal of the reference. + pub poc: i32, + /// Marked as long-term reference. + pub long_term: bool, +} + +/// One coded H.265 picture to decode. Slices are complete NAL units with their two-byte header, no start code. +#[derive(Debug, Clone, Copy)] +pub struct H265DecodePicture<'a> { + /// video_parameter_set_id of the active VPS. + pub vps_id: u8, + /// seq_parameter_set_id of the active SPS. + pub sps_id: u8, + /// pic_parameter_set_id of the active PPS. + pub pps_id: u8, + /// IRAP picture. + pub irap: bool, + /// IDR picture. + pub idr: bool, + /// Reference picture. + pub reference: bool, + /// PicOrderCntVal. + pub poc: i32, + /// DPB slot the picture is decoded into. + pub setup_slot: u32, + /// short_term_ref_pic_set_sps_flag of the slice header. + pub short_term_ref_pic_set_sps: bool, + /// NumDeltaPocsOfRefRpsIdx, 0 unless the slice header set is inter predicted. + pub num_delta_pocs_of_ref_rps_idx: u8, + /// NumBitsForSTRefPicSetInSlice, 0 when the set comes from the SPS. + pub st_rps_bits: u32, + /// DPB slots of RefPicSetStCurrBefore. + pub st_curr_before: &'a [u32], + /// DPB slots of RefPicSetStCurrAfter. + pub st_curr_after: &'a [u32], + /// DPB slots of RefPicSetLtCurr. + pub lt_curr: &'a [u32], + /// Every DPB picture in use as a reference, all in slots other than setup_slot. + pub refs: &'a [H265RefSlot], + /// Slice segment NAL units in decoding order. + pub slices: &'a [&'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, + h265: vk::VideoDecodeH265ProfileInfoKHR, +} + +impl Profile { + fn new() -> Box { + let mut p = Box::new(Profile { + info: vk::VideoProfileInfoKHR::builder() + .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_H265) + .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) + .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .build(), + h265: vk::VideoDecodeH265ProfileInfoKHR::builder() + .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN) + .build(), + }); + p.info.next = &p.h265 as *const _ as *const c_void; + p + } +} + +/// An H.265 Main Vulkan Video decode session: NV12 DPB images per slot and a separate NV12 output image. +pub struct H265DecodeSession { + gpu: Gpu, + family: u32, + queue: vk::Queue, + graphics: u32, + graphics_queue: vk::Queue, + video_session: vk::VideoSessionKHR, + session_memories: Vec, + params: Option, + sps: Vec, + 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 H265DecodeSession { + /// Creates a session with its DPB, bitstream and readback buffers. + pub fn new(gpu: &Gpu, cfg: &H265DecodeConfig) -> 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("H.265 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_H265_EXTENSION.name) + { + return Err(Error::Unsupported("H.265 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!("H.265 decode {width}x{height}"))); + } + if !caps.distinct { + return Err(Error::Unsupported( + "H.265 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 = H265DecodeSession { + gpu: gpu.clone(), + family, + queue, + graphics, + graphics_queue, + video_session: Default::default(), + session_memories: Vec::new(), + params: None, + sps: Vec::new(), + 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 VPS, SPS and PPS sets. + pub fn set_parameters( + &mut self, + vps: &[H265Vps], + sps: &[H265Sps], + pps: &[H265Pps], + ) -> Result<(), Error> { + if sps.iter().any(|s| { + s.chroma_format_idc != 1 + || s.bit_depth_luma_minus8 != 0 + || s.bit_depth_chroma_minus8 != 0 + }) { + return Err(Error::Unsupported("H.265 decode beyond 8-bit 4:2:0".into())); + } + let gpu = self.gpu.clone(); + let d = gpu.device(); + + let vps_ptl = vps + .iter() + .map(|v| std_ptl(&v.profile_tier_level).map(Box::new)) + .collect::, Error>>()?; + let vps_dpbm: Vec<_> = vps + .iter() + .map(|v| Box::new(std_dpbm(&v.dec_pic_buf_mgr))) + .collect(); + let std_vps: Vec = vps + .iter() + .zip(&vps_ptl) + .zip(&vps_dpbm) + .map(|((v, ptl), dpbm)| std_vps(v, ptl, dpbm)) + .collect(); + + let sps_ptl = sps + .iter() + .map(|s| std_ptl(&s.profile_tier_level).map(Box::new)) + .collect::, Error>>()?; + let sps_dpbm: Vec<_> = sps + .iter() + .map(|s| Box::new(std_dpbm(&s.dec_pic_buf_mgr))) + .collect(); + let sps_lists: Vec<_> = sps + .iter() + .map(|s| s.scaling_lists.as_ref().map(|l| Box::new(std_lists(l)))) + .collect(); + let sps_rps = sps + .iter() + .map(|s| { + s.short_term_ref_pic_sets + .iter() + .map(std_rps) + .collect::, Error>>() + }) + .collect::, Error>>()?; + let sps_lt = sps + .iter() + .map(|s| std_lt(&s.long_term_ref_pics_sps).map(Box::new)) + .collect::, Error>>()?; + let std_sps = sps + .iter() + .enumerate() + .map(|(i, s)| { + std_sps( + s, + &sps_ptl[i], + &sps_dpbm[i], + sps_lists[i].as_deref(), + &sps_rps[i], + &sps_lt[i], + ) + }) + .collect::, Error>>()?; + + let pps_lists: Vec<_> = pps + .iter() + .map(|p| p.scaling_lists.as_ref().map(|l| Box::new(std_lists(l)))) + .collect(); + let std_pps = pps + .iter() + .zip(&pps_lists) + .map(|(p, lists)| { + let vps_id = sps + .iter() + .find(|s| s.id == p.sps_id) + .map(|s| s.vps_id) + .ok_or_else(|| Error::Invalid(format!("PPS names unknown SPS {}", p.sps_id)))?; + std_pps(p, vps_id, lists.as_deref()) + }) + .collect::, Error>>()?; + + let add = vk::VideoDecodeH265SessionParametersAddInfoKHR::builder() + .std_vp_ss(&std_vps) + .std_sp_ss(&std_sps) + .std_pp_ss(&std_pps) + .build(); + let mut h265 = vk::VideoDecodeH265SessionParametersCreateInfoKHR::builder() + .max_std_vps_count(vps.len().max(1) as u32) + .max_std_sps_count(sps.len().max(1) as u32) + .max_std_pps_count(pps.len().max(1) as u32) + .parameters_add_info(&add) + .build(); + let info = vk::VideoSessionParametersCreateInfoKHR::builder() + .video_session(self.video_session) + .push_next(&mut h265) + .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.sps = sps.to_vec(); + Ok(()) + } + + /// Decodes one picture into its setup slot, referencing the given DPB slots. + pub fn decode(&mut self, pic: &H265DecodePicture) -> Result<(), Error> { + let params = self + .params + .ok_or_else(|| Error::Invalid("session parameters not set".into()))?; + let extent = { + let sps = self + .sps + .iter() + .find(|s| s.id == pic.sps_id) + .ok_or_else(|| Error::Invalid(format!("unknown SPS {}", pic.sps_id)))?; + vk::Extent2D { + width: sps.pic_width_in_luma_samples, + height: sps.pic_height_in_luma_samples, + } + }; + if extent.width > self.max_extent.width || extent.height > self.max_extent.height { + return Err(Error::Invalid("picture larger than session".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())); + } + if pic + .refs + .iter() + .any(|r| r.slot >= self.max_dpb_slots || r.slot == pic.setup_slot) + { + return Err(Error::Invalid("reference DPB slot".into())); + } + for list in [pic.st_curr_before, pic.st_curr_after, pic.lt_curr] { + if list.len() > 8 { + return Err(Error::Invalid("too many RPS entries".into())); + } + if list.iter().any(|s| !pic.refs.iter().any(|r| r.slot == *s)) { + return Err(Error::Invalid("RPS entry is not a listed reference".into())); + } + } + if pic.slices.is_empty() { + return Err(Error::Invalid("no slices".into())); + } + + let total: usize = pic.slices.iter().map(|s| 3 + s.len()).sum(); + if total as u64 > self.bitstream.size { + return Err(Error::Invalid("slices larger than bitstream buffer".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) }; + let mut offsets = Vec::with_capacity(pic.slices.len()); + let mut at = 0usize; + for slice in pic.slices { + offsets.push(at as u32); + buf[at..at + 3].copy_from_slice(&[0, 0, 1]); + buf[at + 3..at + 3 + slice.len()].copy_from_slice(slice); + at += 3 + slice.len(); + } + let range = align_u64(at 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(pic.poc, false); + let mut setup_dpb = vk::VideoDecodeH265DpbSlotInfoKHR::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.poc, r.long_term)) + .collect(); + let mut ref_dpb: Vec = ref_std + .iter() + .map(|s| { + vk::VideoDecodeH265DpbSlotInfoKHR::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 mut std_pic = zeroed::(); + std_pic.flags.set_IrapPicFlag(pic.irap as u32); + std_pic.flags.set_IdrPicFlag(pic.idr as u32); + std_pic.flags.set_IsReference(pic.reference as u32); + std_pic + .flags + .set_short_term_ref_pic_set_sps_flag(pic.short_term_ref_pic_set_sps as u32); + std_pic.sps_video_parameter_set_id = pic.vps_id; + std_pic.pps_seq_parameter_set_id = pic.sps_id; + std_pic.pps_pic_parameter_set_id = pic.pps_id; + std_pic.NumDeltaPocsOfRefRpsIdx = pic.num_delta_pocs_of_ref_rps_idx; + std_pic.PicOrderCntVal = pic.poc; + std_pic.NumBitsForSTRefPicSetInSlice = pic.st_rps_bits as u16; + std_pic.RefPicSetStCurrBefore = rps_slots(pic.st_curr_before); + std_pic.RefPicSetStCurrAfter = rps_slots(pic.st_curr_after); + std_pic.RefPicSetLtCurr = rps_slots(pic.lt_curr); + + let mut h265 = vk::VideoDecodeH265PictureInfoKHR::builder() + .std_picture_info(&std_pic) + .slice_segment_offsets(&offsets) + .build(); + 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 h265) + .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 H265DecodeSession { + 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 h265 = vk::VideoDecodeH265CapabilitiesKHR::builder(); + let mut decode = vk::VideoDecodeCapabilitiesKHR::builder(); + let mut caps = vk::VideoCapabilitiesKHR::builder() + .push_next(&mut h265) + .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 rps_slots(slots: &[u32]) -> [u8; 8] { + let mut out = [0xff; 8]; + for (o, &s) in out.iter_mut().zip(slots) { + *o = s as u8; + } + out +} + +fn ref_info(poc: i32, long_term: bool) -> vk::video::StdVideoDecodeH265ReferenceInfo { + let mut info = zeroed::(); + info.flags + .set_used_for_long_term_reference(long_term as u32); + info.PicOrderCntVal = poc; + info +} + +fn level(idc: u8) -> Result { + use vk::video::*; + let table = [ + (30, STD_VIDEO_H265_LEVEL_IDC_1_0), + (60, STD_VIDEO_H265_LEVEL_IDC_2_0), + (63, STD_VIDEO_H265_LEVEL_IDC_2_1), + (90, STD_VIDEO_H265_LEVEL_IDC_3_0), + (93, STD_VIDEO_H265_LEVEL_IDC_3_1), + (120, STD_VIDEO_H265_LEVEL_IDC_4_0), + (123, STD_VIDEO_H265_LEVEL_IDC_4_1), + (150, STD_VIDEO_H265_LEVEL_IDC_5_0), + (153, STD_VIDEO_H265_LEVEL_IDC_5_1), + (156, STD_VIDEO_H265_LEVEL_IDC_5_2), + (180, STD_VIDEO_H265_LEVEL_IDC_6_0), + (183, STD_VIDEO_H265_LEVEL_IDC_6_1), + (186, STD_VIDEO_H265_LEVEL_IDC_6_2), + ]; + table + .into_iter() + .find(|&(v, _)| v == idc) + .map(|(_, level)| level) + .ok_or_else(|| Error::Invalid(format!("H.265 level_idc {idc}"))) +} + +fn std_ptl(p: &H265ProfileTierLevel) -> Result { + let mut out = zeroed::(); + out.flags.set_general_tier_flag(p.tier_flag as u32); + out.flags + .set_general_progressive_source_flag(p.progressive_source as u32); + out.flags + .set_general_interlaced_source_flag(p.interlaced_source as u32); + out.flags + .set_general_non_packed_constraint_flag(p.non_packed_constraint as u32); + out.flags + .set_general_frame_only_constraint_flag(p.frame_only_constraint as u32); + out.general_profile_idc = vk::video::StdVideoH265ProfileIdc(p.profile_idc as i32); + out.general_level_idc = level(p.level_idc)?; + Ok(out) +} + +fn std_dpbm(d: &H265DecPicBufMgr) -> vk::video::StdVideoH265DecPicBufMgr { + vk::video::StdVideoH265DecPicBufMgr { + max_latency_increase_plus1: d.max_latency_increase_plus1, + max_dec_pic_buffering_minus1: d.max_dec_pic_buffering_minus1, + max_num_reorder_pics: d.max_num_reorder_pics, + } +} + +fn std_lists(l: &H265ScalingLists) -> vk::video::StdVideoH265ScalingLists { + vk::video::StdVideoH265ScalingLists { + ScalingList4x4: l.list_4x4, + ScalingList8x8: l.list_8x8, + ScalingList16x16: l.list_16x16, + ScalingList32x32: l.list_32x32, + ScalingListDCCoef16x16: l.dc_16x16, + ScalingListDCCoef32x32: l.dc_32x32, + } +} + +fn std_vps( + v: &H265Vps, + ptl: &vk::video::StdVideoH265ProfileTierLevel, + dpbm: &vk::video::StdVideoH265DecPicBufMgr, +) -> vk::video::StdVideoH265VideoParameterSet { + let mut out = zeroed::(); + out.vps_video_parameter_set_id = v.id; + out.vps_max_sub_layers_minus1 = v.max_sub_layers_minus1; + out.pProfileTierLevel = ptl as *const _; + out.pDecPicBufMgr = dpbm as *const _; + out +} + +fn std_lt( + lt: &[H265LongTermRefPicSps], +) -> Result { + if lt.len() > 32 { + return Err(Error::Invalid("too many SPS long-term pictures".into())); + } + let mut out = zeroed::(); + for (i, l) in lt.iter().enumerate() { + out.lt_ref_pic_poc_lsb_sps[i] = l.poc_lsb; + out.used_by_curr_pic_lt_sps_flag |= (l.used_by_curr_pic as u32) << i; + } + Ok(out) +} + +fn deltas(d: &[i32], negative: bool) -> Result<[u16; 16], Error> { + let mut out = [0u16; 16]; + let mut prev = 0i32; + for (o, &cur) in out.iter_mut().zip(d) { + let step = if negative { prev - cur } else { cur - prev }; + *o = u16::try_from(step - 1) + .map_err(|_| Error::Invalid("short-term RPS deltas not monotonic".into()))?; + prev = cur; + } + Ok(out) +} + +fn std_rps(r: &H265ShortTermRefPicSet) -> Result { + let (n0, n1) = (r.delta_poc_s0.len(), r.delta_poc_s1.len()); + if n0 + n1 > 16 || r.used_by_curr_pic_s0.len() != n0 || r.used_by_curr_pic_s1.len() != n1 { + return Err(Error::Invalid("short-term RPS shape".into())); + } + let mask = |flags: &[bool]| { + flags + .iter() + .enumerate() + .fold(0u32, |m, (i, &f)| m | ((f as u32) << i)) + }; + let used0 = mask(&r.used_by_curr_pic_s0); + let used1 = mask(&r.used_by_curr_pic_s1); + let mut out = zeroed::(); + out.num_negative_pics = n0 as u8; + out.num_positive_pics = n1 as u8; + out.used_by_curr_pic_s0_flag = used0 as u16; + out.used_by_curr_pic_s1_flag = used1 as u16; + out.used_by_curr_pic_flag = (used0 | (used1 << n0)) as u16; + out.delta_poc_s0_minus1 = deltas(&r.delta_poc_s0, true)?; + out.delta_poc_s1_minus1 = deltas(&r.delta_poc_s1, false)?; + Ok(out) +} + +fn std_sps( + s: &H265Sps, + ptl: &vk::video::StdVideoH265ProfileTierLevel, + dpbm: &vk::video::StdVideoH265DecPicBufMgr, + lists: Option<&vk::video::StdVideoH265ScalingLists>, + rps: &[vk::video::StdVideoH265ShortTermRefPicSet], + lt: &vk::video::StdVideoH265LongTermRefPicsSps, +) -> Result { + let mut out = zeroed::(); + out.flags + .set_conformance_window_flag((s.conformance_window != [0; 4]) as u32); + out.flags + .set_scaling_list_enabled_flag(s.scaling_list_enabled as u32); + out.flags + .set_sps_scaling_list_data_present_flag(lists.is_some() as u32); + out.flags.set_amp_enabled_flag(s.amp_enabled as u32); + out.flags + .set_sample_adaptive_offset_enabled_flag(s.sample_adaptive_offset_enabled as u32); + out.flags.set_pcm_enabled_flag(s.pcm.is_some() as u32); + out.flags + .set_long_term_ref_pics_present_flag(s.long_term_ref_pics_present as u32); + out.flags + .set_sps_temporal_mvp_enabled_flag(s.temporal_mvp_enabled as u32); + out.flags + .set_strong_intra_smoothing_enabled_flag(s.strong_intra_smoothing_enabled as u32); + if let Some(p) = s.pcm { + out.flags + .set_pcm_loop_filter_disabled_flag(p.loop_filter_disabled as u32); + out.pcm_sample_bit_depth_luma_minus1 = p.bit_depth_luma_minus1; + out.pcm_sample_bit_depth_chroma_minus1 = p.bit_depth_chroma_minus1; + out.log2_min_pcm_luma_coding_block_size_minus3 = p.log2_min_luma_coding_block_size_minus3; + out.log2_diff_max_min_pcm_luma_coding_block_size = + p.log2_diff_max_min_luma_coding_block_size; + } + out.chroma_format_idc = vk::video::StdVideoH265ChromaFormatIdc(s.chroma_format_idc as i32); + out.pic_width_in_luma_samples = s.pic_width_in_luma_samples; + out.pic_height_in_luma_samples = s.pic_height_in_luma_samples; + out.sps_video_parameter_set_id = s.vps_id; + out.sps_max_sub_layers_minus1 = s.max_sub_layers_minus1; + out.sps_seq_parameter_set_id = s.id; + out.bit_depth_luma_minus8 = s.bit_depth_luma_minus8; + out.bit_depth_chroma_minus8 = s.bit_depth_chroma_minus8; + out.log2_max_pic_order_cnt_lsb_minus4 = s.log2_max_pic_order_cnt_lsb_minus4; + out.log2_min_luma_coding_block_size_minus3 = s.log2_min_luma_coding_block_size_minus3; + out.log2_diff_max_min_luma_coding_block_size = s.log2_diff_max_min_luma_coding_block_size; + out.log2_min_luma_transform_block_size_minus2 = s.log2_min_luma_transform_block_size_minus2; + out.log2_diff_max_min_luma_transform_block_size = s.log2_diff_max_min_luma_transform_block_size; + out.max_transform_hierarchy_depth_inter = s.max_transform_hierarchy_depth_inter; + out.max_transform_hierarchy_depth_intra = s.max_transform_hierarchy_depth_intra; + out.num_short_term_ref_pic_sets = rps.len() as u8; + out.num_long_term_ref_pics_sps = s.long_term_ref_pics_sps.len() as u8; + out.conf_win_left_offset = s.conformance_window[0]; + out.conf_win_right_offset = s.conformance_window[1]; + out.conf_win_top_offset = s.conformance_window[2]; + out.conf_win_bottom_offset = s.conformance_window[3]; + out.pProfileTierLevel = ptl as *const _; + out.pDecPicBufMgr = dpbm as *const _; + out.pScalingLists = lists.map_or(std::ptr::null(), |l| l as *const _); + out.pShortTermRefPicSet = rps.as_ptr(); + out.pLongTermRefPicsSps = lt as *const _; + Ok(out) +} + +fn std_pps( + p: &H265Pps, + vps_id: u8, + lists: Option<&vk::video::StdVideoH265ScalingLists>, +) -> Result { + if p.column_width_minus1.len() > 19 || p.row_height_minus1.len() > 21 { + return Err(Error::Invalid("too many tile columns or rows".into())); + } + let mut out = zeroed::(); + out.flags + .set_dependent_slice_segments_enabled_flag(p.dependent_slice_segments_enabled as u32); + out.flags + .set_output_flag_present_flag(p.output_flag_present as u32); + out.flags + .set_sign_data_hiding_enabled_flag(p.sign_data_hiding_enabled as u32); + out.flags + .set_cabac_init_present_flag(p.cabac_init_present as u32); + out.flags + .set_constrained_intra_pred_flag(p.constrained_intra_pred as u32); + out.flags + .set_transform_skip_enabled_flag(p.transform_skip_enabled as u32); + out.flags + .set_cu_qp_delta_enabled_flag(p.cu_qp_delta_enabled as u32); + out.flags + .set_pps_slice_chroma_qp_offsets_present_flag(p.slice_chroma_qp_offsets_present as u32); + out.flags.set_weighted_pred_flag(p.weighted_pred as u32); + out.flags.set_weighted_bipred_flag(p.weighted_bipred as u32); + out.flags + .set_transquant_bypass_enabled_flag(p.transquant_bypass_enabled as u32); + out.flags.set_tiles_enabled_flag(p.tiles_enabled as u32); + out.flags + .set_entropy_coding_sync_enabled_flag(p.entropy_coding_sync_enabled as u32); + out.flags.set_uniform_spacing_flag(p.uniform_spacing as u32); + out.flags + .set_loop_filter_across_tiles_enabled_flag(p.loop_filter_across_tiles_enabled as u32); + out.flags + .set_pps_loop_filter_across_slices_enabled_flag(p.loop_filter_across_slices_enabled as u32); + out.flags + .set_deblocking_filter_control_present_flag(p.deblocking_filter_control_present as u32); + out.flags + .set_deblocking_filter_override_enabled_flag(p.deblocking_filter_override_enabled as u32); + out.flags + .set_pps_deblocking_filter_disabled_flag(p.deblocking_filter_disabled as u32); + out.flags + .set_pps_scaling_list_data_present_flag(lists.is_some() as u32); + out.flags + .set_lists_modification_present_flag(p.lists_modification_present as u32); + out.flags.set_slice_segment_header_extension_present_flag( + p.slice_segment_header_extension_present as u32, + ); + out.pps_pic_parameter_set_id = p.id; + out.pps_seq_parameter_set_id = p.sps_id; + out.sps_video_parameter_set_id = vps_id; + out.num_extra_slice_header_bits = p.num_extra_slice_header_bits; + out.num_ref_idx_l0_default_active_minus1 = p.num_ref_idx_l0_default_active_minus1; + out.num_ref_idx_l1_default_active_minus1 = p.num_ref_idx_l1_default_active_minus1; + out.init_qp_minus26 = p.init_qp_minus26; + out.diff_cu_qp_delta_depth = p.diff_cu_qp_delta_depth; + out.pps_cb_qp_offset = p.cb_qp_offset; + out.pps_cr_qp_offset = p.cr_qp_offset; + out.pps_beta_offset_div2 = p.beta_offset_div2; + out.pps_tc_offset_div2 = p.tc_offset_div2; + out.log2_parallel_merge_level_minus2 = p.log2_parallel_merge_level_minus2; + out.num_tile_columns_minus1 = p.num_tile_columns_minus1; + out.num_tile_rows_minus1 = p.num_tile_rows_minus1; + out.column_width_minus1[..p.column_width_minus1.len()].copy_from_slice(&p.column_width_minus1); + out.row_height_minus1[..p.row_height_minus1.len()].copy_from_slice(&p.row_height_minus1); + out.pScalingLists = lists.map_or(std::ptr::null(), |l| l as *const _); + Ok(out) +} diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index f1c8f8ac..7bbc4768 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -9,6 +9,7 @@ use std::sync::Arc; mod av1_encode; mod h264_decode; mod h264_encode; +mod h265_decode; mod h265_encode; mod rgb_convert; @@ -18,6 +19,11 @@ pub use h264_decode::{ ScalingLists, }; pub use h264_encode::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, RateControl}; +pub use h265_decode::{ + H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps, + H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet, + H265Sps, H265Vps, +}; pub use h265_encode::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref}; use vk::KhrVideoQueueExtensionInstanceCommands;