use std::ffi::c_void; use vulkanalia::prelude::v1_3::*; use vulkanalia::vk::{ KhrVideoEncodeQueueExtensionDeviceCommands, KhrVideoQueueExtensionDeviceCommands, }; #[cfg(target_os = "linux")] use crate::dmabuf::DmaBuf; use crate::h264_encode::validate; use crate::rgb_convert::{Input, check_rgb}; use crate::session::{ quality_level, DPB_SLOTS, Encoder, VideoSession, align, component_bit_depth, picture_resource, video_caps, vk, zeroed, }; use crate::{Colour, Error, Gpu, RateControl}; /// Settings fixed for the life of a session. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct H265EncodeConfig { /// Width in luma samples, even. pub width: u32, /// Height in luma samples, even. pub height: u32, /// Frame rate as numerator and denominator. pub fps: (u32, u32), /// Rate control. pub rate: RateControl, /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input). pub bit_depth: u8, /// `general_level_idc` (30 to 186), chosen by the caller and clamped to the driver maximum. pub level: u8, /// Colour description for the VUI, or none. pub colour: Option, /// Speed/quality trade-off as in ec-hw's `EncoderConfig::quality`: 0 for the default level, 1 for the driver's best, each step up one level faster. pub quality: u32, } /// One picture to encode. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct H265Picture { /// Encode as IDR, POC must be 0. pub idr: bool, /// PicOrderCntVal. pub poc: i32, /// DPB slot this picture is written to, below `DPB_SLOTS`. pub slot: u32, /// Reference for a P picture, None for IDR. pub reference: Option, /// PicOrderCntVal of every other picture the decoder keeps for a later reference, none for IDR. pub keep: [Option; DPB_SLOTS], } /// A picture held in the DPB. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct H265Ref { /// DPB slot, below `DPB_SLOTS`. pub slot: u32, /// PicOrderCntVal of the reference, lower than the picture's. pub poc: i32, } struct Caps { std_header_version: vk::ExtensionProperties, max_extent: vk::Extent2D, size_align: u64, rc_modes: vk::VideoEncodeRateControlModeFlagsKHR, quality_levels: u32, max_refs: u32, max_level: vk::video::StdVideoH265LevelIdc, ctb_sizes: vk::VideoEncodeH265CtbSizeFlagsKHR, transform_sizes: vk::VideoEncodeH265TransformBlockSizeFlagsKHR, std_flags: vk::VideoEncodeH265StdFlagsKHR, } struct Coding { width: u32, height: u32, ctb_log2: u32, min_cb_log2: u32, min_tb_log2: u32, max_tb_log2: u32, sao: bool, transform_skip: bool, level: vk::video::StdVideoH265LevelIdc, } struct Profile { info: vk::VideoProfileInfoKHR, codec: vk::VideoEncodeH265ProfileInfoKHR, usage: vk::VideoEncodeUsageInfoKHR, } impl Profile { fn new(bit_depth: u8) -> Box { let component = component_bit_depth(bit_depth); let mut p = Box::new(Profile { info: vk::VideoProfileInfoKHR::builder() .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_H265) .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) .luma_bit_depth(component) .chroma_bit_depth(component) .build(), codec: vk::VideoEncodeH265ProfileInfoKHR::builder() .std_profile_idc(profile_idc(bit_depth)) .build(), usage: vk::VideoEncodeUsageInfoKHR::builder() .video_usage_hints(vk::VideoEncodeUsageFlagsKHR::STREAMING) .video_content_hints(vk::VideoEncodeContentFlagsKHR::DESKTOP) .tuning_mode(vk::VideoEncodeTuningModeKHR::LOW_LATENCY) .build(), }); p.codec.next = &p.usage as *const _ as *const c_void; p.info.next = &p.codec as *const _ as *const c_void; p } } struct RateChain { rc: vk::VideoEncodeRateControlInfoKHR, rc_h265: vk::VideoEncodeH265RateControlInfoKHR, layer: vk::VideoEncodeRateControlLayerInfoKHR, layer_h265: vk::VideoEncodeH265RateControlLayerInfoKHR, } impl RateChain { fn new(rate: RateControl, fps: (u32, u32)) -> Box { let mode = rate.mode(); let layers = u32::from(rate.layer().is_some()); let (bitrate, max_bitrate, buffer_ms) = rate.layer().unwrap_or_default(); let mut c = Box::new(RateChain { rc: vk::VideoEncodeRateControlInfoKHR::builder() .rate_control_mode(mode) .virtual_buffer_size_in_ms(buffer_ms) .initial_virtual_buffer_size_in_ms(buffer_ms) .build(), rc_h265: vk::VideoEncodeH265RateControlInfoKHR::builder() .flags( vk::VideoEncodeH265RateControlFlagsKHR::REGULAR_GOP | vk::VideoEncodeH265RateControlFlagsKHR::REFERENCE_PATTERN_FLAT, ) .gop_frame_count(u32::MAX) .idr_period(u32::MAX) .consecutive_b_frame_count(0) .sub_layer_count(1) .build(), layer: vk::VideoEncodeRateControlLayerInfoKHR::builder() .average_bitrate(bitrate as u64) .max_bitrate(max_bitrate as u64) .frame_rate_numerator(fps.0) .frame_rate_denominator(fps.1) .build(), layer_h265: { let mut layer = vk::VideoEncodeH265RateControlLayerInfoKHR::builder(); if let Some(q) = rate.min_qp() { layer = layer.use_min_qp(true).min_qp(vk::VideoEncodeH265QpKHR { qp_i: q as i32, qp_p: q as i32, qp_b: q as i32 }); } if let Some(m) = rate.max_frame_bytes() { layer = layer.use_max_frame_size(true).max_frame_size(vk::VideoEncodeH265FrameSizeKHR { frame_i_size: m, frame_p_size: m, frame_b_size: m }); } layer.build() }, }); c.rc.next = &c.rc_h265 as *const _ as *const c_void; c.rc.layer_count = layers; c.rc.layers = &c.layer; c.layer.next = &c.layer_h265 as *const _ as *const c_void; c } } /// An H.265 Vulkan Video encode session: IDR and P pictures, one reference, Main profile, NV12 uploaded from CPU. pub struct H265EncodeSession { enc: Encoder, } impl H265EncodeSession { /// Creates a session with its DPB, buffers and parameter sets. pub fn new(gpu: &Gpu, cfg: &H265EncodeConfig) -> Result { validate(cfg.width, cfg.height, cfg.fps, cfg.rate)?; if cfg.bit_depth != 8 && cfg.bit_depth != 10 { return Err(Error::Invalid("H.265 bit depth".into())); } let family = gpu .encode_family() .ok_or_else(|| Error::Unsupported("H.265 encode queue family".into()))?; if !gpu .device() .extensions() .contains(&vk::KHR_VIDEO_ENCODE_H265_EXTENSION.name) { return Err(Error::Unsupported("H.265 encode".into())); } let profile = Profile::new(cfg.bit_depth); let caps = query_caps(gpu, &profile.info).map_err(|e| match e { Error::Vk(..) if cfg.bit_depth == 10 => { Error::Unsupported("10-bit H.265 encode".into()) } e => e, })?; let coding = coding(&caps, cfg)?; if coding.width > caps.max_extent.width || coding.height > caps.max_extent.height { return Err(Error::Unsupported(format!( "H.265 encode {}x{}", coding.width, coding.height ))); } if caps.max_refs < 1 { return Err(Error::Unsupported("H.265 encode reference".into())); } let mode = cfg.rate.mode(); if !caps.rc_modes.contains(mode) { return Err(Error::Unsupported(format!("rate control {mode:?}"))); } let upload_family = gpu .graphics_family() .ok_or_else(|| Error::Unsupported("graphics queue family for upload".into()))?; let extent = vk::Extent2D { width: coding.width, height: coding.height, }; let vs = VideoSession::new( gpu, family, &profile.info, &caps.std_header_version, extent, DPB_SLOTS as u32, 1, )?; let mut enc = Encoder::new( vs, &profile.info, upload_family, (cfg.width, cfg.height), extent, (cfg.rate, cfg.fps), caps.size_align, )?; enc.vs.quality_level = quality_level(cfg.quality, caps.quality_levels); let params = create_parameters(&enc.vs, cfg, &coding)?; enc.vs.set_params(params); Ok(H265EncodeSession { enc }) } /// Annex-B VPS, SPS and PPS of this session. pub fn parameter_sets(&self) -> Result, Error> { let mut h265 = vk::VideoEncodeH265SessionParametersGetInfoKHR::builder() .write_std_vps(true) .write_std_sps(true) .write_std_pps(true) .std_vps_id(0) .std_sps_id(0) .std_pps_id(0) .build(); let info = vk::VideoEncodeSessionParametersGetInfoKHR::builder() .video_session_parameters(self.enc.vs.params) .push_next(&mut h265) .build(); vk( unsafe { self.enc .vs .gpu .device() .get_encoded_video_session_parameters_khr(&info, None) }, "vkGetEncodedVideoSessionParametersKHR", ) } /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result>, Error> { if y.len() != self.enc.input.0 * self.enc.input.1 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 { return Err(Error::Invalid("NV12 plane size".into())); } self.check(pic)?; self.enc.upload(Input::Nv12 { y, uv })?; self.encode_uploaded(pic) } /// Submits one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session without waiting; returns the oldest picture once two are in flight. pub fn submit_16( &mut self, y: &[u16], uv: &[u16], pic: &H265Picture, ) -> Result>, Error> { if y.len() != self.enc.input.0 * self.enc.input.1 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 { return Err(Error::Invalid("P010 plane size".into())); } self.check(pic)?; self.enc.upload(Input::P010 { y, uv })?; self.encode_uploaded(pic) } /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU. pub fn submit_rgb( &mut self, rgb: &[u8], src_width: u32, src_height: u32, stride_bytes: u32, bgr: bool, pic: &H265Picture, ) -> Result>, Error> { self.check(pic)?; let src = (src_width as usize, src_height as usize); check_rgb( (self.enc.input.0, self.enc.input.1), src, rgb, stride_bytes as usize, )?; self.enc.upload(Input::Rgb { data: rgb, width: src.0, height: src.1, stride: stride_bytes as usize, bgr, })?; self.encode_uploaded(pic) } /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size. #[cfg(target_os = "linux")] pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result>, Error> { self.check(pic)?; self.enc.upload_dmabuf(src)?; self.encode_uploaded(pic) } /// Encodes one picture from a shared D3D11 texture of BGRA or RGBA pixels, downscaled to the encoder size. #[cfg(windows)] pub fn submit_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H265Picture) -> Result>, Error> { self.check(pic)?; self.enc.upload_d3d11(src)?; self.encode_uploaded(pic) } fn encode_uploaded(&mut self, pic: &H265Picture) -> Result>, Error> { let extent = self.enc.extent; let primary = if pic.idr { vk::video::STD_VIDEO_H265_PICTURE_TYPE_IDR } else { vk::video::STD_VIDEO_H265_PICTURE_TYPE_P }; let dpb_pr = self.enc.dpb.each_ref().map(|d| picture_resource(d.view, extent)); let src_pr = picture_resource(self.enc.src_view(), extent); let new_std = reference_info(primary, pic.poc); let ref_std = pic .reference .map(|r| reference_info(vk::video::STD_VIDEO_H265_PICTURE_TYPE_P, r.poc)); let mut new_dpb = vk::VideoEncodeH265DpbSlotInfoKHR::builder() .std_reference_info(&new_std) .build(); let mut ref_dpb = ref_std.as_ref().map(|s| { vk::VideoEncodeH265DpbSlotInfoKHR::builder() .std_reference_info(s) .build() }); let mut refs = Vec::new(); if let (Some(r), Some(dpb)) = (pic.reference, ref_dpb.as_mut()) { refs.push( vk::VideoReferenceSlotInfoKHR::builder() .slot_index(r.slot as i32) .picture_resource(&dpb_pr[r.slot as usize]) .push_next(dpb) .build(), ); } let setup = vk::VideoReferenceSlotInfoKHR::builder() .slot_index(pic.slot as i32) .picture_resource(&dpb_pr[pic.slot as usize]) .push_next(&mut new_dpb) .build(); let order = match pic.reference { Some(r) => [pic.slot, r.slot], None => [0, 1], }; let begin_slots: Vec = order .iter() .map(|&i| { let active = pic .reference .filter(|r| r.slot == i) .map_or(-1, |_| i as i32); vk::VideoReferenceSlotInfoKHR::builder() .slot_index(active) .picture_resource(&dpb_pr[i as usize]) .build() }) .collect(); let mut list0 = [0xffu8; 15]; if let Some(r) = pic.reference { list0[0] = r.slot as u8; } let mut lists = zeroed::(); lists.RefPicList0 = list0; lists.RefPicList1 = [0xff; 15]; let rps = pic.reference.map(|r| short_term_rps(pic.poc, r.poc, &pic.keep)); let mut pic_std = zeroed::(); pic_std.flags.set_IrapPicFlag(pic.idr as u32); pic_std.flags.set_is_reference(1); pic_std.flags.set_pic_output_flag(1); pic_std.pic_type = primary; pic_std.PicOrderCntVal = pic.poc; pic_std.pRefLists = &lists; pic_std.pShortTermRefPicSet = rps.as_ref().map_or(std::ptr::null(), |r| r as *const _); let mut slice_std = zeroed::(); slice_std.flags.set_first_slice_segment_in_pic_flag(1); slice_std.slice_type = if pic.idr { vk::video::STD_VIDEO_H265_SLICE_TYPE_I } else { vk::video::STD_VIDEO_H265_SLICE_TYPE_P }; slice_std.MaxNumMergeCand = 5; let constant_qp = self.enc.rate.constant_qp().map_or(0, i32::from); let slices = [vk::VideoEncodeH265NaluSliceSegmentInfoKHR::builder() .constant_qp(constant_qp) .std_slice_segment_header(&slice_std) .build()]; let mut h265_pic = vk::VideoEncodeH265PictureInfoKHR::builder() .nalu_slice_segment_entries(&slices) .std_picture_info(&pic_std) .build(); let encode = vk::VideoEncodeInfoKHR::builder() .dst_buffer(self.enc.bitstream_buffer()) .dst_buffer_offset(0) .dst_buffer_range(self.enc.bitstream_len) .src_picture_resource(src_pr) .setup_reference_slot(&setup) .reference_slots(&refs) .push_next(&mut h265_pic) .build(); let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1); let mut chain = RateChain::new(self.enc.rate, self.enc.fps); self.enc .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) } /// Waits for queued pictures and returns their coded bytes in order. pub fn flush(&mut self) -> Result>, Error> { self.enc.flush() } /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> { self.enc.set_rate(rate, fps) } fn check(&self, pic: &H265Picture) -> Result<(), Error> { if pic.slot as usize >= DPB_SLOTS { return Err(Error::Invalid("DPB slot".into())); } match pic.reference { None if pic.idr && pic.poc == 0 && pic.keep.iter().all(Option::is_none) => Ok(()), Some(r) if !pic.idr && (r.slot as usize) < DPB_SLOTS && r.slot != pic.slot && pic.keep.iter().flatten().chain([&r.poc]).all(|&p| (1..=32768).contains(&(pic.poc - p))) && pic.keep.iter().flatten().filter(|&&p| p == r.poc).count() == 0 => { Ok(()) } _ => Err(Error::Invalid("picture and reference do not match".into())), } } } fn create_parameters( vs: &VideoSession, cfg: &H265EncodeConfig, c: &Coding, ) -> Result { let cropped = c.width != cfg.width || c.height != cfg.height; let mut ptl = zeroed::(); ptl.general_profile_idc = profile_idc(cfg.bit_depth); ptl.general_level_idc = c.level; ptl.flags.set_general_progressive_source_flag(1); ptl.flags.set_general_frame_only_constraint_flag(1); let mut dpb = zeroed::(); dpb.max_dec_pic_buffering_minus1[0] = (DPB_SLOTS - 1) as u8; let mut vui = zeroed::(); vui.flags.set_vui_timing_info_present_flag(1); vui.flags.set_vui_poc_proportional_to_timing_flag(1); vui.vui_num_units_in_tick = cfg.fps.1; vui.vui_time_scale = cfg.fps.0; if let Some(c) = cfg.colour { vui.flags.set_video_signal_type_present_flag(1); vui.flags.set_video_full_range_flag(c.full_range as u32); vui.flags.set_colour_description_present_flag(1); vui.video_format = 5; vui.colour_primaries = c.primaries; vui.transfer_characteristics = c.transfer; vui.matrix_coeffs = c.matrix; } let mut vps = zeroed::(); vps.flags.set_vps_temporal_id_nesting_flag(1); vps.flags.set_vps_timing_info_present_flag(1); vps.flags.set_vps_poc_proportional_to_timing_flag(1); vps.vps_num_units_in_tick = cfg.fps.1; vps.vps_time_scale = cfg.fps.0; vps.pDecPicBufMgr = &dpb; vps.pProfileTierLevel = &ptl; let mut sps = zeroed::(); sps.flags.set_sps_temporal_id_nesting_flag(1); sps.flags.set_conformance_window_flag(cropped as u32); sps.flags.set_vui_parameters_present_flag(1); sps.flags.set_amp_enabled_flag(1); sps.flags .set_sample_adaptive_offset_enabled_flag(c.sao as u32); sps.chroma_format_idc = vk::video::STD_VIDEO_H265_CHROMA_FORMAT_IDC_420; sps.bit_depth_luma_minus8 = cfg.bit_depth - 8; sps.bit_depth_chroma_minus8 = cfg.bit_depth - 8; sps.pic_width_in_luma_samples = c.width; sps.pic_height_in_luma_samples = c.height; sps.log2_max_pic_order_cnt_lsb_minus4 = 4; sps.log2_min_luma_coding_block_size_minus3 = (c.min_cb_log2 - 3) as u8; sps.log2_diff_max_min_luma_coding_block_size = (c.ctb_log2 - c.min_cb_log2) as u8; sps.log2_min_luma_transform_block_size_minus2 = (c.min_tb_log2 - 2) as u8; sps.log2_diff_max_min_luma_transform_block_size = (c.max_tb_log2 - c.min_tb_log2) as u8; sps.max_transform_hierarchy_depth_inter = (c.ctb_log2 - c.min_tb_log2) as u8; sps.max_transform_hierarchy_depth_intra = (c.ctb_log2 - c.min_tb_log2) as u8; sps.conf_win_right_offset = (c.width - cfg.width) / 2; sps.conf_win_bottom_offset = (c.height - cfg.height) / 2; sps.pProfileTierLevel = &ptl; sps.pDecPicBufMgr = &dpb; sps.pSequenceParameterSetVui = &vui; let mut pps = zeroed::(); pps.flags .set_transform_skip_enabled_flag(c.transform_skip as u32); pps.flags.set_pps_loop_filter_across_slices_enabled_flag(1); pps.flags .set_cu_qp_delta_enabled_flag((!matches!(cfg.rate, RateControl::ConstantQp { .. })) as u32); let add = vk::VideoEncodeH265SessionParametersAddInfoKHR::builder() .std_vp_ss(std::slice::from_ref(&vps)) .std_sp_ss(std::slice::from_ref(&sps)) .std_pp_ss(std::slice::from_ref(&pps)) .build(); let mut h265 = vk::VideoEncodeH265SessionParametersCreateInfoKHR::builder() .max_std_vps_count(1) .max_std_sps_count(1) .max_std_pps_count(1) .parameters_add_info(&add) .build(); let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder() .quality_level(vs.quality_level) .build(); let info = vk::VideoSessionParametersCreateInfoKHR::builder() .video_session(vs.session) .push_next(&mut quality) .push_next(&mut h265) .build(); unsafe { vk( vs.gpu .device() .create_video_session_parameters_khr(&info, None), "vkCreateVideoSessionParametersKHR", ) } } fn coding(caps: &Caps, cfg: &H265EncodeConfig) -> Result { type T = vk::VideoEncodeH265TransformBlockSizeFlagsKHR; let ctb_log2 = [ (vk::VideoEncodeH265CtbSizeFlagsKHR::_64, 6), (vk::VideoEncodeH265CtbSizeFlagsKHR::_32, 5), (vk::VideoEncodeH265CtbSizeFlagsKHR::_16, 4), ] .into_iter() .find(|(flag, _)| caps.ctb_sizes.contains(*flag)) .map(|(_, log2)| log2) .ok_or_else(|| Error::Unsupported("H.265 CTB size".into()))?; let min_tb_log2 = [(T::_4, 2), (T::_8, 3), (T::_16, 4), (T::_32, 5)] .into_iter() .find(|(flag, _)| caps.transform_sizes.contains(*flag)) .map(|(_, log2)| log2) .ok_or_else(|| Error::Unsupported("H.265 transform block size".into()))?; let max_tb_log2 = [(T::_32, 5), (T::_16, 4), (T::_8, 3), (T::_4, 2)] .into_iter() .find(|(flag, _)| caps.transform_sizes.contains(*flag)) .map(|(_, log2)| log2) .ok_or_else(|| Error::Unsupported("H.265 transform block size".into()))?; let min_cb_log2 = if ctb_log2 >= 5 { 4 } else { 3 }; let width = align(cfg.width, 1 << min_cb_log2); let height = align(cfg.height, 1 << min_cb_log2); Ok(Coding { width, height, ctb_log2, min_cb_log2, min_tb_log2, max_tb_log2: max_tb_log2.min(ctb_log2), sao: caps .std_flags .contains(vk::VideoEncodeH265StdFlagsKHR::SAMPLE_ADAPTIVE_OFFSET_ENABLED_FLAG_SET), transform_skip: caps .std_flags .contains(vk::VideoEncodeH265StdFlagsKHR::TRANSFORM_SKIP_ENABLED_FLAG_SET), level: h265_level(cfg.level, caps.max_level)?, }) } fn profile_idc(bit_depth: u8) -> vk::video::StdVideoH265ProfileIdc { if bit_depth == 10 { vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10 } else { vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN } } fn h265_level( idc: u8, driver_max: vk::video::StdVideoH265LevelIdc, ) -> Result { const LEVELS: [(u8, vk::video::StdVideoH265LevelIdc); 13] = [ (30, vk::video::STD_VIDEO_H265_LEVEL_IDC_1_0), (60, vk::video::STD_VIDEO_H265_LEVEL_IDC_2_0), (63, vk::video::STD_VIDEO_H265_LEVEL_IDC_2_1), (90, vk::video::STD_VIDEO_H265_LEVEL_IDC_3_0), (93, vk::video::STD_VIDEO_H265_LEVEL_IDC_3_1), (120, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_0), (123, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_1), (150, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_0), (153, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_1), (156, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_2), (180, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_0), (183, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_1), (186, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_2), ]; let (_, level) = LEVELS .into_iter() .find(|(value, _)| *value == idc) .ok_or_else(|| Error::Invalid(format!("H.265 general_level_idc {idc}")))?; Ok(if level.0 > driver_max.0 { driver_max } else { level }) } fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result { let mut h265 = vk::VideoEncodeH265CapabilitiesKHR::builder(); let mut encode = vk::VideoEncodeCapabilitiesKHR::builder(); let mut caps = vk::VideoCapabilitiesKHR::builder() .push_next(&mut h265) .push_next(&mut encode); video_caps(gpu, profile, &mut caps)?; Ok(Caps { std_header_version: caps.std_header_version.clone(), max_extent: caps.max_coded_extent, size_align: caps.min_bitstream_buffer_size_alignment, rc_modes: encode.rate_control_modes, quality_levels: encode.max_quality_levels, max_refs: h265.max_p_picture_l0_reference_count, max_level: h265.max_level_idc, ctb_sizes: h265.ctb_sizes, transform_sizes: h265.transform_block_sizes, std_flags: h265.std_syntax_flags, }) } fn reference_info( primary: vk::video::StdVideoH265PictureType, poc: i32, ) -> vk::video::StdVideoEncodeH265ReferenceInfo { let mut info = zeroed::(); info.pic_type = primary; info.PicOrderCntVal = poc; info } fn short_term_rps(poc: i32, used: i32, keep: &[Option]) -> vk::video::StdVideoH265ShortTermRefPicSet { let mut pocs: Vec = keep.iter().flatten().copied().chain([used]).collect(); pocs.sort_unstable_by(|a, b| b.cmp(a)); let mut rps = zeroed::(); rps.num_negative_pics = pocs.len() as u8; let mut prev = poc; for (i, &p) in pocs.iter().enumerate() { rps.delta_poc_s0_minus1[i] = (prev - p - 1) as u16; if p == used { rps.used_by_curr_pic_s0_flag |= 1 << i; } prev = p; } rps }