forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

av1_encode.rs778 lines, 27.9 KiBHistoryRawDownload
1use std::ffi::c_void;
2
3use vulkanalia::prelude::v1_3::*;
4use vulkanalia::vk::KhrVideoQueueExtensionDeviceCommands;
5
6#[cfg(target_os = "linux")]
7use crate::dmabuf::DmaBuf;
8use crate::rgb_convert::{Input, check_rgb};
9use crate::session::{
10 quality_level,
11 DPB_SLOTS, Encoder, VideoSession, component_bit_depth, picture_resource, validate_rate,
12 video_caps, vk, zeroed,
13};
14use crate::{Colour, Error, Gpu, RateControl};
15
16const AV1_SLOTS: usize = 8;
17const CBR_Q_INDEX: u32 = 128;
18
19/// Settings fixed for the life of an AV1 session.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Av1EncodeConfig {
22 /// Width in luma samples, multiple of 8.
23 pub width: u32,
24 /// Height in luma samples, multiple of 8.
25 pub height: u32,
26 /// Frame rate as numerator and denominator.
27 pub fps: (u32, u32),
28 /// Rate control; ConstantQp qp is mapped to AV1 base_q_idx as qp * 5.
29 pub rate: RateControl,
30 /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input).
31 pub bit_depth: u8,
32 /// `seq_level_idx` (0 to 23), chosen by the caller and clamped to the driver maximum.
33 pub level: u8,
34 /// Colour config of the sequence header, or none (unspecified).
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)]
42pub struct Av1Picture {
43 /// Encode as KEY frame.
44 pub key: bool,
45 /// order_hint of this frame.
46 pub order_hint: u8,
47 /// DPB slot this picture is written to, below `DPB_SLOTS`.
48 pub slot: u32,
49 /// Reference for an INTER frame, None for KEY.
50 pub reference: Option<Av1Ref>,
51}
52
53/// A picture held in the DPB.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct Av1Ref {
56 /// DPB slot, below `DPB_SLOTS`.
57 pub slot: u32,
58 /// order_hint of the reference.
59 pub order_hint: u8,
60}
61
62struct Caps {
63 std_header_version: vk::ExtensionProperties,
64 max_extent: vk::Extent2D,
65 size_align: u64,
66 rc_modes: vk::VideoEncodeRateControlModeFlagsKHR,
67 quality_levels: u32,
68 single_ref: bool,
69 sb64: bool,
70 max_level: vk::video::StdVideoAV1Level,
71}
72
73struct Profile {
74 info: vk::VideoProfileInfoKHR,
75 codec: vk::VideoEncodeAV1ProfileInfoKHR,
76 usage: vk::VideoEncodeUsageInfoKHR,
77}
78
79impl Profile {
80 fn new(bit_depth: u8) -> Box<Self> {
81 let component = component_bit_depth(bit_depth);
82 let mut p = Box::new(Profile {
83 info: vk::VideoProfileInfoKHR::builder()
84 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_AV1)
85 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
86 .luma_bit_depth(component)
87 .chroma_bit_depth(component)
88 .build(),
89 codec: vk::VideoEncodeAV1ProfileInfoKHR::builder()
90 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN)
91 .build(),
92 usage: vk::VideoEncodeUsageInfoKHR::builder()
93 .video_usage_hints(vk::VideoEncodeUsageFlagsKHR::STREAMING)
94 .video_content_hints(vk::VideoEncodeContentFlagsKHR::DESKTOP)
95 .tuning_mode(vk::VideoEncodeTuningModeKHR::LOW_LATENCY)
96 .build(),
97 });
98 p.codec.next = &p.usage as *const _ as *const c_void;
99 p.info.next = &p.codec as *const _ as *const c_void;
100 p
101 }
102}
103
104struct RateChain {
105 rc: vk::VideoEncodeRateControlInfoKHR,
106 rc_av1: vk::VideoEncodeAV1RateControlInfoKHR,
107 layer: vk::VideoEncodeRateControlLayerInfoKHR,
108 layer_av1: vk::VideoEncodeAV1RateControlLayerInfoKHR,
109}
110
111impl RateChain {
112 fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> {
113 let mode = rate.mode();
114 let layers = u32::from(rate.layer().is_some());
115 let (bitrate, max_bitrate, buffer_ms) = rate.layer().unwrap_or_default();
116 let mut c = Box::new(RateChain {
117 rc: vk::VideoEncodeRateControlInfoKHR::builder()
118 .rate_control_mode(mode)
119 .virtual_buffer_size_in_ms(buffer_ms)
120 .initial_virtual_buffer_size_in_ms(buffer_ms)
121 .build(),
122 rc_av1: vk::VideoEncodeAV1RateControlInfoKHR::builder()
123 .flags(vk::VideoEncodeAV1RateControlFlagsKHR::VIDEO_ENCODE_AV1_RATE_CONTROL_REGULAR_GOP | vk::VideoEncodeAV1RateControlFlagsKHR::VIDEO_ENCODE_AV1_RATE_CONTROL_REFERENCE_PATTERN_FLAT)
124 .gop_frame_count(u32::MAX)
125 .key_frame_period(u32::MAX)
126 .consecutive_bipredictive_frame_count(0)
127 .temporal_layer_count(1)
128 .build(),
129 layer: vk::VideoEncodeRateControlLayerInfoKHR::builder()
130 .average_bitrate(bitrate as u64)
131 .max_bitrate(max_bitrate as u64)
132 .frame_rate_numerator(fps.0)
133 .frame_rate_denominator(fps.1)
134 .build(),
135 layer_av1: {
136 let mut layer = vk::VideoEncodeAV1RateControlLayerInfoKHR::builder();
137 if let Some(q) = rate.min_qp() {
138 layer = layer.use_min_q_index(true).min_q_index(vk::VideoEncodeAV1QIndexKHR { intra_q_index: q as u32 * 5, predictive_q_index: q as u32 * 5, bipredictive_q_index: q as u32 * 5 });
139 }
140 if let Some(m) = rate.max_frame_bytes() {
141 layer = layer.use_max_frame_size(true).max_frame_size(vk::VideoEncodeAV1FrameSizeKHR { intra_frame_size: m, predictive_frame_size: m, bipredictive_frame_size: m });
142 }
143 layer.build()
144 },
145 });
146 c.rc.next = &c.rc_av1 as *const _ as *const c_void;
147 c.rc.layer_count = layers;
148 c.rc.layers = &c.layer;
149 c.layer.next = &c.layer_av1 as *const _ as *const c_void;
150 c
151 }
152}
153
154/// An AV1 Vulkan Video encode session: KEY and INTER frames, LAST reference, NV12 uploaded from CPU.
155pub struct Av1EncodeSession {
156 enc: Encoder,
157 seq: Vec<u8>,
158 slot_key: [bool; DPB_SLOTS],
159 ref_order_hint: [u8; AV1_SLOTS],
160}
161
162impl Av1EncodeSession {
163 /// Creates a session with its DPB, buffers and sequence header.
164 pub fn new(gpu: &Gpu, cfg: &Av1EncodeConfig) -> Result<Self, Error> {
165 validate(cfg)?;
166 let family = gpu
167 .encode_family()
168 .ok_or_else(|| Error::Unsupported("AV1 encode queue family".into()))?;
169 if !gpu
170 .device()
171 .extensions()
172 .contains(&vk::KHR_VIDEO_ENCODE_AV1_EXTENSION.name)
173 {
174 return Err(Error::Unsupported("AV1 encode".into()));
175 }
176 let profile = Profile::new(cfg.bit_depth);
177 let caps = query_caps(gpu, &profile.info).map_err(|e| match e {
178 Error::Vk(..) if cfg.bit_depth == 10 => Error::Unsupported("10-bit AV1 encode".into()),
179 e => e,
180 })?;
181 if cfg.width > caps.max_extent.width || cfg.height > caps.max_extent.height {
182 return Err(Error::Unsupported(format!(
183 "AV1 encode {}x{}",
184 cfg.width, cfg.height
185 )));
186 }
187 if !caps.single_ref {
188 return Err(Error::Unsupported("AV1 single LAST reference".into()));
189 }
190 let level = av1_level(cfg.level, caps.max_level)?;
191 let mode = cfg.rate.mode();
192 if !caps.rc_modes.contains(mode) {
193 return Err(Error::Unsupported(format!("rate control {mode:?}")));
194 }
195
196 let upload_family = gpu
197 .graphics_family()
198 .ok_or_else(|| Error::Unsupported("graphics queue family for upload".into()))?;
199 let sb128 = !caps.sb64;
200 let extent = vk::Extent2D {
201 width: cfg.width,
202 height: cfg.height,
203 };
204 let vs = VideoSession::new(
205 gpu,
206 family,
207 &profile.info,
208 &caps.std_header_version,
209 extent,
210 DPB_SLOTS as u32,
211 1,
212 )?;
213 let mut enc = Encoder::new(
214 vs,
215 &profile.info,
216 upload_family,
217 (cfg.width, cfg.height),
218 extent,
219 (cfg.rate, cfg.fps),
220 caps.size_align,
221 )?;
222 enc.vs.quality_level = quality_level(cfg.quality, caps.quality_levels);
223 let params = create_parameters(&enc.vs, extent, sb128, cfg, level)?;
224 enc.vs.set_params(params);
225 Ok(Av1EncodeSession {
226 enc,
227 seq: sequence_header_obu(cfg, sb128, level),
228 slot_key: [false; DPB_SLOTS],
229 ref_order_hint: [0; AV1_SLOTS],
230 })
231 }
232
233 /// OBU_SEQUENCE_HEADER bytes of this session, with OBU header.
234 pub fn sequence_header(&self) -> Vec<u8> {
235 self.seq.clone()
236 }
237
238 /// Submits one NV12 picture (y: width*height, uv: interleaved CbCr width*height/2) without waiting; returns the oldest picture once two are in flight.
239 pub fn submit(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
240 if y.len() != self.enc.input.0 * self.enc.input.1
241 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
242 {
243 return Err(Error::Invalid("NV12 plane size".into()));
244 }
245 self.check(pic)?;
246 self.enc.upload(Input::Nv12 { y, uv })?;
247 self.encode_uploaded(pic)
248 }
249
250 /// 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.
251 pub fn submit_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
252 if y.len() != self.enc.input.0 * self.enc.input.1
253 || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
254 {
255 return Err(Error::Invalid("P010 plane size".into()));
256 }
257 self.check(pic)?;
258 self.enc.upload(Input::P010 { y, uv })?;
259 self.encode_uploaded(pic)
260 }
261
262 /// 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.
263 pub fn submit_rgb(
264 &mut self,
265 rgb: &[u8],
266 src_width: u32,
267 src_height: u32,
268 stride_bytes: u32,
269 bgr: bool,
270 pic: &Av1Picture,
271 ) -> Result<Option<Vec<u8>>, Error> {
272 self.check(pic)?;
273 let src = (src_width as usize, src_height as usize);
274 check_rgb(
275 (self.enc.input.0, self.enc.input.1),
276 src,
277 rgb,
278 stride_bytes as usize,
279 )?;
280 self.enc.upload(Input::Rgb {
281 data: rgb,
282 width: src.0,
283 height: src.1,
284 stride: stride_bytes as usize,
285 bgr,
286 })?;
287 self.encode_uploaded(pic)
288 }
289 /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.
290 #[cfg(target_os = "linux")]
291 pub fn submit_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
292 self.check(pic)?;
293 self.enc.upload_dmabuf(src)?;
294 self.encode_uploaded(pic)
295 }
296
297 /// Encodes one picture from a shared D3D11 texture of BGRA or RGBA pixels, downscaled to the encoder size.
298 #[cfg(windows)]
299 pub fn submit_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
300 self.check(pic)?;
301 self.enc.upload_d3d11(src)?;
302 self.encode_uploaded(pic)
303 }
304
305 /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes.
306 #[cfg(windows)]
307 pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
308 self.submit_d3d11(src, pic)?;
309 self.enc.flush_last()
310 }
311
312 /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once.
313 #[cfg(windows)]
314 pub fn d3d11_imports(&self) -> usize {
315 self.enc.import_count()
316 }
317
318 /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once.
319 #[cfg(target_os = "linux")]
320 pub fn dmabuf_imports(&self) -> usize {
321 self.enc.import_count()
322 }
323
324 fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Option<Vec<u8>>, Error> {
325 let extent = self.enc.extent;
326
327 let refresh: u8 = if pic.key { 0xff } else { 1 << pic.slot };
328 let dpb_pr = self.enc.dpb.each_ref().map(|d| picture_resource(d.view, extent));
329 let src_pr = picture_resource(self.enc.src_view(), extent);
330
331 let key_of = self.slot_key;
332 let mut new_std = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>();
333 new_std.frame_type = frame_type(pic.key);
334 new_std.OrderHint = pic.order_hint;
335 let mut new_dpb = vk::VideoEncodeAV1DpbSlotInfoKHR::builder()
336 .std_reference_info(&new_std)
337 .build();
338 let ref_std = pic.reference.map(|r| {
339 let mut s = zeroed::<vk::video::StdVideoEncodeAV1ReferenceInfo>();
340 s.frame_type = frame_type(key_of[r.slot as usize]);
341 s.OrderHint = r.order_hint;
342 s
343 });
344 let mut ref_dpb = ref_std.as_ref().map(|s| {
345 vk::VideoEncodeAV1DpbSlotInfoKHR::builder()
346 .std_reference_info(s)
347 .build()
348 });
349
350 let mut refs = Vec::new();
351 if let (Some(r), Some(dpb)) = (pic.reference, ref_dpb.as_mut()) {
352 refs.push(
353 vk::VideoReferenceSlotInfoKHR::builder()
354 .slot_index(r.slot as i32)
355 .picture_resource(&dpb_pr[r.slot as usize])
356 .push_next(dpb)
357 .build(),
358 );
359 }
360 let setup = vk::VideoReferenceSlotInfoKHR::builder()
361 .slot_index(pic.slot as i32)
362 .picture_resource(&dpb_pr[pic.slot as usize])
363 .push_next(&mut new_dpb)
364 .build();
365
366 let begin_slots: Vec<vk::VideoReferenceSlotInfoKHR> = (0..DPB_SLOTS)
367 .map(|i| {
368 let active = pic
369 .reference
370 .filter(|r| r.slot as usize == i)
371 .map_or(-1, |_| i as i32);
372 vk::VideoReferenceSlotInfoKHR::builder()
373 .slot_index(active)
374 .picture_resource(&dpb_pr[i])
375 .build()
376 })
377 .collect();
378
379 let ref_slot = pic.reference.map_or(0, |r| r.slot as i8);
380 let mut std_pic = zeroed::<vk::video::StdVideoEncodeAV1PictureInfo>();
381 std_pic.flags.set_show_frame(1);
382 std_pic.flags.set_error_resilient_mode(pic.key as u32);
383 std_pic.frame_type = frame_type(pic.key);
384 std_pic.order_hint = pic.order_hint;
385 std_pic.primary_ref_frame = if pic.key {
386 vk::video::STD_VIDEO_AV1_PRIMARY_REF_NONE as u8
387 } else {
388 0
389 };
390 std_pic.refresh_frame_flags = refresh;
391 std_pic.TxMode = vk::video::STD_VIDEO_AV1_TX_MODE_SELECT;
392 std_pic.interpolation_filter = vk::video::STD_VIDEO_AV1_INTERPOLATION_FILTER_SWITCHABLE;
393 std_pic.ref_order_hint = self.ref_order_hint;
394 std_pic.ref_frame_idx = [ref_slot; 7];
395 let mut tile = zeroed::<vk::video::StdVideoAV1TileInfo>();
396 tile.flags.set_uniform_tile_spacing_flag(1);
397 tile.TileCols = 1;
398 tile.TileRows = 1;
399 let mut quant = zeroed::<vk::video::StdVideoAV1Quantization>();
400 quant.base_q_idx = q_index(self.enc.rate) as u8;
401 let mut loop_filter = zeroed::<vk::video::StdVideoAV1LoopFilter>();
402 loop_filter.loop_filter_level = [1; 4];
403 let cdef = cdef_params();
404 let restoration = zeroed::<vk::video::StdVideoAV1LoopRestoration>();
405 let motion = zeroed::<vk::video::StdVideoAV1GlobalMotion>();
406 std_pic.pTileInfo = &tile;
407 std_pic.pQuantization = &quant;
408 std_pic.pSegmentation = std::ptr::null();
409 std_pic.pLoopFilter = &loop_filter;
410 std_pic.pCDEF = &cdef;
411 std_pic.pLoopRestoration = &restoration;
412 std_pic.pGlobalMotion = &motion;
413
414 let mut ref_names = [-1i32; 7];
415 if let Some(r) = pic.reference {
416 ref_names[0] = r.slot as i32;
417 }
418 let mut av1_pic = vk::VideoEncodeAV1PictureInfoKHR {
419 prediction_mode: if pic.key {
420 vk::VideoEncodeAV1PredictionModeKHR::VIDEO_ENCODE_AV1_PREDICTION_MODE_INTRA_ONLY
421 } else {
422 vk::VideoEncodeAV1PredictionModeKHR::VIDEO_ENCODE_AV1_PREDICTION_MODE_SINGLE_REFERENCE
423 },
424 rate_control_group: if pic.key {
425 vk::VideoEncodeAV1RateControlGroupKHR::VIDEO_ENCODE_AV1_RATE_CONTROL_GROUP_INTRA
426 } else {
427 vk::VideoEncodeAV1RateControlGroupKHR::VIDEO_ENCODE_AV1_RATE_CONTROL_GROUP_PREDICTIVE
428 },
429 constant_q_index: constant_q_index(self.enc.rate),
430 std_picture_info: &std_pic,
431 reference_name_slot_indices: ref_names,
432 ..Default::default()
433 };
434
435 let encode = vk::VideoEncodeInfoKHR::builder()
436 .dst_buffer(self.enc.bitstream_buffer())
437 .dst_buffer_offset(0)
438 .dst_buffer_range(self.enc.bitstream_len)
439 .src_picture_resource(src_pr)
440 .setup_reference_slot(&setup)
441 .reference_slots(&refs)
442 .push_next(&mut av1_pic)
443 .build();
444
445 let mut applied = RateChain::new(self.enc.applied.0, self.enc.applied.1);
446 let mut chain = RateChain::new(self.enc.rate, self.enc.fps);
447 let out = self
448 .enc
449 .submit(&begin_slots, &mut applied.rc, &mut chain.rc, &encode)?;
450 for i in 0..DPB_SLOTS {
451 if refresh >> i & 1 == 1 {
452 self.slot_key[i] = pic.key;
453 }
454 }
455 for i in 0..AV1_SLOTS {
456 if refresh >> i & 1 == 1 {
457 self.ref_order_hint[i] = pic.order_hint;
458 }
459 }
460 Ok(out)
461 }
462
463 /// Encodes one picture synchronously and returns its coded bytes.
464 pub fn encode(&mut self, y: &[u8], uv: &[u8], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
465 self.submit(y, uv, pic)?;
466 self.enc.flush_last()
467 }
468
469 /// Encodes one picture synchronously and returns its coded bytes.
470 pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
471 self.submit_16(y, uv, pic)?;
472 self.enc.flush_last()
473 }
474
475 /// Encodes one picture synchronously and returns its coded bytes.
476 pub fn encode_rgb(
477 &mut self,
478 rgb: &[u8],
479 src_width: u32,
480 src_height: u32,
481 stride_bytes: u32,
482 bgr: bool,
483 pic: &Av1Picture,
484 ) -> Result<Vec<u8>, Error> {
485 self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, pic)?;
486 self.enc.flush_last()
487 }
488
489 #[cfg(target_os = "linux")]
490 /// Encodes one picture synchronously and returns its coded bytes.
491 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
492 self.submit_dmabuf(src, pic)?;
493 self.enc.flush_last()
494 }
495
496 /// Waits for queued pictures and returns their coded bytes in order.
497 pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, Error> {
498 self.enc.flush()
499 }
500
501 /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
502 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
503 self.enc.set_rate(rate, fps)
504 }
505
506 fn check(&self, pic: &Av1Picture) -> Result<(), Error> {
507 if pic.slot as usize >= DPB_SLOTS {
508 return Err(Error::Invalid("DPB slot".into()));
509 }
510 match pic.reference {
511 None if pic.key => Ok(()),
512 Some(r)
513 if !pic.key
514 && self.enc.coded
515 && (r.slot as usize) < DPB_SLOTS
516 && r.slot != pic.slot =>
517 {
518 Ok(())
519 }
520 _ => Err(Error::Invalid("picture and reference do not match".into())),
521 }
522 }
523}
524
525fn create_parameters(
526 vs: &VideoSession,
527 extent: vk::Extent2D,
528 sb128: bool,
529 cfg: &Av1EncodeConfig,
530 level: vk::video::StdVideoAV1Level,
531) -> Result<vk::VideoSessionParametersKHR, Error> {
532 let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>();
533 color.BitDepth = cfg.bit_depth;
534 color.subsampling_x = 1;
535 color.subsampling_y = 1;
536 color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED;
537 color.transfer_characteristics = vk::video::STD_VIDEO_AV1_TRANSFER_CHARACTERISTICS_UNSPECIFIED;
538 color.matrix_coefficients = vk::video::STD_VIDEO_AV1_MATRIX_COEFFICIENTS_UNSPECIFIED;
539 color.chroma_sample_position = vk::video::STD_VIDEO_AV1_CHROMA_SAMPLE_POSITION_UNKNOWN;
540 if let Some(c) = cfg.colour {
541 color.flags.set_color_description_present_flag(1);
542 color.flags.set_color_range(c.full_range as u32);
543 color.color_primaries = vk::video::StdVideoAV1ColorPrimaries(i32::from(c.primaries));
544 color.transfer_characteristics =
545 vk::video::StdVideoAV1TransferCharacteristics(i32::from(c.transfer));
546 color.matrix_coefficients = vk::video::StdVideoAV1MatrixCoefficients(i32::from(c.matrix));
547 }
548
549 let mut timing = zeroed::<vk::video::StdVideoAV1TimingInfo>();
550 timing.flags.set_equal_picture_interval(1);
551 timing.num_units_in_display_tick = cfg.fps.1;
552 timing.time_scale = cfg.fps.0;
553 let mut seq = zeroed::<vk::video::StdVideoAV1SequenceHeader>();
554 seq.flags.set_enable_order_hint(1);
555 seq.flags.set_use_128x128_superblock(sb128 as u32);
556 seq.flags.set_timing_info_present_flag(1);
557 seq.pTimingInfo = &timing;
558 seq.seq_profile = vk::video::STD_VIDEO_AV1_PROFILE_MAIN;
559 seq.frame_width_bits_minus_1 = (bits(extent.width) - 1) as u8;
560 seq.frame_height_bits_minus_1 = (bits(extent.height) - 1) as u8;
561 seq.max_frame_width_minus_1 = (extent.width - 1) as u16;
562 seq.max_frame_height_minus_1 = (extent.height - 1) as u16;
563 seq.order_hint_bits_minus_1 = 7;
564 seq.seq_force_integer_mv = vk::video::STD_VIDEO_AV1_SELECT_INTEGER_MV as u8;
565 seq.flags.set_enable_cdef(1);
566 seq.pColorConfig = &color;
567
568 let mut op = zeroed::<vk::video::StdVideoEncodeAV1OperatingPointInfo>();
569 op.seq_level_idx = level.0 as u8;
570
571 let mut av1 = vk::VideoEncodeAV1SessionParametersCreateInfoKHR {
572 std_sequence_header: &seq,
573 std_operating_point_count: 1,
574 std_operating_points: &op,
575 ..Default::default()
576 };
577 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()
578 .quality_level(vs.quality_level)
579 .build();
580 let info = vk::VideoSessionParametersCreateInfoKHR::builder()
581 .video_session(vs.session)
582 .push_next(&mut quality)
583 .push_next(&mut av1)
584 .build();
585 unsafe {
586 vk(
587 vs.gpu
588 .device()
589 .create_video_session_parameters_khr(&info, None),
590 "vkCreateVideoSessionParametersKHR",
591 )
592 }
593}
594
595struct Bits(Vec<u8>);
596
597impl Bits {
598 fn put(&mut self, value: u32, n: u32) {
599 self.0
600 .extend((0..n).rev().map(|i| ((value >> i) & 1) as u8));
601 }
602
603 fn finish(mut self) -> Vec<u8> {
604 self.0.push(1);
605 while self.0.len() % 8 != 0 {
606 self.0.push(0);
607 }
608 self.0
609 .chunks(8)
610 .map(|c| c.iter().fold(0u8, |acc, &b| (acc << 1) | b))
611 .collect()
612 }
613}
614
615fn bits(value: u32) -> u32 {
616 (32 - value.leading_zeros()).max(1)
617}
618
619fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {
620 let mut out = vec![(kind << 3) | 2];
621 let mut len = payload.len();
622 loop {
623 let byte = (len & 0x7f) as u8;
624 len >>= 7;
625 if len == 0 {
626 out.push(byte);
627 break;
628 }
629 out.push(byte | 0x80);
630 }
631 out.extend_from_slice(payload);
632 out
633}
634
635fn sequence_header_obu(
636 cfg: &Av1EncodeConfig,
637 sb128: bool,
638 level: vk::video::StdVideoAV1Level,
639) -> Vec<u8> {
640 let (width, height, bit_depth) = (cfg.width, cfg.height, cfg.bit_depth);
641 let mut b = Bits(Vec::new());
642 b.put(0, 3);
643 b.put(0, 1);
644 b.put(0, 1);
645 b.put(1, 1);
646 b.put(cfg.fps.1, 32);
647 b.put(cfg.fps.0, 32);
648 b.put(1, 1);
649 b.put(1, 1);
650 b.put(0, 1);
651 b.put(0, 1);
652 b.put(0, 5);
653 b.put(0, 12);
654 b.put(level.0 as u32, 5);
655 if level.0 > 7 {
656 b.put(0, 1);
657 }
658 b.put(bits(width) - 1, 4);
659 b.put(bits(height) - 1, 4);
660 b.put(width - 1, bits(width));
661 b.put(height - 1, bits(height));
662 b.put(0, 1);
663 b.put(sb128 as u32, 1);
664 b.put(0, 1);
665 b.put(0, 1);
666 b.put(0, 1);
667 b.put(0, 1);
668 b.put(0, 1);
669 b.put(0, 1);
670 b.put(1, 1);
671 b.put(0, 1);
672 b.put(0, 1);
673 b.put(0, 1);
674 b.put(0, 1);
675 b.put(7, 3);
676 b.put(0, 1);
677 b.put(1, 1);
678 b.put(0, 1);
679 b.put((bit_depth == 10) as u32, 1);
680 b.put(0, 1);
681 match cfg.colour {
682 Some(c) => {
683 b.put(1, 1);
684 b.put(u32::from(c.primaries), 8);
685 b.put(u32::from(c.transfer), 8);
686 b.put(u32::from(c.matrix), 8);
687 b.put(c.full_range as u32, 1);
688 }
689 None => {
690 b.put(0, 1);
691 b.put(0, 1);
692 }
693 }
694 b.put(0, 2);
695 b.put(0, 1);
696 b.put(0, 1);
697 obu(1, &b.finish())
698}
699
700fn validate(cfg: &Av1EncodeConfig) -> Result<(), Error> {
701 if cfg.bit_depth != 8 && cfg.bit_depth != 10 {
702 return Err(Error::Invalid("AV1 bit depth".into()));
703 }
704 if cfg.width == 0 || cfg.height == 0 || cfg.width % 8 != 0 || cfg.height % 8 != 0 {
705 return Err(Error::Invalid(
706 "size must be a non-zero multiple of 8".into(),
707 ));
708 }
709 validate_rate(cfg.fps, cfg.rate)
710}
711
712fn q_index(rate: RateControl) -> u32 {
713 match rate {
714 RateControl::ConstantQp { qp } => qp as u32 * 5,
715 RateControl::Cbr { .. } | RateControl::Vbr { .. } => CBR_Q_INDEX,
716 }
717}
718
719fn constant_q_index(rate: RateControl) -> u32 {
720 match rate {
721 RateControl::ConstantQp { qp } => qp as u32 * 5,
722 RateControl::Cbr { .. } | RateControl::Vbr { .. } => 0,
723 }
724}
725
726fn frame_type(key: bool) -> vk::video::StdVideoAV1FrameType {
727 if key {
728 vk::video::STD_VIDEO_AV1_FRAME_TYPE_KEY
729 } else {
730 vk::video::STD_VIDEO_AV1_FRAME_TYPE_INTER
731 }
732}
733
734fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> {
735 let mut av1 = vk::VideoEncodeAV1CapabilitiesKHR::builder();
736 let mut encode = vk::VideoEncodeCapabilitiesKHR::builder();
737 let mut caps = vk::VideoCapabilitiesKHR::builder()
738 .push_next(&mut av1)
739 .push_next(&mut encode);
740 video_caps(gpu, profile, &mut caps)?;
741 Ok(Caps {
742 std_header_version: caps.std_header_version.clone(),
743 max_extent: caps.max_coded_extent,
744 size_align: caps.min_bitstream_buffer_size_alignment,
745 rc_modes: encode.rate_control_modes,
746 quality_levels: encode.max_quality_levels,
747 single_ref: av1.max_single_reference_count > 0 && av1.single_reference_name_mask & 1 != 0,
748 sb64: av1.superblock_sizes.contains(
749 vk::VideoEncodeAV1SuperblockSizeFlagsKHR::VIDEO_ENCODE_AV1_SUPERBLOCK_SIZE_64,
750 ),
751 max_level: av1.max_level,
752 })
753}
754
755fn av1_level(
756 idx: u8,
757 driver_max: vk::video::StdVideoAV1Level,
758) -> Result<vk::video::StdVideoAV1Level, Error> {
759 if idx > 23 {
760 return Err(Error::Invalid(format!("AV1 seq_level_idx {idx}")));
761 }
762 let level = vk::video::StdVideoAV1Level(i32::from(idx));
763 Ok(if level.0 > driver_max.0 { driver_max } else { level })
764}
765
766/// CDEF candidates the encoder picks from per 64x64 block: a main strength, off for fine texture, half and double.
767fn cdef_params() -> vk::video::StdVideoAV1CDEF {
768 let mut cdef = zeroed::<vk::video::StdVideoAV1CDEF>();
769 cdef.cdef_damping_minus_3 = 2;
770 cdef.cdef_bits = 2;
771 for (i, (pri, sec)) in [(4, 1), (0, 0), (2, 1), (8, 2)].into_iter().enumerate() {
772 cdef.cdef_y_pri_strength[i] = pri;
773 cdef.cdef_uv_pri_strength[i] = pri;
774 cdef.cdef_y_sec_strength[i] = sec;
775 cdef.cdef_uv_sec_strength[i] = sec;
776 }
777 cdef
778}