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::rgb_convert::{Input, check_rgb}; |
| 11 | use crate::session::{ |
| 12 | quality_level, |
| 13 | DPB_SLOTS, Encoder, VideoSession, align, picture_resource, validate_rate, video_caps, vk, |
| 14 | zeroed, |
| 15 | }; |
| 16 | use crate::{Colour, Error, Gpu}; |
| 17 | |
| 18 | /// Rate control of an encode session. |
| 19 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 20 | pub enum RateControl { |
| 21 | /// Fixed quantizer for every slice. |
| 22 | ConstantQp { |
| 23 | /// Quantizer, 0 to 51. |
| 24 | qp: u8, |
| 25 | }, |
| 26 | /// Constant bitrate. |
| 27 | Cbr { |
| 28 | /// Target bitrate in bit/s. |
| 29 | bitrate: u32, |
| 30 | /// HRD virtual buffer in milliseconds of `bitrate`, also the initial fullness. |
| 31 | buffer_ms: u32, |
| 32 | }, |
| 33 | /// Variable bitrate: `bitrate` on average, `max_bitrate` at peak, and no |
| 34 | /// quantizer below `min_qp` when set, so easy content spends less. |
| 35 | Vbr { |
| 36 | /// Average bitrate in bit/s. |
| 37 | bitrate: u32, |
| 38 | /// Peak bitrate in bit/s, at least `bitrate`. |
| 39 | max_bitrate: u32, |
| 40 | /// HRD virtual buffer in milliseconds, also the initial fullness. |
| 41 | buffer_ms: u32, |
| 42 | /// Quantizer floor, 0 to 51. |
| 43 | min_qp: Option<u8>, |
| 44 | }, |
| 45 | } |
| 46 | |
| 47 | impl RateControl { |
| 48 | pub(crate) fn mode(self) -> vk::VideoEncodeRateControlModeFlagsKHR { |
| 49 | match self { |
| 50 | RateControl::ConstantQp { .. } => vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, |
| 51 | RateControl::Cbr { .. } => vk::VideoEncodeRateControlModeFlagsKHR::CBR, |
| 52 | RateControl::Vbr { .. } => vk::VideoEncodeRateControlModeFlagsKHR::VBR, |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | pub(crate) fn layer(self) -> Option<(u32, u32, u32)> { |
| 57 | match self { |
| 58 | RateControl::ConstantQp { .. } => None, |
| 59 | RateControl::Cbr { bitrate, buffer_ms } => Some((bitrate, bitrate, buffer_ms)), |
| 60 | RateControl::Vbr { |
| 61 | bitrate, |
| 62 | max_bitrate, |
| 63 | buffer_ms, |
| 64 | .. |
| 65 | } => Some((bitrate, max_bitrate, buffer_ms)), |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | pub(crate) fn constant_qp(self) -> Option<u8> { |
| 70 | match self { |
| 71 | RateControl::ConstantQp { qp } => Some(qp), |
| 72 | _ => None, |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// Variable bitrate caps each coded picture at what its HRD buffer holds: `buffer_ms` of the peak bitrate, in bytes. radv's VBR leaves the buffer to the cap; constant bitrate pads up to a cap instead of spending it, so it gets none. |
| 77 | pub(crate) fn max_frame_bytes(self) -> Option<u32> { |
| 78 | match self { |
| 79 | RateControl::Vbr { |
| 80 | max_bitrate, |
| 81 | buffer_ms, |
| 82 | .. |
| 83 | } => Some((u64::from(max_bitrate) * u64::from(buffer_ms) / 8000).clamp(1, u64::from(u32::MAX)) as u32), |
| 84 | _ => None, |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub(crate) fn min_qp(self) -> Option<u8> { |
| 89 | match self { |
| 90 | RateControl::Vbr { min_qp, .. } => min_qp, |
| 91 | _ => None, |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// H.264 profile written into the SPS and PPS. |
| 97 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 98 | pub enum H264Profile { |
| 99 | /// `profile_idc` 66 with `constraint_set1_flag`; CAVLC. |
| 100 | ConstrainedBaseline, |
| 101 | /// `profile_idc` 77; CABAC, no 8x8 transform. |
| 102 | Main, |
| 103 | /// `profile_idc` 100; CABAC with the 8x8 transform. |
| 104 | High, |
| 105 | } |
| 106 | |
| 107 | /// Settings fixed for the life of a session. |
| 108 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 109 | pub struct H264EncodeConfig { |
| 110 | /// Width in luma samples, even. |
| 111 | pub width: u32, |
| 112 | /// Height in luma samples, even. |
| 113 | pub height: u32, |
| 114 | /// Frame rate as numerator and denominator. |
| 115 | pub fps: (u32, u32), |
| 116 | /// Rate control. |
| 117 | pub rate: RateControl, |
| 118 | /// H.264 profile. |
| 119 | pub profile: H264Profile, |
| 120 | /// `level_idc` (10 to 62), chosen by the caller and clamped to the driver maximum. |
| 121 | pub level: u8, |
| 122 | /// Colour description for the VUI, or none. |
| 123 | pub colour: Option<Colour>, |
| 124 | /// 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. |
| 125 | pub quality: u32, |
| 126 | } |
| 127 | |
| 128 | /// frame_num wraps at 1 << LOG2_MAX_FRAME_NUM. |
| 129 | pub const LOG2_MAX_FRAME_NUM: u8 = 8; |
| 130 | const MAX_REF_FRAMES: u8 = DPB_SLOTS as u8 + 1; |
| 131 | |
| 132 | /// One picture to encode. |
| 133 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 134 | pub struct H264Picture { |
| 135 | /// Encode as IDR. |
| 136 | pub idr: bool, |
| 137 | /// idr_pic_id of an IDR picture. |
| 138 | pub idr_pic_id: u16, |
| 139 | /// frame_num. |
| 140 | pub frame_num: u32, |
| 141 | /// PicOrderCnt. |
| 142 | pub poc: i32, |
| 143 | /// DPB slot this picture is written to, below `DPB_SLOTS`, 0 for IDR; it becomes long-term reference `slot`. |
| 144 | pub slot: u32, |
| 145 | /// Reference for a P picture, None for IDR. |
| 146 | pub reference: Option<H264Ref>, |
| 147 | } |
| 148 | |
| 149 | /// A picture held in the DPB as a long-term reference, LongTermFrameIdx = slot. |
| 150 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 151 | pub struct H264Ref { |
| 152 | /// DPB slot, below `DPB_SLOTS`. |
| 153 | pub slot: u32, |
| 154 | /// frame_num of the reference. |
| 155 | pub frame_num: u32, |
| 156 | /// PicOrderCnt of the reference. |
| 157 | pub poc: i32, |
| 158 | } |
| 159 | |
| 160 | struct Caps { |
| 161 | std_header_version: vk::ExtensionProperties, |
| 162 | max_extent: vk::Extent2D, |
| 163 | size_align: u64, |
| 164 | rc_modes: vk::VideoEncodeRateControlModeFlagsKHR, |
| 165 | quality_levels: u32, |
| 166 | max_refs: u32, |
| 167 | max_level: vk::video::StdVideoH264LevelIdc, |
| 168 | } |
| 169 | |
| 170 | struct Profile { |
| 171 | info: vk::VideoProfileInfoKHR, |
| 172 | codec: vk::VideoEncodeH264ProfileInfoKHR, |
| 173 | usage: vk::VideoEncodeUsageInfoKHR, |
| 174 | } |
| 175 | |
| 176 | impl Profile { |
| 177 | fn new(profile: H264Profile) -> Box<Self> { |
| 178 | let idc = match profile { |
| 179 | H264Profile::ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE, |
| 180 | H264Profile::Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN, |
| 181 | H264Profile::High => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH, |
| 182 | }; |
| 183 | let mut p = Box::new(Profile { |
| 184 | info: vk::VideoProfileInfoKHR::builder() |
| 185 | .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_H264) |
| 186 | .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) |
| 187 | .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) |
| 188 | .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) |
| 189 | .build(), |
| 190 | codec: vk::VideoEncodeH264ProfileInfoKHR::builder() |
| 191 | .std_profile_idc(idc) |
| 192 | .build(), |
| 193 | usage: vk::VideoEncodeUsageInfoKHR::builder() |
| 194 | .video_usage_hints(vk::VideoEncodeUsageFlagsKHR::STREAMING) |
| 195 | .video_content_hints(vk::VideoEncodeContentFlagsKHR::DESKTOP) |
| 196 | .tuning_mode(vk::VideoEncodeTuningModeKHR::LOW_LATENCY) |
| 197 | .build(), |
| 198 | }); |
| 199 | p.codec.next = &p.usage as *const _ as *const c_void; |
| 200 | p.info.next = &p.codec as *const _ as *const c_void; |
| 201 | p |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | struct RateChain { |
| 206 | rc: vk::VideoEncodeRateControlInfoKHR, |
| 207 | rc_h264: vk::VideoEncodeH264RateControlInfoKHR, |
| 208 | layer: vk::VideoEncodeRateControlLayerInfoKHR, |
| 209 | layer_h264: vk::VideoEncodeH264RateControlLayerInfoKHR, |
| 210 | } |
| 211 | |
| 212 | impl RateChain { |
| 213 | fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> { |
| 214 | let mode = rate.mode(); |
| 215 | let layers = u32::from(rate.layer().is_some()); |
| 216 | let (bitrate, max_bitrate, buffer_ms) = rate.layer().unwrap_or_default(); |
| 217 | let mut c = Box::new(RateChain { |
| 218 | rc: vk::VideoEncodeRateControlInfoKHR::builder() |
| 219 | .rate_control_mode(mode) |
| 220 | .virtual_buffer_size_in_ms(buffer_ms) |
| 221 | .initial_virtual_buffer_size_in_ms(buffer_ms) |
| 222 | .build(), |
| 223 | rc_h264: vk::VideoEncodeH264RateControlInfoKHR::builder() |
| 224 | .flags( |
| 225 | vk::VideoEncodeH264RateControlFlagsKHR::REGULAR_GOP |
| 226 | | vk::VideoEncodeH264RateControlFlagsKHR::REFERENCE_PATTERN_FLAT, |
| 227 | ) |
| 228 | .gop_frame_count(u32::MAX) |
| 229 | .idr_period(u32::MAX) |
| 230 | .consecutive_b_frame_count(0) |
| 231 | .temporal_layer_count(1) |
| 232 | .build(), |
| 233 | layer: vk::VideoEncodeRateControlLayerInfoKHR::builder() |
| 234 | .average_bitrate(bitrate as u64) |
| 235 | .max_bitrate(max_bitrate as u64) |
| 236 | .frame_rate_numerator(fps.0) |
| 237 | .frame_rate_denominator(fps.1) |
| 238 | .build(), |
| 239 | layer_h264: { |
| 240 | let mut layer = vk::VideoEncodeH264RateControlLayerInfoKHR::builder(); |
| 241 | if let Some(q) = rate.min_qp() { |
| 242 | layer = layer.use_min_qp(true).min_qp(vk::VideoEncodeH264QpKHR { qp_i: q as i32, qp_p: q as i32, qp_b: q as i32 }); |
| 243 | } |
| 244 | if let Some(m) = rate.max_frame_bytes() { |
| 245 | layer = layer.use_max_frame_size(true).max_frame_size(vk::VideoEncodeH264FrameSizeKHR { frame_i_size: m, frame_p_size: m, frame_b_size: m }); |
| 246 | } |
| 247 | layer.build() |
| 248 | }, |
| 249 | }); |
| 250 | c.rc.next = &c.rc_h264 as *const _ as *const c_void; |
| 251 | c.rc.layer_count = layers; |
| 252 | c.rc.layers = &c.layer; |
| 253 | c.layer.next = &c.layer_h264 as *const _ as *const c_void; |
| 254 | c |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// An H.264 Vulkan Video encode session: IDR and P pictures, one reference, NV12 uploaded from CPU. |
| 259 | pub struct H264EncodeSession { |
| 260 | enc: Encoder, |
| 261 | long_term_open: bool, |
| 262 | } |
| 263 | |
| 264 | impl H264EncodeSession { |
| 265 | /// Creates a session with its DPB, buffers and parameter sets. |
| 266 | pub fn new(gpu: &Gpu, cfg: &H264EncodeConfig) -> Result<Self, Error> { |
| 267 | validate(cfg.width, cfg.height, cfg.fps, cfg.rate)?; |
| 268 | let family = gpu |
| 269 | .encode_family() |
| 270 | .ok_or_else(|| Error::Unsupported("H.264 encode queue family".into()))?; |
| 271 | if !gpu |
| 272 | .device() |
| 273 | .extensions() |
| 274 | .contains(&vk::KHR_VIDEO_ENCODE_H264_EXTENSION.name) |
| 275 | { |
| 276 | return Err(Error::Unsupported("H.264 encode".into())); |
| 277 | } |
| 278 | let width = align(cfg.width, 16); |
| 279 | let height = align(cfg.height, 16); |
| 280 | let profile = Profile::new(cfg.profile); |
| 281 | let caps = query_caps(gpu, &profile.info).map_err(|e| match e { |
| 282 | Error::Vk(..) => Error::Unsupported(format!("H.264 {:?} encode", cfg.profile)), |
| 283 | other => other, |
| 284 | })?; |
| 285 | let level = h264_level(cfg.level, caps.max_level)?; |
| 286 | if width > caps.max_extent.width || height > caps.max_extent.height { |
| 287 | return Err(Error::Unsupported(format!("H.264 encode {width}x{height}"))); |
| 288 | } |
| 289 | if caps.max_refs < 1 { |
| 290 | return Err(Error::Unsupported("H.264 encode reference".into())); |
| 291 | } |
| 292 | let mode = cfg.rate.mode(); |
| 293 | if !caps.rc_modes.contains(mode) { |
| 294 | return Err(Error::Unsupported(format!("rate control {mode:?}"))); |
| 295 | } |
| 296 | |
| 297 | let upload_family = gpu |
| 298 | .graphics_family() |
| 299 | .ok_or_else(|| Error::Unsupported("graphics queue family for upload".into()))?; |
| 300 | let extent = vk::Extent2D { width, height }; |
| 301 | let vs = VideoSession::new( |
| 302 | gpu, |
| 303 | family, |
| 304 | &profile.info, |
| 305 | &caps.std_header_version, |
| 306 | extent, |
| 307 | DPB_SLOTS as u32, |
| 308 | 1, |
| 309 | )?; |
| 310 | let mut enc = Encoder::new( |
| 311 | vs, |
| 312 | &profile.info, |
| 313 | upload_family, |
| 314 | (cfg.width, cfg.height), |
| 315 | extent, |
| 316 | (cfg.rate, cfg.fps), |
| 317 | caps.size_align, |
| 318 | )?; |
| 319 | enc.vs.quality_level = quality_level(cfg.quality, caps.quality_levels); |
| 320 | let params = create_parameters(&enc.vs, cfg, level)?; |
| 321 | enc.vs.set_params(params); |
| 322 | Ok(H264EncodeSession { |
| 323 | enc, |
| 324 | long_term_open: false, |
| 325 | }) |
| 326 | } |
| 327 | |
| 328 | /// Annex-B SPS and PPS of this session. |
| 329 | pub fn parameter_sets(&self) -> Result<Vec<u8>, Error> { |
| 330 | let mut h264 = vk::VideoEncodeH264SessionParametersGetInfoKHR::builder() |
| 331 | .write_std_sps(true) |
| 332 | .write_std_pps(true) |
| 333 | .std_sps_id(0) |
| 334 | .std_pps_id(0) |
| 335 | .build(); |
| 336 | let info = vk::VideoEncodeSessionParametersGetInfoKHR::builder() |
| 337 | .video_session_parameters(self.enc.vs.params) |
| 338 | .push_next(&mut h264) |
| 339 | .build(); |
| 340 | vk( |
| 341 | unsafe { |
| 342 | self.enc |
| 343 | .vs |
| 344 | .gpu |
| 345 | .device() |
| 346 | .get_encoded_video_session_parameters_khr(&info, None) |
| 347 | }, |
| 348 | "vkGetEncodedVideoSessionParametersKHR", |
| 349 | ) |
| 350 | } |
| 351 | |
| 352 | /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight. |
| 353 | pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> { |
| 354 | let (w, h) = self.enc.input; |
| 355 | if y.len() != w * h || uv.len() != w * h / 2 { |
| 356 | return Err(Error::Invalid("NV12 plane size".into())); |
| 357 | } |
| 358 | self.check(pic)?; |
| 359 | self.enc.upload(Input::Nv12 { y, uv })?; |
| 360 | self.encode_uploaded(pic) |
| 361 | } |
| 362 | |
| 363 | /// 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. |
| 364 | pub fn submit_rgb( |
| 365 | &mut self, |
| 366 | rgb: &[u8], |
| 367 | src_width: u32, |
| 368 | src_height: u32, |
| 369 | stride_bytes: u32, |
| 370 | bgr: bool, |
| 371 | pic: &H264Picture, |
| 372 | ) -> Result<Option<Vec<u8>>, Error> { |
| 373 | self.check(pic)?; |
| 374 | let src = (src_width as usize, src_height as usize); |
| 375 | check_rgb(self.enc.input, src, rgb, stride_bytes as usize)?; |
| 376 | self.enc.upload(Input::Rgb { |
| 377 | data: rgb, |
| 378 | width: src.0, |
| 379 | height: src.1, |
| 380 | stride: stride_bytes as usize, |
| 381 | bgr, |
| 382 | })?; |
| 383 | self.encode_uploaded(pic) |
| 384 | } |
| 385 | |
| 386 | /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 of the encoder size. |
| 387 | #[cfg(target_os = "linux")] |
| 388 | pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> { |
| 389 | self.check(pic)?; |
| 390 | self.enc.upload_dmabuf(src)?; |
| 391 | self.encode_uploaded(pic) |
| 392 | } |
| 393 | |
| 394 | /// Encodes one picture from a shared D3D11 texture of BGRA or RGBA pixels, downscaled to the encoder size. |
| 395 | #[cfg(windows)] |
| 396 | pub fn submit_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> { |
| 397 | self.check(pic)?; |
| 398 | self.enc.upload_d3d11(src)?; |
| 399 | self.encode_uploaded(pic) |
| 400 | } |
| 401 | |
| 402 | /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes. |
| 403 | #[cfg(windows)] |
| 404 | pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> { |
| 405 | self.submit_d3d11(src, pic)?; |
| 406 | self.enc.flush_last() |
| 407 | } |
| 408 | |
| 409 | /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once. |
| 410 | #[cfg(windows)] |
| 411 | pub fn d3d11_imports(&self) -> usize { |
| 412 | self.enc.import_count() |
| 413 | } |
| 414 | |
| 415 | /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once. |
| 416 | #[cfg(target_os = "linux")] |
| 417 | pub fn dmabuf_imports(&self) -> usize { |
| 418 | self.enc.import_count() |
| 419 | } |
| 420 | |
| 421 | fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Option<Vec<u8>>, Error> { |
| 422 | let extent = self.enc.extent; |
| 423 | |
| 424 | let primary = if pic.idr { |
| 425 | vk::video::STD_VIDEO_H264_PICTURE_TYPE_IDR |
| 426 | } else { |
| 427 | vk::video::STD_VIDEO_H264_PICTURE_TYPE_P |
| 428 | }; |
| 429 | let dpb_pr = self.enc.dpb.each_ref().map(|d| picture_resource(d.view, extent)); |
| 430 | let src_pr = picture_resource(self.enc.src_view(), extent); |
| 431 | |
| 432 | let new_std = reference_info(primary, pic.frame_num, pic.poc, pic.slot); |
| 433 | let ref_std = pic.reference.map(|r| { |
| 434 | reference_info(vk::video::STD_VIDEO_H264_PICTURE_TYPE_P, r.frame_num, r.poc, r.slot) |
| 435 | }); |
| 436 | let mut new_dpb = vk::VideoEncodeH264DpbSlotInfoKHR::builder() |
| 437 | .std_reference_info(&new_std) |
| 438 | .build(); |
| 439 | let mut ref_dpb = ref_std.as_ref().map(|s| { |
| 440 | vk::VideoEncodeH264DpbSlotInfoKHR::builder() |
| 441 | .std_reference_info(s) |
| 442 | .build() |
| 443 | }); |
| 444 | |
| 445 | let mut refs = Vec::new(); |
| 446 | if let (Some(r), Some(dpb)) = (pic.reference, ref_dpb.as_mut()) { |
| 447 | refs.push( |
| 448 | vk::VideoReferenceSlotInfoKHR::builder() |
| 449 | .slot_index(r.slot as i32) |
| 450 | .picture_resource(&dpb_pr[r.slot as usize]) |
| 451 | .push_next(dpb) |
| 452 | .build(), |
| 453 | ); |
| 454 | } |
| 455 | let setup = vk::VideoReferenceSlotInfoKHR::builder() |
| 456 | .slot_index(pic.slot as i32) |
| 457 | .picture_resource(&dpb_pr[pic.slot as usize]) |
| 458 | .push_next(&mut new_dpb) |
| 459 | .build(); |
| 460 | |
| 461 | let order = match pic.reference { |
| 462 | Some(r) => [pic.slot, r.slot], |
| 463 | None => [0, 1], |
| 464 | }; |
| 465 | let begin_slots: Vec<vk::VideoReferenceSlotInfoKHR> = order |
| 466 | .iter() |
| 467 | .map(|&i| { |
| 468 | let active = pic |
| 469 | .reference |
| 470 | .filter(|r| r.slot == i) |
| 471 | .map_or(-1, |_| i as i32); |
| 472 | vk::VideoReferenceSlotInfoKHR::builder() |
| 473 | .slot_index(active) |
| 474 | .picture_resource(&dpb_pr[i as usize]) |
| 475 | .build() |
| 476 | }) |
| 477 | .collect(); |
| 478 | |
| 479 | let mut list0 = [0xffu8; 32]; |
| 480 | if let Some(r) = pic.reference { |
| 481 | list0[0] = r.slot as u8; |
| 482 | } |
| 483 | let mut modification = zeroed::<vk::video::StdVideoEncodeH264RefListModEntry>(); |
| 484 | modification.modification_of_pic_nums_idc = |
| 485 | vk::video::STD_VIDEO_H264_MODIFICATION_OF_PIC_NUMS_IDC_LONG_TERM; |
| 486 | modification.long_term_pic_num = pic.reference.map_or(0, |r| r.slot as u16); |
| 487 | let mut marking = [zeroed::<vk::video::StdVideoEncodeH264RefPicMarkingEntry>(); 3]; |
| 488 | marking[0].memory_management_control_operation = |
| 489 | vk::video::STD_VIDEO_H264_MEM_MGMT_CONTROL_OP_SET_MAX_LONG_TERM_INDEX; |
| 490 | marking[0].max_long_term_frame_idx_plus1 = DPB_SLOTS as u16; |
| 491 | marking[1].memory_management_control_operation = |
| 492 | vk::video::STD_VIDEO_H264_MEM_MGMT_CONTROL_OP_MARK_CURRENT_AS_LONG_TERM; |
| 493 | marking[1].long_term_frame_idx = pic.slot as u16; |
| 494 | marking[2].memory_management_control_operation = |
| 495 | vk::video::STD_VIDEO_H264_MEM_MGMT_CONTROL_OP_END; |
| 496 | let mut lists = zeroed::<vk::video::StdVideoEncodeH264ReferenceListsInfo>(); |
| 497 | lists.RefPicList0 = list0; |
| 498 | lists.RefPicList1 = [0xff; 32]; |
| 499 | if !pic.idr { |
| 500 | let first = usize::from(self.long_term_open); |
| 501 | lists.flags.set_ref_pic_list_modification_flag_l0(1); |
| 502 | lists.refList0ModOpCount = 1; |
| 503 | lists.pRefList0ModOperations = &modification; |
| 504 | lists.refPicMarkingOpCount = (marking.len() - first) as u8; |
| 505 | lists.pRefPicMarkingOperations = marking[first..].as_ptr(); |
| 506 | } |
| 507 | self.long_term_open = !pic.idr; |
| 508 | |
| 509 | let mut pic_std = zeroed::<vk::video::StdVideoEncodeH264PictureInfo>(); |
| 510 | pic_std.flags.set_IdrPicFlag(pic.idr as u32); |
| 511 | pic_std.flags.set_is_reference(1); |
| 512 | pic_std.flags.set_long_term_reference_flag(pic.idr as u32); |
| 513 | pic_std.flags.set_adaptive_ref_pic_marking_mode_flag(!pic.idr as u32); |
| 514 | pic_std.idr_pic_id = pic.idr_pic_id; |
| 515 | pic_std.primary_pic_type = primary; |
| 516 | pic_std.frame_num = pic.frame_num; |
| 517 | pic_std.PicOrderCnt = pic.poc; |
| 518 | pic_std.pRefLists = &lists; |
| 519 | |
| 520 | let mut slice_std = zeroed::<vk::video::StdVideoEncodeH264SliceHeader>(); |
| 521 | slice_std.slice_type = if pic.idr { |
| 522 | vk::video::STD_VIDEO_H264_SLICE_TYPE_I |
| 523 | } else { |
| 524 | vk::video::STD_VIDEO_H264_SLICE_TYPE_P |
| 525 | }; |
| 526 | let constant_qp = self.enc.rate.constant_qp().map_or(0, i32::from); |
| 527 | let slices = [vk::VideoEncodeH264NaluSliceInfoKHR::builder() |
| 528 | .constant_qp(constant_qp) |
| 529 | .std_slice_header(&slice_std) |
| 530 | .build()]; |
| 531 | let mut h264_pic = vk::VideoEncodeH264PictureInfoKHR::builder() |
| 532 | .nalu_slice_entries(&slices) |
| 533 | .std_picture_info(&pic_std) |
| 534 | .generate_prefix_nalu(false) |
| 535 | .build(); |
| 536 | |
| 537 | let encode = vk::VideoEncodeInfoKHR::builder() |
| 538 | .dst_buffer(self.enc.bitstream_buffer()) |
| 539 | .dst_buffer_offset(0) |
| 540 | .dst_buffer_range(self.enc.bitstream_len) |
| 541 | .src_picture_resource(src_pr) |
| 542 | .setup_reference_slot(&setup) |
| 543 | .reference_slots(&refs) |
| 544 | .push_next(&mut h264_pic) |
| 545 | .build(); |
| 546 | |
| 547 | let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1); |
| 548 | let mut chain = RateChain::new(self.enc.rate, self.enc.fps); |
| 549 | self.enc |
| 550 | .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode) |
| 551 | } |
| 552 | |
| 553 | /// Encodes one picture synchronously and returns its coded bytes. |
| 554 | pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &H264Picture) -> Result<Vec<u8>, Error> { |
| 555 | self.submit(y, uv, pic)?; |
| 556 | self.enc.flush_last() |
| 557 | } |
| 558 | |
| 559 | /// Encodes one picture synchronously and returns its coded bytes. |
| 560 | pub fn encode_rgb( |
| 561 | &mut self, |
| 562 | rgb: &[u8], |
| 563 | src_width: u32, |
| 564 | src_height: u32, |
| 565 | stride_bytes: u32, |
| 566 | bgr: bool, |
| 567 | pic: &H264Picture, |
| 568 | ) -> Result<Vec<u8>, Error> { |
| 569 | self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?; |
| 570 | self.enc.flush_last() |
| 571 | } |
| 572 | |
| 573 | #[cfg(target_os = "linux")] |
| 574 | /// Encodes one picture synchronously and returns its coded bytes. |
| 575 | pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> { |
| 576 | self.submit_dmabuf(src, pic)?; |
| 577 | self.enc.flush_last() |
| 578 | } |
| 579 | |
| 580 | /// Waits for queued pictures and returns their coded bytes in order. |
| 581 | pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> { |
| 582 | self.enc.flush() |
| 583 | } |
| 584 | |
| 585 | /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change. |
| 586 | pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> { |
| 587 | self.enc.set_rate(rate, fps) |
| 588 | } |
| 589 | |
| 590 | fn check(&self, pic: &H264Picture) -> Result<(), Error> { |
| 591 | if pic.slot as usize >= DPB_SLOTS { |
| 592 | return Err(Error::Invalid("DPB slot".into())); |
| 593 | } |
| 594 | match pic.reference { |
| 595 | None if pic.idr && pic.slot == 0 => Ok(()), |
| 596 | Some(r) if !pic.idr && (r.slot as usize) < DPB_SLOTS && r.slot != pic.slot => Ok(()), |
| 597 | _ => Err(Error::Invalid("picture and reference do not match".into())), |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | fn create_parameters( |
| 603 | vs: &VideoSession, |
| 604 | cfg: &H264EncodeConfig, |
| 605 | level: vk::video::StdVideoH264LevelIdc, |
| 606 | ) -> Result<vk::VideoSessionParametersKHR, Error> { |
| 607 | let aw = align(cfg.width, 16); |
| 608 | let ah = align(cfg.height, 16); |
| 609 | let cropped = aw != cfg.width || ah != cfg.height; |
| 610 | let profile_idc = match cfg.profile { |
| 611 | H264Profile::ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE, |
| 612 | H264Profile::Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN, |
| 613 | H264Profile::High => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH, |
| 614 | }; |
| 615 | |
| 616 | let mut vui = zeroed::<vk::video::StdVideoH264SequenceParameterSetVui>(); |
| 617 | vui.flags.set_timing_info_present_flag(1); |
| 618 | vui.flags.set_fixed_frame_rate_flag(1); |
| 619 | vui.flags.set_bitstream_restriction_flag(1); |
| 620 | vui.aspect_ratio_idc = vk::video::STD_VIDEO_H264_ASPECT_RATIO_IDC_UNSPECIFIED; |
| 621 | vui.num_units_in_tick = cfg.fps.1; |
| 622 | vui.time_scale = cfg.fps.0 * 2; |
| 623 | vui.max_num_reorder_frames = 0; |
| 624 | vui.max_dec_frame_buffering = MAX_REF_FRAMES; |
| 625 | if let Some(c) = cfg.colour { |
| 626 | vui.flags.set_video_signal_type_present_flag(1); |
| 627 | vui.flags.set_video_full_range_flag(c.full_range as u32); |
| 628 | vui.flags.set_color_description_present_flag(1); |
| 629 | vui.video_format = 5; |
| 630 | vui.colour_primaries = c.primaries; |
| 631 | vui.transfer_characteristics = c.transfer; |
| 632 | vui.matrix_coefficients = c.matrix; |
| 633 | } |
| 634 | |
| 635 | let mut sps = zeroed::<vk::video::StdVideoH264SequenceParameterSet>(); |
| 636 | sps.flags.set_direct_8x8_inference_flag(1); |
| 637 | sps.flags.set_frame_mbs_only_flag(1); |
| 638 | sps.flags.set_frame_cropping_flag(cropped as u32); |
| 639 | sps.flags.set_vui_parameters_present_flag(1); |
| 640 | sps.profile_idc = profile_idc; |
| 641 | sps.flags |
| 642 | .set_constraint_set1_flag((cfg.profile == H264Profile::ConstrainedBaseline) as u32); |
| 643 | sps.level_idc = level; |
| 644 | sps.chroma_format_idc = vk::video::STD_VIDEO_H264_CHROMA_FORMAT_IDC_420; |
| 645 | sps.pic_order_cnt_type = vk::video::STD_VIDEO_H264_POC_TYPE_2; |
| 646 | sps.max_num_ref_frames = MAX_REF_FRAMES; |
| 647 | sps.log2_max_frame_num_minus4 = LOG2_MAX_FRAME_NUM - 4; |
| 648 | sps.flags.set_gaps_in_frame_num_value_allowed_flag(1); |
| 649 | sps.pic_width_in_mbs_minus1 = aw / 16 - 1; |
| 650 | sps.pic_height_in_map_units_minus1 = ah / 16 - 1; |
| 651 | sps.frame_crop_right_offset = (aw - cfg.width) / 2; |
| 652 | sps.frame_crop_bottom_offset = (ah - cfg.height) / 2; |
| 653 | sps.pSequenceParameterSetVui = &vui; |
| 654 | |
| 655 | let mut pps = zeroed::<vk::video::StdVideoH264PictureParameterSet>(); |
| 656 | pps.flags |
| 657 | .set_transform_8x8_mode_flag((cfg.profile == H264Profile::High) as u32); |
| 658 | pps.flags.set_deblocking_filter_control_present_flag(1); |
| 659 | pps.flags |
| 660 | .set_entropy_coding_mode_flag((cfg.profile != H264Profile::ConstrainedBaseline) as u32); |
| 661 | pps.weighted_bipred_idc = vk::video::STD_VIDEO_H264_WEIGHTED_BIPRED_IDC_DEFAULT; |
| 662 | |
| 663 | let add = vk::VideoEncodeH264SessionParametersAddInfoKHR::builder() |
| 664 | .std_sp_ss(std::slice::from_ref(&sps)) |
| 665 | .std_pp_ss(std::slice::from_ref(&pps)) |
| 666 | .build(); |
| 667 | let mut h264 = vk::VideoEncodeH264SessionParametersCreateInfoKHR::builder() |
| 668 | .max_std_sps_count(1) |
| 669 | .max_std_pps_count(1) |
| 670 | .parameters_add_info(&add) |
| 671 | .build(); |
| 672 | let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder() |
| 673 | .quality_level(vs.quality_level) |
| 674 | .build(); |
| 675 | let info = vk::VideoSessionParametersCreateInfoKHR::builder() |
| 676 | .video_session(vs.session) |
| 677 | .push_next(&mut quality) |
| 678 | .push_next(&mut h264) |
| 679 | .build(); |
| 680 | unsafe { |
| 681 | vk( |
| 682 | vs.gpu |
| 683 | .device() |
| 684 | .create_video_session_parameters_khr(&info, None), |
| 685 | "vkCreateVideoSessionParametersKHR", |
| 686 | ) |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | pub(crate) fn validate( |
| 691 | width: u32, |
| 692 | height: u32, |
| 693 | fps: (u32, u32), |
| 694 | rate: RateControl, |
| 695 | ) -> Result<(), Error> { |
| 696 | if width == 0 || height == 0 || width % 2 != 0 || height % 2 != 0 { |
| 697 | return Err(Error::Invalid("size must be even and non-zero".into())); |
| 698 | } |
| 699 | validate_rate(fps, rate) |
| 700 | } |
| 701 | |
| 702 | fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { |
| 703 | let mut h264 = vk::VideoEncodeH264CapabilitiesKHR::builder(); |
| 704 | let mut encode = vk::VideoEncodeCapabilitiesKHR::builder(); |
| 705 | let mut caps = vk::VideoCapabilitiesKHR::builder() |
| 706 | .push_next(&mut h264) |
| 707 | .push_next(&mut encode); |
| 708 | video_caps(gpu, profile, &mut caps)?; |
| 709 | Ok(Caps { |
| 710 | std_header_version: caps.std_header_version.clone(), |
| 711 | max_extent: caps.max_coded_extent, |
| 712 | size_align: caps.min_bitstream_buffer_size_alignment, |
| 713 | rc_modes: encode.rate_control_modes, |
| 714 | quality_levels: encode.max_quality_levels, |
| 715 | max_refs: h264.max_p_picture_l0_reference_count, |
| 716 | max_level: h264.max_level_idc, |
| 717 | }) |
| 718 | } |
| 719 | |
| 720 | fn reference_info( |
| 721 | primary: vk::video::StdVideoH264PictureType, |
| 722 | frame_num: u32, |
| 723 | poc: i32, |
| 724 | slot: u32, |
| 725 | ) -> vk::video::StdVideoEncodeH264ReferenceInfo { |
| 726 | let mut info = zeroed::<vk::video::StdVideoEncodeH264ReferenceInfo>(); |
| 727 | info.flags.set_used_for_long_term_reference(1); |
| 728 | info.primary_pic_type = primary; |
| 729 | info.FrameNum = frame_num; |
| 730 | info.PicOrderCnt = poc; |
| 731 | info.long_term_pic_num = slot as u16; |
| 732 | info.long_term_frame_idx = slot as u16; |
| 733 | info |
| 734 | } |
| 735 | |
| 736 | fn h264_level( |
| 737 | idc: u8, |
| 738 | driver_max: vk::video::StdVideoH264LevelIdc, |
| 739 | ) -> Result<vk::video::StdVideoH264LevelIdc, Error> { |
| 740 | const LEVELS: [(u8, vk::video::StdVideoH264LevelIdc); 19] = [ |
| 741 | (10, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_0), |
| 742 | (11, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_1), |
| 743 | (12, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_2), |
| 744 | (13, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_3), |
| 745 | (20, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_0), |
| 746 | (21, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_1), |
| 747 | (22, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_2), |
| 748 | (30, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_0), |
| 749 | (31, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_1), |
| 750 | (32, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_2), |
| 751 | (40, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_0), |
| 752 | (41, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_1), |
| 753 | (42, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_2), |
| 754 | (50, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_0), |
| 755 | (51, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_1), |
| 756 | (52, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_2), |
| 757 | (60, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_0), |
| 758 | (61, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_1), |
| 759 | (62, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_2), |
| 760 | ]; |
| 761 | let (_, level) = LEVELS |
| 762 | .into_iter() |
| 763 | .find(|(value, _)| *value == idc) |
| 764 | .ok_or_else(|| Error::Invalid(format!("H.264 level_idc {idc}")))?; |
| 765 | Ok(if level.0 > driver_max.0 { driver_max } else { level }) |
| 766 | } |