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
5353 use crate::error::{Error, Result};
5454 use crate::frame::{Frame, I420, I420_16};
5555 use crate::pool::{PooledSurface, SurfacePool};
56+use crate::rate::{RATE_WINDOW_MS, RateFeedback, hrd_buffer_ms};
5657
5758 pub use crate::types::{
5859 CodedFrame, Colour, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, Tunings,
@@ -78,64 +79,9 @@ impl H264Profile {
7879 }
7980 }
8081
81-/// The rate window the request is spread over, in milliseconds (`window_size`).
82-const RATE_WINDOW_MS: u32 = 1000;
83-
8482 /// Pictures the pipelined path keeps in flight before the oldest is read back.
8583 const DEPTH: usize = 3;
8684
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-
13985 impl RateControlMode {
14086 /// The `VAConfigAttribRateControl` value this mode is configured with.
14187 ///
@@ -718,38 +664,11 @@ impl Encoder {
718664 }
719665
720666 fn steered_bitrate(&self) -> u32 {
721- (f64::from(self.tunings.bitrate) * self.rc.scale) as u32
667+ self.rc.steered_bitrate(self.tunings.bitrate)
722668 }
723669
724670 fn track_rate(&mut self, bytes: usize) {
725- if !matches!(
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;
671+ if self.rc.track(bytes, self.config.rate_control, self.tunings) {
753672 self.tunings_dirty = true;
754673 }
755674 }
@@ -799,7 +718,7 @@ impl Encoder {
799718 out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(
800719 EncMiscParameterFrameRate::new(packed, 0),
801720 )));
802- if bits > 0 && !std::mem::take(&mut self.rc.steered) {
721+ if bits > 0 && !self.rc.take_steered() {
803722 // The buffer starts full. Starting at three quarters full cost a
804723 // quarter of a window of budget: radeonsi then spent 12.5% under the
805724 // 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};
1414 use crate::picture::{rgb_size, yuv_to_rgb};
1515 #[cfg(target_os = "linux")]
1616 use ec_core::color::{ColorDescription, Matrix, Tags};
17+use crate::rate::{RateFeedback, hrd_buffer_ms};
1718 use crate::types::{
18- Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings,
19+ Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode,
20+ Tunings,
1921 };
2022 use crate::vkdec_av1::VkAv1Decoder;
2123 use crate::vkdec_vp9::VkVp9Decoder;
@@ -386,6 +388,8 @@ pub struct HwEncoder {
386388 config: EncoderConfig,
387389 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
388390 size: (usize, usize),
391+ tunings: Tunings,
392+ rc: RateFeedback,
389393 }
390394
391395 impl HwEncoder {
@@ -406,6 +410,11 @@ impl HwEncoder {
406410 born_epoch,
407411 config,
408412 size,
413+ tunings: Tunings {
414+ bitrate: config.bitrate,
415+ framerate: config.framerate,
416+ },
417+ rc: RateFeedback::default(),
409418 });
410419 }
411420 Err(e) => reasons.push(format!("{backend:?}: {e}")),
@@ -431,12 +440,9 @@ impl HwEncoder {
431440 match &mut self.inner {
432441 EncInner::Vk(enc) => {
433442 vk_session_alive(self.born_epoch)?;
434- let rate = match self.config.rate_control {
435- RateControlMode::ConstantQp { .. } => vk_rate(&self.config),
436- _ => ec_vk::RateControl::Cbr {
437- bitrate: tunings.bitrate,
438- },
439- };
443+ self.tunings = tunings;
444+ self.rc = RateFeedback::default();
445+ let rate = vk_rate(&self.config, tunings.bitrate);
440446 enc.set_rate(rate, tunings.framerate)?;
441447 }
442448 #[cfg(target_os = "linux")]
@@ -445,12 +451,26 @@ impl HwEncoder {
445451 Ok(())
446452 }
447453
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+
448467 /// Encode one frame; `meta.force_keyframe` starts a new GOP.
449468 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
450469 match &mut self.inner {
451470 EncInner::Vk(enc) => {
452471 vk_session_alive(self.born_epoch)?;
453472 let coded = enc.encode(frame, meta.force_keyframe)?;
473+ self.steer(coded.data.len())?;
454474 Ok(CodedFrame {
455475 data: coded.data,
456476 timestamp: meta.timestamp,
@@ -467,6 +487,7 @@ impl HwEncoder {
467487 match &mut self.inner {
468488 EncInner::Vk(enc) => {
469489 let coded = enc.encode_16(frame, meta.force_keyframe)?;
490+ self.steer(coded.data.len())?;
470491 Ok(CodedFrame {
471492 data: coded.data,
472493 timestamp: meta.timestamp,
@@ -484,6 +505,7 @@ impl HwEncoder {
484505 EncInner::Vk(enc) => {
485506 vk_session_alive(self.born_epoch)?;
486507 let coded = enc.encode_rgb(frame, meta.force_keyframe)?;
508+ self.steer(coded.data.len())?;
487509 Ok(CodedFrame {
488510 data: coded.data,
489511 timestamp: meta.timestamp,
@@ -506,6 +528,7 @@ impl HwEncoder {
506528 EncInner::Vk(enc) => {
507529 vk_session_alive(self.born_epoch)?;
508530 let coded = enc.encode_dmabuf(frame, meta.force_keyframe)?;
531+ self.steer(coded.data.len())?;
509532 Ok(CodedFrame {
510533 data: coded.data,
511534 timestamp: meta.timestamp,
@@ -543,13 +566,19 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
543566 }
544567 let gpu = vk_gpu()
545568 .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);
547570 let (width, height, fps, gop_size) = (
548571 config.width,
549572 config.height,
550573 config.framerate,
551574 config.gop_size,
552575 );
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+ });
553582 Ok(match config.codec {
554583 EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new(
555584 &gpu,
@@ -559,6 +588,8 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
559588 fps,
560589 gop_size,
561590 rate,
591+ profile: vk_h264_profile(config.h264_profile),
592+ colour,
562593 },
563594 )?),
564595 EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new(
@@ -570,6 +601,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
570601 gop_size,
571602 rate,
572603 bit_depth: config.bit_depth,
604+ colour,
573605 },
574606 )?),
575607 EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new(
@@ -581,12 +613,21 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
581613 gop_size,
582614 rate,
583615 bit_depth: config.bit_depth,
616+ colour,
584617 },
585618 )?),
586619 })
587620 }
588621
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 {
590631 match (config.rate_control, config.codec) {
591632 (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp {
592633 qp: (qp / 5).min(51) as u8,
@@ -595,7 +636,8 @@ fn vk_rate(config: &EncoderConfig) -> ec_vk::RateControl {
595636 qp: qp.min(51) as u8,
596637 },
597638 _ => ec_vk::RateControl::Cbr {
598- bitrate: config.bitrate,
639+ bitrate,
640+ buffer_ms: hrd_buffer_ms(config.gop_size),
599641 },
600642 }
601643 }
crates/ec-hw/src/lib.rsmodified+1 -0
@@ -63,6 +63,7 @@ pub mod error;
6363 pub(crate) mod dpb264;
6464 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
6565 pub(crate) mod h264_common;
66+pub(crate) mod rate;
6667 pub(crate) mod ref_slots;
6768 pub(crate) mod vkdec_vp9;
6869 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() {
3131 rate: match std::env::args().nth(2) {
3232 Some(b) => RateControl::Cbr {
3333 bitrate: b.parse().expect("bitrate"),
34+ buffer_ms: 1000,
3435 },
3536 None => RateControl::ConstantQp { qp: 26 },
3637 },
3738 bit_depth: 8,
39+ colour: None,
3840 };
3941 let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder");
4042
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};
22
33 const W: u32 = 1280;
44 const H: u32 = 720;
@@ -27,8 +27,13 @@ fn main() {
2727 height: H,
2828 fps: (30, 1),
2929 gop_size: 30,
30+ profile: H264Profile::High,
31+ colour: None,
3032 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+ },
3237 None => RateControl::ConstantQp { qp: 26 },
3338 },
3439 };
crates/ec-vk/examples/h265_encode.rsmodified+2 -0
@@ -30,10 +30,12 @@ fn main() {
3030 rate: match std::env::args().nth(2) {
3131 Some(b) => RateControl::Cbr {
3232 bitrate: b.parse().expect("bitrate"),
33+ buffer_ms: 1000,
3334 },
3435 None => RateControl::ConstantQp { qp: 26 },
3536 },
3637 bit_depth: 8,
38+ colour: None,
3739 };
3840 let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder");
3941 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};
22
33 #[cfg(target_os = "linux")]
44 use crate::DmaBuf;
5-use crate::{CodedFrame, Error, Gpu, RateControl};
5+use crate::{CodedFrame, Colour, Error, Gpu, RateControl};
66
77 const TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00];
88
@@ -21,6 +21,8 @@ pub struct Av1EncoderConfig {
2121 pub rate: RateControl,
2222 /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
2323 pub bit_depth: u8,
24+ /// Colour config of the sequence header, or none.
25+ pub colour: Option<Colour>,
2426 }
2527
2628 /// AV1 encoder: order hint, DPB slot and LAST reference bookkeeping over [`Av1EncodeSession`].
@@ -51,6 +53,7 @@ impl Av1Encoder {
5153 fps: cfg.fps,
5254 rate: cfg.rate,
5355 bit_depth: cfg.bit_depth,
56+ colour: cfg.colour,
5457 },
5558 )?;
5659 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};
22
33 #[cfg(target_os = "linux")]
44 use crate::DmaBuf;
5-use crate::{CodedFrame, Error, Gpu, RateControl};
5+use crate::{CodedFrame, Colour, Error, Gpu, RateControl};
66
77 /// H.265 encoder settings.
88 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -19,6 +19,8 @@ pub struct H265EncoderConfig {
1919 pub rate: RateControl,
2020 /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
2121 pub bit_depth: u8,
22+ /// Colour description for the VUI, or none.
23+ pub colour: Option<Colour>,
2224 }
2325
2426 /// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`].
@@ -49,6 +51,7 @@ impl H265Encoder {
4951 fps: cfg.fps,
5052 rate: cfg.rate,
5153 bit_depth: cfg.bit_depth,
54+ colour: cfg.colour,
5255 },
5356 )?;
5457 let parameter_sets = session.parameter_sets()?;
crates/ec-vk/src/lib.rsmodified+13 -8
@@ -15,13 +15,13 @@ pub use vk_video_ffi::{
1515 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
1616 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
1717 Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,
18- Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Direction,
19- Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot,
20- H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,
21- H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists,
22- H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, Vp9ColorConfig,
23- Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, Vp9InterpolationFilter,
24- Vp9LoopFilter, Vp9Segmentation,
18+ Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Colour,
19+ Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps,
20+ H264Profile, H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture,
21+ H265DecodeSession, H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot,
22+ H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists,
23+ Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,
24+ Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,
2525 };
2626
2727 /// Encoder settings.
@@ -37,6 +37,10 @@ pub struct H264EncoderConfig {
3737 pub gop_size: u32,
3838 /// Rate control.
3939 pub rate: RateControl,
40+ /// H.264 profile.
41+ pub profile: H264Profile,
42+ /// Colour description for the VUI, or none.
43+ pub colour: Option<Colour>,
4044 }
4145
4246 /// One coded frame, Annex-B. Keyframes carry SPS and PPS before the slice.
@@ -76,7 +80,8 @@ impl H264Encoder {
7680 height: cfg.height,
7781 fps: cfg.fps,
7882 rate: cfg.rate,
79- profile_high: true,
83+ profile: cfg.profile,
84+ colour: cfg.colour,
8085 },
8186 )?;
8287 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};
33 use vk_video_ffi::{
44 Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, Error, Gpu, H264EncodeConfig,
55 H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, H265EncodeSession, H265Picture,
6- H265Ref, RateControl,
6+ H265Ref, H264Profile, RateControl,
77 };
88 use vulkanalia::prelude::v1_3::*;
99 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;
@@ -37,7 +37,8 @@ impl Encode for H264EncodeSession {
3737 height: size.1,
3838 fps: FPS,
3939 rate: RATE,
40- profile_high: true,
40+ profile: H264Profile::High,
41+ colour: None,
4142 };
4243 H264EncodeSession::new(gpu, &cfg)
4344 }
@@ -83,6 +84,7 @@ impl Encode for H265EncodeSession {
8384 fps: FPS,
8485 rate: RATE,
8586 bit_depth: 8,
87+ colour: None,
8688 };
8789 H265EncodeSession::new(gpu, &cfg)
8890 }
@@ -117,6 +119,7 @@ impl Encode for Av1EncodeSession {
117119 fps: FPS,
118120 rate: RATE,
119121 bit_depth: 8,
122+ colour: None,
120123 };
121124 Av1EncodeSession::new(gpu, &cfg)
122125 }
shims/vk-video-ffi/src/av1_encode.rsmodified+42 -17
@@ -7,10 +7,10 @@ use vulkanalia::vk::KhrVideoQueueExtensionDeviceCommands;
77 use crate::dmabuf::DmaBuf;
88 use crate::rgb_convert::{Input, check_rgb};
99 use crate::session::{
10- DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession,
11- component_bit_depth, picture_resource, validate_rate, video_caps, vk, zeroed,
10+ DPB_SLOTS, Encoder, VideoSession, component_bit_depth, picture_resource, validate_rate,
11+ video_caps, vk, zeroed,
1212 };
13-use crate::{Error, Gpu, RateControl};
13+use crate::{Colour, Error, Gpu, RateControl};
1414
1515 const AV1_SLOTS: usize = 8;
1616 const LEVEL: vk::video::StdVideoAV1Level = vk::video::STD_VIDEO_AV1_LEVEL_5_1;
@@ -29,6 +29,8 @@ pub struct Av1EncodeConfig {
2929 pub rate: RateControl,
3030 /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input).
3131 pub bit_depth: u8,
32+ /// Colour config of the sequence header, or none (unspecified).
33+ pub colour: Option<Colour>,
3234 }
3335
3436 /// One picture to encode.
@@ -102,19 +104,22 @@ struct RateChain {
102104
103105 impl RateChain {
104106 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 {
106108 RateControl::ConstantQp { .. } => {
107- (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0)
108- }
109- RateControl::Cbr { bitrate } => {
110- (vk::VideoEncodeRateControlModeFlagsKHR::CBR, 1, bitrate)
109+ (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0, 0)
111110 }
111+ RateControl::Cbr { bitrate, buffer_ms } => (
112+ vk::VideoEncodeRateControlModeFlagsKHR::CBR,
113+ 1,
114+ bitrate,
115+ buffer_ms,
116+ ),
112117 };
113118 let mut c = Box::new(RateChain {
114119 rc: vk::VideoEncodeRateControlInfoKHR::builder()
115120 .rate_control_mode(mode)
116- .virtual_buffer_size_in_ms(VIRTUAL_BUFFER_MS)
117- .initial_virtual_buffer_size_in_ms(INITIAL_VIRTUAL_BUFFER_MS)
121+ .virtual_buffer_size_in_ms(buffer_ms)
122+ .initial_virtual_buffer_size_in_ms(buffer_ms)
118123 .build(),
119124 rc_av1: vk::VideoEncodeAV1RateControlInfoKHR::builder()
120125 .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 {
209214 (cfg.rate, cfg.fps),
210215 caps.size_align,
211216 )?;
212- let params = create_parameters(&enc.vs, extent, sb128, cfg.bit_depth)?;
217+ let params = create_parameters(&enc.vs, extent, sb128, cfg)?;
213218 enc.vs.set_params(params);
214219 Ok(Av1EncodeSession {
215220 enc,
216- seq: sequence_header_obu(cfg.width, cfg.height, sb128, cfg.bit_depth),
221+ seq: sequence_header_obu(cfg, sb128),
217222 slot_key: [false; DPB_SLOTS],
218223 ref_order_hint: [0; AV1_SLOTS],
219224 })
@@ -448,16 +453,24 @@ fn create_parameters(
448453 vs: &VideoSession,
449454 extent: vk::Extent2D,
450455 sb128: bool,
451- bit_depth: u8,
456+ cfg: &Av1EncodeConfig,
452457 ) -> Result<vk::VideoSessionParametersKHR, Error> {
453458 let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>();
454- color.BitDepth = bit_depth;
459+ color.BitDepth = cfg.bit_depth;
455460 color.subsampling_x = 1;
456461 color.subsampling_y = 1;
457462 color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED;
458463 color.transfer_characteristics = vk::video::STD_VIDEO_AV1_TRANSFER_CHARACTERISTICS_UNSPECIFIED;
459464 color.matrix_coefficients = vk::video::STD_VIDEO_AV1_MATRIX_COEFFICIENTS_UNSPECIFIED;
460465 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+ }
461474
462475 let mut seq = zeroed::<vk::video::StdVideoAV1SequenceHeader>();
463476 seq.flags.set_enable_order_hint(1);
@@ -534,7 +547,8 @@ fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {
534547 out
535548 }
536549
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);
538552 let mut b = Bits(Vec::new());
539553 b.put(0, 3);
540554 b.put(0, 1);
@@ -568,8 +582,19 @@ fn sequence_header_obu(width: u32, height: u32, sb128: bool, bit_depth: u8) -> V
568582 b.put(0, 1);
569583 b.put((bit_depth == 10) as u32, 1);
570584 b.put(0, 1);
571- b.put(0, 1);
572- 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 => {
594+ b.put(0, 1);
595+ b.put(0, 1);
596+ }
597+ }
573598 b.put(0, 2);
574599 b.put(0, 1);
575600 b.put(0, 1);
shims/vk-video-ffi/src/h264_encode.rsmodified+58 -25
@@ -9,10 +9,10 @@ use vulkanalia::vk::{
99 use crate::dmabuf::DmaBuf;
1010 use crate::rgb_convert::{Input, check_rgb};
1111 use crate::session::{
12- DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession, align,
13- picture_resource, validate_rate, video_caps, vk, zeroed,
12+ DPB_SLOTS, Encoder, VideoSession, align, picture_resource, validate_rate, video_caps, vk,
13+ zeroed,
1414 };
15-use crate::{Error, Gpu};
15+use crate::{Colour, Error, Gpu};
1616
1717 /// Rate control of an encode session.
1818 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -26,9 +26,22 @@ pub enum RateControl {
2626 Cbr {
2727 /// Target bitrate in bit/s.
2828 bitrate: u32,
29+ /// HRD virtual buffer in milliseconds of `bitrate`, also the initial fullness.
30+ buffer_ms: u32,
2931 },
3032 }
3133
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+
3245 /// Settings fixed for the life of a session.
3346 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
3447 pub struct H264EncodeConfig {
@@ -40,8 +53,10 @@ pub struct H264EncodeConfig {
4053 pub fps: (u32, u32),
4154 /// Rate control.
4255 pub rate: RateControl,
43- /// High profile when true, Main otherwise.
44- pub profile_high: bool,
56+ /// H.264 profile.
57+ pub profile: H264Profile,
58+ /// Colour description for the VUI, or none.
59+ pub colour: Option<Colour>,
4560 }
4661
4762 /// One picture to encode.
@@ -87,11 +102,11 @@ struct Profile {
87102 }
88103
89104 impl Profile {
90- fn new(high: bool) -> Box<Self> {
91- let idc = if high {
92- vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH
93- } else {
94- vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN
105+ fn new(profile: H264Profile) -> Box<Self> {
106+ let idc = match profile {
107+ H264Profile::ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE,
108+ H264Profile::Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN,
109+ H264Profile::High => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH,
95110 };
96111 let mut p = Box::new(Profile {
97112 info: vk::VideoProfileInfoKHR::builder()
@@ -124,19 +139,22 @@ struct RateChain {
124139
125140 impl RateChain {
126141 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 {
128143 RateControl::ConstantQp { .. } => {
129- (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0)
130- }
131- RateControl::Cbr { bitrate } => {
132- (vk::VideoEncodeRateControlModeFlagsKHR::CBR, 1, bitrate)
144+ (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0, 0)
133145 }
146+ RateControl::Cbr { bitrate, buffer_ms } => (
147+ vk::VideoEncodeRateControlModeFlagsKHR::CBR,
148+ 1,
149+ bitrate,
150+ buffer_ms,
151+ ),
134152 };
135153 let mut c = Box::new(RateChain {
136154 rc: vk::VideoEncodeRateControlInfoKHR::builder()
137155 .rate_control_mode(mode)
138- .virtual_buffer_size_in_ms(VIRTUAL_BUFFER_MS)
139- .initial_virtual_buffer_size_in_ms(INITIAL_VIRTUAL_BUFFER_MS)
156+ .virtual_buffer_size_in_ms(buffer_ms)
157+ .initial_virtual_buffer_size_in_ms(buffer_ms)
140158 .build(),
141159 rc_h264: vk::VideoEncodeH264RateControlInfoKHR::builder()
142160 .flags(
@@ -186,8 +204,11 @@ impl H264EncodeSession {
186204 let width = align(cfg.width, 16);
187205 let height = align(cfg.height, 16);
188206 let level = level_for(width, height, cfg.fps)?;
189- let profile = Profile::new(cfg.profile_high);
190- let caps = query_caps(gpu, &profile.info)?;
207+ let profile = Profile::new(cfg.profile);
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+ })?;
191212 if width > caps.max_extent.width || height > caps.max_extent.height {
192213 return Err(Error::Unsupported(format!("H.264 encode {width}x{height}")));
193214 }
@@ -434,10 +455,10 @@ fn create_parameters(
434455 let aw = align(cfg.width, 16);
435456 let ah = align(cfg.height, 16);
436457 let cropped = aw != cfg.width || ah != cfg.height;
437- let profile_idc = if cfg.profile_high {
438- vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH
439- } else {
440- vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN
458+ let profile_idc = match cfg.profile {
459+ H264Profile::ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE,
460+ H264Profile::Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN,
461+ H264Profile::High => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH,
441462 };
442463
443464 let mut vui = zeroed::<vk::video::StdVideoH264SequenceParameterSetVui>();
@@ -449,6 +470,15 @@ fn create_parameters(
449470 vui.time_scale = cfg.fps.0 * 2;
450471 vui.max_num_reorder_frames = 0;
451472 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+ }
452482
453483 let mut sps = zeroed::<vk::video::StdVideoH264SequenceParameterSet>();
454484 sps.flags.set_direct_8x8_inference_flag(1);
@@ -456,6 +486,8 @@ fn create_parameters(
456486 sps.flags.set_frame_cropping_flag(cropped as u32);
457487 sps.flags.set_vui_parameters_present_flag(1);
458488 sps.profile_idc = profile_idc;
489+ sps.flags
490+ .set_constraint_set1_flag((cfg.profile == H264Profile::ConstrainedBaseline) as u32);
459491 sps.level_idc = level;
460492 sps.chroma_format_idc = vk::video::STD_VIDEO_H264_CHROMA_FORMAT_IDC_420;
461493 sps.pic_order_cnt_type = vk::video::STD_VIDEO_H264_POC_TYPE_2;
@@ -468,9 +500,10 @@ fn create_parameters(
468500
469501 let mut pps = zeroed::<vk::video::StdVideoH264PictureParameterSet>();
470502 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);
472504 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);
474507 pps.weighted_bipred_idc = vk::video::STD_VIDEO_H264_WEIGHTED_BIPRED_IDC_DEFAULT;
475508
476509 let add = vk::VideoEncodeH264SessionParametersAddInfoKHR::builder()
shims/vk-video-ffi/src/h265_encode.rsmodified+24 -10
@@ -10,10 +10,10 @@ use crate::dmabuf::DmaBuf;
1010 use crate::h264_encode::validate;
1111 use crate::rgb_convert::{Input, check_rgb};
1212 use crate::session::{
13- DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession, align,
14- component_bit_depth, picture_resource, video_caps, vk, zeroed,
13+ DPB_SLOTS, Encoder, VideoSession, align, component_bit_depth, picture_resource, video_caps, vk,
14+ zeroed,
1515 };
16-use crate::{Error, Gpu, RateControl};
16+use crate::{Colour, Error, Gpu, RateControl};
1717
1818 /// Settings fixed for the life of a session.
1919 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -28,6 +28,8 @@ pub struct H265EncodeConfig {
2828 pub rate: RateControl,
2929 /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input).
3030 pub bit_depth: u8,
31+ /// Colour description for the VUI, or none.
32+ pub colour: Option<Colour>,
3133 }
3234
3335 /// One picture to encode.
@@ -115,19 +117,22 @@ struct RateChain {
115117
116118 impl RateChain {
117119 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 {
119121 RateControl::ConstantQp { .. } => {
120- (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0)
121- }
122- RateControl::Cbr { bitrate } => {
123- (vk::VideoEncodeRateControlModeFlagsKHR::CBR, 1, bitrate)
122+ (vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, 0, 0, 0)
124123 }
124+ RateControl::Cbr { bitrate, buffer_ms } => (
125+ vk::VideoEncodeRateControlModeFlagsKHR::CBR,
126+ 1,
127+ bitrate,
128+ buffer_ms,
129+ ),
125130 };
126131 let mut c = Box::new(RateChain {
127132 rc: vk::VideoEncodeRateControlInfoKHR::builder()
128133 .rate_control_mode(mode)
129- .virtual_buffer_size_in_ms(VIRTUAL_BUFFER_MS)
130- .initial_virtual_buffer_size_in_ms(INITIAL_VIRTUAL_BUFFER_MS)
134+ .virtual_buffer_size_in_ms(buffer_ms)
135+ .initial_virtual_buffer_size_in_ms(buffer_ms)
131136 .build(),
132137 rc_h265: vk::VideoEncodeH265RateControlInfoKHR::builder()
133138 .flags(
@@ -485,6 +490,15 @@ fn create_parameters(
485490 vui.flags.set_vui_poc_proportional_to_timing_flag(1);
486491 vui.vui_num_units_in_tick = cfg.fps.1;
487492 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+ }
488502
489503 let mut vps = zeroed::<vk::video::StdVideoH265VideoParameterSet>();
490504 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::{
3636 H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,
3737 ScalingLists,
3838 };
39-pub use h264_encode::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, RateControl};
39+pub use h264_encode::{
40+ H264EncodeConfig, H264EncodeSession, H264Picture, H264Profile, H264Ref, RateControl,
41+};
4042 pub use h265_decode::{
4143 H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps,
4244 H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet,
@@ -44,6 +46,19 @@ pub use h265_decode::{
4446 };
4547 pub use h265_encode::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref};
4648
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+
4762 use vk::KhrVideoQueueExtensionInstanceCommands;
4863 use vulkanalia::loader::LibloadingLoader;
4964 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
1717 pub(crate) const DPB_SLOTS: usize = 2;
1818 pub(crate) const PLANE_0: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_0;
1919 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;
2220
2321 pub(crate) type Stage = (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2);
2422
@@ -65,7 +63,8 @@ pub(crate) fn validate_rate(fps: (u32, u32), rate: RateControl) -> Result<(), Er
6563 }
6664 match rate {
6765 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())),
6968 _ => Ok(()),
7069 }
7170 }