forge
Explore
Log in

Don't you dare go Hollow

vk: VA rate feedback and HRD buffer on Vulkan, H.264 profile, colour config

Browse files at this commit

ff39f7fe2602b4f69a263d38b701d2def4eb05f5Ahmet Kaan GümüşParent: a9418fa
hrd_buffer_ms and RateFeedback move to a shared ec-hw rate module, used by
the VA and Vulkan encoders. Vulkan CBR now runs the 1000 ms buffer for
GOP >= 10 and applies the steered bitrate through set_rate, no IDR.

The H.264 profile maps to profile_idc, constraint_set1 (Constrained
Baseline), PPS transform_8x8_mode and entropy_coding_mode. A profile the
driver rejects is Unsupported. The colour description goes into the
H.264/H.265 VUI and the AV1 colour config, as VA writes it.

Adds the hw_config example: H.264 Main, BT.601 full range, GOP 15, forced
key frame at 7; Vulkan and VA match in ffprobe fields and key frames.
crates/ec-hw/examples/hw_config.rsadded+139 -0
@@ -0,0 +1,139 @@
1+use std::fs;
2+use std::path::{Path, PathBuf};
3+use std::process::Command;
4+
5+use ec_hw::{
6+ Backend, EncCodec, EncoderConfig, FrameMetadata, H264Profile, HwEncoder, I420, RateControlMode,
7+};
8+
9+const WIDTH: u32 = 640;
10+const HEIGHT: u32 = 360;
11+const FRAMES: usize = 30;
12+const FPS: u32 = 30;
13+const GOP: u32 = 15;
14+const FORCE_AT: usize = 7;
15+const BITRATE: u32 = 2_000_000;
16+const FIELDS: [&str; 7] = [
17+ "profile",
18+ "width",
19+ "height",
20+ "color_space",
21+ "color_transfer",
22+ "color_primaries",
23+ "color_range",
24+];
25+
26+fn config() -> EncoderConfig {
27+ EncoderConfig {
28+ bitrate: BITRATE,
29+ framerate: (FPS, 1),
30+ gop_size: GOP,
31+ rate_control: RateControlMode::ConstantBitrate,
32+ ..EncoderConfig::new(EncCodec::H264, WIDTH, HEIGHT)
33+ }
34+ .h264_profile(H264Profile::Main)
35+ .colour(6, 6, 6, true)
36+}
37+
38+fn frame(t: usize) -> I420 {
39+ let (w, h) = (WIDTH as usize, HEIGHT as usize);
40+ let y = (0..w * h)
41+ .map(|i| ((i % w + i / w + 3 * t) & 0xff) as u8)
42+ .collect();
43+ let chroma = w / 2 * h / 2;
44+ I420 {
45+ y,
46+ u: vec![(96 + t % 64) as u8; chroma],
47+ v: vec![160; chroma],
48+ width: WIDTH,
49+ height: HEIGHT,
50+ }
51+}
52+
53+fn encode(dir: &Path, name: &str, backend: Backend) -> Option<PathBuf> {
54+ let mut encoder = match HwEncoder::open(config(), Some(backend)) {
55+ Ok(encoder) => encoder,
56+ Err(e) => {
57+ println!("{name}: {e}");
58+ return None;
59+ }
60+ };
61+ let mut stream = Vec::new();
62+ for t in 0..FRAMES {
63+ let meta = FrameMetadata {
64+ timestamp: t as i64,
65+ force_keyframe: t == FORCE_AT,
66+ };
67+ let coded = encoder.encode(&frame(t), meta).expect("encode frame");
68+ stream.extend_from_slice(&coded.data);
69+ }
70+ let path = dir.join(format!("{name}.h264"));
71+ fs::write(&path, stream).expect("write stream");
72+ Some(path)
73+}
74+
75+fn probe(path: &Path) -> Vec<(String, String)> {
76+ let out = Command::new("ffprobe")
77+ .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
78+ .arg(format!("stream={}", FIELDS.join(",")))
79+ .args(["-of", "default=nw=1"])
80+ .arg(path)
81+ .output()
82+ .expect("run ffprobe");
83+ String::from_utf8_lossy(&out.stdout)
84+ .lines()
85+ .filter_map(|l| l.split_once('='))
86+ .map(|(k, v)| (k.to_string(), v.to_string()))
87+ .collect()
88+}
89+
90+fn keyframes(path: &Path) -> Vec<usize> {
91+ let out = Command::new("ffprobe")
92+ .args([
93+ "-v",
94+ "error",
95+ "-select_streams",
96+ "v:0",
97+ "-show_entries",
98+ "frame=key_frame",
99+ ])
100+ .args(["-of", "csv=p=0"])
101+ .arg(path)
102+ .output()
103+ .expect("run ffprobe");
104+ String::from_utf8_lossy(&out.stdout)
105+ .lines()
106+ .enumerate()
107+ .filter(|(_, l)| l.trim() == "1")
108+ .map(|(i, _)| i)
109+ .collect()
110+}
111+
112+fn value(info: &[(String, String)], key: &str) -> String {
113+ info.iter()
114+ .find(|(k, _)| k == key)
115+ .map_or("-".to_string(), |(_, v)| v.clone())
116+}
117+
118+fn main() {
119+ let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument"));
120+ let Some(vk) = encode(&dir, "vk", Backend::Vk) else {
121+ return;
122+ };
123+ let Some(va) = encode(&dir, "va", Backend::Va) else {
124+ return;
125+ };
126+ let (vk_info, va_info) = (probe(&vk), probe(&va));
127+ let mut same = true;
128+ println!("{:<16}{:<16}{:<16}", "field", "vk", "va");
129+ for key in FIELDS {
130+ let (a, b) = (value(&vk_info, key), value(&va_info, key));
131+ same &= a == b;
132+ println!("{key:<16}{a:<16}{b:<16}");
133+ }
134+ let (kv, ka) = (keyframes(&vk), keyframes(&va));
135+ same &= kv == ka;
136+ let list = |k: &[usize]| k.iter().map(usize::to_string).collect::<Vec<_>>().join(",");
137+ println!("{:<16}{:<16}{:<16}", "keyframes", list(&kv), list(&ka));
138+ println!("match: {same}");
139+}
crates/ec-hw/src/enc/mod.rsmodified+4 -85
@@ -53,6 +53,7 @@ use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceS
53 use crate::error::{Error, Result};53 use crate::error::{Error, Result};
54 use crate::frame::{Frame, I420, I420_16};54 use crate::frame::{Frame, I420, I420_16};
55 use crate::pool::{PooledSurface, SurfacePool};55 use crate::pool::{PooledSurface, SurfacePool};
56+use crate::rate::{RATE_WINDOW_MS, RateFeedback, hrd_buffer_ms};
56 57
57 pub use crate::types::{58 pub use crate::types::{
58 CodedFrame, Colour, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, Tunings,59 CodedFrame, Colour, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, Tunings,
@@ -78,64 +79,9 @@ impl H264Profile {
78 }79 }
79 }80 }
80 81
81-/// The rate window the request is spread over, in milliseconds (`window_size`).
82-const RATE_WINDOW_MS: u32 = 1000;
83-
84 /// Pictures the pipelined path keeps in flight before the oldest is read back.82 /// Pictures the pipelined path keeps in flight before the oldest is read back.
85 const DEPTH: usize = 3;83 const DEPTH: usize = 3;
86 84
87-/// The HRD buffer for a GOP of `gop_size` pictures, in milliseconds of the
88-/// requested bitrate.
89-///
90-/// The buffer is what radeonsi's constant-bitrate loop works against, and it
91-/// must be short when pictures are mostly key frames. Measured at 720p,
92-/// testsrc2, 240 pictures, HEVC, requested 1, 3 and 8 Mb/s:
93-///
94-/// | GOP | buffer | delivered (3 Mb/s request) |
95-/// |---|---|---|
96-/// | 1 | 1000 ms | 7.63 Mb/s (+154%) |
97-/// | 1 | 33 ms | 3.29 Mb/s (+9.5%) |
98-/// | 1 | 20 ms | 3.02 Mb/s (+0.7%) |
99-/// | 2 | 1000 ms | +9.4% |
100-/// | 5 | 1000 ms | +4.3% |
101-/// | 10 | 1000 ms | +1.8% |
102-/// | 30 | 1000 ms | +1.0%, 43.5 dB |
103-/// | 30 | 20 ms | +0.0%, 40.1 dB |
104-///
105-/// So a GOP shorter than ten pictures gets a 20 ms buffer. A GOP of thirty keeps
106-/// the full rate window: the short buffer lands on the request there too, but
107-/// costs 3.4 dB at the same rate.
108-fn hrd_buffer_ms(gop_size: u32) -> u32 {
109- if gop_size < 10 { 20 } else { RATE_WINDOW_MS }
110-}
111-
112-/// Closed-loop correction of the driver's rate control, which lands off the ask
113-/// on detailed content (testsrc2: +12..19% on mesa 26.2.6, ffmpeg's VA-API
114-/// encoders too): once a second the bitrate sent is rescaled by the measured
115-/// bias, plus whatever was over- or under-spent so far.
116-#[derive(Debug, Clone, Copy)]
117-struct RateFeedback {
118- scale: f64,
119- spent: f64,
120- frames: u32,
121- window: f64,
122- window_frames: u32,
123- steered: bool,
124-}
125-
126-impl Default for RateFeedback {
127- fn default() -> Self {
128- RateFeedback {
129- scale: 1.0,
130- spent: 0.0,
131- frames: 0,
132- window: 0.0,
133- window_frames: 0,
134- steered: false,
135- }
136- }
137-}
138-
139 impl RateControlMode {85 impl RateControlMode {
140 /// The `VAConfigAttribRateControl` value this mode is configured with.86 /// The `VAConfigAttribRateControl` value this mode is configured with.
141 ///87 ///
@@ -718,38 +664,11 @@ impl Encoder {
718 }664 }
719 665
720 fn steered_bitrate(&self) -> u32 {666 fn steered_bitrate(&self) -> u32 {
721- (f64::from(self.tunings.bitrate) * self.rc.scale) as u32667+ self.rc.steered_bitrate(self.tunings.bitrate)
722 }668 }
723 669
724 fn track_rate(&mut self, bytes: usize) {670 fn track_rate(&mut self, bytes: usize) {
725- if !matches!(671+ if self.rc.track(bytes, self.config.rate_control, self.tunings) {
726- self.config.rate_control,
727- RateControlMode::ConstantBitrate | RateControlMode::VariableBitrate
728- ) {
729- return;
730- }
731- let (num, den) = self.tunings.framerate;
732- let fps = f64::from(num.max(1)) / f64::from(den.max(1));
733- let rate = f64::from(self.tunings.bitrate);
734- let per_frame = rate / fps;
735- let rc = &mut self.rc;
736- let bits = bytes as f64 * 8.0;
737- rc.spent += bits;
738- rc.frames += 1;
739- rc.window += bits;
740- rc.window_frames += 1;
741- if f64::from(rc.window_frames) < fps.round().max(1.0) {
742- return;
743- }
744- let asked = rc.scale * per_frame * f64::from(rc.window_frames);
745- let bias = rc.window / asked;
746- let debt = f64::from(rc.frames) * per_frame - rc.spent;
747- let scale = ((rate + debt) / rate / bias).clamp(0.5, 1.5);
748- rc.window = 0.0;
749- rc.window_frames = 0;
750- if (scale / rc.scale - 1.0).abs() > 0.02 {
751- rc.scale = scale;
752- rc.steered = true;
753 self.tunings_dirty = true;672 self.tunings_dirty = true;
754 }673 }
755 }674 }
@@ -799,7 +718,7 @@ impl Encoder {
799 out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(718 out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(
800 EncMiscParameterFrameRate::new(packed, 0),719 EncMiscParameterFrameRate::new(packed, 0),
801 )));720 )));
802- if bits > 0 && !std::mem::take(&mut self.rc.steered) {721+ if bits > 0 && !self.rc.take_steered() {
803 // The buffer starts full. Starting at three quarters full cost a722 // The buffer starts full. Starting at three quarters full cost a
804 // quarter of a window of budget: radeonsi then spent 12.5% under the723 // quarter of a window of budget: radeonsi then spent 12.5% under the
805 // ask on a 2 s clip, and the gap is exactly that quarter over the724 // ask on a 2 s clip, and the gap is exactly that quarter over the
crates/ec-hw/src/hw.rsmodified+52 -10
@@ -14,8 +14,10 @@ use crate::picture::{Decoded, I420, I420_16, RgbPicture};
14 use crate::picture::{rgb_size, yuv_to_rgb};14 use crate::picture::{rgb_size, yuv_to_rgb};
15 #[cfg(target_os = "linux")]15 #[cfg(target_os = "linux")]
16 use ec_core::color::{ColorDescription, Matrix, Tags};16 use ec_core::color::{ColorDescription, Matrix, Tags};
17+use crate::rate::{RateFeedback, hrd_buffer_ms};
17 use crate::types::{18 use crate::types::{
18- Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings,19+ Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode,
20+ Tunings,
19 };21 };
20 use crate::vkdec_av1::VkAv1Decoder;22 use crate::vkdec_av1::VkAv1Decoder;
21 use crate::vkdec_vp9::VkVp9Decoder;23 use crate::vkdec_vp9::VkVp9Decoder;
@@ -386,6 +388,8 @@ pub struct HwEncoder {
386 config: EncoderConfig,388 config: EncoderConfig,
387 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]389 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
388 size: (usize, usize),390 size: (usize, usize),
391+ tunings: Tunings,
392+ rc: RateFeedback,
389 }393 }
390 394
391 impl HwEncoder {395 impl HwEncoder {
@@ -406,6 +410,11 @@ impl HwEncoder {
406 born_epoch,410 born_epoch,
407 config,411 config,
408 size,412 size,
413+ tunings: Tunings {
414+ bitrate: config.bitrate,
415+ framerate: config.framerate,
416+ },
417+ rc: RateFeedback::default(),
409 });418 });
410 }419 }
411 Err(e) => reasons.push(format!("{backend:?}: {e}")),420 Err(e) => reasons.push(format!("{backend:?}: {e}")),
@@ -431,12 +440,9 @@ impl HwEncoder {
431 match &mut self.inner {440 match &mut self.inner {
432 EncInner::Vk(enc) => {441 EncInner::Vk(enc) => {
433 vk_session_alive(self.born_epoch)?;442 vk_session_alive(self.born_epoch)?;
434- let rate = match self.config.rate_control {443+ self.tunings = tunings;
435- RateControlMode::ConstantQp { .. } => vk_rate(&self.config),444+ self.rc = RateFeedback::default();
436- _ => ec_vk::RateControl::Cbr {445+ let rate = vk_rate(&self.config, tunings.bitrate);
437- bitrate: tunings.bitrate,
438- },
439- };
440 enc.set_rate(rate, tunings.framerate)?;446 enc.set_rate(rate, tunings.framerate)?;
441 }447 }
442 #[cfg(target_os = "linux")]448 #[cfg(target_os = "linux")]
@@ -445,12 +451,26 @@ impl HwEncoder {
445 Ok(())451 Ok(())
446 }452 }
447 453
454+ fn steer(&mut self, bytes: usize) -> Result<()> {
455+ if !self.rc.track(bytes, self.config.rate_control, self.tunings) {
456+ return Ok(());
457+ }
458+ let rate = vk_rate(&self.config, self.rc.steered_bitrate(self.tunings.bitrate));
459+ match &mut self.inner {
460+ EncInner::Vk(enc) => enc.set_rate(rate, self.tunings.framerate)?,
461+ #[cfg(target_os = "linux")]
462+ EncInner::Va(_) => {}
463+ }
464+ Ok(())
465+ }
466+
448 /// Encode one frame; `meta.force_keyframe` starts a new GOP.467 /// Encode one frame; `meta.force_keyframe` starts a new GOP.
449 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {468 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
450 match &mut self.inner {469 match &mut self.inner {
451 EncInner::Vk(enc) => {470 EncInner::Vk(enc) => {
452 vk_session_alive(self.born_epoch)?;471 vk_session_alive(self.born_epoch)?;
453 let coded = enc.encode(frame, meta.force_keyframe)?;472 let coded = enc.encode(frame, meta.force_keyframe)?;
473+ self.steer(coded.data.len())?;
454 Ok(CodedFrame {474 Ok(CodedFrame {
455 data: coded.data,475 data: coded.data,
456 timestamp: meta.timestamp,476 timestamp: meta.timestamp,
@@ -467,6 +487,7 @@ impl HwEncoder {
467 match &mut self.inner {487 match &mut self.inner {
468 EncInner::Vk(enc) => {488 EncInner::Vk(enc) => {
469 let coded = enc.encode_16(frame, meta.force_keyframe)?;489 let coded = enc.encode_16(frame, meta.force_keyframe)?;
490+ self.steer(coded.data.len())?;
470 Ok(CodedFrame {491 Ok(CodedFrame {
471 data: coded.data,492 data: coded.data,
472 timestamp: meta.timestamp,493 timestamp: meta.timestamp,
@@ -484,6 +505,7 @@ impl HwEncoder {
484 EncInner::Vk(enc) => {505 EncInner::Vk(enc) => {
485 vk_session_alive(self.born_epoch)?;506 vk_session_alive(self.born_epoch)?;
486 let coded = enc.encode_rgb(frame, meta.force_keyframe)?;507 let coded = enc.encode_rgb(frame, meta.force_keyframe)?;
508+ self.steer(coded.data.len())?;
487 Ok(CodedFrame {509 Ok(CodedFrame {
488 data: coded.data,510 data: coded.data,
489 timestamp: meta.timestamp,511 timestamp: meta.timestamp,
@@ -506,6 +528,7 @@ impl HwEncoder {
506 EncInner::Vk(enc) => {528 EncInner::Vk(enc) => {
507 vk_session_alive(self.born_epoch)?;529 vk_session_alive(self.born_epoch)?;
508 let coded = enc.encode_dmabuf(frame, meta.force_keyframe)?;530 let coded = enc.encode_dmabuf(frame, meta.force_keyframe)?;
531+ self.steer(coded.data.len())?;
509 Ok(CodedFrame {532 Ok(CodedFrame {
510 data: coded.data,533 data: coded.data,
511 timestamp: meta.timestamp,534 timestamp: meta.timestamp,
@@ -543,13 +566,19 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
543 }566 }
544 let gpu = vk_gpu()567 let gpu = vk_gpu()
545 .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?;568 .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?;
546- let rate = vk_rate(&config);569+ let rate = vk_rate(&config, config.bitrate);
547 let (width, height, fps, gop_size) = (570 let (width, height, fps, gop_size) = (
548 config.width,571 config.width,
549 config.height,572 config.height,
550 config.framerate,573 config.framerate,
551 config.gop_size,574 config.gop_size,
552 );575 );
576+ let colour = config.colour.map(|c| ec_vk::Colour {
577+ primaries: c.primaries,
578+ transfer: c.transfer,
579+ matrix: c.matrix,
580+ full_range: c.full_range,
581+ });
553 Ok(match config.codec {582 Ok(match config.codec {
554 EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new(583 EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new(
555 &gpu,584 &gpu,
@@ -559,6 +588,8 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
559 fps,588 fps,
560 gop_size,589 gop_size,
561 rate,590 rate,
591+ profile: vk_h264_profile(config.h264_profile),
592+ colour,
562 },593 },
563 )?),594 )?),
564 EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new(595 EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new(
@@ -570,6 +601,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
570 gop_size,601 gop_size,
571 rate,602 rate,
572 bit_depth: config.bit_depth,603 bit_depth: config.bit_depth,
604+ colour,
573 },605 },
574 )?),606 )?),
575 EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new(607 EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new(
@@ -581,12 +613,21 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
581 gop_size,613 gop_size,
582 rate,614 rate,
583 bit_depth: config.bit_depth,615 bit_depth: config.bit_depth,
616+ colour,
584 },617 },
585 )?),618 )?),
586 })619 })
587 }620 }
588 621
589-fn vk_rate(config: &EncoderConfig) -> ec_vk::RateControl {622+fn vk_h264_profile(profile: H264Profile) -> ec_vk::H264Profile {
623+ match profile {
624+ H264Profile::ConstrainedBaseline => ec_vk::H264Profile::ConstrainedBaseline,
625+ H264Profile::Main => ec_vk::H264Profile::Main,
626+ H264Profile::High => ec_vk::H264Profile::High,
627+ }
628+}
629+
630+fn vk_rate(config: &EncoderConfig, bitrate: u32) -> ec_vk::RateControl {
590 match (config.rate_control, config.codec) {631 match (config.rate_control, config.codec) {
591 (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp {632 (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp {
592 qp: (qp / 5).min(51) as u8,633 qp: (qp / 5).min(51) as u8,
@@ -595,7 +636,8 @@ fn vk_rate(config: &EncoderConfig) -> ec_vk::RateControl {
595 qp: qp.min(51) as u8,636 qp: qp.min(51) as u8,
596 },637 },
597 _ => ec_vk::RateControl::Cbr {638 _ => ec_vk::RateControl::Cbr {
598- bitrate: config.bitrate,639+ bitrate,
640+ buffer_ms: hrd_buffer_ms(config.gop_size),
599 },641 },
600 }642 }
601 }643 }
crates/ec-hw/src/lib.rsmodified+1 -0
@@ -63,6 +63,7 @@ pub mod error;
63 pub(crate) mod dpb264;63 pub(crate) mod dpb264;
64 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]64 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
65 pub(crate) mod h264_common;65 pub(crate) mod h264_common;
66+pub(crate) mod rate;
66 pub(crate) mod ref_slots;67 pub(crate) mod ref_slots;
67 pub(crate) mod vkdec_vp9;68 pub(crate) mod vkdec_vp9;
68 pub(crate) mod hevc_dpb;69 pub(crate) mod hevc_dpb;
crates/ec-hw/src/rate.rsadded+100 -0
@@ -0,0 +1,100 @@
1+use crate::types::{RateControlMode, Tunings};
2+
3+pub(crate) const RATE_WINDOW_MS: u32 = 1000;
4+
5+/// The HRD buffer for a GOP of `gop_size` pictures, in milliseconds of the
6+/// requested bitrate.
7+///
8+/// The buffer is what radeonsi's constant-bitrate loop works against, and it
9+/// must be short when pictures are mostly key frames. Measured at 720p,
10+/// testsrc2, 240 pictures, HEVC, requested 1, 3 and 8 Mb/s:
11+///
12+/// | GOP | buffer | delivered (3 Mb/s request) |
13+/// |---|---|---|
14+/// | 1 | 1000 ms | 7.63 Mb/s (+154%) |
15+/// | 1 | 33 ms | 3.29 Mb/s (+9.5%) |
16+/// | 1 | 20 ms | 3.02 Mb/s (+0.7%) |
17+/// | 2 | 1000 ms | +9.4% |
18+/// | 5 | 1000 ms | +4.3% |
19+/// | 10 | 1000 ms | +1.8% |
20+/// | 30 | 1000 ms | +1.0%, 43.5 dB |
21+/// | 30 | 20 ms | +0.0%, 40.1 dB |
22+///
23+/// So a GOP shorter than ten pictures gets a 20 ms buffer. A GOP of thirty keeps
24+/// the full rate window: the short buffer lands on the request there too, but
25+/// costs 3.4 dB at the same rate.
26+pub(crate) fn hrd_buffer_ms(gop_size: u32) -> u32 {
27+ if gop_size < 10 { 20 } else { RATE_WINDOW_MS }
28+}
29+
30+/// Closed-loop correction of the driver's rate control, which lands off the ask
31+/// on detailed content (testsrc2: +12..19% on mesa 26.2.6, ffmpeg's VA-API
32+/// encoders too): once a second the bitrate sent is rescaled by the measured
33+/// bias, plus whatever was over- or under-spent so far.
34+#[derive(Debug, Clone, Copy)]
35+pub(crate) struct RateFeedback {
36+ scale: f64,
37+ spent: f64,
38+ frames: u32,
39+ window: f64,
40+ window_frames: u32,
41+ steered: bool,
42+}
43+
44+impl Default for RateFeedback {
45+ fn default() -> Self {
46+ RateFeedback {
47+ scale: 1.0,
48+ spent: 0.0,
49+ frames: 0,
50+ window: 0.0,
51+ window_frames: 0,
52+ steered: false,
53+ }
54+ }
55+}
56+
57+impl RateFeedback {
58+ pub(crate) fn steered_bitrate(&self, bitrate: u32) -> u32 {
59+ (f64::from(bitrate) * self.scale) as u32
60+ }
61+
62+ #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
63+ pub(crate) fn take_steered(&mut self) -> bool {
64+ std::mem::take(&mut self.steered)
65+ }
66+
67+ /// Account one coded picture of `bytes`; true when the bitrate sent has changed.
68+ pub(crate) fn track(&mut self, bytes: usize, mode: RateControlMode, tunings: Tunings) -> bool {
69+ if !matches!(
70+ mode,
71+ RateControlMode::ConstantBitrate | RateControlMode::VariableBitrate
72+ ) {
73+ return false;
74+ }
75+ let (num, den) = tunings.framerate;
76+ let fps = f64::from(num.max(1)) / f64::from(den.max(1));
77+ let rate = f64::from(tunings.bitrate);
78+ let per_frame = rate / fps;
79+ let bits = bytes as f64 * 8.0;
80+ self.spent += bits;
81+ self.frames += 1;
82+ self.window += bits;
83+ self.window_frames += 1;
84+ if f64::from(self.window_frames) < fps.round().max(1.0) {
85+ return false;
86+ }
87+ let asked = self.scale * per_frame * f64::from(self.window_frames);
88+ let bias = self.window / asked;
89+ let debt = f64::from(self.frames) * per_frame - self.spent;
90+ let scale = ((rate + debt) / rate / bias).clamp(0.5, 1.5);
91+ self.window = 0.0;
92+ self.window_frames = 0;
93+ if (scale / self.scale - 1.0).abs() > 0.02 {
94+ self.scale = scale;
95+ self.steered = true;
96+ return true;
97+ }
98+ false
99+ }
100+}
crates/ec-vk/examples/av1_encode.rsmodified+2 -0
@@ -31,10 +31,12 @@ fn main() {
31 rate: match std::env::args().nth(2) {31 rate: match std::env::args().nth(2) {
32 Some(b) => RateControl::Cbr {32 Some(b) => RateControl::Cbr {
33 bitrate: b.parse().expect("bitrate"),33 bitrate: b.parse().expect("bitrate"),
34+ buffer_ms: 1000,
34 },35 },
35 None => RateControl::ConstantQp { qp: 26 },36 None => RateControl::ConstantQp { qp: 26 },
36 },37 },
37 bit_depth: 8,38 bit_depth: 8,
39+ colour: None,
38 };40 };
39 let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder");41 let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder");
40 42
crates/ec-vk/examples/h264_encode.rsmodified+7 -2
@@ -1,4 +1,4 @@
1-use ec_vk::{Gpu, H264Encoder, H264EncoderConfig, RateControl};1+use ec_vk::{Gpu, H264Encoder, H264EncoderConfig, H264Profile, RateControl};
2 2
3 const W: u32 = 1280;3 const W: u32 = 1280;
4 const H: u32 = 720;4 const H: u32 = 720;
@@ -27,8 +27,13 @@ fn main() {
27 height: H,27 height: H,
28 fps: (30, 1),28 fps: (30, 1),
29 gop_size: 30,29 gop_size: 30,
30+ profile: H264Profile::High,
31+ colour: None,
30 rate: match std::env::args().nth(2) {32 rate: match std::env::args().nth(2) {
31- Some(b) => RateControl::Cbr { bitrate: b.parse().expect("bitrate") },33+ Some(b) => RateControl::Cbr {
34+ bitrate: b.parse().expect("bitrate"),
35+ buffer_ms: 1000,
36+ },
32 None => RateControl::ConstantQp { qp: 26 },37 None => RateControl::ConstantQp { qp: 26 },
33 },38 },
34 };39 };
crates/ec-vk/examples/h265_encode.rsmodified+2 -0
@@ -30,10 +30,12 @@ fn main() {
30 rate: match std::env::args().nth(2) {30 rate: match std::env::args().nth(2) {
31 Some(b) => RateControl::Cbr {31 Some(b) => RateControl::Cbr {
32 bitrate: b.parse().expect("bitrate"),32 bitrate: b.parse().expect("bitrate"),
33+ buffer_ms: 1000,
33 },34 },
34 None => RateControl::ConstantQp { qp: 26 },35 None => RateControl::ConstantQp { qp: 26 },
35 },36 },
36 bit_depth: 8,37 bit_depth: 8,
38+ colour: None,
37 };39 };
38 let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder");40 let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder");
39 let mut out = Vec::new();41 let mut out = Vec::new();
crates/ec-vk/src/av1.rsmodified+4 -1
@@ -2,7 +2,7 @@ use vk_video_ffi::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
2 2
3 #[cfg(target_os = "linux")]3 #[cfg(target_os = "linux")]
4 use crate::DmaBuf;4 use crate::DmaBuf;
5-use crate::{CodedFrame, Error, Gpu, RateControl};5+use crate::{CodedFrame, Colour, Error, Gpu, RateControl};
6 6
7 const TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00];7 const TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00];
8 8
@@ -21,6 +21,8 @@ pub struct Av1EncoderConfig {
21 pub rate: RateControl,21 pub rate: RateControl,
22 /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).22 /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
23 pub bit_depth: u8,23 pub bit_depth: u8,
24+ /// Colour config of the sequence header, or none.
25+ pub colour: Option<Colour>,
24 }26 }
25 27
26 /// AV1 encoder: order hint, DPB slot and LAST reference bookkeeping over [`Av1EncodeSession`].28 /// AV1 encoder: order hint, DPB slot and LAST reference bookkeeping over [`Av1EncodeSession`].
@@ -51,6 +53,7 @@ impl Av1Encoder {
51 fps: cfg.fps,53 fps: cfg.fps,
52 rate: cfg.rate,54 rate: cfg.rate,
53 bit_depth: cfg.bit_depth,55 bit_depth: cfg.bit_depth,
56+ colour: cfg.colour,
54 },57 },
55 )?;58 )?;
56 let sequence_header = session.sequence_header();59 let sequence_header = session.sequence_header();
crates/ec-vk/src/h265.rsmodified+4 -1
@@ -2,7 +2,7 @@ use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref};
2 2
3 #[cfg(target_os = "linux")]3 #[cfg(target_os = "linux")]
4 use crate::DmaBuf;4 use crate::DmaBuf;
5-use crate::{CodedFrame, Error, Gpu, RateControl};5+use crate::{CodedFrame, Colour, Error, Gpu, RateControl};
6 6
7 /// H.265 encoder settings.7 /// H.265 encoder settings.
8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -19,6 +19,8 @@ pub struct H265EncoderConfig {
19 pub rate: RateControl,19 pub rate: RateControl,
20 /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).20 /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
21 pub bit_depth: u8,21 pub bit_depth: u8,
22+ /// Colour description for the VUI, or none.
23+ pub colour: Option<Colour>,
22 }24 }
23 25
24 /// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`].26 /// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`].
@@ -49,6 +51,7 @@ impl H265Encoder {
49 fps: cfg.fps,51 fps: cfg.fps,
50 rate: cfg.rate,52 rate: cfg.rate,
51 bit_depth: cfg.bit_depth,53 bit_depth: cfg.bit_depth,
54+ colour: cfg.colour,
52 },55 },
53 )?;56 )?;
54 let parameter_sets = session.parameter_sets()?;57 let parameter_sets = session.parameter_sets()?;
crates/ec-vk/src/lib.rsmodified+13 -8
@@ -15,13 +15,13 @@ pub use vk_video_ffi::{
15 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,15 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
16 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,16 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
17 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,17 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,
18- Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Direction,18+ Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Colour,
19- Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot,19+ Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps,
20- H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,20+ H264Profile, H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture,
21- H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists,21+ H265DecodeSession, H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot,
22- H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, Vp9ColorConfig,22+ H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists,
23- Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, Vp9InterpolationFilter,23+ Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,
24- Vp9LoopFilter, Vp9Segmentation,24+ Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,
25 };25 };
26 26
27 /// Encoder settings.27 /// Encoder settings.
@@ -37,6 +37,10 @@ pub struct H264EncoderConfig {
37 pub gop_size: u32,37 pub gop_size: u32,
38 /// Rate control.38 /// Rate control.
39 pub rate: RateControl,39 pub rate: RateControl,
40+ /// H.264 profile.
41+ pub profile: H264Profile,
42+ /// Colour description for the VUI, or none.
43+ pub colour: Option<Colour>,
40 }44 }
41 45
42 /// One coded frame, Annex-B. Keyframes carry SPS and PPS before the slice.46 /// One coded frame, Annex-B. Keyframes carry SPS and PPS before the slice.
@@ -76,7 +80,8 @@ impl H264Encoder {
76 height: cfg.height,80 height: cfg.height,
77 fps: cfg.fps,81 fps: cfg.fps,
78 rate: cfg.rate,82 rate: cfg.rate,
79- profile_high: true,83+ profile: cfg.profile,
84+ colour: cfg.colour,
80 },85 },
81 )?;86 )?;
82 let parameter_sets = session.parameter_sets()?;87 let parameter_sets = session.parameter_sets()?;
shims/vk-video-ffi/examples/dmabuf_smoke.rsmodified+5 -2
@@ -3,7 +3,7 @@ use std::os::fd::{AsFd, FromRawFd, OwnedFd};
3 use vk_video_ffi::{3 use vk_video_ffi::{
4 Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, Error, Gpu, H264EncodeConfig,4 Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, Error, Gpu, H264EncodeConfig,
5 H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, H265EncodeSession, H265Picture,5 H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, H265EncodeSession, H265Picture,
6- H265Ref, RateControl,6+ H265Ref, H264Profile, RateControl,
7 };7 };
8 use vulkanalia::prelude::v1_3::*;8 use vulkanalia::prelude::v1_3::*;
9 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;9 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;
@@ -37,7 +37,8 @@ impl Encode for H264EncodeSession {
37 height: size.1,37 height: size.1,
38 fps: FPS,38 fps: FPS,
39 rate: RATE,39 rate: RATE,
40- profile_high: true,40+ profile: H264Profile::High,
41+ colour: None,
41 };42 };
42 H264EncodeSession::new(gpu, &cfg)43 H264EncodeSession::new(gpu, &cfg)
43 }44 }
@@ -83,6 +84,7 @@ impl Encode for H265EncodeSession {
83 fps: FPS,84 fps: FPS,
84 rate: RATE,85 rate: RATE,
85 bit_depth: 8,86 bit_depth: 8,
87+ colour: None,
86 };88 };
87 H265EncodeSession::new(gpu, &cfg)89 H265EncodeSession::new(gpu, &cfg)
88 }90 }
@@ -117,6 +119,7 @@ impl Encode for Av1EncodeSession {
117 fps: FPS,119 fps: FPS,
118 rate: RATE,120 rate: RATE,
119 bit_depth: 8,121 bit_depth: 8,
122+ colour: None,
120 };123 };
121 Av1EncodeSession::new(gpu, &cfg)124 Av1EncodeSession::new(gpu, &cfg)
122 }125 }
shims/vk-video-ffi/src/av1_encode.rsmodified+40 -15
@@ -7,10 +7,10 @@ use vulkanalia::vk::KhrVideoQueueExtensionDeviceCommands;
7 use crate::dmabuf::DmaBuf;7 use crate::dmabuf::DmaBuf;
8 use crate::rgb_convert::{Input, check_rgb};8 use crate::rgb_convert::{Input, check_rgb};
9 use crate::session::{9 use crate::session::{
10- DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession,10+ DPB_SLOTS, Encoder, VideoSession, component_bit_depth, picture_resource, validate_rate,
11- component_bit_depth, picture_resource, validate_rate, video_caps, vk, zeroed,11+ video_caps, vk, zeroed,
12 };12 };
13-use crate::{Error, Gpu, RateControl};13+use crate::{Colour, Error, Gpu, RateControl};
14 14
15 const AV1_SLOTS: usize = 8;15 const AV1_SLOTS: usize = 8;
16 const LEVEL: vk::video::StdVideoAV1Level = vk::video::STD_VIDEO_AV1_LEVEL_5_1;16 const LEVEL: vk::video::StdVideoAV1Level = vk::video::STD_VIDEO_AV1_LEVEL_5_1;
@@ -29,6 +29,8 @@ pub struct Av1EncodeConfig {
29 pub rate: RateControl,29 pub rate: RateControl,
30 /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input).30 /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input).
31 pub bit_depth: u8,31 pub bit_depth: u8,
32+ /// Colour config of the sequence header, or none (unspecified).
33+ pub colour: Option<Colour>,
32 }34 }
33 35
34 /// One picture to encode.36 /// One picture to encode.
@@ -102,19 +104,22 @@ struct RateChain {
102 104
103 impl RateChain {105 impl RateChain {
104 fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> {106 fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> {
105- let (mode, layers, bitrate) = match rate {107+ let (mode, layers, bitrate, buffer_ms) = match rate {
106 RateControl::ConstantQp { .. } => {108 RateControl::ConstantQp { .. } => {
107- (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0)109+ (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0, 0)
108- }
109- RateControl::Cbr { bitrate } => {
110- (vk::VideoEncodeRateControlModeFlagsKHR::CBR, 1, bitrate)
111 }110 }
111+ RateControl::Cbr { bitrate, buffer_ms } => (
112+ vk::VideoEncodeRateControlModeFlagsKHR::CBR,
113+ 1,
114+ bitrate,
115+ buffer_ms,
116+ ),
112 };117 };
113 let mut c = Box::new(RateChain {118 let mut c = Box::new(RateChain {
114 rc: vk::VideoEncodeRateControlInfoKHR::builder()119 rc: vk::VideoEncodeRateControlInfoKHR::builder()
115 .rate_control_mode(mode)120 .rate_control_mode(mode)
116- .virtual_buffer_size_in_ms(VIRTUAL_BUFFER_MS)121+ .virtual_buffer_size_in_ms(buffer_ms)
117- .initial_virtual_buffer_size_in_ms(INITIAL_VIRTUAL_BUFFER_MS)122+ .initial_virtual_buffer_size_in_ms(buffer_ms)
118 .build(),123 .build(),
119 rc_av1: vk::VideoEncodeAV1RateControlInfoKHR::builder()124 rc_av1: vk::VideoEncodeAV1RateControlInfoKHR::builder()
120 .flags(vk::VideoEncodeAV1RateControlFlagsKHR::VIDEO_ENCODE_AV1_RATE_CONTROL_REGULAR_GOP | vk::VideoEncodeAV1RateControlFlagsKHR::VIDEO_ENCODE_AV1_RATE_CONTROL_REFERENCE_PATTERN_FLAT)125 .flags(vk::VideoEncodeAV1RateControlFlagsKHR::VIDEO_ENCODE_AV1_RATE_CONTROL_REGULAR_GOP | vk::VideoEncodeAV1RateControlFlagsKHR::VIDEO_ENCODE_AV1_RATE_CONTROL_REFERENCE_PATTERN_FLAT)
@@ -209,11 +214,11 @@ impl Av1EncodeSession {
209 (cfg.rate, cfg.fps),214 (cfg.rate, cfg.fps),
210 caps.size_align,215 caps.size_align,
211 )?;216 )?;
212- let params = create_parameters(&enc.vs, extent, sb128, cfg.bit_depth)?;217+ let params = create_parameters(&enc.vs, extent, sb128, cfg)?;
213 enc.vs.set_params(params);218 enc.vs.set_params(params);
214 Ok(Av1EncodeSession {219 Ok(Av1EncodeSession {
215 enc,220 enc,
216- seq: sequence_header_obu(cfg.width, cfg.height, sb128, cfg.bit_depth),221+ seq: sequence_header_obu(cfg, sb128),
217 slot_key: [false; DPB_SLOTS],222 slot_key: [false; DPB_SLOTS],
218 ref_order_hint: [0; AV1_SLOTS],223 ref_order_hint: [0; AV1_SLOTS],
219 })224 })
@@ -448,16 +453,24 @@ fn create_parameters(
448 vs: &VideoSession,453 vs: &VideoSession,
449 extent: vk::Extent2D,454 extent: vk::Extent2D,
450 sb128: bool,455 sb128: bool,
451- bit_depth: u8,456+ cfg: &Av1EncodeConfig,
452 ) -> Result<vk::VideoSessionParametersKHR, Error> {457 ) -> Result<vk::VideoSessionParametersKHR, Error> {
453 let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>();458 let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>();
454- color.BitDepth = bit_depth;459+ color.BitDepth = cfg.bit_depth;
455 color.subsampling_x = 1;460 color.subsampling_x = 1;
456 color.subsampling_y = 1;461 color.subsampling_y = 1;
457 color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED;462 color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED;
458 color.transfer_characteristics = vk::video::STD_VIDEO_AV1_TRANSFER_CHARACTERISTICS_UNSPECIFIED;463 color.transfer_characteristics = vk::video::STD_VIDEO_AV1_TRANSFER_CHARACTERISTICS_UNSPECIFIED;
459 color.matrix_coefficients = vk::video::STD_VIDEO_AV1_MATRIX_COEFFICIENTS_UNSPECIFIED;464 color.matrix_coefficients = vk::video::STD_VIDEO_AV1_MATRIX_COEFFICIENTS_UNSPECIFIED;
460 color.chroma_sample_position = vk::video::STD_VIDEO_AV1_CHROMA_SAMPLE_POSITION_UNKNOWN;465 color.chroma_sample_position = vk::video::STD_VIDEO_AV1_CHROMA_SAMPLE_POSITION_UNKNOWN;
466+ if let Some(c) = cfg.colour {
467+ color.flags.set_color_description_present_flag(1);
468+ color.flags.set_color_range(c.full_range as u32);
469+ color.color_primaries = vk::video::StdVideoAV1ColorPrimaries(i32::from(c.primaries));
470+ color.transfer_characteristics =
471+ vk::video::StdVideoAV1TransferCharacteristics(i32::from(c.transfer));
472+ color.matrix_coefficients = vk::video::StdVideoAV1MatrixCoefficients(i32::from(c.matrix));
473+ }
461 474
462 let mut seq = zeroed::<vk::video::StdVideoAV1SequenceHeader>();475 let mut seq = zeroed::<vk::video::StdVideoAV1SequenceHeader>();
463 seq.flags.set_enable_order_hint(1);476 seq.flags.set_enable_order_hint(1);
@@ -534,7 +547,8 @@ fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {
534 out547 out
535 }548 }
536 549
537-fn sequence_header_obu(width: u32, height: u32, sb128: bool, bit_depth: u8) -> Vec<u8> {550+fn sequence_header_obu(cfg: &Av1EncodeConfig, sb128: bool) -> Vec<u8> {
551+ let (width, height, bit_depth) = (cfg.width, cfg.height, cfg.bit_depth);
538 let mut b = Bits(Vec::new());552 let mut b = Bits(Vec::new());
539 b.put(0, 3);553 b.put(0, 3);
540 b.put(0, 1);554 b.put(0, 1);
@@ -568,8 +582,19 @@ fn sequence_header_obu(width: u32, height: u32, sb128: bool, bit_depth: u8) -> V
568 b.put(0, 1);582 b.put(0, 1);
569 b.put((bit_depth == 10) as u32, 1);583 b.put((bit_depth == 10) as u32, 1);
570 b.put(0, 1);584 b.put(0, 1);
585+ match cfg.colour {
586+ Some(c) => {
587+ b.put(1, 1);
588+ b.put(u32::from(c.primaries), 8);
589+ b.put(u32::from(c.transfer), 8);
590+ b.put(u32::from(c.matrix), 8);
591+ b.put(c.full_range as u32, 1);
592+ }
593+ None => {
571 b.put(0, 1);594 b.put(0, 1);
572 b.put(0, 1);595 b.put(0, 1);
596+ }
597+ }
573 b.put(0, 2);598 b.put(0, 2);
574 b.put(0, 1);599 b.put(0, 1);
575 b.put(0, 1);600 b.put(0, 1);
shims/vk-video-ffi/src/h264_encode.rsmodified+58 -25
@@ -9,10 +9,10 @@ use vulkanalia::vk::{
9 use crate::dmabuf::DmaBuf;9 use crate::dmabuf::DmaBuf;
10 use crate::rgb_convert::{Input, check_rgb};10 use crate::rgb_convert::{Input, check_rgb};
11 use crate::session::{11 use crate::session::{
12- DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession, align,12+ DPB_SLOTS, Encoder, VideoSession, align, picture_resource, validate_rate, video_caps, vk,
13- picture_resource, validate_rate, video_caps, vk, zeroed,13+ zeroed,
14 };14 };
15-use crate::{Error, Gpu};15+use crate::{Colour, Error, Gpu};
16 16
17 /// Rate control of an encode session.17 /// Rate control of an encode session.
18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -26,9 +26,22 @@ pub enum RateControl {
26 Cbr {26 Cbr {
27 /// Target bitrate in bit/s.27 /// Target bitrate in bit/s.
28 bitrate: u32,28 bitrate: u32,
29+ /// HRD virtual buffer in milliseconds of `bitrate`, also the initial fullness.
30+ buffer_ms: u32,
29 },31 },
30 }32 }
31 33
34+/// H.264 profile written into the SPS and PPS.
35+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36+pub enum H264Profile {
37+ /// `profile_idc` 66 with `constraint_set1_flag`; CAVLC.
38+ ConstrainedBaseline,
39+ /// `profile_idc` 77; CABAC, no 8x8 transform.
40+ Main,
41+ /// `profile_idc` 100; CABAC with the 8x8 transform.
42+ High,
43+}
44+
32 /// Settings fixed for the life of a session.45 /// Settings fixed for the life of a session.
33 #[derive(Debug, Clone, Copy, PartialEq, Eq)]46 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
34 pub struct H264EncodeConfig {47 pub struct H264EncodeConfig {
@@ -40,8 +53,10 @@ pub struct H264EncodeConfig {
40 pub fps: (u32, u32),53 pub fps: (u32, u32),
41 /// Rate control.54 /// Rate control.
42 pub rate: RateControl,55 pub rate: RateControl,
43- /// High profile when true, Main otherwise.56+ /// H.264 profile.
44- pub profile_high: bool,57+ pub profile: H264Profile,
58+ /// Colour description for the VUI, or none.
59+ pub colour: Option<Colour>,
45 }60 }
46 61
47 /// One picture to encode.62 /// One picture to encode.
@@ -87,11 +102,11 @@ struct Profile {
87 }102 }
88 103
89 impl Profile {104 impl Profile {
90- fn new(high: bool) -> Box<Self> {105+ fn new(profile: H264Profile) -> Box<Self> {
91- let idc = if high {106+ let idc = match profile {
92- vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH107+ H264Profile::ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE,
93- } else {108+ H264Profile::Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN,
94- vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN109+ H264Profile::High => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH,
95 };110 };
96 let mut p = Box::new(Profile {111 let mut p = Box::new(Profile {
97 info: vk::VideoProfileInfoKHR::builder()112 info: vk::VideoProfileInfoKHR::builder()
@@ -124,19 +139,22 @@ struct RateChain {
124 139
125 impl RateChain {140 impl RateChain {
126 fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> {141 fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> {
127- let (mode, layers, bitrate) = match rate {142+ let (mode, layers, bitrate, buffer_ms) = match rate {
128 RateControl::ConstantQp { .. } => {143 RateControl::ConstantQp { .. } => {
129- (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0)144+ (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0, 0)
130- }
131- RateControl::Cbr { bitrate } => {
132- (vk::VideoEncodeRateControlModeFlagsKHR::CBR, 1, bitrate)
133 }145 }
146+ RateControl::Cbr { bitrate, buffer_ms } => (
147+ vk::VideoEncodeRateControlModeFlagsKHR::CBR,
148+ 1,
149+ bitrate,
150+ buffer_ms,
151+ ),
134 };152 };
135 let mut c = Box::new(RateChain {153 let mut c = Box::new(RateChain {
136 rc: vk::VideoEncodeRateControlInfoKHR::builder()154 rc: vk::VideoEncodeRateControlInfoKHR::builder()
137 .rate_control_mode(mode)155 .rate_control_mode(mode)
138- .virtual_buffer_size_in_ms(VIRTUAL_BUFFER_MS)156+ .virtual_buffer_size_in_ms(buffer_ms)
139- .initial_virtual_buffer_size_in_ms(INITIAL_VIRTUAL_BUFFER_MS)157+ .initial_virtual_buffer_size_in_ms(buffer_ms)
140 .build(),158 .build(),
141 rc_h264: vk::VideoEncodeH264RateControlInfoKHR::builder()159 rc_h264: vk::VideoEncodeH264RateControlInfoKHR::builder()
142 .flags(160 .flags(
@@ -186,8 +204,11 @@ impl H264EncodeSession {
186 let width = align(cfg.width, 16);204 let width = align(cfg.width, 16);
187 let height = align(cfg.height, 16);205 let height = align(cfg.height, 16);
188 let level = level_for(width, height, cfg.fps)?;206 let level = level_for(width, height, cfg.fps)?;
189- let profile = Profile::new(cfg.profile_high);207+ let profile = Profile::new(cfg.profile);
190- let caps = query_caps(gpu, &profile.info)?;208+ let caps = query_caps(gpu, &profile.info).map_err(|e| match e {
209+ Error::Vk(..) => Error::Unsupported(format!("H.264 {:?} encode", cfg.profile)),
210+ other => other,
211+ })?;
191 if width > caps.max_extent.width || height > caps.max_extent.height {212 if width > caps.max_extent.width || height > caps.max_extent.height {
192 return Err(Error::Unsupported(format!("H.264 encode {width}x{height}")));213 return Err(Error::Unsupported(format!("H.264 encode {width}x{height}")));
193 }214 }
@@ -434,10 +455,10 @@ fn create_parameters(
434 let aw = align(cfg.width, 16);455 let aw = align(cfg.width, 16);
435 let ah = align(cfg.height, 16);456 let ah = align(cfg.height, 16);
436 let cropped = aw != cfg.width || ah != cfg.height;457 let cropped = aw != cfg.width || ah != cfg.height;
437- let profile_idc = if cfg.profile_high {458+ let profile_idc = match cfg.profile {
438- vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH459+ H264Profile::ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE,
439- } else {460+ H264Profile::Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN,
440- vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN461+ H264Profile::High => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH,
441 };462 };
442 463
443 let mut vui = zeroed::<vk::video::StdVideoH264SequenceParameterSetVui>();464 let mut vui = zeroed::<vk::video::StdVideoH264SequenceParameterSetVui>();
@@ -449,6 +470,15 @@ fn create_parameters(
449 vui.time_scale = cfg.fps.0 * 2;470 vui.time_scale = cfg.fps.0 * 2;
450 vui.max_num_reorder_frames = 0;471 vui.max_num_reorder_frames = 0;
451 vui.max_dec_frame_buffering = 1;472 vui.max_dec_frame_buffering = 1;
473+ if let Some(c) = cfg.colour {
474+ vui.flags.set_video_signal_type_present_flag(1);
475+ vui.flags.set_video_full_range_flag(c.full_range as u32);
476+ vui.flags.set_color_description_present_flag(1);
477+ vui.video_format = 5;
478+ vui.colour_primaries = c.primaries;
479+ vui.transfer_characteristics = c.transfer;
480+ vui.matrix_coefficients = c.matrix;
481+ }
452 482
453 let mut sps = zeroed::<vk::video::StdVideoH264SequenceParameterSet>();483 let mut sps = zeroed::<vk::video::StdVideoH264SequenceParameterSet>();
454 sps.flags.set_direct_8x8_inference_flag(1);484 sps.flags.set_direct_8x8_inference_flag(1);
@@ -456,6 +486,8 @@ fn create_parameters(
456 sps.flags.set_frame_cropping_flag(cropped as u32);486 sps.flags.set_frame_cropping_flag(cropped as u32);
457 sps.flags.set_vui_parameters_present_flag(1);487 sps.flags.set_vui_parameters_present_flag(1);
458 sps.profile_idc = profile_idc;488 sps.profile_idc = profile_idc;
489+ sps.flags
490+ .set_constraint_set1_flag((cfg.profile == H264Profile::ConstrainedBaseline) as u32);
459 sps.level_idc = level;491 sps.level_idc = level;
460 sps.chroma_format_idc = vk::video::STD_VIDEO_H264_CHROMA_FORMAT_IDC_420;492 sps.chroma_format_idc = vk::video::STD_VIDEO_H264_CHROMA_FORMAT_IDC_420;
461 sps.pic_order_cnt_type = vk::video::STD_VIDEO_H264_POC_TYPE_2;493 sps.pic_order_cnt_type = vk::video::STD_VIDEO_H264_POC_TYPE_2;
@@ -468,9 +500,10 @@ fn create_parameters(
468 500
469 let mut pps = zeroed::<vk::video::StdVideoH264PictureParameterSet>();501 let mut pps = zeroed::<vk::video::StdVideoH264PictureParameterSet>();
470 pps.flags502 pps.flags
471- .set_transform_8x8_mode_flag((cfg.profile_high) as u32);503+ .set_transform_8x8_mode_flag((cfg.profile == H264Profile::High) as u32);
472 pps.flags.set_deblocking_filter_control_present_flag(1);504 pps.flags.set_deblocking_filter_control_present_flag(1);
473- pps.flags.set_entropy_coding_mode_flag(1);505+ pps.flags
506+ .set_entropy_coding_mode_flag((cfg.profile != H264Profile::ConstrainedBaseline) as u32);
474 pps.weighted_bipred_idc = vk::video::STD_VIDEO_H264_WEIGHTED_BIPRED_IDC_DEFAULT;507 pps.weighted_bipred_idc = vk::video::STD_VIDEO_H264_WEIGHTED_BIPRED_IDC_DEFAULT;
475 508
476 let add = vk::VideoEncodeH264SessionParametersAddInfoKHR::builder()509 let add = vk::VideoEncodeH264SessionParametersAddInfoKHR::builder()
shims/vk-video-ffi/src/h265_encode.rsmodified+24 -10
@@ -10,10 +10,10 @@ use crate::dmabuf::DmaBuf;
10 use crate::h264_encode::validate;10 use crate::h264_encode::validate;
11 use crate::rgb_convert::{Input, check_rgb};11 use crate::rgb_convert::{Input, check_rgb};
12 use crate::session::{12 use crate::session::{
13- DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession, align,13+ DPB_SLOTS, Encoder, VideoSession, align, component_bit_depth, picture_resource, video_caps, vk,
14- component_bit_depth, picture_resource, video_caps, vk, zeroed,14+ zeroed,
15 };15 };
16-use crate::{Error, Gpu, RateControl};16+use crate::{Colour, Error, Gpu, RateControl};
17 17
18 /// Settings fixed for the life of a session.18 /// Settings fixed for the life of a session.
19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -28,6 +28,8 @@ pub struct H265EncodeConfig {
28 pub rate: RateControl,28 pub rate: RateControl,
29 /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input).29 /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input).
30 pub bit_depth: u8,30 pub bit_depth: u8,
31+ /// Colour description for the VUI, or none.
32+ pub colour: Option<Colour>,
31 }33 }
32 34
33 /// One picture to encode.35 /// One picture to encode.
@@ -115,19 +117,22 @@ struct RateChain {
115 117
116 impl RateChain {118 impl RateChain {
117 fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> {119 fn new(rate: RateControl, fps: (u32, u32)) -> Box<Self> {
118- let (mode, layers, bitrate) = match rate {120+ let (mode, layers, bitrate, buffer_ms) = match rate {
119 RateControl::ConstantQp { .. } => {121 RateControl::ConstantQp { .. } => {
120- (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0)122+ (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0, 0)
121- }
122- RateControl::Cbr { bitrate } => {
123- (vk::VideoEncodeRateControlModeFlagsKHR::CBR, 1, bitrate)
124 }123 }
124+ RateControl::Cbr { bitrate, buffer_ms } => (
125+ vk::VideoEncodeRateControlModeFlagsKHR::CBR,
126+ 1,
127+ bitrate,
128+ buffer_ms,
129+ ),
125 };130 };
126 let mut c = Box::new(RateChain {131 let mut c = Box::new(RateChain {
127 rc: vk::VideoEncodeRateControlInfoKHR::builder()132 rc: vk::VideoEncodeRateControlInfoKHR::builder()
128 .rate_control_mode(mode)133 .rate_control_mode(mode)
129- .virtual_buffer_size_in_ms(VIRTUAL_BUFFER_MS)134+ .virtual_buffer_size_in_ms(buffer_ms)
130- .initial_virtual_buffer_size_in_ms(INITIAL_VIRTUAL_BUFFER_MS)135+ .initial_virtual_buffer_size_in_ms(buffer_ms)
131 .build(),136 .build(),
132 rc_h265: vk::VideoEncodeH265RateControlInfoKHR::builder()137 rc_h265: vk::VideoEncodeH265RateControlInfoKHR::builder()
133 .flags(138 .flags(
@@ -485,6 +490,15 @@ fn create_parameters(
485 vui.flags.set_vui_poc_proportional_to_timing_flag(1);490 vui.flags.set_vui_poc_proportional_to_timing_flag(1);
486 vui.vui_num_units_in_tick = cfg.fps.1;491 vui.vui_num_units_in_tick = cfg.fps.1;
487 vui.vui_time_scale = cfg.fps.0;492 vui.vui_time_scale = cfg.fps.0;
493+ if let Some(c) = cfg.colour {
494+ vui.flags.set_video_signal_type_present_flag(1);
495+ vui.flags.set_video_full_range_flag(c.full_range as u32);
496+ vui.flags.set_colour_description_present_flag(1);
497+ vui.video_format = 5;
498+ vui.colour_primaries = c.primaries;
499+ vui.transfer_characteristics = c.transfer;
500+ vui.matrix_coeffs = c.matrix;
501+ }
488 502
489 let mut vps = zeroed::<vk::video::StdVideoH265VideoParameterSet>();503 let mut vps = zeroed::<vk::video::StdVideoH265VideoParameterSet>();
490 vps.flags.set_vps_temporal_id_nesting_flag(1);504 vps.flags.set_vps_temporal_id_nesting_flag(1);
shims/vk-video-ffi/src/lib.rsmodified+16 -1
@@ -36,7 +36,9 @@ pub use h264_decode::{
36 H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,36 H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,
37 ScalingLists,37 ScalingLists,
38 };38 };
39-pub use h264_encode::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, RateControl};39+pub use h264_encode::{
40+ H264EncodeConfig, H264EncodeSession, H264Picture, H264Profile, H264Ref, RateControl,
41+};
40 pub use h265_decode::{42 pub use h265_decode::{
41 H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps,43 H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps,
42 H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet,44 H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet,
@@ -44,6 +46,19 @@ pub use h265_decode::{
44 };46 };
45 pub use h265_encode::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref};47 pub use h265_encode::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref};
46 48
49+/// Colour description written into the VUI (H.264, H.265) or the colour config (AV1).
50+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51+pub struct Colour {
52+ /// `colour_primaries` (H.273 code points).
53+ pub primaries: u8,
54+ /// `transfer_characteristics`.
55+ pub transfer: u8,
56+ /// `matrix_coefficients`.
57+ pub matrix: u8,
58+ /// `video_full_range_flag` / `color_range`.
59+ pub full_range: bool,
60+}
61+
47 use vk::KhrVideoQueueExtensionInstanceCommands;62 use vk::KhrVideoQueueExtensionInstanceCommands;
48 use vulkanalia::loader::LibloadingLoader;63 use vulkanalia::loader::LibloadingLoader;
49 use vulkanalia::prelude::v1_3::*;64 use vulkanalia::prelude::v1_3::*;
shims/vk-video-ffi/src/session.rsmodified+2 -3
@@ -17,8 +17,6 @@ pub(crate) const P010: vk::Format = vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNOR
17 pub(crate) const DPB_SLOTS: usize = 2;17 pub(crate) const DPB_SLOTS: usize = 2;
18 pub(crate) const PLANE_0: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_0;18 pub(crate) const PLANE_0: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_0;
19 pub(crate) const PLANE_1: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_1;19 pub(crate) const PLANE_1: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_1;
20-pub(crate) const VIRTUAL_BUFFER_MS: u32 = 25;
21-pub(crate) const INITIAL_VIRTUAL_BUFFER_MS: u32 = 12;
22 20
23 pub(crate) type Stage = (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2);21 pub(crate) type Stage = (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2);
24 22
@@ -65,7 +63,8 @@ pub(crate) fn validate_rate(fps: (u32, u32), rate: RateControl) -> Result<(), Er
65 }63 }
66 match rate {64 match rate {
67 RateControl::ConstantQp { qp } if qp > 51 => Err(Error::Invalid("qp above 51".into())),65 RateControl::ConstantQp { qp } if qp > 51 => Err(Error::Invalid("qp above 51".into())),
68- RateControl::Cbr { bitrate: 0 } => Err(Error::Invalid("bitrate is zero".into())),66+ RateControl::Cbr { bitrate: 0, .. } => Err(Error::Invalid("bitrate is zero".into())),
67+ RateControl::Cbr { buffer_ms: 0, .. } => Err(Error::Invalid("buffer is zero".into())),
69 _ => Ok(()),68 _ => Ok(()),
70 }69 }
71 }70 }