Merge Vk encode config parity (H.264 profile, colour, gop, forced keyframes) and shared VA/Vk rate control (hrd_buffer_ms, RateFeedback), steered on pipelined submit/flush too
Browse files at this commit17 changed files +481 -165
- crates/ec-hw/examples/hw_config.rs +139 -0
- crates/ec-hw/src/enc/mod.rs +4 -85
- crates/ec-hw/src/hw.rs +58 -10
- crates/ec-hw/src/lib.rs +1 -0
- crates/ec-hw/src/rate.rs +100 -0
- crates/ec-vk/examples/av1_encode.rs +2 -0
- crates/ec-vk/examples/h264_encode.rs +7 -2
- crates/ec-vk/examples/h265_encode.rs +2 -0
- crates/ec-vk/src/av1.rs +4 -1
- crates/ec-vk/src/h265.rs +4 -1
- crates/ec-vk/src/lib.rs +13 -8
- shims/vk-video-ffi/examples/dmabuf_smoke.rs +5 -2
- shims/vk-video-ffi/src/av1_encode.rs +42 -17
- shims/vk-video-ffi/src/h264_encode.rs +58 -25
- shims/vk-video-ffi/src/h265_encode.rs +24 -10
- shims/vk-video-ffi/src/lib.rs +16 -1
- shims/vk-video-ffi/src/session.rs +2 -3
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 u32 | 667 | + 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 a | 722 | // The buffer starts full. Starting at three quarters full cost a |
| 804 | // quarter of a window of budget: radeonsi then spent 12.5% under the | 723 | // 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 the | 724 | // ask on a 2 s clip, and the gap is exactly that quarter over the |
crates/ec-hw/src/hw.rsmodified+58 -10
| @@ -15,8 +15,10 @@ use crate::picture::{Decoded, I420, I420_16, RgbPicture}; | |||
| 15 | use crate::picture::{DmaBufPicture, i420_to_rgb}; | 15 | use crate::picture::{DmaBufPicture, i420_to_rgb}; |
| 16 | #[cfg(target_os = "linux")] | 16 | #[cfg(target_os = "linux")] |
| 17 | use ec_core::color::{ColorDescription, Matrix, Tags}; | 17 | use ec_core::color::{ColorDescription, Matrix, Tags}; |
| 18 | +use crate::rate::{RateFeedback, hrd_buffer_ms}; | ||
| 18 | use crate::types::{ | 19 | use crate::types::{ |
| 19 | - Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings, | 20 | + Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, |
| 21 | + Tunings, | ||
| 20 | }; | 22 | }; |
| 21 | use crate::vkdec_av1::VkAv1Decoder; | 23 | use crate::vkdec_av1::VkAv1Decoder; |
| 22 | use crate::vkdec_vp9::VkVp9Decoder; | 24 | use crate::vkdec_vp9::VkVp9Decoder; |
| @@ -564,6 +566,8 @@ pub struct HwEncoder { | |||
| 564 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | 566 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] |
| 565 | size: (usize, usize), | 567 | size: (usize, usize), |
| 566 | pending: VecDeque<i64>, | 568 | pending: VecDeque<i64>, |
| 569 | + tunings: Tunings, | ||
| 570 | + rc: RateFeedback, | ||
| 567 | } | 571 | } |
| 568 | 572 | ||
| 569 | impl HwEncoder { | 573 | impl HwEncoder { |
| @@ -585,6 +589,11 @@ impl HwEncoder { | |||
| 585 | config, | 589 | config, |
| 586 | size, | 590 | size, |
| 587 | pending: VecDeque::new(), | 591 | pending: VecDeque::new(), |
| 592 | + tunings: Tunings { | ||
| 593 | + bitrate: config.bitrate, | ||
| 594 | + framerate: config.framerate, | ||
| 595 | + }, | ||
| 596 | + rc: RateFeedback::default(), | ||
| 588 | }); | 597 | }); |
| 589 | } | 598 | } |
| 590 | Err(e) => reasons.push(format!("{backend:?}: {e}")), | 599 | Err(e) => reasons.push(format!("{backend:?}: {e}")), |
| @@ -610,12 +619,9 @@ impl HwEncoder { | |||
| 610 | match &mut self.inner { | 619 | match &mut self.inner { |
| 611 | EncInner::Vk(enc) => { | 620 | EncInner::Vk(enc) => { |
| 612 | vk_session_alive(self.born_epoch)?; | 621 | vk_session_alive(self.born_epoch)?; |
| 613 | - let rate = match self.config.rate_control { | 622 | + self.tunings = tunings; |
| 614 | - RateControlMode::ConstantQp { .. } => vk_rate(&self.config), | 623 | + self.rc = RateFeedback::default(); |
| 615 | - _ => ec_vk::RateControl::Cbr { | 624 | + let rate = vk_rate(&self.config, tunings.bitrate); |
| 616 | - bitrate: tunings.bitrate, | ||
| 617 | - }, | ||
| 618 | - }; | ||
| 619 | enc.set_rate(rate, tunings.framerate)?; | 625 | enc.set_rate(rate, tunings.framerate)?; |
| 620 | } | 626 | } |
| 621 | #[cfg(target_os = "linux")] | 627 | #[cfg(target_os = "linux")] |
| @@ -631,6 +637,9 @@ impl HwEncoder { | |||
| 631 | vk_session_alive(self.born_epoch)?; | 637 | vk_session_alive(self.born_epoch)?; |
| 632 | self.pending.push_back(meta.timestamp); | 638 | self.pending.push_back(meta.timestamp); |
| 633 | let out = enc.submit(input, meta.force_keyframe)?; | 639 | let out = enc.submit(input, meta.force_keyframe)?; |
| 640 | + if let Some(coded) = &out { | ||
| 641 | + self.steer(coded.data.len())?; | ||
| 642 | + } | ||
| 634 | Ok(out.map(|coded| stamp(&mut self.pending, coded))) | 643 | Ok(out.map(|coded| stamp(&mut self.pending, coded))) |
| 635 | } | 644 | } |
| 636 | #[cfg(target_os = "linux")] | 645 | #[cfg(target_os = "linux")] |
| @@ -652,6 +661,9 @@ impl HwEncoder { | |||
| 652 | EncInner::Vk(enc) => { | 661 | EncInner::Vk(enc) => { |
| 653 | vk_session_alive(self.born_epoch)?; | 662 | vk_session_alive(self.born_epoch)?; |
| 654 | let frames = enc.flush()?; | 663 | let frames = enc.flush()?; |
| 664 | + for coded in &frames { | ||
| 665 | + self.steer(coded.data.len())?; | ||
| 666 | + } | ||
| 655 | Ok(frames | 667 | Ok(frames |
| 656 | .into_iter() | 668 | .into_iter() |
| 657 | .map(|coded| stamp(&mut self.pending, coded)) | 669 | .map(|coded| stamp(&mut self.pending, coded)) |
| @@ -670,6 +682,19 @@ impl HwEncoder { | |||
| 670 | } | 682 | } |
| 671 | } | 683 | } |
| 672 | 684 | ||
| 685 | + fn steer(&mut self, bytes: usize) -> Result<()> { | ||
| 686 | + if !self.rc.track(bytes, self.config.rate_control, self.tunings) { | ||
| 687 | + return Ok(()); | ||
| 688 | + } | ||
| 689 | + let rate = vk_rate(&self.config, self.rc.steered_bitrate(self.tunings.bitrate)); | ||
| 690 | + match &mut self.inner { | ||
| 691 | + EncInner::Vk(enc) => enc.set_rate(rate, self.tunings.framerate)?, | ||
| 692 | + #[cfg(target_os = "linux")] | ||
| 693 | + EncInner::Va(_) => {} | ||
| 694 | + } | ||
| 695 | + Ok(()) | ||
| 696 | + } | ||
| 697 | + | ||
| 673 | /// Encode one frame; `meta.force_keyframe` starts a new GOP. | 698 | /// Encode one frame; `meta.force_keyframe` starts a new GOP. |
| 674 | pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { | 699 | pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { |
| 675 | self.idle()?; | 700 | self.idle()?; |
| @@ -677,6 +702,7 @@ impl HwEncoder { | |||
| 677 | EncInner::Vk(enc) => { | 702 | EncInner::Vk(enc) => { |
| 678 | vk_session_alive(self.born_epoch)?; | 703 | vk_session_alive(self.born_epoch)?; |
| 679 | let coded = enc.encode(frame, meta.force_keyframe)?; | 704 | let coded = enc.encode(frame, meta.force_keyframe)?; |
| 705 | + self.steer(coded.data.len())?; | ||
| 680 | Ok(CodedFrame { | 706 | Ok(CodedFrame { |
| 681 | data: coded.data, | 707 | data: coded.data, |
| 682 | timestamp: meta.timestamp, | 708 | timestamp: meta.timestamp, |
| @@ -694,6 +720,7 @@ impl HwEncoder { | |||
| 694 | match &mut self.inner { | 720 | match &mut self.inner { |
| 695 | EncInner::Vk(enc) => { | 721 | EncInner::Vk(enc) => { |
| 696 | let coded = enc.encode_16(frame, meta.force_keyframe)?; | 722 | let coded = enc.encode_16(frame, meta.force_keyframe)?; |
| 723 | + self.steer(coded.data.len())?; | ||
| 697 | Ok(CodedFrame { | 724 | Ok(CodedFrame { |
| 698 | data: coded.data, | 725 | data: coded.data, |
| 699 | timestamp: meta.timestamp, | 726 | timestamp: meta.timestamp, |
| @@ -712,6 +739,7 @@ impl HwEncoder { | |||
| 712 | EncInner::Vk(enc) => { | 739 | EncInner::Vk(enc) => { |
| 713 | vk_session_alive(self.born_epoch)?; | 740 | vk_session_alive(self.born_epoch)?; |
| 714 | let coded = enc.encode_rgb(frame, meta.force_keyframe)?; | 741 | let coded = enc.encode_rgb(frame, meta.force_keyframe)?; |
| 742 | + self.steer(coded.data.len())?; | ||
| 715 | Ok(CodedFrame { | 743 | Ok(CodedFrame { |
| 716 | data: coded.data, | 744 | data: coded.data, |
| 717 | timestamp: meta.timestamp, | 745 | timestamp: meta.timestamp, |
| @@ -775,6 +803,7 @@ impl HwEncoder { | |||
| 775 | EncInner::Vk(enc) => { | 803 | EncInner::Vk(enc) => { |
| 776 | vk_session_alive(self.born_epoch)?; | 804 | vk_session_alive(self.born_epoch)?; |
| 777 | let coded = enc.encode_dmabuf(src, meta.force_keyframe)?; | 805 | let coded = enc.encode_dmabuf(src, meta.force_keyframe)?; |
| 806 | + self.steer(coded.data.len())?; | ||
| 778 | Ok(CodedFrame { | 807 | Ok(CodedFrame { |
| 779 | data: coded.data, | 808 | data: coded.data, |
| 780 | timestamp: meta.timestamp, | 809 | timestamp: meta.timestamp, |
| @@ -812,13 +841,19 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> { | |||
| 812 | } | 841 | } |
| 813 | let gpu = vk_gpu() | 842 | let gpu = vk_gpu() |
| 814 | .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; | 843 | .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; |
| 815 | - let rate = vk_rate(&config); | 844 | + let rate = vk_rate(&config, config.bitrate); |
| 816 | let (width, height, fps, gop_size) = ( | 845 | let (width, height, fps, gop_size) = ( |
| 817 | config.width, | 846 | config.width, |
| 818 | config.height, | 847 | config.height, |
| 819 | config.framerate, | 848 | config.framerate, |
| 820 | config.gop_size, | 849 | config.gop_size, |
| 821 | ); | 850 | ); |
| 851 | + let colour = config.colour.map(|c| ec_vk::Colour { | ||
| 852 | + primaries: c.primaries, | ||
| 853 | + transfer: c.transfer, | ||
| 854 | + matrix: c.matrix, | ||
| 855 | + full_range: c.full_range, | ||
| 856 | + }); | ||
| 822 | Ok(match config.codec { | 857 | Ok(match config.codec { |
| 823 | EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new( | 858 | EncCodec::H264 => VkEncoder::H264(ec_vk::H264Encoder::new( |
| 824 | &gpu, | 859 | &gpu, |
| @@ -828,6 +863,8 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> { | |||
| 828 | fps, | 863 | fps, |
| 829 | gop_size, | 864 | gop_size, |
| 830 | rate, | 865 | rate, |
| 866 | + profile: vk_h264_profile(config.h264_profile), | ||
| 867 | + colour, | ||
| 831 | }, | 868 | }, |
| 832 | )?), | 869 | )?), |
| 833 | EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new( | 870 | EncCodec::H265 => VkEncoder::H265(ec_vk::H265Encoder::new( |
| @@ -839,6 +876,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> { | |||
| 839 | gop_size, | 876 | gop_size, |
| 840 | rate, | 877 | rate, |
| 841 | bit_depth: config.bit_depth, | 878 | bit_depth: config.bit_depth, |
| 879 | + colour, | ||
| 842 | }, | 880 | }, |
| 843 | )?), | 881 | )?), |
| 844 | EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( | 882 | EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( |
| @@ -850,12 +888,21 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> { | |||
| 850 | gop_size, | 888 | gop_size, |
| 851 | rate, | 889 | rate, |
| 852 | bit_depth: config.bit_depth, | 890 | bit_depth: config.bit_depth, |
| 891 | + colour, | ||
| 853 | }, | 892 | }, |
| 854 | )?), | 893 | )?), |
| 855 | }) | 894 | }) |
| 856 | } | 895 | } |
| 857 | 896 | ||
| 858 | -fn vk_rate(config: &EncoderConfig) -> ec_vk::RateControl { | 897 | +fn vk_h264_profile(profile: H264Profile) -> ec_vk::H264Profile { |
| 898 | + match profile { | ||
| 899 | + H264Profile::ConstrainedBaseline => ec_vk::H264Profile::ConstrainedBaseline, | ||
| 900 | + H264Profile::Main => ec_vk::H264Profile::Main, | ||
| 901 | + H264Profile::High => ec_vk::H264Profile::High, | ||
| 902 | + } | ||
| 903 | +} | ||
| 904 | + | ||
| 905 | +fn vk_rate(config: &EncoderConfig, bitrate: u32) -> ec_vk::RateControl { | ||
| 859 | match (config.rate_control, config.codec) { | 906 | match (config.rate_control, config.codec) { |
| 860 | (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp { | 907 | (RateControlMode::ConstantQp { qp }, EncCodec::Av1) => ec_vk::RateControl::ConstantQp { |
| 861 | qp: (qp / 5).min(51) as u8, | 908 | qp: (qp / 5).min(51) as u8, |
| @@ -864,7 +911,8 @@ fn vk_rate(config: &EncoderConfig) -> ec_vk::RateControl { | |||
| 864 | qp: qp.min(51) as u8, | 911 | qp: qp.min(51) as u8, |
| 865 | }, | 912 | }, |
| 866 | _ => ec_vk::RateControl::Cbr { | 913 | _ => ec_vk::RateControl::Cbr { |
| 867 | - bitrate: config.bitrate, | 914 | + bitrate, |
| 915 | + buffer_ms: hrd_buffer_ms(config.gop_size), | ||
| 868 | }, | 916 | }, |
| 869 | } | 917 | } |
| 870 | } | 918 | } |
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, Flight, Gpu, RateControl, last_frame}; | 5 | +use crate::{CodedFrame, Colour, Error, Flight, Gpu, RateControl, last_frame}; |
| 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`]. |
| @@ -52,6 +54,7 @@ impl Av1Encoder { | |||
| 52 | fps: cfg.fps, | 54 | fps: cfg.fps, |
| 53 | rate: cfg.rate, | 55 | rate: cfg.rate, |
| 54 | bit_depth: cfg.bit_depth, | 56 | bit_depth: cfg.bit_depth, |
| 57 | + colour: cfg.colour, | ||
| 55 | }, | 58 | }, |
| 56 | )?; | 59 | )?; |
| 57 | let sequence_header = session.sequence_header(); | 60 | 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, Flight, Gpu, RateControl, last_frame}; | 5 | +use crate::{CodedFrame, Colour, Error, Flight, Gpu, RateControl, last_frame}; |
| 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`]. |
| @@ -50,6 +52,7 @@ impl H265Encoder { | |||
| 50 | fps: cfg.fps, | 52 | fps: cfg.fps, |
| 51 | rate: cfg.rate, | 53 | rate: cfg.rate, |
| 52 | bit_depth: cfg.bit_depth, | 54 | bit_depth: cfg.bit_depth, |
| 55 | + colour: cfg.colour, | ||
| 53 | }, | 56 | }, |
| 54 | )?; | 57 | )?; |
| 55 | let parameter_sets = session.parameter_sets()?; | 58 | let parameter_sets = session.parameter_sets()?; |
crates/ec-vk/src/lib.rsmodified+13 -8
| @@ -17,13 +17,13 @@ pub use vk_video_ffi::{ | |||
| 17 | Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, | 17 | Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, |
| 18 | Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, | 18 | Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, |
| 19 | Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation, | 19 | Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation, |
| 20 | - Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, CodecProfile, Direction, | 20 | + Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, CodecProfile, Colour, |
| 21 | - Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, | 21 | + Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, |
| 22 | - H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, | 22 | + H264Profile, H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, |
| 23 | - H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, | 23 | + H265DecodeSession, H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, |
| 24 | - H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, Vp9ColorConfig, | 24 | + H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, |
| 25 | - Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, Vp9InterpolationFilter, | 25 | + Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, |
| 26 | - Vp9LoopFilter, Vp9Segmentation, | 26 | + Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation, |
| 27 | }; | 27 | }; |
| 28 | 28 | ||
| 29 | /// Encoder settings. | 29 | /// Encoder settings. |
| @@ -39,6 +39,10 @@ pub struct H264EncoderConfig { | |||
| 39 | pub gop_size: u32, | 39 | pub gop_size: u32, |
| 40 | /// Rate control. | 40 | /// Rate control. |
| 41 | pub rate: RateControl, | 41 | pub rate: RateControl, |
| 42 | + /// H.264 profile. | ||
| 43 | + pub profile: H264Profile, | ||
| 44 | + /// Colour description for the VUI, or none. | ||
| 45 | + pub colour: Option<Colour>, | ||
| 42 | } | 46 | } |
| 43 | 47 | ||
| 44 | /// One coded frame, Annex-B. Keyframes carry SPS and PPS before the slice. | 48 | /// One coded frame, Annex-B. Keyframes carry SPS and PPS before the slice. |
| @@ -102,7 +106,8 @@ impl H264Encoder { | |||
| 102 | height: cfg.height, | 106 | height: cfg.height, |
| 103 | fps: cfg.fps, | 107 | fps: cfg.fps, |
| 104 | rate: cfg.rate, | 108 | rate: cfg.rate, |
| 105 | - profile_high: true, | 109 | + profile: cfg.profile, |
| 110 | + colour: cfg.colour, | ||
| 106 | }, | 111 | }, |
| 107 | )?; | 112 | )?; |
| 108 | let parameter_sets = session.parameter_sets()?; | 113 | 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, DmaBufFormat, DmaBufPlane, | 4 | Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, DmaBufFormat, DmaBufPlane, |
| 5 | Error, Gpu, H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, | 5 | Error, Gpu, H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, |
| 6 | - H265EncodeSession, H265Picture, H265Ref, RateControl, | 6 | + H265EncodeSession, H265Picture, 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; |
| @@ -87,7 +87,8 @@ impl Encode for H264EncodeSession { | |||
| 87 | height: size.1, | 87 | height: size.1, |
| 88 | fps: FPS, | 88 | fps: FPS, |
| 89 | rate: RATE, | 89 | rate: RATE, |
| 90 | - profile_high: true, | 90 | + profile: H264Profile::High, |
| 91 | + colour: None, | ||
| 91 | }; | 92 | }; |
| 92 | H264EncodeSession::new(gpu, &cfg) | 93 | H264EncodeSession::new(gpu, &cfg) |
| 93 | } | 94 | } |
| @@ -129,6 +130,7 @@ impl Encode for H265EncodeSession { | |||
| 129 | fps: FPS, | 130 | fps: FPS, |
| 130 | rate: RATE, | 131 | rate: RATE, |
| 131 | bit_depth: bits, | 132 | bit_depth: bits, |
| 133 | + colour: None, | ||
| 132 | }; | 134 | }; |
| 133 | H265EncodeSession::new(gpu, &cfg) | 135 | H265EncodeSession::new(gpu, &cfg) |
| 134 | } | 136 | } |
| @@ -172,6 +174,7 @@ impl Encode for Av1EncodeSession { | |||
| 172 | fps: FPS, | 174 | fps: FPS, |
| 173 | rate: RATE, | 175 | rate: RATE, |
| 174 | bit_depth: bits, | 176 | bit_depth: bits, |
| 177 | + colour: None, | ||
| 175 | }; | 178 | }; |
| 176 | Av1EncodeSession::new(gpu, &cfg) | 179 | Av1EncodeSession::new(gpu, &cfg) |
| 177 | } | 180 | } |
shims/vk-video-ffi/src/av1_encode.rsmodified+42 -17
| @@ -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 | }) |
| @@ -492,16 +497,24 @@ fn create_parameters( | |||
| 492 | vs: &VideoSession, | 497 | vs: &VideoSession, |
| 493 | extent: vk::Extent2D, | 498 | extent: vk::Extent2D, |
| 494 | sb128: bool, | 499 | sb128: bool, |
| 495 | - bit_depth: u8, | 500 | + cfg: &Av1EncodeConfig, |
| 496 | ) -> Result<vk::VideoSessionParametersKHR, Error> { | 501 | ) -> Result<vk::VideoSessionParametersKHR, Error> { |
| 497 | let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>(); | 502 | let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>(); |
| 498 | - color.BitDepth = bit_depth; | 503 | + color.BitDepth = cfg.bit_depth; |
| 499 | color.subsampling_x = 1; | 504 | color.subsampling_x = 1; |
| 500 | color.subsampling_y = 1; | 505 | color.subsampling_y = 1; |
| 501 | color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED; | 506 | color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED; |
| 502 | color.transfer_characteristics = vk::video::STD_VIDEO_AV1_TRANSFER_CHARACTERISTICS_UNSPECIFIED; | 507 | color.transfer_characteristics = vk::video::STD_VIDEO_AV1_TRANSFER_CHARACTERISTICS_UNSPECIFIED; |
| 503 | color.matrix_coefficients = vk::video::STD_VIDEO_AV1_MATRIX_COEFFICIENTS_UNSPECIFIED; | 508 | color.matrix_coefficients = vk::video::STD_VIDEO_AV1_MATRIX_COEFFICIENTS_UNSPECIFIED; |
| 504 | color.chroma_sample_position = vk::video::STD_VIDEO_AV1_CHROMA_SAMPLE_POSITION_UNKNOWN; | 509 | color.chroma_sample_position = vk::video::STD_VIDEO_AV1_CHROMA_SAMPLE_POSITION_UNKNOWN; |
| 510 | + if let Some(c) = cfg.colour { | ||
| 511 | + color.flags.set_color_description_present_flag(1); | ||
| 512 | + color.flags.set_color_range(c.full_range as u32); | ||
| 513 | + color.color_primaries = vk::video::StdVideoAV1ColorPrimaries(i32::from(c.primaries)); | ||
| 514 | + color.transfer_characteristics = | ||
| 515 | + vk::video::StdVideoAV1TransferCharacteristics(i32::from(c.transfer)); | ||
| 516 | + color.matrix_coefficients = vk::video::StdVideoAV1MatrixCoefficients(i32::from(c.matrix)); | ||
| 517 | + } | ||
| 505 | 518 | ||
| 506 | let mut seq = zeroed::<vk::video::StdVideoAV1SequenceHeader>(); | 519 | let mut seq = zeroed::<vk::video::StdVideoAV1SequenceHeader>(); |
| 507 | seq.flags.set_enable_order_hint(1); | 520 | seq.flags.set_enable_order_hint(1); |
| @@ -578,7 +591,8 @@ fn obu(kind: u8, payload: &[u8]) -> Vec<u8> { | |||
| 578 | out | 591 | out |
| 579 | } | 592 | } |
| 580 | 593 | ||
| 581 | -fn sequence_header_obu(width: u32, height: u32, sb128: bool, bit_depth: u8) -> Vec<u8> { | 594 | +fn sequence_header_obu(cfg: &Av1EncodeConfig, sb128: bool) -> Vec<u8> { |
| 595 | + let (width, height, bit_depth) = (cfg.width, cfg.height, cfg.bit_depth); | ||
| 582 | let mut b = Bits(Vec::new()); | 596 | let mut b = Bits(Vec::new()); |
| 583 | b.put(0, 3); | 597 | b.put(0, 3); |
| 584 | b.put(0, 1); | 598 | b.put(0, 1); |
| @@ -612,8 +626,19 @@ fn sequence_header_obu(width: u32, height: u32, sb128: bool, bit_depth: u8) -> V | |||
| 612 | b.put(0, 1); | 626 | b.put(0, 1); |
| 613 | b.put((bit_depth == 10) as u32, 1); | 627 | b.put((bit_depth == 10) as u32, 1); |
| 614 | b.put(0, 1); | 628 | b.put(0, 1); |
| 615 | - b.put(0, 1); | 629 | + match cfg.colour { |
| 616 | - b.put(0, 1); | 630 | + Some(c) => { |
| 631 | + b.put(1, 1); | ||
| 632 | + b.put(u32::from(c.primaries), 8); | ||
| 633 | + b.put(u32::from(c.transfer), 8); | ||
| 634 | + b.put(u32::from(c.matrix), 8); | ||
| 635 | + b.put(c.full_range as u32, 1); | ||
| 636 | + } | ||
| 637 | + None => { | ||
| 638 | + b.put(0, 1); | ||
| 639 | + b.put(0, 1); | ||
| 640 | + } | ||
| 641 | + } | ||
| 617 | b.put(0, 2); | 642 | b.put(0, 2); |
| 618 | b.put(0, 1); | 643 | b.put(0, 1); |
| 619 | b.put(0, 1); | 644 | 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_HIGH | 107 | + 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_MAIN | 109 | + 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 | } |
| @@ -472,10 +493,10 @@ fn create_parameters( | |||
| 472 | let aw = align(cfg.width, 16); | 493 | let aw = align(cfg.width, 16); |
| 473 | let ah = align(cfg.height, 16); | 494 | let ah = align(cfg.height, 16); |
| 474 | let cropped = aw != cfg.width || ah != cfg.height; | 495 | let cropped = aw != cfg.width || ah != cfg.height; |
| 475 | - let profile_idc = if cfg.profile_high { | 496 | + let profile_idc = match cfg.profile { |
| 476 | - vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH | 497 | + H264Profile::ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE, |
| 477 | - } else { | 498 | + H264Profile::Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN, |
| 478 | - vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN | 499 | + H264Profile::High => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH, |
| 479 | }; | 500 | }; |
| 480 | 501 | ||
| 481 | let mut vui = zeroed::<vk::video::StdVideoH264SequenceParameterSetVui>(); | 502 | let mut vui = zeroed::<vk::video::StdVideoH264SequenceParameterSetVui>(); |
| @@ -487,6 +508,15 @@ fn create_parameters( | |||
| 487 | vui.time_scale = cfg.fps.0 * 2; | 508 | vui.time_scale = cfg.fps.0 * 2; |
| 488 | vui.max_num_reorder_frames = 0; | 509 | vui.max_num_reorder_frames = 0; |
| 489 | vui.max_dec_frame_buffering = 1; | 510 | vui.max_dec_frame_buffering = 1; |
| 511 | + if let Some(c) = cfg.colour { | ||
| 512 | + vui.flags.set_video_signal_type_present_flag(1); | ||
| 513 | + vui.flags.set_video_full_range_flag(c.full_range as u32); | ||
| 514 | + vui.flags.set_color_description_present_flag(1); | ||
| 515 | + vui.video_format = 5; | ||
| 516 | + vui.colour_primaries = c.primaries; | ||
| 517 | + vui.transfer_characteristics = c.transfer; | ||
| 518 | + vui.matrix_coefficients = c.matrix; | ||
| 519 | + } | ||
| 490 | 520 | ||
| 491 | let mut sps = zeroed::<vk::video::StdVideoH264SequenceParameterSet>(); | 521 | let mut sps = zeroed::<vk::video::StdVideoH264SequenceParameterSet>(); |
| 492 | sps.flags.set_direct_8x8_inference_flag(1); | 522 | sps.flags.set_direct_8x8_inference_flag(1); |
| @@ -494,6 +524,8 @@ fn create_parameters( | |||
| 494 | sps.flags.set_frame_cropping_flag(cropped as u32); | 524 | sps.flags.set_frame_cropping_flag(cropped as u32); |
| 495 | sps.flags.set_vui_parameters_present_flag(1); | 525 | sps.flags.set_vui_parameters_present_flag(1); |
| 496 | sps.profile_idc = profile_idc; | 526 | sps.profile_idc = profile_idc; |
| 527 | + sps.flags | ||
| 528 | + .set_constraint_set1_flag((cfg.profile == H264Profile::ConstrainedBaseline) as u32); | ||
| 497 | sps.level_idc = level; | 529 | sps.level_idc = level; |
| 498 | sps.chroma_format_idc = vk::video::STD_VIDEO_H264_CHROMA_FORMAT_IDC_420; | 530 | sps.chroma_format_idc = vk::video::STD_VIDEO_H264_CHROMA_FORMAT_IDC_420; |
| 499 | sps.pic_order_cnt_type = vk::video::STD_VIDEO_H264_POC_TYPE_2; | 531 | sps.pic_order_cnt_type = vk::video::STD_VIDEO_H264_POC_TYPE_2; |
| @@ -506,9 +538,10 @@ fn create_parameters( | |||
| 506 | 538 | ||
| 507 | let mut pps = zeroed::<vk::video::StdVideoH264PictureParameterSet>(); | 539 | let mut pps = zeroed::<vk::video::StdVideoH264PictureParameterSet>(); |
| 508 | pps.flags | 540 | pps.flags |
| 509 | - .set_transform_8x8_mode_flag((cfg.profile_high) as u32); | 541 | + .set_transform_8x8_mode_flag((cfg.profile == H264Profile::High) as u32); |
| 510 | pps.flags.set_deblocking_filter_control_present_flag(1); | 542 | pps.flags.set_deblocking_filter_control_present_flag(1); |
| 511 | - pps.flags.set_entropy_coding_mode_flag(1); | 543 | + pps.flags |
| 544 | + .set_entropy_coding_mode_flag((cfg.profile != H264Profile::ConstrainedBaseline) as u32); | ||
| 512 | pps.weighted_bipred_idc = vk::video::STD_VIDEO_H264_WEIGHTED_BIPRED_IDC_DEFAULT; | 545 | pps.weighted_bipred_idc = vk::video::STD_VIDEO_H264_WEIGHTED_BIPRED_IDC_DEFAULT; |
| 513 | 546 | ||
| 514 | let add = vk::VideoEncodeH264SessionParametersAddInfoKHR::builder() | 547 | 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( |
| @@ -529,6 +534,15 @@ fn create_parameters( | |||
| 529 | vui.flags.set_vui_poc_proportional_to_timing_flag(1); | 534 | vui.flags.set_vui_poc_proportional_to_timing_flag(1); |
| 530 | vui.vui_num_units_in_tick = cfg.fps.1; | 535 | vui.vui_num_units_in_tick = cfg.fps.1; |
| 531 | vui.vui_time_scale = cfg.fps.0; | 536 | vui.vui_time_scale = cfg.fps.0; |
| 537 | + if let Some(c) = cfg.colour { | ||
| 538 | + vui.flags.set_video_signal_type_present_flag(1); | ||
| 539 | + vui.flags.set_video_full_range_flag(c.full_range as u32); | ||
| 540 | + vui.flags.set_colour_description_present_flag(1); | ||
| 541 | + vui.video_format = 5; | ||
| 542 | + vui.colour_primaries = c.primaries; | ||
| 543 | + vui.transfer_characteristics = c.transfer; | ||
| 544 | + vui.matrix_coeffs = c.matrix; | ||
| 545 | + } | ||
| 532 | 546 | ||
| 533 | let mut vps = zeroed::<vk::video::StdVideoH265VideoParameterSet>(); | 547 | let mut vps = zeroed::<vk::video::StdVideoH265VideoParameterSet>(); |
| 534 | vps.flags.set_vps_temporal_id_nesting_flag(1); | 548 | 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
| @@ -19,8 +19,6 @@ pub(crate) const P010: vk::Format = vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNOR | |||
| 19 | pub(crate) const DPB_SLOTS: usize = 2; | 19 | pub(crate) const DPB_SLOTS: usize = 2; |
| 20 | pub(crate) const PLANE_0: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_0; | 20 | pub(crate) const PLANE_0: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_0; |
| 21 | pub(crate) const PLANE_1: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_1; | 21 | pub(crate) const PLANE_1: vk::ImageAspectFlags = vk::ImageAspectFlags::PLANE_1; |
| 22 | -pub(crate) const VIRTUAL_BUFFER_MS: u32 = 25; | ||
| 23 | -pub(crate) const INITIAL_VIRTUAL_BUFFER_MS: u32 = 12; | ||
| 24 | 22 | ||
| 25 | pub(crate) type Stage = (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2); | 23 | pub(crate) type Stage = (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2); |
| 26 | 24 | ||
| @@ -67,7 +65,8 @@ pub(crate) fn validate_rate(fps: (u32, u32), rate: RateControl) -> Result<(), Er | |||
| 67 | } | 65 | } |
| 68 | match rate { | 66 | match rate { |
| 69 | RateControl::ConstantQp { qp } if qp > 51 => Err(Error::Invalid("qp above 51".into())), | 67 | RateControl::ConstantQp { qp } if qp > 51 => Err(Error::Invalid("qp above 51".into())), |
| 70 | - RateControl::Cbr { bitrate: 0 } => Err(Error::Invalid("bitrate is zero".into())), | 68 | + RateControl::Cbr { bitrate: 0, .. } => Err(Error::Invalid("bitrate is zero".into())), |
| 69 | + RateControl::Cbr { buffer_ms: 0, .. } => Err(Error::Invalid("buffer is zero".into())), | ||
| 71 | _ => Ok(()), | 70 | _ => Ok(()), |
| 72 | } | 71 | } |
| 73 | } | 72 | } |