forge
Explore
Log in

Don't you dare go Hollow

Vk runtime rate change: set_rate in the shim sessions (rate-control re-sent inside the coding scope, no new IDR), ec-vk set_rate, HwEncoder::tune for Vk and VA; hw_tune example

Browse files at this commit

0c81983d348de729daa62ad92b670450e7bbd0e5Ahmet Kaan GümüşParent: a26af31
crates/ec-hw/examples/hw_tune.rsadded+102 -0
@@ -0,0 +1,102 @@
1+use ec_hw::{
2+ Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, RateControlMode, RgbFrame,
3+ RgbOrder, Tunings,
4+};
5+
6+const W: u32 = 1280;
7+const H: u32 = 720;
8+const FPS: u32 = 30;
9+const SEGMENT: u32 = 90;
10+
11+fn main() {
12+ for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] {
13+ if let Err(e) = run(codec) {
14+ println!("{codec:?}: error: {e}");
15+ }
16+ }
17+}
18+
19+fn run(codec: EncCodec) -> ec_hw::Result<()> {
20+ let config = EncoderConfig {
21+ bitrate: 4_000_000,
22+ rate_control: RateControlMode::ConstantBitrate,
23+ framerate: (FPS, 1),
24+ gop_size: 1000,
25+ ..EncoderConfig::new(codec, W, H)
26+ };
27+ let mut encoder = HwEncoder::open(config, None)?;
28+ let mut coded = Vec::new();
29+ for index in 0..3 * SEGMENT {
30+ if index == SEGMENT {
31+ encoder.tune(Tunings {
32+ bitrate: 1_000_000,
33+ framerate: (FPS, 1),
34+ })?;
35+ }
36+ if index == 2 * SEGMENT {
37+ encoder.tune(Tunings {
38+ bitrate: 3_000_000,
39+ framerate: (FPS, 1),
40+ })?;
41+ }
42+ let pixels = bgra_gradient(index);
43+ let frame = RgbFrame {
44+ data: &pixels,
45+ width: W,
46+ height: H,
47+ stride: W * 4,
48+ order: RgbOrder::Bgra,
49+ };
50+ let meta = FrameMetadata {
51+ timestamp: index as i64,
52+ force_keyframe: index == 0,
53+ };
54+ coded.push(encoder.encode_rgb(&frame, meta)?);
55+ }
56+
57+ let mut line = format!("{codec:?} {:?} kb/s per segment:", encoder.backend());
58+ for chunk in coded.chunks(SEGMENT as usize) {
59+ let bytes: usize = chunk.iter().map(|c| c.data.len()).sum();
60+ let kbps = bytes as f64 * 8.0 * FPS as f64 / SEGMENT as f64 / 1000.0;
61+ line += &format!(" {kbps:.0}");
62+ }
63+ let keyframes = coded.iter().filter(|c| c.is_keyframe).count();
64+ println!("{line}, keyframes {keyframes}");
65+
66+ let mut decoder = HwDecoder::open(decode_codec(codec))?;
67+ let mut decoded = 0;
68+ for c in &coded {
69+ decoder.decode(&c.data, c.timestamp)?;
70+ while decoder.next_frame()?.is_some() {
71+ decoded += 1;
72+ }
73+ }
74+ decoder.flush()?;
75+ while decoder.next_frame()?.is_some() {
76+ decoded += 1;
77+ }
78+ println!(" decoded {decoded} of {}", coded.len());
79+ Ok(())
80+}
81+
82+fn decode_codec(codec: EncCodec) -> Codec {
83+ match codec {
84+ EncCodec::H264 => Codec::H264,
85+ EncCodec::H265 => Codec::H265,
86+ EncCodec::Av1 => Codec::Av1,
87+ }
88+}
89+
90+fn bgra_gradient(index: u32) -> Vec<u8> {
91+ let shift = index as usize * 4;
92+ let mut out = Vec::with_capacity(W as usize * H as usize * 4);
93+ for y in 0..H as usize {
94+ for x in 0..W as usize {
95+ let r = (x + shift) & 0xff;
96+ let g = (y + 2 * shift) & 0xff;
97+ let b = ((x + y) / 2 + 3 * shift) & 0xff;
98+ out.extend_from_slice(&[b as u8, g as u8, r as u8, 0xff]);
99+ }
100+ }
101+ out
102+}
crates/ec-hw/src/hw.rsmodified+39 -2
@@ -2,7 +2,9 @@
22
33 use crate::error::{Error, Result};
44 use crate::picture::I420;
5-use crate::types::{Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode};
5+use crate::types::{
6+ Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings,
7+};
68 use crate::vkdec264::VkH264Decoder;
79 use crate::vkdec265::VkH265Decoder;
810 use crate::vkdec_av1::VkAv1Decoder;
@@ -246,6 +248,18 @@ impl VkEncoder {
246248 }
247249 }
248250
251+ fn set_rate(
252+ &mut self,
253+ rate: ec_vk::RateControl,
254+ fps: (u32, u32),
255+ ) -> std::result::Result<(), ec_vk::Error> {
256+ match self {
257+ VkEncoder::H264(e) => e.set_rate(rate, fps),
258+ VkEncoder::H265(e) => e.set_rate(rate, fps),
259+ VkEncoder::Av1(e) => e.set_rate(rate, fps),
260+ }
261+ }
262+
249263 fn encode_rgb(
250264 &mut self,
251265 frame: &RgbFrame,
@@ -270,6 +284,7 @@ enum EncInner {
270284 /// A hardware encoder on whichever backend opened.
271285 pub struct HwEncoder {
272286 inner: EncInner,
287+ config: EncoderConfig,
273288 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
274289 size: (usize, usize),
275290 }
@@ -286,7 +301,11 @@ impl HwEncoder {
286301 match open_backend(backend, config) {
287302 Ok(inner) => {
288303 let size = (config.width as usize, config.height as usize);
289- return Ok(HwEncoder { inner, size });
304+ return Ok(HwEncoder {
305+ inner,
306+ config,
307+ size,
308+ });
290309 }
291310 Err(e) => reasons.push(format!("{backend:?}: {e}")),
292311 }
@@ -306,6 +325,24 @@ impl HwEncoder {
306325 }
307326 }
308327
328+ /// Change bitrate or frame rate from the next frame; a constant-QP encoder keeps its QP.
329+ pub fn tune(&mut self, tunings: Tunings) -> Result<()> {
330+ match &mut self.inner {
331+ EncInner::Vk(enc) => {
332+ let rate = match self.config.rate_control {
333+ RateControlMode::ConstantQp { .. } => vk_rate(&self.config),
334+ _ => ec_vk::RateControl::Cbr {
335+ bitrate: tunings.bitrate,
336+ },
337+ };
338+ enc.set_rate(rate, tunings.framerate)?;
339+ }
340+ #[cfg(target_os = "linux")]
341+ EncInner::Va(enc) => enc.tune(tunings),
342+ }
343+ Ok(())
344+ }
345+
309346 /// Encode one frame; `meta.force_keyframe` starts a new GOP.
310347 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
311348 match &mut self.inner {
crates/ec-vk/src/av1.rsmodified+5 -0
@@ -82,6 +82,11 @@ impl Av1Encoder {
8282 Ok(self.finish(&pic, frame))
8383 }
8484
85+ /// Changes bitrate or frame rate; takes effect on the next frame.
86+ pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
87+ Ok(self.session.set_rate(rate, fps)?)
88+ }
89+
8590 /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
8691 pub fn encode_rgb(
8792 &mut self,
crates/ec-vk/src/h265.rsmodified+5 -0
@@ -80,6 +80,11 @@ impl H265Encoder {
8080 Ok(self.finish(&pic, slice))
8181 }
8282
83+ /// Changes bitrate or frame rate; takes effect on the next frame.
84+ pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
85+ Ok(self.session.set_rate(rate, fps)?)
86+ }
87+
8388 /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
8489 pub fn encode_rgb(
8590 &mut self,
crates/ec-vk/src/lib.rsmodified+5 -0
@@ -112,6 +112,11 @@ impl H264Encoder {
112112 Ok(self.finish(&pic, slice))
113113 }
114114
115+ /// Changes bitrate or frame rate; takes effect on the next frame.
116+ pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
117+ Ok(self.session.set_rate(rate, fps)?)
118+ }
119+
115120 /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU.
116121 pub fn encode_rgb(
117122 &mut self,
shims/vk-video-ffi/src/av1_encode.rsmodified+36 -19
@@ -6,6 +6,7 @@ use vulkanalia::vk::{
66 KhrVideoQueueExtensionInstanceCommands,
77 };
88
9+use crate::h264_encode::validate_rate;
910 use crate::rgb_convert::{Input, RgbConverter, check_rgb};
1011 use crate::{Error, Gpu, RateControl};
1112
@@ -160,6 +161,8 @@ pub struct Av1EncodeSession {
160161 height: u32,
161162 fps: (u32, u32),
162163 rate: RateControl,
164+ applied: (RateControl, (u32, u32)),
165+ dirty: bool,
163166 sb128: bool,
164167 seq: Vec<u8>,
165168 bitstream_len: u64,
@@ -233,6 +236,8 @@ impl Av1EncodeSession {
233236 height: cfg.height,
234237 fps: cfg.fps,
235238 rate: cfg.rate,
239+ applied: (cfg.rate, cfg.fps),
240+ dirty: false,
236241 sb128,
237242 seq: sequence_header_obu(cfg.width, cfg.height, sb128),
238243 bitstream_len: 0,
@@ -423,11 +428,13 @@ impl Av1EncodeSession {
423428 .push_next(&mut av1_pic)
424429 .build();
425430
431+ let mut applied = RateChain::new(self.applied.0, self.applied.1);
426432 let mut chain = RateChain::new(self.rate, self.fps);
427433 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()
428434 .quality_level(0)
429435 .build();
430436 let reset = !self.coded;
437+ let update = reset || self.dirty;
431438
432439 unsafe {
433440 let begin = vk::CommandBufferBeginInfo::builder()
@@ -439,20 +446,23 @@ impl Av1EncodeSession {
439446 .video_session(self.video_session)
440447 .video_session_parameters(self.params)
441448 .reference_slots(&begin_slots)
442- .push_next(&mut chain.rc)
449+ .push_next(&mut applied.rc)
443450 .build();
444451 d.cmd_begin_video_coding_khr(cb, &begin_info);
445452
446- if reset {
447- let control = vk::VideoCodingControlInfoKHR::builder()
448- .flags(
449- vk::VideoCodingControlFlagsKHR::RESET
450- | vk::VideoCodingControlFlagsKHR::ENCODE_QUALITY_LEVEL
451- | vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL,
452- )
453- .push_next(&mut quality)
454- .push_next(&mut chain.rc)
455- .build();
453+ if update {
454+ let flags = if reset {
455+ vk::VideoCodingControlFlagsKHR::RESET
456+ | vk::VideoCodingControlFlagsKHR::ENCODE_QUALITY_LEVEL
457+ | vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL
458+ } else {
459+ vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL
460+ };
461+ let mut control = vk::VideoCodingControlInfoKHR::builder().flags(flags);
462+ if reset {
463+ control = control.push_next(&mut quality);
464+ }
465+ let control = control.push_next(&mut chain.rc).build();
456466 d.cmd_control_video_coding_khr(cb, &control);
457467 }
458468
@@ -466,6 +476,8 @@ impl Av1EncodeSession {
466476
467477 self.submit(self.queue, cb)?;
468478 self.coded = true;
479+ self.applied = (self.rate, self.fps);
480+ self.dirty = false;
469481 for i in 0..DPB_SLOTS {
470482 if refresh >> i & 1 == 1 {
471483 self.slot_key[i] = pic.key;
@@ -479,6 +491,18 @@ impl Av1EncodeSession {
479491 self.read_bitstream()
480492 }
481493
494+ /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
495+ pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
496+ validate_rate(fps, rate)?;
497+ if std::mem::discriminant(&rate) != std::mem::discriminant(&self.rate) {
498+ return Err(Error::Invalid("rate control mode change".into()));
499+ }
500+ self.rate = rate;
501+ self.fps = fps;
502+ self.dirty = true;
503+ Ok(())
504+ }
505+
482506 fn check(&self, pic: &Av1Picture) -> Result<(), Error> {
483507 if pic.slot as usize >= DPB_SLOTS {
484508 return Err(Error::Invalid("DPB slot".into()));
@@ -1056,14 +1080,7 @@ fn validate(cfg: &Av1EncodeConfig) -> Result<(), Error> {
10561080 "size must be a non-zero multiple of 8".into(),
10571081 ));
10581082 }
1059- if cfg.fps.0 == 0 || cfg.fps.1 == 0 {
1060- return Err(Error::Invalid("frame rate".into()));
1061- }
1062- match cfg.rate {
1063- RateControl::ConstantQp { qp } if qp > 51 => Err(Error::Invalid("qp above 51".into())),
1064- RateControl::Cbr { bitrate: 0 } => Err(Error::Invalid("bitrate is zero".into())),
1065- _ => Ok(()),
1066- }
1083+ validate_rate(cfg.fps, cfg.rate)
10671084 }
10681085
10691086 fn q_index(rate: RateControl) -> u32 {
shims/vk-video-ffi/src/h264_encode.rsmodified+38 -11
@@ -184,6 +184,8 @@ pub struct H264EncodeSession {
184184 height: u32,
185185 fps: (u32, u32),
186186 rate: RateControl,
187+ applied: (RateControl, (u32, u32)),
188+ dirty: bool,
187189 bitstream_len: u64,
188190 video_session: vk::VideoSessionKHR,
189191 params: vk::VideoSessionParametersKHR,
@@ -252,6 +254,8 @@ impl H264EncodeSession {
252254 height,
253255 fps: cfg.fps,
254256 rate: cfg.rate,
257+ applied: (cfg.rate, cfg.fps),
258+ dirty: false,
255259 bitstream_len: 0,
256260 video_session: Default::default(),
257261 params: Default::default(),
@@ -443,11 +447,13 @@ impl H264EncodeSession {
443447 .push_next(&mut h264_pic)
444448 .build();
445449
450+ let mut applied = RateChain::new(self.applied.0, self.applied.1);
446451 let mut chain = RateChain::new(self.rate, self.fps);
447452 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()
448453 .quality_level(0)
449454 .build();
450455 let reset = !self.coded;
456+ let update = reset || self.dirty;
451457
452458 unsafe {
453459 let begin = vk::CommandBufferBeginInfo::builder()
@@ -459,20 +465,23 @@ impl H264EncodeSession {
459465 .video_session(self.video_session)
460466 .video_session_parameters(self.params)
461467 .reference_slots(&begin_slots)
462- .push_next(&mut chain.rc)
468+ .push_next(&mut applied.rc)
463469 .build();
464470 d.cmd_begin_video_coding_khr(cb, &begin_info);
465471
466- if reset {
467- let control = vk::VideoCodingControlInfoKHR::builder()
468- .flags(
469- vk::VideoCodingControlFlagsKHR::RESET
470- | vk::VideoCodingControlFlagsKHR::ENCODE_QUALITY_LEVEL
471- | vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL,
472- )
473- .push_next(&mut quality)
474- .push_next(&mut chain.rc)
475- .build();
472+ if update {
473+ let flags = if reset {
474+ vk::VideoCodingControlFlagsKHR::RESET
475+ | vk::VideoCodingControlFlagsKHR::ENCODE_QUALITY_LEVEL
476+ | vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL
477+ } else {
478+ vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL
479+ };
480+ let mut control = vk::VideoCodingControlInfoKHR::builder().flags(flags);
481+ if reset {
482+ control = control.push_next(&mut quality);
483+ }
484+ let control = control.push_next(&mut chain.rc).build();
476485 d.cmd_control_video_coding_khr(cb, &control);
477486 }
478487
@@ -486,9 +495,23 @@ impl H264EncodeSession {
486495
487496 self.submit(self.queue, cb)?;
488497 self.coded = true;
498+ self.applied = (self.rate, self.fps);
499+ self.dirty = false;
489500 self.read_bitstream()
490501 }
491502
503+ /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
504+ pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
505+ validate_rate(fps, rate)?;
506+ if std::mem::discriminant(&rate) != std::mem::discriminant(&self.rate) {
507+ return Err(Error::Invalid("rate control mode change".into()));
508+ }
509+ self.rate = rate;
510+ self.fps = fps;
511+ self.dirty = true;
512+ Ok(())
513+ }
514+
492515 fn check(&self, pic: &H264Picture) -> Result<(), Error> {
493516 if pic.slot as usize >= DPB_SLOTS {
494517 return Err(Error::Invalid("DPB slot".into()));
@@ -1004,6 +1027,10 @@ pub(crate) fn validate(
10041027 if width == 0 || height == 0 || width % 2 != 0 || height % 2 != 0 {
10051028 return Err(Error::Invalid("size must be even and non-zero".into()));
10061029 }
1030+ validate_rate(fps, rate)
1031+}
1032+
1033+pub(crate) fn validate_rate(fps: (u32, u32), rate: RateControl) -> Result<(), Error> {
10071034 if fps.0 == 0 || fps.1 == 0 {
10081035 return Err(Error::Invalid("frame rate".into()));
10091036 }
shims/vk-video-ffi/src/h265_encode.rsmodified+36 -12
@@ -8,7 +8,8 @@ use vulkanalia::vk::{
88
99 use crate::h264_encode::{
1010 BufferRes, DPB_SLOTS, ImageRes, NV12, PLANE_0, PLANE_1, align, alloc_cb, barrier, color_range,
11- copy_region, create_pool, fill_nv12, memory_type, picture_resource, validate, vk, zeroed,
11+ copy_region, create_pool, fill_nv12, memory_type, picture_resource, validate, validate_rate,
12+ vk, zeroed,
1213 };
1314 use crate::rgb_convert::{Input, RgbConverter, check_rgb};
1415 use crate::{Error, Gpu, RateControl};
@@ -160,6 +161,8 @@ pub struct H265EncodeSession {
160161 height: u32,
161162 fps: (u32, u32),
162163 rate: RateControl,
164+ applied: (RateControl, (u32, u32)),
165+ dirty: bool,
163166 bitstream_len: u64,
164167 video_session: vk::VideoSessionKHR,
165168 params: vk::VideoSessionParametersKHR,
@@ -229,6 +232,8 @@ impl H265EncodeSession {
229232 height: coding.height,
230233 fps: cfg.fps,
231234 rate: cfg.rate,
235+ applied: (cfg.rate, cfg.fps),
236+ dirty: false,
232237 bitstream_len: 0,
233238 video_session: Default::default(),
234239 params: Default::default(),
@@ -425,11 +430,13 @@ impl H265EncodeSession {
425430 .push_next(&mut h265_pic)
426431 .build();
427432
433+ let mut applied = RateChain::new(self.applied.0, self.applied.1);
428434 let mut chain = RateChain::new(self.rate, self.fps);
429435 let mut quality = vk::VideoEncodeQualityLevelInfoKHR::builder()
430436 .quality_level(0)
431437 .build();
432438 let reset = !self.coded;
439+ let update = reset || self.dirty;
433440
434441 unsafe {
435442 let begin = vk::CommandBufferBeginInfo::builder()
@@ -441,20 +448,23 @@ impl H265EncodeSession {
441448 .video_session(self.video_session)
442449 .video_session_parameters(self.params)
443450 .reference_slots(&begin_slots)
444- .push_next(&mut chain.rc)
451+ .push_next(&mut applied.rc)
445452 .build();
446453 d.cmd_begin_video_coding_khr(cb, &begin_info);
447454
448- if reset {
449- let control = vk::VideoCodingControlInfoKHR::builder()
450- .flags(
451- vk::VideoCodingControlFlagsKHR::RESET
452- | vk::VideoCodingControlFlagsKHR::ENCODE_QUALITY_LEVEL
453- | vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL,
454- )
455- .push_next(&mut quality)
456- .push_next(&mut chain.rc)
457- .build();
455+ if update {
456+ let flags = if reset {
457+ vk::VideoCodingControlFlagsKHR::RESET
458+ | vk::VideoCodingControlFlagsKHR::ENCODE_QUALITY_LEVEL
459+ | vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL
460+ } else {
461+ vk::VideoCodingControlFlagsKHR::ENCODE_RATE_CONTROL
462+ };
463+ let mut control = vk::VideoCodingControlInfoKHR::builder().flags(flags);
464+ if reset {
465+ control = control.push_next(&mut quality);
466+ }
467+ let control = control.push_next(&mut chain.rc).build();
458468 d.cmd_control_video_coding_khr(cb, &control);
459469 }
460470
@@ -468,9 +478,23 @@ impl H265EncodeSession {
468478
469479 self.submit(self.queue, cb)?;
470480 self.coded = true;
481+ self.applied = (self.rate, self.fps);
482+ self.dirty = false;
471483 self.read_bitstream()
472484 }
473485
486+ /// Changes bitrate or frame rate; the next encode applies it. The rate control mode cannot change.
487+ pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
488+ validate_rate(fps, rate)?;
489+ if std::mem::discriminant(&rate) != std::mem::discriminant(&self.rate) {
490+ return Err(Error::Invalid("rate control mode change".into()));
491+ }
492+ self.rate = rate;
493+ self.fps = fps;
494+ self.dirty = true;
495+ Ok(())
496+ }
497+
474498 fn check(&self, pic: &H265Picture) -> Result<(), Error> {
475499 if pic.slot as usize >= DPB_SLOTS {
476500 return Err(Error::Invalid("DPB slot".into()));