edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | use std::ffi::c_void; |
| 2 | |
| 3 | use vulkanalia::prelude::v1_3::*; |
| 4 | use vulkanalia::vk::{ |
| 5 | KhrVideoEncodeQueueExtensionDeviceCommands, KhrVideoQueueExtensionDeviceCommands, |
| 6 | }; |
| 7 | |
| 8 | #[cfg(target_os = "linux")] |
| 9 | use crate::dmabuf::DmaBuf; |
| 10 | use crate::h264_encode::validate; |
| 11 | use crate::rgb_convert::{Input, check_rgb}; |
| 12 | use crate::session::{ |
| 13 | quality_level, |
| 14 | DPB_SLOTS, Encoder, VideoSession, align, component_bit_depth, picture_resource, video_caps, vk, |
| 15 | zeroed, |
| 16 | }; |
| 17 | use crate::{Colour, Error, Gpu, RateControl}; |
| 18 | |
| 19 | /// Settings fixed for the life of a session. |
| 20 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 21 | pub struct H265EncodeConfig { |
| 22 | /// Width in luma samples, even. |
| 23 | pub width: u32, |
| 24 | /// Height in luma samples, even. |
| 25 | pub height: u32, |
| 26 | /// Frame rate as numerator and denominator. |
| 27 | pub fps: (u32, u32), |
| 28 | /// Rate control. |
| 29 | pub rate: RateControl, |
| 30 | /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input). |
| 31 | pub bit_depth: u8, |
| 32 | /// `general_level_idc` (30 to 186), chosen by the caller and clamped to the driver maximum. |
| 33 | pub level: u8, |
| 34 | /// Colour description for the VUI, or none. |
| 35 | pub colour: Option<Colour>, |
| 36 | /// 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. |
| 37 | pub quality: u32, |
| 38 | } |
| 39 | |
| 40 | /// One picture to encode. |
| 41 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 42 | pub struct H265Picture { |
| 43 | /// Encode as IDR, POC must be 0. |
| 44 | pub idr: bool, |
| 45 | /// PicOrderCntVal. |
| 46 | pub poc: i32, |
| 47 | /// DPB slot this picture is written to, below `DPB_SLOTS`. |
| 48 | pub slot: u32, |
| 49 | /// Reference for a P picture, None for IDR. |
| 50 | pub reference: Option<H265Ref>, |
| 51 | /// PicOrderCntVal of every other picture the decoder keeps for a later reference, none for IDR. |
| 52 | pub keep: [Option<i32>; DPB_SLOTS], |
| 53 | } |
| 54 | |
| 55 | /// A picture held in the DPB. |
| 56 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 57 | pub struct H265Ref { |
| 58 | /// DPB slot, below `DPB_SLOTS`. |
| 59 | pub slot: u32, |
| 60 | /// PicOrderCntVal of the reference, lower than the picture's. |
| 61 | pub poc: i32, |
| 62 | } |
| 63 | |
| 64 | struct Caps { |
| 65 | std_header_version: vk::ExtensionProperties, |
| 66 | max_extent: vk::Extent2D, |
| 67 | size_align: u64, |
| 68 | rc_modes: vk::VideoEncodeRateControlModeFlagsKHR, |
| 69 | quality_levels: u32, |
| 70 | max_refs: u32, |
| 71 | max_level: vk::video::StdVideoH265LevelIdc, |
| 72 | ctb_sizes: vk::VideoEncodeH265CtbSizeFlagsKHR, |
| 73 | transform_sizes: vk::VideoEncodeH265TransformBlockSizeFlagsKHR, |
| 74 | std_flags: vk::VideoEncodeH265StdFlagsKHR, |
| 75 | } |
| 76 | |
| 77 | struct Coding { |
| 78 | width: u32, |
| 79 | height: u32, |
| 80 | ctb_log2: u32, |
| 81 | min_cb_log2: u32, |
| 82 | min_tb_log2: u32, |
| 83 | max_tb_log2: u32, |
| 84 | sao: bool, |
| 85 | transform_skip: bool, |
| 86 | level: vk::video::StdVideoH265LevelIdc, |
| 87 | } |
| 88 | |
| 89 | struct Profile { |
| 90 | info: vk::VideoProfileInfoKHR, |
| 91 | codec: vk::VideoEncodeH265ProfileInfoKHR, |
| 92 | usage: vk::VideoEncodeUsageInfoKHR, |
| 93 | } |
| 94 | |
| 95 | impl Profile { |
| 96 | fn new(bit_depth: u8) -> Box<Self> { |
| 97 | let component = component_bit_depth(bit_depth); |
| 98 | let mut p = Box::new(Profile { |
| 99 | info: vk::VideoProfileInfoKHR::builder() |
| 100 | .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_H265) |
| 101 | .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) |
| 102 | .luma_bit_depth(component) |
| 103 | .chroma_bit_depth(component) |
| 104 | .build(), |
| 105 | codec: vk::VideoEncodeH265ProfileInfoKHR::builder() |
| 106 | .std_profile_idc(profile_idc(bit_depth)) |
| 107 | .build(), |
| 108 | usage: vk::VideoEncodeUsageInfoKHR::builder() |
| 109 | .video_usage_hints(vk::VideoEncodeUsageFlagsKHR::STREAMING) |
| 110 | .video_content_hints(vk::VideoEncodeContentFlagsKHR::DESKTOP) |
| 111 | .tuning_mode(vk::VideoEncodeTuningModeKHR::LOW_LATENCY) |
| 112 | .build(), |
| 113 | }); |
| 114 | p.codec.next = &p.usage as *const _ as *const c_void; |
| 115 | p.info.next = &p.codec as *const _ as *const c_void; |
| 116 | p |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | struct RateChain { |
| 121 | rc: vk::VideoEncodeRateControlInfoKHR, |
| 122 | rc_h265: vk::VideoEncodeH265RateControlInfoKHR, |
| 123 | layer: vk::VideoEncodeRateControlLayerInfoKHR, |
| 124 | layer_h265: vk::VideoEncodeH265RateControlLayerInfoKHR, |
| 125 | } |
| 126 | |
| 127 | impl RateChain { |
| 128 | fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> { |
| 129 | let mode = rate.mode(); |
| 130 | let layers = u32::from(rate.layer().is_some()); |
| 131 | let (bitrate, max_bitrate, buffer_ms) = rate.layer().unwrap_or_default(); |
| 132 | let mut c = Box::new(RateChain { |
| 133 | rc: vk::VideoEncodeRateControlInfoKHR::builder() |
| 134 | .rate_control_mode(mode) |
| 135 | .virtual_buffer_size_in_ms(buffer_ms) |
| 136 | .initial_virtual_buffer_size_in_ms(buffer_ms) |
| 137 | .build(), |
| 138 | rc_h265: vk::VideoEncodeH265RateControlInfoKHR::builder() |
| 139 | .flags( |
| 140 | vk::VideoEncodeH265RateControlFlagsKHR::REGULAR_GOP |
| 141 | | vk::VideoEncodeH265RateControlFlagsKHR::REFERENCE_PATTERN_FLAT, |
| 142 | ) |
| 143 | .gop_frame_count(u32::MAX) |
| 144 | .idr_period(u32::MAX) |
| 145 | .consecutive_b_frame_count(0) |
| 146 | .sub_layer_count(1) |
| 147 | .build(), |
| 148 | layer: vk::VideoEncodeRateControlLayerInfoKHR::builder() |
| 149 | .average_bitrate(bitrate as u64) |
| 150 | .max_bitrate(max_bitrate as u64) |
| 151 | .frame_rate_numerator(fps.0) |
| 152 | .frame_rate_denominator(fps.1) |
| 153 | .build(), |
| 154 | layer_h265: { |
| 155 | let mut layer = vk::VideoEncodeH265RateControlLayerInfoKHR::builder(); |
| 156 | if let Some(q) = rate.min_qp() { |
| 157 | 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 }); |
| 158 | } |
| 159 | if let Some(m) = rate.max_frame_bytes() { |
| 160 | layer = layer.use_max_frame_size(true).max_frame_size(vk::VideoEncodeH265FrameSizeKHR { frame_i_size: m, frame_p_size: m, frame_b_size: m }); |
| 161 | } |
| 162 | layer.build() |
| 163 | }, |
| 164 | }); |
| 165 | c.rc.next = &c.rc_h265 as *const _ as *const c_void; |
| 166 | c.rc.layer_count = layers; |
| 167 | c.rc.layers = &c.layer; |
| 168 | c.layer.next = &c.layer_h265 as *const _ as *const c_void; |
| 169 | c |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /// An H.265 Vulkan Video encode session: IDR and P pictures, one reference, Main profile, NV12 uploaded from CPU. |
| 174 | pub struct H265EncodeSession { |
| 175 | enc: Encoder, |
| 176 | } |
| 177 | |
| 178 | impl H265EncodeSession { |
| 179 | /// Creates a session with its DPB, buffers and parameter sets. |
| 180 | pub fn new(gpu: &Gpu, cfg: &H265EncodeConfig) -> Result<Self, Error> { |
| 181 | validate(cfg.width, cfg.height, cfg.fps, cfg.rate)?; |
| 182 | if cfg.bit_depth != 8 && cfg.bit_depth != 10 { |
| 183 | return Err(Error::Invalid("H.265 bit depth".into())); |
| 184 | } |
| 185 | let family = gpu |
| 186 | .encode_family() |
| 187 | .ok_or_else(|| Error::Unsupported("H.265 encode queue family".into()))?; |
| 188 | if !gpu |
| 189 | .device() |
| 190 | .extensions() |
| 191 | .contains(&vk::KHR_VIDEO_ENCODE_H265_EXTENSION.name) |
| 192 | { |
| 193 | return Err(Error::Unsupported("H.265 encode".into())); |
| 194 | } |
| 195 | let profile = Profile::new(cfg.bit_depth); |
| 196 | let caps = query_caps(gpu, &profile.info).map_err(|e| match e { |
| 197 | Error::Vk(..) if cfg.bit_depth == 10 => { |
| 198 | Error::Unsupported("10-bit H.265 encode".into()) |
| 199 | } |
| 200 | e => e, |
| 201 | })?; |
| 202 | let coding = coding(&caps, cfg)?; |
| 203 | if coding.width > caps.max_extent.width || coding.height > caps.max_extent.height { |
| 204 | return Err(Error::Unsupported(format!( |
| 205 | "H.265 encode {}x{}", |
| 206 | coding.width, coding.height |
| 207 | ))); |
| 208 | } |
| 209 | if caps.max_refs < 1 { |
| 210 | return Err(Error::Unsupported("H.265 encode reference".into())); |
| 211 | } |
| 212 | let mode = cfg.rate.mode(); |
| 213 | if !caps.rc_modes.contains(mode) { |
| 214 | return Err(Error::Unsupported(format!("rate control {mode:?}"))); |
| 215 | } |
| 216 | |
| 217 | let upload_family = gpu |
| 218 | .graphics_family() |
| 219 | .ok_or_else(|| Error::Unsupported("graphics queue family for upload".into()))?; |
| 220 | let extent = vk::Extent2D { |
| 221 | width: coding.width, |
| 222 | height: coding.height, |
| 223 | }; |
| 224 | let vs = VideoSession::new( |
| 225 | gpu, |
| 226 | family, |
| 227 | &profile.info, |
| 228 | &caps.std_header_version, |
| 229 | extent, |
| 230 | DPB_SLOTS as u32, |
| 231 | 1, |
| 232 | )?; |
| 233 | let mut enc = Encoder::new( |
| 234 | vs, |
| 235 | &profile.info, |
| 236 | upload_family, |
| 237 | (cfg.width, cfg.height), |
| 238 | extent, |
| 239 | (cfg.rate, cfg.fps), |
| 240 | caps.size_align, |
| 241 | )?; |
| 242 | enc.vs.quality_level = quality_level(cfg.quality, caps.quality_levels); |
| 243 | let params = create_parameters(&enc.vs, cfg, &coding)?; |
| 244 | enc.vs.set_params(params); |
| 245 | Ok(H265EncodeSession { enc }) |
| 246 | } |
| 247 | |
| 248 | /// Annex-B VPS, SPS and PPS of this session. |
| 249 | pub fn parameter_sets(&self) -> Result<Vec<u8>, Error> { |
| 250 | let mut h265 = vk::VideoEncodeH265SessionParametersGetInfoKHR::builder() |
| 251 | .write_std_vps(true) |
| 252 | .write_std_sps(true) |
| 253 | .write_std_pps(true) |
| 254 | .std_vps_id(0) |
| 255 | .std_sps_id(0) |
| 256 | .std_pps_id(0) |
| 257 | .build(); |
| 258 | let info = vk::VideoEncodeSessionParametersGetInfoKHR::builder() |
| 259 | .video_session_parameters(self.enc.vs.params) |
| 260 | .push_next(&mut h265) |
| 261 | .build(); |
| 262 | vk( |
| 263 | unsafe { |
| 264 | self.enc |
| 265 | .vs |
| 266 | .gpu |
| 267 | .device() |
| 268 | .get_encoded_video_session_parameters_khr(&info, None) |
| 269 | }, |
| 270 | "vkGetEncodedVideoSessionParametersKHR", |
| 271 | ) |
| 272 | } |
| 273 | |
| 274 | /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. |
| 275 | pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> { |
| 276 | if y.len() != self.enc.input.0 * self.enc.input.1 |
| 277 | || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 |
| 278 | { |
| 279 | return Err(Error::Invalid("NV12 plane size".into())); |
| 280 | } |
| 281 | self.check(pic)?; |
| 282 | self.enc.upload(Input::Nv12 { y, uv })?; |
| 283 | self.encode_uploaded(pic) |
| 284 | } |
| 285 | |
| 286 | /// 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. |
| 287 | pub fn submit_16( |
| 288 | &mut self, |
| 289 | y: &[u16], |
| 290 | uv: &[u16], |
| 291 | pic: &H265Picture, |
| 292 | ) -> Result<Option<Vec<u8>>, Error> { |
| 293 | if y.len() != self.enc.input.0 * self.enc.input.1 |
| 294 | || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 |
| 295 | { |
| 296 | return Err(Error::Invalid("P010 plane size".into())); |
| 297 | } |
| 298 | self.check(pic)?; |
| 299 | self.enc.upload(Input::P010 { y, uv })?; |
| 300 | self.encode_uploaded(pic) |
| 301 | } |
| 302 | |
| 303 | /// 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. |
| 304 | pub fn submit_rgb( |
| 305 | &mut self, |
| 306 | rgb: &[u8], |
| 307 | src_width: u32, |
| 308 | src_height: u32, |
| 309 | stride_bytes: u32, |
| 310 | bgr: bool, |
| 311 | pic: &H265Picture, |
| 312 | ) -> Result<Option<Vec<u8>>, Error> { |
| 313 | self.check(pic)?; |
| 314 | let src = (src_width as usize, src_height as usize); |
| 315 | check_rgb( |
| 316 | (self.enc.input.0, self.enc.input.1), |
| 317 | src, |
| 318 | rgb, |
| 319 | stride_bytes as usize, |
| 320 | )?; |
| 321 | self.enc.upload(Input::Rgb { |
| 322 | data: rgb, |
| 323 | width: src.0, |
| 324 | height: src.1, |
| 325 | stride: stride_bytes as usize, |
| 326 | bgr, |
| 327 | })?; |
| 328 | self.encode_uploaded(pic) |
| 329 | } |
| 330 | |
| 331 | /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size. |
| 332 | #[cfg(target_os = "linux")] |
| 333 | pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> { |
| 334 | self.check(pic)?; |
| 335 | self.enc.upload_dmabuf(src)?; |
| 336 | self.encode_uploaded(pic) |
| 337 | } |
| 338 | |
| 339 | /// Encodes one picture from a shared D3D11 texture of BGRA or RGBA pixels, downscaled to the encoder size. |
| 340 | #[cfg(windows)] |
| 341 | pub fn submit_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> { |
| 342 | self.check(pic)?; |
| 343 | self.enc.upload_d3d11(src)?; |
| 344 | self.encode_uploaded(pic) |
| 345 | } |
| 346 | |
| 347 | /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes. |
| 348 | #[cfg(windows)] |
| 349 | pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> { |
| 350 | self.submit_d3d11(src, pic)?; |
| 351 | self.enc.flush_last() |
| 352 | } |
| 353 | |
| 354 | /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once. |
| 355 | #[cfg(windows)] |
| 356 | pub fn d3d11_imports(&self) -> usize { |
| 357 | self.enc.import_count() |
| 358 | } |
| 359 | |
| 360 | /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once. |
| 361 | #[cfg(target_os = "linux")] |
| 362 | pub fn dmabuf_imports(&self) -> usize { |
| 363 | self.enc.import_count() |
| 364 | } |
| 365 | |
| 366 | fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Option<Vec<u8>>, Error> { |
| 367 | let extent = self.enc.extent; |
| 368 | |
| 369 | let primary = if pic.idr { |
| 370 | vk::video::STD_VIDEO_H265_PICTURE_TYPE_IDR |
| 371 | } else { |
| 372 | vk::video::STD_VIDEO_H265_PICTURE_TYPE_P |
| 373 | }; |
| 374 | let dpb_pr = self.enc.dpb.each_ref().map(|d| picture_resource(d.view, extent)); |
| 375 | let src_pr = picture_resource(self.enc.src_view(), extent); |
| 376 | |
| 377 | let new_std = reference_info(primary, pic.poc); |
| 378 | let ref_std = pic |
| 379 | .reference |
| 380 | .map(|r| reference_info(vk::video::STD_VIDEO_H265_PICTURE_TYPE_P, r.poc)); |
| 381 | let mut new_dpb = vk::VideoEncodeH265DpbSlotInfoKHR::builder() |
| 382 | .std_reference_info(&new_std) |
| 383 | .build(); |
| 384 | let mut ref_dpb = ref_std.as_ref().map(|s| { |
| 385 | vk::VideoEncodeH265DpbSlotInfoKHR::builder() |
| 386 | .std_reference_info(s) |
| 387 | .build() |
| 388 | }); |
| 389 | |
| 390 | let mut refs = Vec::new(); |
| 391 | if let (Some(r), Some(dpb)) = (pic.reference, ref_dpb.as_mut()) { |
| 392 | refs.push( |
| 393 | vk::VideoReferenceSlotInfoKHR::builder() |
| 394 | .slot_index(r.slot as i32) |
| 395 | .picture_resource(&dpb_pr[r.slot as usize]) |
| 396 | .push_next(dpb) |
| 397 | .build(), |
| 398 | ); |
| 399 | } |
| 400 | let setup = vk::VideoReferenceSlotInfoKHR::builder() |
| 401 | .slot_index(pic.slot as i32) |
| 402 | .picture_resource(&dpb_pr[pic.slot as usize]) |
| 403 | .push_next(&mut new_dpb) |
| 404 | .build(); |
| 405 | |
| 406 | let order = match pic.reference { |
| 407 | Some(r) => [pic.slot, r.slot], |
| 408 | None => [0, 1], |
| 409 | }; |
| 410 | let begin_slots: Vec<vk::VideoReferenceSlotInfoKHR> = order |
| 411 | .iter() |
| 412 | .map(|&i| { |
| 413 | let active = pic |
| 414 | .reference |
| 415 | .filter(|r| r.slot == i) |
| 416 | .map_or(-1, |_| i as i32); |
| 417 | vk::VideoReferenceSlotInfoKHR::builder() |
| 418 | .slot_index(active) |
| 419 | .picture_resource(&dpb_pr[i as usize]) |
| 420 | .build() |
| 421 | }) |
| 422 | .collect(); |
| 423 | |
| 424 | let mut list0 = [0xffu8; 15]; |
| 425 | if let Some(r) = pic.reference { |
| 426 | list0[0] = r.slot as u8; |
| 427 | } |
| 428 | let mut lists = zeroed::<vk::video::StdVideoEncodeH265ReferenceListsInfo>(); |
| 429 | lists.RefPicList0 = list0; |
| 430 | lists.RefPicList1 = [0xff; 15]; |
| 431 | |
| 432 | let rps = pic.reference.map(|r| short_term_rps(pic.poc, r.poc, &pic.keep)); |
| 433 | |
| 434 | let mut pic_std = zeroed::<vk::video::StdVideoEncodeH265PictureInfo>(); |
| 435 | pic_std.flags.set_IrapPicFlag(pic.idr as u32); |
| 436 | pic_std.flags.set_is_reference(1); |
| 437 | pic_std.flags.set_pic_output_flag(1); |
| 438 | pic_std.pic_type = primary; |
| 439 | pic_std.PicOrderCntVal = pic.poc; |
| 440 | pic_std.pRefLists = &lists; |
| 441 | pic_std.pShortTermRefPicSet = rps.as_ref().map_or(std::ptr::null(), |r| r as *const _); |
| 442 | |
| 443 | let mut slice_std = zeroed::<vk::video::StdVideoEncodeH265SliceSegmentHeader>(); |
| 444 | slice_std.flags.set_first_slice_segment_in_pic_flag(1); |
| 445 | slice_std.slice_type = if pic.idr { |
| 446 | vk::video::STD_VIDEO_H265_SLICE_TYPE_I |
| 447 | } else { |
| 448 | vk::video::STD_VIDEO_H265_SLICE_TYPE_P |
| 449 | }; |
| 450 | slice_std.MaxNumMergeCand = 5; |
| 451 | let constant_qp = self.enc.rate.constant_qp().map_or(0, i32::from); |
| 452 | let slices = [vk::VideoEncodeH265NaluSliceSegmentInfoKHR::builder() |
| 453 | .constant_qp(constant_qp) |
| 454 | .std_slice_segment_header(&slice_std) |
| 455 | .build()]; |
| 456 | let mut h265_pic = vk::VideoEncodeH265PictureInfoKHR::builder() |
| 457 | .nalu_slice_segment_entries(&slices) |
| 458 | .std_picture_info(&pic_std) |
| 459 | .build(); |
| 460 | |
| 461 | let encode = vk::VideoEncodeInfoKHR::builder() |
| 462 | .dst_buffer(self.enc.bitstream_buffer()) |
| 463 | .dst_buffer_offset(0) |
| 464 | .dst_buffer_range(self.enc.bitstream_len) |
| 465 | .src_picture_resource(src_pr) |
| 466 | .setup_reference_slot(&setup) |
| 467 | .reference_slots(&refs) |
| 468 | .push_next(&mut h265_pic) |
| 469 | .build(); |
| 470 | |
| 471 | let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1); |
| 472 | let mut chain = RateChain::new(self.enc.rate, self.enc.fps); |
| 473 | self.enc |
| 474 | .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) |
| 475 | } |
| 476 | |
| 477 | /// Encodes one picture synchronously and returns its coded bytes. |
| 478 | pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H265Picture) -> Result<Vec<u8>, Error> { |
| 479 | self.submit(y, uv, pic)?; |
| 480 | self.enc.flush_last() |
| 481 | } |
| 482 | |
| 483 | /// Encodes one picture synchronously and returns its coded bytes. |
| 484 | pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &H265Picture) -> Result<Vec<u8>, Error> { |
| 485 | self.submit_16(y, uv, pic)?; |
| 486 | self.enc.flush_last() |
| 487 | } |
| 488 | |
| 489 | /// Encodes one picture synchronously and returns its coded bytes. |
| 490 | pub fn encode_rgb( |
| 491 | &mut self, |
| 492 | rgb: &[u8], |
| 493 | src_width: u32, |
| 494 | src_height: u32, |
| 495 | stride_bytes: u32, |
| 496 | bgr: bool, |
| 497 | pic: &H265Picture, |
| 498 | ) -> Result<Vec<u8>, Error> { |
| 499 | self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; |
| 500 | self.enc.flush_last() |
| 501 | } |
| 502 | |
| 503 | #[cfg(target_os = "linux")] |
| 504 | /// Encodes one picture synchronously and returns its coded bytes. |
| 505 | pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> { |
| 506 | self.submit_dmabuf(src, pic)?; |
| 507 | self.enc.flush_last() |
| 508 | } |
| 509 | |
| 510 | /// Waits for queued pictures and returns their coded bytes in order. |
| 511 | pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> { |
| 512 | self.enc.flush() |
| 513 | } |
| 514 | |
| 515 | /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. |
| 516 | pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> { |
| 517 | self.enc.set_rate(rate, fps) |
| 518 | } |
| 519 | |
| 520 | fn check(&self, pic: &H265Picture) -> Result<(), Error> { |
| 521 | if pic.slot as usize >= DPB_SLOTS { |
| 522 | return Err(Error::Invalid("DPB slot".into())); |
| 523 | } |
| 524 | match pic.reference { |
| 525 | None if pic.idr && pic.poc == 0 && pic.keep.iter().all(Option::is_none) => Ok(()), |
| 526 | Some(r) |
| 527 | if !pic.idr |
| 528 | && (r.slot as usize) < DPB_SLOTS |
| 529 | && r.slot != pic.slot |
| 530 | && pic.keep.iter().flatten().chain([&r.poc]).all(|&p| (1..=32768).contains(&(pic.poc - p))) |
| 531 | && pic.keep.iter().flatten().filter(|&&p| p == r.poc).count() == 0 => |
| 532 | { |
| 533 | Ok(()) |
| 534 | } |
| 535 | _ => Err(Error::Invalid("picture and reference do not match".into())), |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | fn create_parameters( |
| 541 | vs: &VideoSession, |
| 542 | cfg: &H265EncodeConfig, |
| 543 | c: &Coding, |
| 544 | ) -> Result<vk::VideoSessionParametersKHR, Error> { |
| 545 | let cropped = c.width != cfg.width || c.height != cfg.height; |
| 546 | |
| 547 | let mut ptl = zeroed::<vk::video::StdVideoH265ProfileTierLevel>(); |
| 548 | ptl.general_profile_idc = profile_idc(cfg.bit_depth); |
| 549 | ptl.general_level_idc = c.level; |
| 550 | ptl.flags.set_general_progressive_source_flag(1); |
| 551 | ptl.flags.set_general_frame_only_constraint_flag(1); |
| 552 | |
| 553 | let mut dpb = zeroed::<vk::video::StdVideoH265DecPicBufMgr>(); |
| 554 | dpb.max_dec_pic_buffering_minus1[0] = (DPB_SLOTS - 1) as u8; |
| 555 | |
| 556 | let mut vui = zeroed::<vk::video::StdVideoH265SequenceParameterSetVui>(); |
| 557 | vui.flags.set_vui_timing_info_present_flag(1); |
| 558 | vui.flags.set_vui_poc_proportional_to_timing_flag(1); |
| 559 | vui.vui_num_units_in_tick = cfg.fps.1; |
| 560 | vui.vui_time_scale = cfg.fps.0; |
| 561 | if let Some(c) = cfg.colour { |
| 562 | vui.flags.set_video_signal_type_present_flag(1); |
| 563 | vui.flags.set_video_full_range_flag(c.full_range as u32); |
| 564 | vui.flags.set_colour_description_present_flag(1); |
| 565 | vui.video_format = 5; |
| 566 | vui.colour_primaries = c.primaries; |
| 567 | vui.transfer_characteristics = c.transfer; |
| 568 | vui.matrix_coeffs = c.matrix; |
| 569 | } |
| 570 | |
| 571 | let mut vps = zeroed::<vk::video::StdVideoH265VideoParameterSet>(); |
| 572 | vps.flags.set_vps_temporal_id_nesting_flag(1); |
| 573 | vps.flags.set_vps_timing_info_present_flag(1); |
| 574 | vps.flags.set_vps_poc_proportional_to_timing_flag(1); |
| 575 | vps.vps_num_units_in_tick = cfg.fps.1; |
| 576 | vps.vps_time_scale = cfg.fps.0; |
| 577 | vps.pDecPicBufMgr = &dpb; |
| 578 | vps.pProfileTierLevel = &ptl; |
| 579 | |
| 580 | let mut sps = zeroed::<vk::video::StdVideoH265SequenceParameterSet>(); |
| 581 | sps.flags.set_sps_temporal_id_nesting_flag(1); |
| 582 | sps.flags.set_conformance_window_flag(cropped as u32); |
| 583 | sps.flags.set_vui_parameters_present_flag(1); |
| 584 | sps.flags.set_amp_enabled_flag(1); |
| 585 | sps.flags |
| 586 | .set_sample_adaptive_offset_enabled_flag(c.sao as u32); |
| 587 | sps.chroma_format_idc = vk::video::STD_VIDEO_H265_CHROMA_FORMAT_IDC_420; |
| 588 | sps.bit_depth_luma_minus8 = cfg.bit_depth - 8; |
| 589 | sps.bit_depth_chroma_minus8 = cfg.bit_depth - 8; |
| 590 | sps.pic_width_in_luma_samples = c.width; |
| 591 | sps.pic_height_in_luma_samples = c.height; |
| 592 | sps.log2_max_pic_order_cnt_lsb_minus4 = 4; |
| 593 | sps.log2_min_luma_coding_block_size_minus3 = (c.min_cb_log2 - 3) as u8; |
| 594 | sps.log2_diff_max_min_luma_coding_block_size = (c.ctb_log2 - c.min_cb_log2) as u8; |
| 595 | sps.log2_min_luma_transform_block_size_minus2 = (c.min_tb_log2 - 2) as u8; |
| 596 | sps.log2_diff_max_min_luma_transform_block_size = (c.max_tb_log2 - c.min_tb_log2) as u8; |
| 597 | sps.max_transform_hierarchy_depth_inter = (c.ctb_log2 - c.min_tb_log2) as u8; |
| 598 | sps.max_transform_hierarchy_depth_intra = (c.ctb_log2 - c.min_tb_log2) as u8; |
| 599 | sps.conf_win_right_offset = (c.width - cfg.width) / 2; |
| 600 | sps.conf_win_bottom_offset = (c.height - cfg.height) / 2; |
| 601 | sps.pProfileTierLevel = &ptl; |
| 602 | sps.pDecPicBufMgr = &dpb; |
| 603 | sps.pSequenceParameterSetVui = &vui; |
| 604 | |
| 605 | let mut pps = zeroed::<vk::video::StdVideoH265PictureParameterSet>(); |
| 606 | pps.flags |
| 607 | .set_transform_skip_enabled_flag(c.transform_skip as u32); |
| 608 | pps.flags.set_pps_loop_filter_across_slices_enabled_flag(1); |
| 609 | pps.flags |
| 610 | .set_cu_qp_delta_enabled_flag((!matches!(cfg.rate, RateControl::ConstantQp { .. })) as u32); |
| 611 | |
| 612 | let add = vk::VideoEncodeH265SessionParametersAddInfoKHR::builder() |
| 613 | .std_vp_ss(std::slice::from_ref(&vps)) |
| 614 | .std_sp_ss(std::slice::from_ref(&sps)) |
| 615 | .std_pp_ss(std::slice::from_ref(&pps)) |
| 616 | .build(); |
| 617 | let mut h265 = vk::VideoEncodeH265SessionParametersCreateInfoKHR::builder() |
| 618 | .max_std_vps_count(1) |
| 619 | .max_std_sps_count(1) |
| 620 | .max_std_pps_count(1) |
| 621 | .parameters_add_info(&add) |
| 622 | .build(); |
| 623 | let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder() |
| 624 | .quality_level(vs.quality_level) |
| 625 | .build(); |
| 626 | let info = vk::VideoSessionParametersCreateInfoKHR::builder() |
| 627 | .video_session(vs.session) |
| 628 | .push_next(&mut quality) |
| 629 | .push_next(&mut h265) |
| 630 | .build(); |
| 631 | unsafe { |
| 632 | vk( |
| 633 | vs.gpu |
| 634 | .device() |
| 635 | .create_video_session_parameters_khr(&info, None), |
| 636 | "vkCreateVideoSessionParametersKHR", |
| 637 | ) |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | fn coding(caps: &Caps, cfg: &H265EncodeConfig) -> Result<Coding, Error> { |
| 642 | type T = vk::VideoEncodeH265TransformBlockSizeFlagsKHR; |
| 643 | let ctb_log2 = [ |
| 644 | (vk::VideoEncodeH265CtbSizeFlagsKHR::_64, 6), |
| 645 | (vk::VideoEncodeH265CtbSizeFlagsKHR::_32, 5), |
| 646 | (vk::VideoEncodeH265CtbSizeFlagsKHR::_16, 4), |
| 647 | ] |
| 648 | .into_iter() |
| 649 | .find(|(flag, _)| caps.ctb_sizes.contains(*flag)) |
| 650 | .map(|(_, log2)| log2) |
| 651 | .ok_or_else(|| Error::Unsupported("H.265 CTB size".into()))?; |
| 652 | let min_tb_log2 = [(T::_4, 2), (T::_8, 3), (T::_16, 4), (T::_32, 5)] |
| 653 | .into_iter() |
| 654 | .find(|(flag, _)| caps.transform_sizes.contains(*flag)) |
| 655 | .map(|(_, log2)| log2) |
| 656 | .ok_or_else(|| Error::Unsupported("H.265 transform block size".into()))?; |
| 657 | let max_tb_log2 = [(T::_32, 5), (T::_16, 4), (T::_8, 3), (T::_4, 2)] |
| 658 | .into_iter() |
| 659 | .find(|(flag, _)| caps.transform_sizes.contains(*flag)) |
| 660 | .map(|(_, log2)| log2) |
| 661 | .ok_or_else(|| Error::Unsupported("H.265 transform block size".into()))?; |
| 662 | let min_cb_log2 = if ctb_log2 >= 5 { 4 } else { 3 }; |
| 663 | let width = align(cfg.width, 1 << min_cb_log2); |
| 664 | let height = align(cfg.height, 1 << min_cb_log2); |
| 665 | Ok(Coding { |
| 666 | width, |
| 667 | height, |
| 668 | ctb_log2, |
| 669 | min_cb_log2, |
| 670 | min_tb_log2, |
| 671 | max_tb_log2: max_tb_log2.min(ctb_log2), |
| 672 | sao: caps |
| 673 | .std_flags |
| 674 | .contains(vk::VideoEncodeH265StdFlagsKHR::SAMPLE_ADAPTIVE_OFFSET_ENABLED_FLAG_SET), |
| 675 | transform_skip: caps |
| 676 | .std_flags |
| 677 | .contains(vk::VideoEncodeH265StdFlagsKHR::TRANSFORM_SKIP_ENABLED_FLAG_SET), |
| 678 | level: h265_level(cfg.level, caps.max_level)?, |
| 679 | }) |
| 680 | } |
| 681 | |
| 682 | fn profile_idc(bit_depth: u8) -> vk::video::StdVideoH265ProfileIdc { |
| 683 | if bit_depth == 10 { |
| 684 | vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10 |
| 685 | } else { |
| 686 | vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | fn h265_level( |
| 691 | idc: u8, |
| 692 | driver_max: vk::video::StdVideoH265LevelIdc, |
| 693 | ) -> Result<vk::video::StdVideoH265LevelIdc, Error> { |
| 694 | const LEVELS: [(u8, vk::video::StdVideoH265LevelIdc); 13] = [ |
| 695 | (30, vk::video::STD_VIDEO_H265_LEVEL_IDC_1_0), |
| 696 | (60, vk::video::STD_VIDEO_H265_LEVEL_IDC_2_0), |
| 697 | (63, vk::video::STD_VIDEO_H265_LEVEL_IDC_2_1), |
| 698 | (90, vk::video::STD_VIDEO_H265_LEVEL_IDC_3_0), |
| 699 | (93, vk::video::STD_VIDEO_H265_LEVEL_IDC_3_1), |
| 700 | (120, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_0), |
| 701 | (123, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_1), |
| 702 | (150, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_0), |
| 703 | (153, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_1), |
| 704 | (156, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_2), |
| 705 | (180, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_0), |
| 706 | (183, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_1), |
| 707 | (186, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_2), |
| 708 | ]; |
| 709 | let (_, level) = LEVELS |
| 710 | .into_iter() |
| 711 | .find(|(value, _)| *value == idc) |
| 712 | .ok_or_else(|| Error::Invalid(format!("H.265 general_level_idc {idc}")))?; |
| 713 | Ok(if level.0 > driver_max.0 { driver_max } else { level }) |
| 714 | } |
| 715 | |
| 716 | fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { |
| 717 | let mut h265 = vk::VideoEncodeH265CapabilitiesKHR::builder(); |
| 718 | let mut encode = vk::VideoEncodeCapabilitiesKHR::builder(); |
| 719 | let mut caps = vk::VideoCapabilitiesKHR::builder() |
| 720 | .push_next(&mut h265) |
| 721 | .push_next(&mut encode); |
| 722 | video_caps(gpu, profile, &mut caps)?; |
| 723 | Ok(Caps { |
| 724 | std_header_version: caps.std_header_version.clone(), |
| 725 | max_extent: caps.max_coded_extent, |
| 726 | size_align: caps.min_bitstream_buffer_size_alignment, |
| 727 | rc_modes: encode.rate_control_modes, |
| 728 | quality_levels: encode.max_quality_levels, |
| 729 | max_refs: h265.max_p_picture_l0_reference_count, |
| 730 | max_level: h265.max_level_idc, |
| 731 | ctb_sizes: h265.ctb_sizes, |
| 732 | transform_sizes: h265.transform_block_sizes, |
| 733 | std_flags: h265.std_syntax_flags, |
| 734 | }) |
| 735 | } |
| 736 | |
| 737 | fn reference_info( |
| 738 | primary: vk::video::StdVideoH265PictureType, |
| 739 | poc: i32, |
| 740 | ) -> vk::video::StdVideoEncodeH265ReferenceInfo { |
| 741 | let mut info = zeroed::<vk::video::StdVideoEncodeH265ReferenceInfo>(); |
| 742 | info.pic_type = primary; |
| 743 | info.PicOrderCntVal = poc; |
| 744 | info |
| 745 | } |
| 746 | |
| 747 | fn short_term_rps(poc: i32, used: i32, keep: &[Option<i32>]) -> vk::video::StdVideoH265ShortTermRefPicSet { |
| 748 | let mut pocs: Vec<i32> = keep.iter().flatten().copied().chain([used]).collect(); |
| 749 | pocs.sort_unstable_by(|a, b| b.cmp(a)); |
| 750 | let mut rps = zeroed::<vk::video::StdVideoH265ShortTermRefPicSet>(); |
| 751 | rps.num_negative_pics = pocs.len() as u8; |
| 752 | let mut prev = poc; |
| 753 | for (i, &p) in pocs.iter().enumerate() { |
| 754 | rps.delta_poc_s0_minus1[i] = (prev - p - 1) as u16; |
| 755 | if p == used { |
| 756 | rps.used_by_curr_pic_s0_flag |= 1 << i; |
| 757 | } |
| 758 | prev = p; |
| 759 | } |
| 760 | rps |
| 761 | } |