forge
Explore
Log in

Don't you dare go Hollow

ec-hw: one level selection per codec for VA and Vulkan; AV1 and HEVC VPS timing_info; VA H.264 High 8x8 transform

Browse files at this commit

ab12e5bd87d8225746a533d5b2a04773a79a137aAhmet Kaan GümüşParent: 42021c7
Level comes from crates/ec-hw/src/level.rs (smallest level fitting size, rate, DPB and bitrate; CQP ignores bitrate). The Vulkan shim takes the level and clamps it to the driver's maxLevel.
AV1 sequence header carries timing_info (VA packed header, Vulkan OBU and std struct).
HEVC VPS carries vps_timing_info when the SPS VUI does.
VA H.264 High sets transform_8x8_mode_flag in the PPS and picture parameters.
crates/ec-h265-syntax/src/ps.rsmodified+23 -1
@@ -186,6 +186,8 @@ pub struct Vps {
186186 pub max_dec_pic_buffering_minus1: u32,
187187 /// `vps_max_num_reorder_pics[0]`; 0 for an intra-only stream.
188188 pub max_num_reorder_pics: u32,
189+ /// `(vps_num_units_in_tick, vps_time_scale)` when `vps_timing_info_present_flag` is set.
190+ pub timing: Option<(u32, u32)>,
189191 }
190192
191193 impl Vps {
@@ -206,7 +208,16 @@ impl Vps {
206208 w.write_ue(0); // vps_max_latency_increase_plus1
207209 w.write_bits(0, 6); // vps_max_layer_id
208210 w.write_ue(0); // vps_num_layer_sets_minus1
209- w.write_bit(false); // vps_timing_info_present_flag
211+ match self.timing {
212+ Some((num_units_in_tick, time_scale)) => {
213+ w.write_bit(true); // vps_timing_info_present_flag
214+ w.write_bits(num_units_in_tick, 32);
215+ w.write_bits(time_scale, 32);
216+ w.write_bit(false); // vps_poc_proportional_to_timing_flag
217+ w.write_ue(0); // vps_num_hrd_parameters
218+ }
219+ None => w.write_bit(false), // vps_timing_info_present_flag
220+ }
210221 w.write_bit(false); // vps_extension_flag
211222 rbsp_trailing_bits(&mut w);
212223 w.into_bytes()
@@ -250,11 +261,19 @@ impl Vps {
250261 max_num_reorder_pics = r.read_ue()?;
251262 r.read_ue()?;
252263 }
264+ r.read_bits(6)?; // vps_max_layer_id
265+ let layer_sets_minus1 = r.read_ue()?;
266+ let timing = if layer_sets_minus1 == 0 && r.read_bit()? {
267+ Some((r.read_bits(32)?, r.read_bits(32)?))
268+ } else {
269+ None
270+ };
253271 Ok(Vps {
254272 id,
255273 ptl,
256274 max_dec_pic_buffering_minus1,
257275 max_num_reorder_pics,
276+ timing,
258277 })
259278 }
260279 }
@@ -1491,6 +1510,7 @@ mod tests {
14911510 ptl: ProfileTierLevel::main(120),
14921511 max_dec_pic_buffering_minus1: 0,
14931512 max_num_reorder_pics: 0,
1513+ timing: None,
14941514 };
14951515 assert_eq!(Vps::parse(&vps.to_rbsp()).unwrap(), vps);
14961516
@@ -1572,6 +1592,7 @@ mod tests {
15721592 ptl: ProfileTierLevel::main(120),
15731593 max_dec_pic_buffering_minus1: 0,
15741594 max_num_reorder_pics: 0,
1595+ timing: None,
15751596 }
15761597 .to_rbsp();
15771598 vps[1] |= 0x0e;
@@ -1678,6 +1699,7 @@ mod tests {
16781699 ptl: ProfileTierLevel::main(120),
16791700 max_dec_pic_buffering_minus1: 16,
16801701 max_num_reorder_pics: 0,
1702+ timing: None,
16811703 };
16821704 refused_naming(Vps::parse(&vps.to_rbsp()), "vps_max_dec_pic_buffering_minus1");
16831705 }
crates/ec-h265-syntax/tests/fuzz.rsmodified+1 -0
@@ -109,6 +109,7 @@ fn ten_thousand_malformed_inputs_never_panic() {
109109 ptl: ProfileTierLevel::main(120),
110110 max_dec_pic_buffering_minus1: 1,
111111 max_num_reorder_pics: 0,
112+ timing: None,
112113 }
113114 .to_rbsp(),
114115 ];
crates/ec-h265/src/encoder.rsmodified+1 -0
@@ -486,6 +486,7 @@ impl Encoder {
486486 ptl,
487487 max_dec_pic_buffering_minus1: dpb_minus1,
488488 max_num_reorder_pics: 0,
489+ timing: None,
489490 };
490491 let log2_ctb = cfg.ctb_size.trailing_zeros();
491492 let sps = Sps {
crates/ec-hw/src/enc/av1.rsmodified+2 -44
@@ -52,7 +52,7 @@ pub(super) fn parameters(
5252 let (width, height) = (config.width.max(1), config.height.max(1));
5353 let cqp = config.rate_control.is_cqp();
5454 let ten_bit = config.bit_depth == 10;
55- let level_idx = seq_level_idx(coded_w, coded_h, config.framerate);
55+ let level_idx = crate::level::av1(&config);
5656
5757 // enable_order_hint, the bit depth and 4:2:0 subsampling; everything else off.
5858 let seq_fields = AV1EncSeqFields::new(
@@ -260,6 +260,7 @@ pub(super) fn parameters(
260260 height,
261261 seq_level_idx: level_idx,
262262 seq_tier: 0,
263+ framerate: config.framerate,
263264 high_bitdepth: ten_bit,
264265 colour: config.colour,
265266 }),
@@ -274,46 +275,3 @@ pub(super) fn parameters(
274275 )));
275276 Ok(())
276277 }
277-
278-/// The lowest AV1 level whose picture size and rate fit (Annex A), as a
279-/// `seq_level_idx`. Levels below 2.0 do not exist, and anything past 6.3 is
280-/// signalled as the maximum-parameters level.
281-fn seq_level_idx(width: u32, height: u32, framerate: (u32, u32)) -> u8 {
282- // (seq_level_idx, MaxPicSize, MaxHSize, MaxVSize, MaxDisplayRate)
283- const LEVELS: [(u8, u64, u32, u32, u64); 12] = [
284- (0, 147_456, 2_048, 1_152, 4_423_680), // 2.0
285- (1, 278_784, 2_816, 1_584, 8_363_520), // 2.1
286- (4, 665_856, 4_352, 2_448, 19_975_680), // 3.0
287- (5, 1_065_024, 5_504, 3_096, 31_950_720), // 3.1
288- (8, 2_359_296, 6_144, 3_456, 70_778_880), // 4.0
289- (9, 2_359_296, 6_144, 3_456, 141_557_760), // 4.1
290- (12, 8_912_896, 8_192, 4_352, 267_386_880), // 5.0
291- (13, 8_912_896, 8_192, 4_352, 534_773_760), // 5.1
292- (14, 8_912_896, 8_192, 4_352, 1_069_547_520), // 5.2
293- (16, 35_651_584, 16_384, 8_704, 1_069_547_520), // 6.0
294- (17, 35_651_584, 16_384, 8_704, 2_139_095_040), // 6.1
295- (18, 35_651_584, 16_384, 8_704, 4_278_190_080), // 6.2
296- ];
297- let samples = u64::from(width) * u64::from(height);
298- let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1));
299- let rate = (samples as f64 * fps).ceil() as u64;
300- for &(idx, max_size, max_h, max_v, max_rate) in &LEVELS {
301- if samples <= max_size && width <= max_h && height <= max_v && rate <= max_rate {
302- return idx;
303- }
304- }
305- 31 // maximum parameters
306-}
307-
308-#[cfg(test)]
309-mod tests {
310- use super::*;
311-
312- #[test]
313- fn levels_follow_size_and_rate() {
314- // 1080p30 is 4.0 (idx 8), 2160p30 5.0 (12), 2160p60 5.1 (13).
315- assert_eq!(seq_level_idx(1920, 1088, (30, 1)), 8);
316- assert_eq!(seq_level_idx(3840, 2176, (30, 1)), 12);
317- assert_eq!(seq_level_idx(3840, 2176, (60, 1)), 13);
318- }
319-}
crates/ec-hw/src/enc/h264.rsmodified+4 -46
@@ -14,7 +14,7 @@ use ec_va::va::{
1414 VABufferID, VA_INVALID_ID,
1515 };
1616
17-use super::{Encoder, RateControlMode, headers};
17+use super::{Encoder, H264Profile, RateControlMode, headers};
1818 use crate::error::Result;
1919 use crate::params::h264::{PICTURE_INVALID, PICTURE_SHORT_TERM_REFERENCE};
2020 use crate::params::INVALID_SURFACE;
@@ -75,7 +75,7 @@ pub(super) fn parameters(
7575 let position = encoder.gop_position();
7676 (frame_num_at(position), 2 * position as i32)
7777 };
78- let level_idc = level_idc(coded_w, coded_h, config.framerate);
78+ let level_idc = crate::level::h264(&config);
7979 let intra_period = config.gop_size.max(1);
8080 let bits_per_second = match config.rate_control {
8181 RateControlMode::ConstantQp { .. } => 0,
@@ -136,6 +136,7 @@ pub(super) fn parameters(
136136 );
137137 }
138138 let cabac = config.h264_profile.cabac();
139+ let transform_8x8 = config.h264_profile == H264Profile::High;
139140 // reference_pic_flag = 1; CABAC in Main and High (10% smaller), CAVLC in
140141 // Constrained Baseline; deblocking_filter_control_present_flag = 1.
141142 let pic_fields = H264EncPicFields::new(
@@ -145,7 +146,7 @@ pub(super) fn parameters(
145146 0,
146147 0,
147148 0,
148- 0,
149+ u32::from(transform_8x8),
149150 1,
150151 0,
151152 0,
@@ -242,46 +243,3 @@ pub(super) fn parameters(
242243 out.push(BufferType::EncSliceParameter(EncSliceParameter::H264(slice)));
243244 Ok(())
244245 }
245-
246-/// The lowest Annex A level that fits the picture size and rate.
247-///
248-/// Advertising level 6.2 for a 640x480 clip is legal and lazy; a player that
249-/// checks levels against its decoder budget deserves the real one.
250-fn level_idc(width: u32, height: u32, framerate: (u32, u32)) -> u8 {
251- const LEVELS: [(u8, u64, u64); 12] = [
252- (10, 1485, 99),
253- (11, 3000, 396),
254- (20, 11880, 396),
255- (21, 19800, 792),
256- (22, 20250, 1620),
257- (30, 40500, 1620),
258- (31, 108000, 3600),
259- (32, 216000, 5120),
260- (40, 245760, 8192),
261- (50, 589824, 22080),
262- (51, 983040, 36864),
263- (52, 2073600, 36864),
264- ];
265- let frame_mbs = u64::from(width / 16) * u64::from(height / 16);
266- let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1));
267- let mbps = (frame_mbs as f64 * fps).ceil() as u64;
268- for &(idc, max_mbps, max_fs) in &LEVELS {
269- if mbps <= max_mbps && frame_mbs <= max_fs {
270- return idc;
271- }
272- }
273- 62
274-}
275-
276-#[cfg(test)]
277-mod tests {
278- use super::*;
279-
280- #[test]
281- fn levels_follow_size_and_rate() {
282- assert_eq!(level_idc(1920, 1088, (30, 1)), 40);
283- assert_eq!(level_idc(1920, 1088, (60, 1)), 50);
284- assert_eq!(level_idc(3840, 2160, (30, 1)), 51);
285- assert_eq!(level_idc(640, 480, (30, 1)), 30);
286- }
287-}
crates/ec-hw/src/enc/headers.rsmodified+13 -1
@@ -155,6 +155,11 @@ pub(super) fn h264_pps(p: &H264Params) -> Packed {
155155 w.write_bit(true); // deblocking_filter_control_present_flag
156156 w.write_bit(false); // constrained_intra_pred_flag
157157 w.write_bit(false); // redundant_pic_cnt_present_flag
158+ if p.profile == super::H264Profile::High {
159+ w.write_bit(true); // transform_8x8_mode_flag
160+ w.write_bit(false); // pic_scaling_matrix_present_flag
161+ w.write_se(0); // second_chroma_qp_index_offset
162+ }
158163 trailing(&mut w);
159164 nal(PACKED_HEADER_PICTURE, &[0x68], &w.into_bytes(), 0)
160165 }
@@ -251,6 +256,7 @@ pub(super) mod hevc {
251256 ptl,
252257 max_dec_pic_buffering_minus1: 1,
253258 max_num_reorder_pics: 0,
259+ timing: Some((p.num_units_in_tick, p.time_scale)),
254260 };
255261 let sps = Sps {
256262 vps_id: 0,
@@ -460,6 +466,7 @@ pub(super) mod av1 {
460466 pub(in crate::enc) height: u32,
461467 pub(in crate::enc) seq_level_idx: u8,
462468 pub(in crate::enc) seq_tier: u8,
469+ pub(in crate::enc) framerate: (u32, u32),
463470 /// 10-bit (`high_bitdepth`); profile 0 has no `twelve_bit`.
464471 pub(in crate::enc) high_bitdepth: bool,
465472 pub(in crate::enc) colour: Option<Colour>,
@@ -476,7 +483,12 @@ pub(super) mod av1 {
476483 w.write_bits(0, 3); // seq_profile
477484 w.write_bit(false); // still_picture
478485 w.write_bit(false); // reduced_still_picture_header
479- w.write_bit(false); // timing_info_present_flag
486+ w.write_bit(true); // timing_info_present_flag
487+ w.write_bits(p.framerate.1.max(1), 32); // num_units_in_display_tick
488+ w.write_bits(p.framerate.0.max(1), 32); // time_scale
489+ w.write_bit(true); // equal_picture_interval
490+ w.write_bit(true); // num_ticks_per_picture_minus_1 = 0, as uvlc
491+ w.write_bit(false); // decoder_model_info_present_flag
480492 w.write_bit(false); // initial_display_delay_present_flag
481493 w.write_bits(0, 5); // operating_points_cnt_minus_1
482494 w.write_bits(0, 12); // operating_point_idc[0]
crates/ec-hw/src/enc/hevc.rsmodified+1 -39
@@ -48,7 +48,7 @@ pub(super) fn parameters(
4848 } else {
4949 encoder.gop_position() as i32
5050 };
51- let general_level_idc = level_idc(coded_w, coded_h, config.framerate);
51+ let general_level_idc = crate::level::hevc(&config);
5252 let intra_period = config.gop_size.max(1);
5353 let bits_per_second = match config.rate_control {
5454 RateControlMode::ConstantQp { .. } => 0,
@@ -242,41 +242,3 @@ pub(super) fn parameters(
242242 )));
243243 Ok(())
244244 }
245-
246-/// The lowest level whose luma sample rate and picture size fit (Annex A).
247-fn level_idc(width: u32, height: u32, framerate: (u32, u32)) -> u8 {
248- // (general_level_idc = level * 30, MaxLumaPs, MaxLumaSr)
249- const LEVELS: [(u8, u64, u64); 9] = [
250- (30, 36_864, 552_960),
251- (60, 122_880, 3_686_400),
252- (63, 245_760, 7_372_800),
253- (90, 552_960, 16_588_800),
254- (93, 983_040, 33_177_600),
255- (120, 2_228_224, 66_846_720),
256- (123, 2_228_224, 133_693_440),
257- (150, 8_912_896, 267_386_880),
258- (153, 8_912_896, 534_773_760),
259- ];
260- let samples = u64::from(width) * u64::from(height);
261- let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1));
262- let rate = (samples as f64 * fps).ceil() as u64;
263- for &(idc, max_ps, max_sr) in &LEVELS {
264- if samples <= max_ps && rate <= max_sr {
265- return idc;
266- }
267- }
268- 186
269-}
270-
271-#[cfg(test)]
272-mod tests {
273- use super::*;
274-
275- #[test]
276- fn levels_follow_size_and_rate() {
277- // 1080p30 is level 4.0 (120), 1080p60 level 4.1 (123), 2160p30 5.0 (150).
278- assert_eq!(level_idc(1920, 1088, (30, 1)), 120);
279- assert_eq!(level_idc(1920, 1088, (60, 1)), 123);
280- assert_eq!(level_idc(3840, 2160, (30, 1)), 150);
281- }
282-}
crates/ec-hw/src/hw.rsmodified+8 -0
@@ -855,6 +855,11 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
855855 let gpu = vk_gpu()
856856 .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?;
857857 let rate = vk_rate(&config, config.bitrate);
858+ let level = match config.codec {
859+ EncCodec::H264 => crate::level::h264(&config),
860+ EncCodec::H265 => crate::level::hevc(&config),
861+ EncCodec::Av1 => crate::level::av1(&config),
862+ };
858863 let (width, height, fps, gop_size) = (
859864 config.width,
860865 config.height,
@@ -877,6 +882,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
877882 gop_size,
878883 rate,
879884 profile: vk_h264_profile(config.h264_profile),
885+ level,
880886 colour,
881887 },
882888 )?),
@@ -889,6 +895,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
889895 gop_size,
890896 rate,
891897 bit_depth: config.bit_depth,
898+ level,
892899 colour,
893900 },
894901 )?),
@@ -901,6 +908,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
901908 gop_size,
902909 rate,
903910 bit_depth: config.bit_depth,
911+ level,
904912 colour,
905913 },
906914 )?),
crates/ec-hw/src/level.rsadded+145 -0
@@ -0,0 +1,145 @@
1+//! Level selection shared by both encoder backends.
2+//!
3+//! Each function returns the smallest level whose picture size, sample rate,
4+//! DPB and bitrate limits hold for the configuration. The Vulkan shim clamps
5+//! the result to the driver's maximum.
6+
7+use crate::types::{EncoderConfig, H264Profile, RateControlMode};
8+
9+/// `max_dec_pic_buffering` the encoders signal: one reference, no reordering.
10+const DPB_FRAMES: u64 = 1;
11+
12+/// H.264 luma macroblock size; the coded picture is a whole number of them.
13+const H264_BLOCK: u32 = 16;
14+
15+/// H.265 coded picture size is a whole number of 32-sample blocks here.
16+const H265_BLOCK: u32 = 32;
17+
18+/// `(level_idc, MaxMBPS, MaxFS, MaxDpbMbs, MaxBR kbit/s)`, Table A-1.
19+const H264_LEVELS: [(u8, u64, u64, u64, u64); 19] = [
20+ (10, 1485, 99, 396, 64),
21+ (11, 3000, 396, 900, 192),
22+ (12, 6000, 396, 2376, 384),
23+ (13, 11880, 396, 2376, 768),
24+ (20, 11880, 396, 2376, 2000),
25+ (21, 19800, 792, 4752, 4000),
26+ (22, 20250, 1620, 8100, 4000),
27+ (30, 40500, 1620, 8100, 10000),
28+ (31, 108000, 3600, 18000, 14000),
29+ (32, 216000, 5120, 20480, 20000),
30+ (40, 245760, 8192, 32768, 20000),
31+ (41, 245760, 8192, 32768, 50000),
32+ (42, 522240, 8704, 34816, 50000),
33+ (50, 589824, 22080, 110400, 135000),
34+ (51, 983040, 36864, 184320, 240000),
35+ (52, 2073600, 36864, 184320, 240000),
36+ (60, 4177920, 139264, 696320, 240000),
37+ (61, 8355840, 139264, 696320, 480000),
38+ (62, 16711680, 139264, 696320, 800000),
39+];
40+
41+/// `(general_level_idc, MaxLumaPs, MaxLumaSr, Main tier MaxBR kbit/s)`, Table A.8.
42+const HEVC_LEVELS: [(u8, u64, u64, u64); 13] = [
43+ (30, 36864, 552960, 128),
44+ (60, 122880, 3686400, 1500),
45+ (63, 245760, 7372800, 3000),
46+ (90, 552960, 16588800, 6000),
47+ (93, 983040, 33177600, 10000),
48+ (120, 2228224, 66846720, 12000),
49+ (123, 2228224, 133693440, 20000),
50+ (150, 8912896, 267386880, 25000),
51+ (153, 8912896, 534773760, 40000),
52+ (156, 8912896, 1069547520, 60000),
53+ (180, 35651584, 1069547520, 60000),
54+ (183, 35651584, 2139095040, 120000),
55+ (186, 35651584, 4278190080, 240000),
56+];
57+
58+/// `(seq_level_idx, MaxPicSize, MaxHSize, MaxVSize, MaxDisplayRate, MainMbps kbit/s)`, Annex A.
59+const AV1_LEVELS: [(u8, u64, u32, u32, u64, u64); 12] = [
60+ (0, 147_456, 2_048, 1_152, 4_423_680, 1_500),
61+ (1, 278_784, 2_816, 1_584, 8_363_520, 3_000),
62+ (4, 665_856, 4_352, 2_448, 19_975_680, 5_000),
63+ (5, 1_065_024, 5_504, 3_096, 31_950_720, 10_000),
64+ (8, 2_359_296, 6_144, 3_456, 70_778_880, 20_000),
65+ (9, 2_359_296, 6_144, 3_456, 141_557_760, 30_000),
66+ (12, 8_912_896, 8_192, 4_352, 267_386_880, 60_000),
67+ (13, 8_912_896, 8_192, 4_352, 534_773_760, 100_000),
68+ (14, 8_912_896, 8_192, 4_352, 1_069_547_520, 160_000),
69+ (16, 35_651_584, 16_384, 8_704, 1_069_547_520, 240_000),
70+ (17, 35_651_584, 16_384, 8_704, 2_139_095_040, 480_000),
71+ (18, 35_651_584, 16_384, 8_704, 4_278_190_080, 800_000),
72+];
73+
74+const H264_MAX_LEVEL: u8 = 62;
75+const HEVC_MAX_LEVEL: u8 = 186;
76+const AV1_MAX_LEVEL: u8 = 31;
77+
78+fn aligned(value: u32, block: u32) -> u64 {
79+ u64::from(value.next_multiple_of(block))
80+}
81+
82+/// Whether `samples` per picture at the frame rate stay within `limit` per second.
83+fn rate_fits(samples: u64, framerate: (u32, u32), limit: u64) -> bool {
84+ let (num, den) = (u64::from(framerate.0.max(1)), u64::from(framerate.1.max(1)));
85+ samples * num <= limit * den
86+}
87+
88+/// The bitrate the level must carry, or `None` when the quantiser is fixed.
89+fn bitrate(config: &EncoderConfig) -> Option<u64> {
90+ match config.rate_control {
91+ RateControlMode::ConstantQp { .. } => None,
92+ _ => Some(u64::from(config.bitrate)),
93+ }
94+}
95+
96+/// `level_idc` of the lowest H.264 level that fits `config`.
97+pub(crate) fn h264(config: &EncoderConfig) -> u8 {
98+ let mbs = (aligned(config.width, H264_BLOCK) / 16) * (aligned(config.height, H264_BLOCK) / 16);
99+ let scale = if config.h264_profile == H264Profile::High {
100+ 5
101+ } else {
102+ 4
103+ };
104+ let bitrate = bitrate(config);
105+ H264_LEVELS
106+ .iter()
107+ .find(|&&(_, mbps, fs, dpb, br)| {
108+ rate_fits(mbs, config.framerate, mbps)
109+ && mbs <= fs
110+ && mbs * DPB_FRAMES <= dpb
111+ && bitrate.is_none_or(|b| b * 4 <= br * 1000 * scale)
112+ })
113+ .map_or(H264_MAX_LEVEL, |level| level.0)
114+}
115+
116+/// `general_level_idc` of the lowest Main-tier H.265 level that fits `config`.
117+pub(crate) fn hevc(config: &EncoderConfig) -> u8 {
118+ let samples = aligned(config.width, H265_BLOCK) * aligned(config.height, H265_BLOCK);
119+ let bitrate = bitrate(config);
120+ HEVC_LEVELS
121+ .iter()
122+ .find(|&&(_, max_ps, max_sr, br)| {
123+ samples <= max_ps
124+ && rate_fits(samples, config.framerate, max_sr)
125+ && bitrate.is_none_or(|b| b * 10 <= br * 1000 * 11)
126+ })
127+ .map_or(HEVC_MAX_LEVEL, |level| level.0)
128+}
129+
130+/// `seq_level_idx` of the lowest AV1 level that fits `config`.
131+pub(crate) fn av1(config: &EncoderConfig) -> u8 {
132+ let (width, height) = (config.width.max(1), config.height.max(1));
133+ let samples = u64::from(width) * u64::from(height);
134+ let bitrate = bitrate(config);
135+ AV1_LEVELS
136+ .iter()
137+ .find(|&&(_, max_size, max_w, max_h, max_rate, main_kbps)| {
138+ samples <= max_size
139+ && width <= max_w
140+ && height <= max_h
141+ && rate_fits(samples, config.framerate, max_rate)
142+ && bitrate.is_none_or(|b| b <= main_kbps * 1000)
143+ })
144+ .map_or(AV1_MAX_LEVEL, |level| level.0)
145+}
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 level;
6667 pub(crate) mod rate;
6768 pub(crate) mod ref_slots;
6869 pub(crate) mod vkdec_vp9;
crates/ec-vk/examples/av1_encode.rsmodified+1 -0
@@ -27,6 +27,7 @@ fn main() {
2727 width: W,
2828 height: H,
2929 fps: (FPS, 1),
30+ level: 23,
3031 gop_size: 30,
3132 rate: match std::env::args().nth(2) {
3233 Some(b) => RateControl::Cbr {
crates/ec-vk/examples/h264_encode.rsmodified+1 -0
@@ -26,6 +26,7 @@ fn main() {
2626 width: W,
2727 height: H,
2828 fps: (30, 1),
29+ level: 62,
2930 gop_size: 30,
3031 profile: H264Profile::High,
3132 colour: None,
crates/ec-vk/examples/h265_encode.rsmodified+1 -0
@@ -26,6 +26,7 @@ fn main() {
2626 width: W,
2727 height: H,
2828 fps: (30, 1),
29+ level: 186,
2930 gop_size: 30,
3031 rate: match std::env::args().nth(2) {
3132 Some(b) => RateControl::Cbr {
crates/ec-vk/src/av1.rsmodified+3 -0
@@ -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+ /// `seq_level_idx`, clamped to the driver maximum.
25+ pub level: u8,
2426 /// Colour config of the sequence header, or none.
2527 pub colour: Option<Colour>,
2628 }
@@ -54,6 +56,7 @@ impl Av1Encoder {
5456 fps: cfg.fps,
5557 rate: cfg.rate,
5658 bit_depth: cfg.bit_depth,
59+ level: cfg.level,
5760 colour: cfg.colour,
5861 },
5962 )?;
crates/ec-vk/src/h265.rsmodified+3 -0
@@ -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+ /// `general_level_idc`, clamped to the driver maximum.
23+ pub level: u8,
2224 /// Colour description for the VUI, or none.
2325 pub colour: Option<Colour>,
2426 }
@@ -52,6 +54,7 @@ impl H265Encoder {
5254 fps: cfg.fps,
5355 rate: cfg.rate,
5456 bit_depth: cfg.bit_depth,
57+ level: cfg.level,
5558 colour: cfg.colour,
5659 },
5760 )?;
crates/ec-vk/src/lib.rsmodified+3 -0
@@ -41,6 +41,8 @@ pub struct H264EncoderConfig {
4141 pub rate: RateControl,
4242 /// H.264 profile.
4343 pub profile: H264Profile,
44+ /// `level_idc`, clamped to the driver maximum.
45+ pub level: u8,
4446 /// Colour description for the VUI, or none.
4547 pub colour: Option<Colour>,
4648 }
@@ -107,6 +109,7 @@ impl H264Encoder {
107109 fps: cfg.fps,
108110 rate: cfg.rate,
109111 profile: cfg.profile,
112+ level: cfg.level,
110113 colour: cfg.colour,
111114 },
112115 )?;
shims/vk-video-ffi/examples/dmabuf_smoke.rsmodified+3 -0
@@ -88,6 +88,7 @@ impl Encode for H264EncodeSession {
8888 fps: FPS,
8989 rate: RATE,
9090 profile: H264Profile::High,
91+ level: 62,
9192 colour: None,
9293 };
9394 H264EncodeSession::new(gpu, &cfg)
@@ -130,6 +131,7 @@ impl Encode for H265EncodeSession {
130131 fps: FPS,
131132 rate: RATE,
132133 bit_depth: bits,
134+ level: 186,
133135 colour: None,
134136 };
135137 H265EncodeSession::new(gpu, &cfg)
@@ -174,6 +176,7 @@ impl Encode for Av1EncodeSession {
174176 fps: FPS,
175177 rate: RATE,
176178 bit_depth: bits,
179+ level: 23,
177180 colour: None,
178181 };
179182 Av1EncodeSession::new(gpu, &cfg)
shims/vk-video-ffi/src/av1_encode.rsmodified+40 -7
@@ -13,7 +13,6 @@ use crate::session::{
1313 use crate::{Colour, Error, Gpu, RateControl};
1414
1515 const AV1_SLOTS: usize = 8;
16-const LEVEL: vk::video::StdVideoAV1Level = vk::video::STD_VIDEO_AV1_LEVEL_5_1;
1716 const CBR_Q_INDEX: u32 = 128;
1817
1918 /// Settings fixed for the life of an AV1 session.
@@ -29,6 +28,8 @@ pub struct Av1EncodeConfig {
2928 pub rate: RateControl,
3029 /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input).
3130 pub bit_depth: u8,
31+ /// `seq_level_idx` (0 to 23), chosen by the caller and clamped to the driver maximum.
32+ pub level: u8,
3233 /// Colour config of the sequence header, or none (unspecified).
3334 pub colour: Option<Colour>,
3435 }
@@ -62,6 +63,7 @@ struct Caps {
6263 rc_modes: vk::VideoEncodeRateControlModeFlagsKHR,
6364 single_ref: bool,
6465 sb64: bool,
66+ max_level: vk::video::StdVideoAV1Level,
6567 }
6668
6769 struct Profile {
@@ -180,6 +182,7 @@ impl Av1EncodeSession {
180182 if !caps.single_ref {
181183 return Err(Error::Unsupported("AV1 single LAST reference".into()));
182184 }
185+ let level = av1_level(cfg.level, caps.max_level)?;
183186 let mode = match cfg.rate {
184187 RateControl::ConstantQp { .. } => vk::VideoEncodeRateControlModeFlagsKHR::DISABLED,
185188 RateControl::Cbr { .. } => vk::VideoEncodeRateControlModeFlagsKHR::CBR,
@@ -214,11 +217,11 @@ impl Av1EncodeSession {
214217 (cfg.rate, cfg.fps),
215218 caps.size_align,
216219 )?;
217- let params = create_parameters(&enc.vs, extent, sb128, cfg)?;
220+ let params = create_parameters(&enc.vs, extent, sb128, cfg, level)?;
218221 enc.vs.set_params(params);
219222 Ok(Av1EncodeSession {
220223 enc,
221- seq: sequence_header_obu(cfg, sb128),
224+ seq: sequence_header_obu(cfg, sb128, level),
222225 slot_key: [false; DPB_SLOTS],
223226 ref_order_hint: [0; AV1_SLOTS],
224227 })
@@ -503,6 +506,7 @@ fn create_parameters(
503506 extent: vk::Extent2D,
504507 sb128: bool,
505508 cfg: &Av1EncodeConfig,
509+ level: vk::video::StdVideoAV1Level,
506510 ) -> Result<vk::VideoSessionParametersKHR, Error> {
507511 let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>();
508512 color.BitDepth = cfg.bit_depth;
@@ -521,9 +525,15 @@ fn create_parameters(
521525 color.matrix_coefficients = vk::video::StdVideoAV1MatrixCoefficients(i32::from(c.matrix));
522526 }
523527
528+ let mut timing = zeroed::<vk::video::StdVideoAV1TimingInfo>();
529+ timing.flags.set_equal_picture_interval(1);
530+ timing.num_units_in_display_tick = cfg.fps.1;
531+ timing.time_scale = cfg.fps.0;
524532 let mut seq = zeroed::<vk::video::StdVideoAV1SequenceHeader>();
525533 seq.flags.set_enable_order_hint(1);
526534 seq.flags.set_use_128x128_superblock(sb128 as u32);
535+ seq.flags.set_timing_info_present_flag(1);
536+ seq.pTimingInfo = &timing;
527537 seq.seq_profile = vk::video::STD_VIDEO_AV1_PROFILE_MAIN;
528538 seq.frame_width_bits_minus_1 = (bits(extent.width) - 1) as u8;
529539 seq.frame_height_bits_minus_1 = (bits(extent.height) - 1) as u8;
@@ -534,7 +544,7 @@ fn create_parameters(
534544 seq.pColorConfig = &color;
535545
536546 let mut op = zeroed::<vk::video::StdVideoEncodeAV1OperatingPointInfo>();
537- op.seq_level_idx = LEVEL.0 as u8;
547+ op.seq_level_idx = level.0 as u8;
538548
539549 let mut av1 = vk::VideoEncodeAV1SessionParametersCreateInfoKHR {
540550 std_sequence_header: &seq,
@@ -596,18 +606,29 @@ fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {
596606 out
597607 }
598608
599-fn sequence_header_obu(cfg: &Av1EncodeConfig, sb128: bool) -> Vec<u8> {
609+fn sequence_header_obu(
610+ cfg: &Av1EncodeConfig,
611+ sb128: bool,
612+ level: vk::video::StdVideoAV1Level,
613+) -> Vec<u8> {
600614 let (width, height, bit_depth) = (cfg.width, cfg.height, cfg.bit_depth);
601615 let mut b = Bits(Vec::new());
602616 b.put(0, 3);
603617 b.put(0, 1);
604618 b.put(0, 1);
619+ b.put(1, 1);
620+ b.put(cfg.fps.1, 32);
621+ b.put(cfg.fps.0, 32);
622+ b.put(1, 1);
623+ b.put(1, 1);
605624 b.put(0, 1);
606625 b.put(0, 1);
607626 b.put(0, 5);
608627 b.put(0, 12);
609- b.put(LEVEL.0 as u32, 5);
610- b.put(0, 1);
628+ b.put(level.0 as u32, 5);
629+ if level.0 > 7 {
630+ b.put(0, 1);
631+ }
611632 b.put(bits(width) - 1, 4);
612633 b.put(bits(height) - 1, 4);
613634 b.put(width - 1, bits(width));
@@ -700,5 +721,17 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Erro
700721 sb64: av1.superblock_sizes.contains(
701722 vk::VideoEncodeAV1SuperblockSizeFlagsKHR::VIDEO_ENCODE_AV1_SUPERBLOCK_SIZE_64,
702723 ),
724+ max_level: av1.max_level,
703725 })
704726 }
727+
728+fn av1_level(
729+ idx: u8,
730+ driver_max: vk::video::StdVideoAV1Level,
731+) -> Result<vk::video::StdVideoAV1Level, Error> {
732+ if idx > 23 {
733+ return Err(Error::Invalid(format!("AV1 seq_level_idx {idx}")));
734+ }
735+ let level = vk::video::StdVideoAV1Level(i32::from(idx));
736+ Ok(if level.0 > driver_max.0 { driver_max } else { level })
737+}
shims/vk-video-ffi/src/h264_encode.rsmodified+37 -20
@@ -55,6 +55,8 @@ pub struct H264EncodeConfig {
5555 pub rate: RateControl,
5656 /// H.264 profile.
5757 pub profile: H264Profile,
58+ /// `level_idc` (10 to 62), chosen by the caller and clamped to the driver maximum.
59+ pub level: u8,
5860 /// Colour description for the VUI, or none.
5961 pub colour: Option<Colour>,
6062 }
@@ -93,6 +95,7 @@ struct Caps {
9395 size_align: u64,
9496 rc_modes: vk::VideoEncodeRateControlModeFlagsKHR,
9597 max_refs: u32,
98+ max_level: vk::video::StdVideoH264LevelIdc,
9699 }
97100
98101 struct Profile {
@@ -203,12 +206,12 @@ impl H264EncodeSession {
203206 }
204207 let width = align(cfg.width, 16);
205208 let height = align(cfg.height, 16);
206- let level = level_for(width, height, cfg.fps)?;
207209 let profile = Profile::new(cfg.profile);
208210 let caps = query_caps(gpu, &profile.info).map_err(|e| match e {
209211 Error::Vk(..) => Error::Unsupported(format!("H.264 {:?} encode", cfg.profile)),
210212 other => other,
211213 })?;
214+ let level = h264_level(cfg.level, caps.max_level)?;
212215 if width > caps.max_extent.width || height > caps.max_extent.height {
213216 return Err(Error::Unsupported(format!("H.264 encode {width}x{height}")));
214217 }
@@ -579,25 +582,6 @@ pub(crate) fn validate(
579582 validate_rate(fps, rate)
580583 }
581584
582-fn level_for(
583- width: u32,
584- height: u32,
585- fps: (u32, u32),
586-) -> Result<vk::video::StdVideoH264LevelIdc, Error> {
587- let mbs = (width / 16) as u64 * (height / 16) as u64;
588- let table = [
589- (8160u64, 245760u64, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_1),
590- (8704, 522240, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_2),
591- (36864, 983040, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_1),
592- (36864, 2073600, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_2),
593- ];
594- table
595- .into_iter()
596- .find(|&(frame, mbps, _)| mbs <= frame && mbs * fps.0 as u64 <= mbps * fps.1 as u64)
597- .map(|(_, _, level)| level)
598- .ok_or_else(|| Error::Unsupported(format!("H.264 level for {width}x{height} at {fps:?}")))
599-}
600-
601585 fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> {
602586 let mut h264 = vk::VideoEncodeH264CapabilitiesKHR::builder();
603587 let mut encode = vk::VideoEncodeCapabilitiesKHR::builder();
@@ -611,6 +595,7 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Erro
611595 size_align: caps.min_bitstream_buffer_size_alignment,
612596 rc_modes: encode.rate_control_modes,
613597 max_refs: h264.max_p_picture_l0_reference_count,
598+ max_level: h264.max_level_idc,
614599 })
615600 }
616601
@@ -625,3 +610,35 @@ fn reference_info(
625610 info.PicOrderCnt = poc;
626611 info
627612 }
613+
614+fn h264_level(
615+ idc: u8,
616+ driver_max: vk::video::StdVideoH264LevelIdc,
617+) -> Result<vk::video::StdVideoH264LevelIdc, Error> {
618+ const LEVELS: [(u8, vk::video::StdVideoH264LevelIdc); 19] = [
619+ (10, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_0),
620+ (11, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_1),
621+ (12, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_2),
622+ (13, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_3),
623+ (20, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_0),
624+ (21, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_1),
625+ (22, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_2),
626+ (30, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_0),
627+ (31, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_1),
628+ (32, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_2),
629+ (40, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_0),
630+ (41, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_1),
631+ (42, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_2),
632+ (50, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_0),
633+ (51, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_1),
634+ (52, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_2),
635+ (60, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_0),
636+ (61, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_1),
637+ (62, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_2),
638+ ];
639+ let (_, level) = LEVELS
640+ .into_iter()
641+ .find(|(value, _)| *value == idc)
642+ .ok_or_else(|| Error::Invalid(format!("H.264 level_idc {idc}")))?;
643+ Ok(if level.0 > driver_max.0 { driver_max } else { level })
644+}
shims/vk-video-ffi/src/h265_encode.rsmodified+26 -19
@@ -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+ /// `general_level_idc` (30 to 186), chosen by the caller and clamped to the driver maximum.
32+ pub level: u8,
3133 /// Colour description for the VUI, or none.
3234 pub colour: Option<Colour>,
3335 }
@@ -60,6 +62,7 @@ struct Caps {
6062 size_align: u64,
6163 rc_modes: vk::VideoEncodeRateControlModeFlagsKHR,
6264 max_refs: u32,
65+ max_level: vk::video::StdVideoH265LevelIdc,
6366 ctb_sizes: vk::VideoEncodeH265CtbSizeFlagsKHR,
6467 transform_sizes: vk::VideoEncodeH265TransformBlockSizeFlagsKHR,
6568 std_flags: vk::VideoEncodeH265StdFlagsKHR,
@@ -647,7 +650,7 @@ fn coding(caps: &Caps, cfg: &H265EncodeConfig) -> Result<Coding, Error> {
647650 transform_skip: caps
648651 .std_flags
649652 .contains(vk::VideoEncodeH265StdFlagsKHR::TRANSFORM_SKIP_ENABLED_FLAG_SET),
650- level: level_for(width, height, cfg.fps)?,
653+ level: h265_level(cfg.level, caps.max_level)?,
651654 })
652655 }
653656
@@ -659,27 +662,30 @@ fn profile_idc(bit_depth: u8) -> vk::video::StdVideoH265ProfileIdc {
659662 }
660663 }
661664
662-fn level_for(
663- width: u32,
664- height: u32,
665- fps: (u32, u32),
665+fn h265_level(
666+ idc: u8,
667+ driver_max: vk::video::StdVideoH265LevelIdc,
666668 ) -> Result<vk::video::StdVideoH265LevelIdc, Error> {
667- let luma = width as u64 * height as u64;
668- let table = [
669- (
670- 983040u64,
671- 33177600u64,
672- vk::video::STD_VIDEO_H265_LEVEL_IDC_3_1,
673- ),
674- (2228224, 66846720, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_0),
675- (2228224, 133693440, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_1),
676- (8912896, 267386880, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_0),
669+ const LEVELS: [(u8, vk::video::StdVideoH265LevelIdc); 13] = [
670+ (30, vk::video::STD_VIDEO_H265_LEVEL_IDC_1_0),
671+ (60, vk::video::STD_VIDEO_H265_LEVEL_IDC_2_0),
672+ (63, vk::video::STD_VIDEO_H265_LEVEL_IDC_2_1),
673+ (90, vk::video::STD_VIDEO_H265_LEVEL_IDC_3_0),
674+ (93, vk::video::STD_VIDEO_H265_LEVEL_IDC_3_1),
675+ (120, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_0),
676+ (123, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_1),
677+ (150, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_0),
678+ (153, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_1),
679+ (156, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_2),
680+ (180, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_0),
681+ (183, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_1),
682+ (186, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_2),
677683 ];
678- table
684+ let (_, level) = LEVELS
679685 .into_iter()
680- .find(|&(ps, sr, _)| luma <= ps && luma * fps.0 as u64 <= sr * fps.1 as u64)
681- .map(|(_, _, level)| level)
682- .ok_or_else(|| Error::Unsupported(format!("H.265 level for {width}x{height} at {fps:?}")))
686+ .find(|(value, _)| *value == idc)
687+ .ok_or_else(|| Error::Invalid(format!("H.265 general_level_idc {idc}")))?;
688+ Ok(if level.0 > driver_max.0 { driver_max } else { level })
683689 }
684690
685691 fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> {
@@ -695,6 +701,7 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Erro
695701 size_align: caps.min_bitstream_buffer_size_alignment,
696702 rc_modes: encode.rate_control_modes,
697703 max_refs: h265.max_p_picture_l0_reference_count,
704+ max_level: h265.max_level_idc,
698705 ctb_sizes: h265.ctb_sizes,
699706 transform_sizes: h265.transform_block_sizes,
700707 std_flags: h265.std_syntax_flags,