diff --git a/crates/ec-h265-syntax/src/ps.rs b/crates/ec-h265-syntax/src/ps.rs index a49b10ec..7a73d300 100644 --- a/crates/ec-h265-syntax/src/ps.rs +++ b/crates/ec-h265-syntax/src/ps.rs @@ -186,6 +186,8 @@ pub struct Vps { pub max_dec_pic_buffering_minus1: u32, /// `vps_max_num_reorder_pics[0]`; 0 for an intra-only stream. pub max_num_reorder_pics: u32, + /// `(vps_num_units_in_tick, vps_time_scale)` when `vps_timing_info_present_flag` is set. + pub timing: Option<(u32, u32)>, } impl Vps { @@ -206,7 +208,16 @@ impl Vps { w.write_ue(0); // vps_max_latency_increase_plus1 w.write_bits(0, 6); // vps_max_layer_id w.write_ue(0); // vps_num_layer_sets_minus1 - w.write_bit(false); // vps_timing_info_present_flag + match self.timing { + Some((num_units_in_tick, time_scale)) => { + w.write_bit(true); // vps_timing_info_present_flag + w.write_bits(num_units_in_tick, 32); + w.write_bits(time_scale, 32); + w.write_bit(false); // vps_poc_proportional_to_timing_flag + w.write_ue(0); // vps_num_hrd_parameters + } + None => w.write_bit(false), // vps_timing_info_present_flag + } w.write_bit(false); // vps_extension_flag rbsp_trailing_bits(&mut w); w.into_bytes() @@ -250,11 +261,19 @@ impl Vps { max_num_reorder_pics = r.read_ue()?; r.read_ue()?; } + r.read_bits(6)?; // vps_max_layer_id + let layer_sets_minus1 = r.read_ue()?; + let timing = if layer_sets_minus1 == 0 && r.read_bit()? { + Some((r.read_bits(32)?, r.read_bits(32)?)) + } else { + None + }; Ok(Vps { id, ptl, max_dec_pic_buffering_minus1, max_num_reorder_pics, + timing, }) } } @@ -1491,6 +1510,7 @@ mod tests { ptl: ProfileTierLevel::main(120), max_dec_pic_buffering_minus1: 0, max_num_reorder_pics: 0, + timing: None, }; assert_eq!(Vps::parse(&vps.to_rbsp()).unwrap(), vps); @@ -1572,6 +1592,7 @@ mod tests { ptl: ProfileTierLevel::main(120), max_dec_pic_buffering_minus1: 0, max_num_reorder_pics: 0, + timing: None, } .to_rbsp(); vps[1] |= 0x0e; @@ -1678,6 +1699,7 @@ mod tests { ptl: ProfileTierLevel::main(120), max_dec_pic_buffering_minus1: 16, max_num_reorder_pics: 0, + timing: None, }; refused_naming(Vps::parse(&vps.to_rbsp()), "vps_max_dec_pic_buffering_minus1"); } diff --git a/crates/ec-h265-syntax/tests/fuzz.rs b/crates/ec-h265-syntax/tests/fuzz.rs index 44a312c5..4f3cdf6a 100644 --- a/crates/ec-h265-syntax/tests/fuzz.rs +++ b/crates/ec-h265-syntax/tests/fuzz.rs @@ -109,6 +109,7 @@ fn ten_thousand_malformed_inputs_never_panic() { ptl: ProfileTierLevel::main(120), max_dec_pic_buffering_minus1: 1, max_num_reorder_pics: 0, + timing: None, } .to_rbsp(), ]; diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index 4b9413b0..fe162e62 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -486,6 +486,7 @@ impl Encoder { ptl, max_dec_pic_buffering_minus1: dpb_minus1, max_num_reorder_pics: 0, + timing: None, }; let log2_ctb = cfg.ctb_size.trailing_zeros(); let sps = Sps { diff --git a/crates/ec-hw/src/enc/av1.rs b/crates/ec-hw/src/enc/av1.rs index 8bd28834..248a174c 100644 --- a/crates/ec-hw/src/enc/av1.rs +++ b/crates/ec-hw/src/enc/av1.rs @@ -52,7 +52,7 @@ pub(super) fn parameters( let (width, height) = (config.width.max(1), config.height.max(1)); let cqp = config.rate_control.is_cqp(); let ten_bit = config.bit_depth == 10; - let level_idx = seq_level_idx(coded_w, coded_h, config.framerate); + let level_idx = crate::level::av1(&config); // enable_order_hint, the bit depth and 4:2:0 subsampling; everything else off. let seq_fields = AV1EncSeqFields::new( @@ -260,6 +260,7 @@ pub(super) fn parameters( height, seq_level_idx: level_idx, seq_tier: 0, + framerate: config.framerate, high_bitdepth: ten_bit, colour: config.colour, }), @@ -274,46 +275,3 @@ pub(super) fn parameters( ))); Ok(()) } - -/// The lowest AV1 level whose picture size and rate fit (Annex A), as a -/// `seq_level_idx`. Levels below 2.0 do not exist, and anything past 6.3 is -/// signalled as the maximum-parameters level. -fn seq_level_idx(width: u32, height: u32, framerate: (u32, u32)) -> u8 { - // (seq_level_idx, MaxPicSize, MaxHSize, MaxVSize, MaxDisplayRate) - const LEVELS: [(u8, u64, u32, u32, u64); 12] = [ - (0, 147_456, 2_048, 1_152, 4_423_680), // 2.0 - (1, 278_784, 2_816, 1_584, 8_363_520), // 2.1 - (4, 665_856, 4_352, 2_448, 19_975_680), // 3.0 - (5, 1_065_024, 5_504, 3_096, 31_950_720), // 3.1 - (8, 2_359_296, 6_144, 3_456, 70_778_880), // 4.0 - (9, 2_359_296, 6_144, 3_456, 141_557_760), // 4.1 - (12, 8_912_896, 8_192, 4_352, 267_386_880), // 5.0 - (13, 8_912_896, 8_192, 4_352, 534_773_760), // 5.1 - (14, 8_912_896, 8_192, 4_352, 1_069_547_520), // 5.2 - (16, 35_651_584, 16_384, 8_704, 1_069_547_520), // 6.0 - (17, 35_651_584, 16_384, 8_704, 2_139_095_040), // 6.1 - (18, 35_651_584, 16_384, 8_704, 4_278_190_080), // 6.2 - ]; - let samples = u64::from(width) * u64::from(height); - let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1)); - let rate = (samples as f64 * fps).ceil() as u64; - for &(idx, max_size, max_h, max_v, max_rate) in &LEVELS { - if samples <= max_size && width <= max_h && height <= max_v && rate <= max_rate { - return idx; - } - } - 31 // maximum parameters -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn levels_follow_size_and_rate() { - // 1080p30 is 4.0 (idx 8), 2160p30 5.0 (12), 2160p60 5.1 (13). - assert_eq!(seq_level_idx(1920, 1088, (30, 1)), 8); - assert_eq!(seq_level_idx(3840, 2176, (30, 1)), 12); - assert_eq!(seq_level_idx(3840, 2176, (60, 1)), 13); - } -} diff --git a/crates/ec-hw/src/enc/h264.rs b/crates/ec-hw/src/enc/h264.rs index 1e7189c8..f31453f4 100644 --- a/crates/ec-hw/src/enc/h264.rs +++ b/crates/ec-hw/src/enc/h264.rs @@ -14,7 +14,7 @@ use ec_va::va::{ VABufferID, VA_INVALID_ID, }; -use super::{Encoder, RateControlMode, headers}; +use super::{Encoder, H264Profile, RateControlMode, headers}; use crate::error::Result; use crate::params::h264::{PICTURE_INVALID, PICTURE_SHORT_TERM_REFERENCE}; use crate::params::INVALID_SURFACE; @@ -75,7 +75,7 @@ pub(super) fn parameters( let position = encoder.gop_position(); (frame_num_at(position), 2 * position as i32) }; - let level_idc = level_idc(coded_w, coded_h, config.framerate); + let level_idc = crate::level::h264(&config); let intra_period = config.gop_size.max(1); let bits_per_second = match config.rate_control { RateControlMode::ConstantQp { .. } => 0, @@ -136,6 +136,7 @@ pub(super) fn parameters( ); } let cabac = config.h264_profile.cabac(); + let transform_8x8 = config.h264_profile == H264Profile::High; // reference_pic_flag = 1; CABAC in Main and High (10% smaller), CAVLC in // Constrained Baseline; deblocking_filter_control_present_flag = 1. let pic_fields = H264EncPicFields::new( @@ -145,7 +146,7 @@ pub(super) fn parameters( 0, 0, 0, - 0, + u32::from(transform_8x8), 1, 0, 0, @@ -242,46 +243,3 @@ pub(super) fn parameters( out.push(BufferType::EncSliceParameter(EncSliceParameter::H264(slice))); Ok(()) } - -/// The lowest Annex A level that fits the picture size and rate. -/// -/// Advertising level 6.2 for a 640x480 clip is legal and lazy; a player that -/// checks levels against its decoder budget deserves the real one. -fn level_idc(width: u32, height: u32, framerate: (u32, u32)) -> u8 { - const LEVELS: [(u8, u64, u64); 12] = [ - (10, 1485, 99), - (11, 3000, 396), - (20, 11880, 396), - (21, 19800, 792), - (22, 20250, 1620), - (30, 40500, 1620), - (31, 108000, 3600), - (32, 216000, 5120), - (40, 245760, 8192), - (50, 589824, 22080), - (51, 983040, 36864), - (52, 2073600, 36864), - ]; - let frame_mbs = u64::from(width / 16) * u64::from(height / 16); - let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1)); - let mbps = (frame_mbs as f64 * fps).ceil() as u64; - for &(idc, max_mbps, max_fs) in &LEVELS { - if mbps <= max_mbps && frame_mbs <= max_fs { - return idc; - } - } - 62 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn levels_follow_size_and_rate() { - assert_eq!(level_idc(1920, 1088, (30, 1)), 40); - assert_eq!(level_idc(1920, 1088, (60, 1)), 50); - assert_eq!(level_idc(3840, 2160, (30, 1)), 51); - assert_eq!(level_idc(640, 480, (30, 1)), 30); - } -} diff --git a/crates/ec-hw/src/enc/headers.rs b/crates/ec-hw/src/enc/headers.rs index 4796a53c..7fd0e64a 100644 --- a/crates/ec-hw/src/enc/headers.rs +++ b/crates/ec-hw/src/enc/headers.rs @@ -155,6 +155,11 @@ pub(super) fn h264_pps(p: &H264Params) -> Packed { w.write_bit(true); // deblocking_filter_control_present_flag w.write_bit(false); // constrained_intra_pred_flag w.write_bit(false); // redundant_pic_cnt_present_flag + if p.profile == super::H264Profile::High { + w.write_bit(true); // transform_8x8_mode_flag + w.write_bit(false); // pic_scaling_matrix_present_flag + w.write_se(0); // second_chroma_qp_index_offset + } trailing(&mut w); nal(PACKED_HEADER_PICTURE, &[0x68], &w.into_bytes(), 0) } @@ -251,6 +256,7 @@ pub(super) mod hevc { ptl, max_dec_pic_buffering_minus1: 1, max_num_reorder_pics: 0, + timing: Some((p.num_units_in_tick, p.time_scale)), }; let sps = Sps { vps_id: 0, @@ -460,6 +466,7 @@ pub(super) mod av1 { pub(in crate::enc) height: u32, pub(in crate::enc) seq_level_idx: u8, pub(in crate::enc) seq_tier: u8, + pub(in crate::enc) framerate: (u32, u32), /// 10-bit (`high_bitdepth`); profile 0 has no `twelve_bit`. pub(in crate::enc) high_bitdepth: bool, pub(in crate::enc) colour: Option, @@ -476,7 +483,12 @@ pub(super) mod av1 { w.write_bits(0, 3); // seq_profile w.write_bit(false); // still_picture w.write_bit(false); // reduced_still_picture_header - w.write_bit(false); // timing_info_present_flag + w.write_bit(true); // timing_info_present_flag + w.write_bits(p.framerate.1.max(1), 32); // num_units_in_display_tick + w.write_bits(p.framerate.0.max(1), 32); // time_scale + w.write_bit(true); // equal_picture_interval + w.write_bit(true); // num_ticks_per_picture_minus_1 = 0, as uvlc + w.write_bit(false); // decoder_model_info_present_flag w.write_bit(false); // initial_display_delay_present_flag w.write_bits(0, 5); // operating_points_cnt_minus_1 w.write_bits(0, 12); // operating_point_idc[0] diff --git a/crates/ec-hw/src/enc/hevc.rs b/crates/ec-hw/src/enc/hevc.rs index b14c1e46..f6bdcc45 100644 --- a/crates/ec-hw/src/enc/hevc.rs +++ b/crates/ec-hw/src/enc/hevc.rs @@ -48,7 +48,7 @@ pub(super) fn parameters( } else { encoder.gop_position() as i32 }; - let general_level_idc = level_idc(coded_w, coded_h, config.framerate); + let general_level_idc = crate::level::hevc(&config); let intra_period = config.gop_size.max(1); let bits_per_second = match config.rate_control { RateControlMode::ConstantQp { .. } => 0, @@ -242,41 +242,3 @@ pub(super) fn parameters( ))); Ok(()) } - -/// The lowest level whose luma sample rate and picture size fit (Annex A). -fn level_idc(width: u32, height: u32, framerate: (u32, u32)) -> u8 { - // (general_level_idc = level * 30, MaxLumaPs, MaxLumaSr) - const LEVELS: [(u8, u64, u64); 9] = [ - (30, 36_864, 552_960), - (60, 122_880, 3_686_400), - (63, 245_760, 7_372_800), - (90, 552_960, 16_588_800), - (93, 983_040, 33_177_600), - (120, 2_228_224, 66_846_720), - (123, 2_228_224, 133_693_440), - (150, 8_912_896, 267_386_880), - (153, 8_912_896, 534_773_760), - ]; - let samples = u64::from(width) * u64::from(height); - let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1)); - let rate = (samples as f64 * fps).ceil() as u64; - for &(idc, max_ps, max_sr) in &LEVELS { - if samples <= max_ps && rate <= max_sr { - return idc; - } - } - 186 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn levels_follow_size_and_rate() { - // 1080p30 is level 4.0 (120), 1080p60 level 4.1 (123), 2160p30 5.0 (150). - assert_eq!(level_idc(1920, 1088, (30, 1)), 120); - assert_eq!(level_idc(1920, 1088, (60, 1)), 123); - assert_eq!(level_idc(3840, 2160, (30, 1)), 150); - } -} diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index da9b7f30..1191cbef 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -855,6 +855,11 @@ fn open_vk(config: EncoderConfig) -> Result { let gpu = vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; let rate = vk_rate(&config, config.bitrate); + let level = match config.codec { + EncCodec::H264 => crate::level::h264(&config), + EncCodec::H265 => crate::level::hevc(&config), + EncCodec::Av1 => crate::level::av1(&config), + }; let (width, height, fps, gop_size) = ( config.width, config.height, @@ -877,6 +882,7 @@ fn open_vk(config: EncoderConfig) -> Result { gop_size, rate, profile: vk_h264_profile(config.h264_profile), + level, colour, }, )?), @@ -889,6 +895,7 @@ fn open_vk(config: EncoderConfig) -> Result { gop_size, rate, bit_depth: config.bit_depth, + level, colour, }, )?), @@ -901,6 +908,7 @@ fn open_vk(config: EncoderConfig) -> Result { gop_size, rate, bit_depth: config.bit_depth, + level, colour, }, )?), diff --git a/crates/ec-hw/src/level.rs b/crates/ec-hw/src/level.rs new file mode 100644 index 00000000..fb3c03a0 --- /dev/null +++ b/crates/ec-hw/src/level.rs @@ -0,0 +1,150 @@ +//! Level selection shared by both encoder backends. +//! +//! Each function returns the smallest level whose picture size, sample rate, +//! DPB and bitrate limits hold for the configuration. The Vulkan shim clamps +//! the result to the driver's maximum. + +use crate::types::{EncoderConfig, H264Profile, RateControlMode}; + +/// `max_dec_pic_buffering` the encoders signal: one reference, no reordering. +const DPB_FRAMES: u64 = 1; + +/// H.264 luma macroblock size; the coded picture is a whole number of them. +const H264_BLOCK: u32 = 16; + +/// `(level_idc, MaxMBPS, MaxFS, MaxDpbMbs, MaxBR kbit/s)`, Table A-1. +const H264_LEVELS: [(u8, u64, u64, u64, u64); 19] = [ + (10, 1485, 99, 396, 64), + (11, 3000, 396, 900, 192), + (12, 6000, 396, 2376, 384), + (13, 11880, 396, 2376, 768), + (20, 11880, 396, 2376, 2000), + (21, 19800, 792, 4752, 4000), + (22, 20250, 1620, 8100, 4000), + (30, 40500, 1620, 8100, 10000), + (31, 108000, 3600, 18000, 14000), + (32, 216000, 5120, 20480, 20000), + (40, 245760, 8192, 32768, 20000), + (41, 245760, 8192, 32768, 50000), + (42, 522240, 8704, 34816, 50000), + (50, 589824, 22080, 110400, 135000), + (51, 983040, 36864, 184320, 240000), + (52, 2073600, 36864, 184320, 240000), + (60, 4177920, 139264, 696320, 240000), + (61, 8355840, 139264, 696320, 480000), + (62, 16711680, 139264, 696320, 800000), +]; + +/// `(general_level_idc, MaxLumaPs, MaxLumaSr, Main tier MaxBR kbit/s)`, Table A.8. +const HEVC_LEVELS: [(u8, u64, u64, u64); 13] = [ + (30, 36864, 552960, 128), + (60, 122880, 3686400, 1500), + (63, 245760, 7372800, 3000), + (90, 552960, 16588800, 6000), + (93, 983040, 33177600, 10000), + (120, 2228224, 66846720, 12000), + (123, 2228224, 133693440, 20000), + (150, 8912896, 267386880, 25000), + (153, 8912896, 534773760, 40000), + (156, 8912896, 1069547520, 60000), + (180, 35651584, 1069547520, 60000), + (183, 35651584, 2139095040, 120000), + (186, 35651584, 4278190080, 240000), +]; + +/// `(seq_level_idx, MaxPicSize, MaxHSize, MaxVSize, MaxDisplayRate, MainMbps kbit/s)`, Annex A. +const AV1_LEVELS: [(u8, u64, u32, u32, u64, u64); 14] = [ + (0, 147_456, 2_048, 1_152, 4_423_680, 1_500), + (1, 278_784, 2_816, 1_584, 8_363_520, 3_000), + (4, 665_856, 4_352, 2_448, 19_975_680, 6_000), + (5, 1_065_024, 5_504, 3_096, 31_950_720, 10_000), + (8, 2_359_296, 6_144, 3_456, 70_778_880, 12_000), + (9, 2_359_296, 6_144, 3_456, 141_557_760, 20_000), + (12, 8_912_896, 8_192, 4_352, 267_386_880, 30_000), + (13, 8_912_896, 8_192, 4_352, 534_773_760, 40_000), + (14, 8_912_896, 8_192, 4_352, 1_069_547_520, 60_000), + (15, 8_912_896, 8_192, 4_352, 1_069_547_520, 60_000), + (16, 35_651_584, 16_384, 8_704, 1_069_547_520, 60_000), + (17, 35_651_584, 16_384, 8_704, 2_139_095_040, 100_000), + (18, 35_651_584, 16_384, 8_704, 4_278_190_080, 160_000), + (19, 35_651_584, 16_384, 8_704, 4_278_190_080, 160_000), +]; + +const H264_MAX_LEVEL: u8 = 62; +const HEVC_MAX_LEVEL: u8 = 186; +const AV1_MAX_LEVEL: u8 = 31; + +fn aligned(value: u32, block: u32) -> u64 { + u64::from(value.next_multiple_of(block)) +} + +/// Whether `samples` per picture at the frame rate stay within `limit` per second. +fn rate_fits(samples: u64, framerate: (u32, u32), limit: u64) -> bool { + let (num, den) = (u64::from(framerate.0.max(1)), u64::from(framerate.1.max(1))); + samples * num <= limit * den +} + +/// The bitrate the level must carry, or `None` when the quantiser is fixed. +fn bitrate(config: &EncoderConfig) -> Option { + match config.rate_control { + RateControlMode::ConstantQp { .. } => None, + _ => Some(u64::from(config.bitrate)), + } +} + +/// `level_idc` of the lowest H.264 level that fits `config`. +pub(crate) fn h264(config: &EncoderConfig) -> u8 { + let mbs = (aligned(config.width, H264_BLOCK) / 16) * (aligned(config.height, H264_BLOCK) / 16); + let (w, h) = (aligned(config.width, H264_BLOCK) / 16, aligned(config.height, H264_BLOCK) / 16); + let nal_factor = if config.h264_profile == H264Profile::High { + 1500 + } else { + 1200 + }; + let bitrate = bitrate(config); + H264_LEVELS + .iter() + .find(|&&(_, mbps, fs, dpb, br)| { + rate_fits(mbs, config.framerate, mbps) + && mbs <= fs + && w * w <= 8 * fs + && h * h <= 8 * fs + && mbs * DPB_FRAMES <= dpb + && bitrate.is_none_or(|b| b <= br * nal_factor) + }) + .map_or(H264_MAX_LEVEL, |level| level.0) +} + +/// `general_level_idc` of the lowest Main-tier H.265 level that fits `config`. +pub(crate) fn hevc(config: &EncoderConfig) -> u8 { + let (w, h) = (u64::from(config.width), u64::from(config.height)); + let samples = w * h; + let bitrate = bitrate(config); + HEVC_LEVELS + .iter() + .find(|&&(_, max_ps, max_sr, br)| { + samples <= max_ps + && w * w <= 8 * max_ps + && h * h <= 8 * max_ps + && rate_fits(samples, config.framerate, max_sr) + && bitrate.is_none_or(|b| b * 10 <= br * 1000 * 11) + }) + .map_or(HEVC_MAX_LEVEL, |level| level.0) +} + +/// `seq_level_idx` of the lowest AV1 level that fits `config`. +pub(crate) fn av1(config: &EncoderConfig) -> u8 { + let (width, height) = (config.width.max(1), config.height.max(1)); + let samples = u64::from(width) * u64::from(height); + let bitrate = bitrate(config); + AV1_LEVELS + .iter() + .find(|&&(_, max_size, max_w, max_h, max_rate, main_kbps)| { + samples <= max_size + && width <= max_w + && height <= max_h + && rate_fits(samples, config.framerate, max_rate) + && bitrate.is_none_or(|b| b <= main_kbps * 1000) + }) + .map_or(AV1_MAX_LEVEL, |level| level.0) +} diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 0e38e90c..a6d93c28 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -63,6 +63,7 @@ pub mod error; pub(crate) mod dpb264; #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub(crate) mod h264_common; +pub(crate) mod level; pub(crate) mod rate; pub(crate) mod ref_slots; pub(crate) mod vkdec_vp9; diff --git a/crates/ec-vk/examples/av1_encode.rs b/crates/ec-vk/examples/av1_encode.rs index 865c6d87..20a6d299 100644 --- a/crates/ec-vk/examples/av1_encode.rs +++ b/crates/ec-vk/examples/av1_encode.rs @@ -27,6 +27,7 @@ fn main() { width: W, height: H, fps: (FPS, 1), + level: 23, gop_size: 30, rate: match std::env::args().nth(2) { Some(b) => RateControl::Cbr { diff --git a/crates/ec-vk/examples/h264_encode.rs b/crates/ec-vk/examples/h264_encode.rs index 1c588db4..e240a352 100644 --- a/crates/ec-vk/examples/h264_encode.rs +++ b/crates/ec-vk/examples/h264_encode.rs @@ -26,6 +26,7 @@ fn main() { width: W, height: H, fps: (30, 1), + level: 62, gop_size: 30, profile: H264Profile::High, colour: None, diff --git a/crates/ec-vk/examples/h265_encode.rs b/crates/ec-vk/examples/h265_encode.rs index d7d7da0b..ca84dddb 100644 --- a/crates/ec-vk/examples/h265_encode.rs +++ b/crates/ec-vk/examples/h265_encode.rs @@ -26,6 +26,7 @@ fn main() { width: W, height: H, fps: (30, 1), + level: 186, gop_size: 30, rate: match std::env::args().nth(2) { Some(b) => RateControl::Cbr { diff --git a/crates/ec-vk/src/av1.rs b/crates/ec-vk/src/av1.rs index b8cd96eb..80271047 100644 --- a/crates/ec-vk/src/av1.rs +++ b/crates/ec-vk/src/av1.rs @@ -21,6 +21,8 @@ pub struct Av1EncoderConfig { pub rate: RateControl, /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`). pub bit_depth: u8, + /// `seq_level_idx`, clamped to the driver maximum. + pub level: u8, /// Colour config of the sequence header, or none. pub colour: Option, } @@ -54,6 +56,7 @@ impl Av1Encoder { fps: cfg.fps, rate: cfg.rate, bit_depth: cfg.bit_depth, + level: cfg.level, colour: cfg.colour, }, )?; diff --git a/crates/ec-vk/src/h265.rs b/crates/ec-vk/src/h265.rs index 66cbdd43..0a62d4af 100644 --- a/crates/ec-vk/src/h265.rs +++ b/crates/ec-vk/src/h265.rs @@ -19,6 +19,8 @@ pub struct H265EncoderConfig { pub rate: RateControl, /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`). pub bit_depth: u8, + /// `general_level_idc`, clamped to the driver maximum. + pub level: u8, /// Colour description for the VUI, or none. pub colour: Option, } @@ -52,6 +54,7 @@ impl H265Encoder { fps: cfg.fps, rate: cfg.rate, bit_depth: cfg.bit_depth, + level: cfg.level, colour: cfg.colour, }, )?; diff --git a/crates/ec-vk/src/lib.rs b/crates/ec-vk/src/lib.rs index 0cbe2cb3..a76a8ba4 100644 --- a/crates/ec-vk/src/lib.rs +++ b/crates/ec-vk/src/lib.rs @@ -41,6 +41,8 @@ pub struct H264EncoderConfig { pub rate: RateControl, /// H.264 profile. pub profile: H264Profile, + /// `level_idc`, clamped to the driver maximum. + pub level: u8, /// Colour description for the VUI, or none. pub colour: Option, } @@ -107,6 +109,7 @@ impl H264Encoder { fps: cfg.fps, rate: cfg.rate, profile: cfg.profile, + level: cfg.level, colour: cfg.colour, }, )?; diff --git a/shims/vk-video-ffi/examples/dmabuf_smoke.rs b/shims/vk-video-ffi/examples/dmabuf_smoke.rs index fe722868..9b377b02 100644 --- a/shims/vk-video-ffi/examples/dmabuf_smoke.rs +++ b/shims/vk-video-ffi/examples/dmabuf_smoke.rs @@ -88,6 +88,7 @@ impl Encode for H264EncodeSession { fps: FPS, rate: RATE, profile: H264Profile::High, + level: 62, colour: None, }; H264EncodeSession::new(gpu, &cfg) @@ -130,6 +131,7 @@ impl Encode for H265EncodeSession { fps: FPS, rate: RATE, bit_depth: bits, + level: 186, colour: None, }; H265EncodeSession::new(gpu, &cfg) @@ -174,6 +176,7 @@ impl Encode for Av1EncodeSession { fps: FPS, rate: RATE, bit_depth: bits, + level: 23, colour: None, }; Av1EncodeSession::new(gpu, &cfg) diff --git a/shims/vk-video-ffi/src/av1_encode.rs b/shims/vk-video-ffi/src/av1_encode.rs index 71fcbc35..e9b55895 100644 --- a/shims/vk-video-ffi/src/av1_encode.rs +++ b/shims/vk-video-ffi/src/av1_encode.rs @@ -13,7 +13,6 @@ use crate::session::{ use crate::{Colour, Error, Gpu, RateControl}; const AV1_SLOTS: usize = 8; -const LEVEL: vk::video::StdVideoAV1Level = vk::video::STD_VIDEO_AV1_LEVEL_5_1; const CBR_Q_INDEX: u32 = 128; /// Settings fixed for the life of an AV1 session. @@ -29,6 +28,8 @@ pub struct Av1EncodeConfig { pub rate: RateControl, /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input). pub bit_depth: u8, + /// `seq_level_idx` (0 to 23), chosen by the caller and clamped to the driver maximum. + pub level: u8, /// Colour config of the sequence header, or none (unspecified). pub colour: Option, } @@ -62,6 +63,7 @@ struct Caps { rc_modes: vk::VideoEncodeRateControlModeFlagsKHR, single_ref: bool, sb64: bool, + max_level: vk::video::StdVideoAV1Level, } struct Profile { @@ -180,6 +182,7 @@ impl Av1EncodeSession { if !caps.single_ref { return Err(Error::Unsupported("AV1 single LAST reference".into())); } + let level = av1_level(cfg.level, caps.max_level)?; let mode = match cfg.rate { RateControl::ConstantQp { .. } => vk::VideoEncodeRateControlModeFlagsKHR::DISABLED, RateControl::Cbr { .. } => vk::VideoEncodeRateControlModeFlagsKHR::CBR, @@ -214,11 +217,11 @@ impl Av1EncodeSession { (cfg.rate, cfg.fps), caps.size_align, )?; - let params = create_parameters(&enc.vs, extent, sb128, cfg)?; + let params = create_parameters(&enc.vs, extent, sb128, cfg, level)?; enc.vs.set_params(params); Ok(Av1EncodeSession { enc, - seq: sequence_header_obu(cfg, sb128), + seq: sequence_header_obu(cfg, sb128, level), slot_key: [false; DPB_SLOTS], ref_order_hint: [0; AV1_SLOTS], }) @@ -503,6 +506,7 @@ fn create_parameters( extent: vk::Extent2D, sb128: bool, cfg: &Av1EncodeConfig, + level: vk::video::StdVideoAV1Level, ) -> Result { let mut color = zeroed::(); color.BitDepth = cfg.bit_depth; @@ -521,9 +525,15 @@ fn create_parameters( color.matrix_coefficients = vk::video::StdVideoAV1MatrixCoefficients(i32::from(c.matrix)); } + let mut timing = zeroed::(); + timing.flags.set_equal_picture_interval(1); + timing.num_units_in_display_tick = cfg.fps.1; + timing.time_scale = cfg.fps.0; let mut seq = zeroed::(); seq.flags.set_enable_order_hint(1); seq.flags.set_use_128x128_superblock(sb128 as u32); + seq.flags.set_timing_info_present_flag(1); + seq.pTimingInfo = &timing; seq.seq_profile = vk::video::STD_VIDEO_AV1_PROFILE_MAIN; seq.frame_width_bits_minus_1 = (bits(extent.width) - 1) as u8; seq.frame_height_bits_minus_1 = (bits(extent.height) - 1) as u8; @@ -534,7 +544,7 @@ fn create_parameters( seq.pColorConfig = &color; let mut op = zeroed::(); - op.seq_level_idx = LEVEL.0 as u8; + op.seq_level_idx = level.0 as u8; let mut av1 = vk::VideoEncodeAV1SessionParametersCreateInfoKHR { std_sequence_header: &seq, @@ -596,18 +606,29 @@ fn obu(kind: u8, payload: &[u8]) -> Vec { out } -fn sequence_header_obu(cfg: &Av1EncodeConfig, sb128: bool) -> Vec { +fn sequence_header_obu( + cfg: &Av1EncodeConfig, + sb128: bool, + level: vk::video::StdVideoAV1Level, +) -> Vec { let (width, height, bit_depth) = (cfg.width, cfg.height, cfg.bit_depth); let mut b = Bits(Vec::new()); b.put(0, 3); b.put(0, 1); b.put(0, 1); + b.put(1, 1); + b.put(cfg.fps.1, 32); + b.put(cfg.fps.0, 32); + b.put(1, 1); + b.put(1, 1); b.put(0, 1); b.put(0, 1); b.put(0, 5); b.put(0, 12); - b.put(LEVEL.0 as u32, 5); - b.put(0, 1); + b.put(level.0 as u32, 5); + if level.0 > 7 { + b.put(0, 1); + } b.put(bits(width) - 1, 4); b.put(bits(height) - 1, 4); b.put(width - 1, bits(width)); @@ -700,5 +721,17 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result Result { + if idx > 23 { + return Err(Error::Invalid(format!("AV1 seq_level_idx {idx}"))); + } + let level = vk::video::StdVideoAV1Level(i32::from(idx)); + Ok(if level.0 > driver_max.0 { driver_max } else { level }) +} diff --git a/shims/vk-video-ffi/src/h264_encode.rs b/shims/vk-video-ffi/src/h264_encode.rs index 6b08b66c..990c9280 100644 --- a/shims/vk-video-ffi/src/h264_encode.rs +++ b/shims/vk-video-ffi/src/h264_encode.rs @@ -55,6 +55,8 @@ pub struct H264EncodeConfig { pub rate: RateControl, /// H.264 profile. pub profile: H264Profile, + /// `level_idc` (10 to 62), chosen by the caller and clamped to the driver maximum. + pub level: u8, /// Colour description for the VUI, or none. pub colour: Option, } @@ -93,6 +95,7 @@ struct Caps { size_align: u64, rc_modes: vk::VideoEncodeRateControlModeFlagsKHR, max_refs: u32, + max_level: vk::video::StdVideoH264LevelIdc, } struct Profile { @@ -203,12 +206,12 @@ impl H264EncodeSession { } let width = align(cfg.width, 16); let height = align(cfg.height, 16); - let level = level_for(width, height, cfg.fps)?; let profile = Profile::new(cfg.profile); let caps = query_caps(gpu, &profile.info).map_err(|e| match e { Error::Vk(..) => Error::Unsupported(format!("H.264 {:?} encode", cfg.profile)), other => other, })?; + let level = h264_level(cfg.level, caps.max_level)?; if width > caps.max_extent.width || height > caps.max_extent.height { return Err(Error::Unsupported(format!("H.264 encode {width}x{height}"))); } @@ -579,25 +582,6 @@ pub(crate) fn validate( validate_rate(fps, rate) } -fn level_for( - width: u32, - height: u32, - fps: (u32, u32), -) -> Result { - let mbs = (width / 16) as u64 * (height / 16) as u64; - let table = [ - (8160u64, 245760u64, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_1), - (8704, 522240, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_2), - (36864, 983040, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_1), - (36864, 2073600, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_2), - ]; - table - .into_iter() - .find(|&(frame, mbps, _)| mbs <= frame && mbs * fps.0 as u64 <= mbps * fps.1 as u64) - .map(|(_, _, level)| level) - .ok_or_else(|| Error::Unsupported(format!("H.264 level for {width}x{height} at {fps:?}"))) -} - fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result { let mut h264 = vk::VideoEncodeH264CapabilitiesKHR::builder(); let mut encode = vk::VideoEncodeCapabilitiesKHR::builder(); @@ -611,6 +595,7 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result Result { + const LEVELS: [(u8, vk::video::StdVideoH264LevelIdc); 19] = [ + (10, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_0), + (11, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_1), + (12, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_2), + (13, vk::video::STD_VIDEO_H264_LEVEL_IDC_1_3), + (20, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_0), + (21, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_1), + (22, vk::video::STD_VIDEO_H264_LEVEL_IDC_2_2), + (30, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_0), + (31, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_1), + (32, vk::video::STD_VIDEO_H264_LEVEL_IDC_3_2), + (40, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_0), + (41, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_1), + (42, vk::video::STD_VIDEO_H264_LEVEL_IDC_4_2), + (50, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_0), + (51, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_1), + (52, vk::video::STD_VIDEO_H264_LEVEL_IDC_5_2), + (60, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_0), + (61, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_1), + (62, vk::video::STD_VIDEO_H264_LEVEL_IDC_6_2), + ]; + let (_, level) = LEVELS + .into_iter() + .find(|(value, _)| *value == idc) + .ok_or_else(|| Error::Invalid(format!("H.264 level_idc {idc}")))?; + Ok(if level.0 > driver_max.0 { driver_max } else { level }) +} diff --git a/shims/vk-video-ffi/src/h265_encode.rs b/shims/vk-video-ffi/src/h265_encode.rs index 8b61a669..91e8e0d7 100644 --- a/shims/vk-video-ffi/src/h265_encode.rs +++ b/shims/vk-video-ffi/src/h265_encode.rs @@ -28,6 +28,8 @@ pub struct H265EncodeConfig { pub rate: RateControl, /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input). pub bit_depth: u8, + /// `general_level_idc` (30 to 186), chosen by the caller and clamped to the driver maximum. + pub level: u8, /// Colour description for the VUI, or none. pub colour: Option, } @@ -60,6 +62,7 @@ struct Caps { size_align: u64, rc_modes: vk::VideoEncodeRateControlModeFlagsKHR, max_refs: u32, + max_level: vk::video::StdVideoH265LevelIdc, ctb_sizes: vk::VideoEncodeH265CtbSizeFlagsKHR, transform_sizes: vk::VideoEncodeH265TransformBlockSizeFlagsKHR, std_flags: vk::VideoEncodeH265StdFlagsKHR, @@ -647,7 +650,7 @@ fn coding(caps: &Caps, cfg: &H265EncodeConfig) -> Result { transform_skip: caps .std_flags .contains(vk::VideoEncodeH265StdFlagsKHR::TRANSFORM_SKIP_ENABLED_FLAG_SET), - level: level_for(width, height, cfg.fps)?, + level: h265_level(cfg.level, caps.max_level)?, }) } @@ -659,27 +662,30 @@ fn profile_idc(bit_depth: u8) -> vk::video::StdVideoH265ProfileIdc { } } -fn level_for( - width: u32, - height: u32, - fps: (u32, u32), +fn h265_level( + idc: u8, + driver_max: vk::video::StdVideoH265LevelIdc, ) -> Result { - let luma = width as u64 * height as u64; - let table = [ - ( - 983040u64, - 33177600u64, - vk::video::STD_VIDEO_H265_LEVEL_IDC_3_1, - ), - (2228224, 66846720, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_0), - (2228224, 133693440, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_1), - (8912896, 267386880, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_0), + const LEVELS: [(u8, vk::video::StdVideoH265LevelIdc); 13] = [ + (30, vk::video::STD_VIDEO_H265_LEVEL_IDC_1_0), + (60, vk::video::STD_VIDEO_H265_LEVEL_IDC_2_0), + (63, vk::video::STD_VIDEO_H265_LEVEL_IDC_2_1), + (90, vk::video::STD_VIDEO_H265_LEVEL_IDC_3_0), + (93, vk::video::STD_VIDEO_H265_LEVEL_IDC_3_1), + (120, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_0), + (123, vk::video::STD_VIDEO_H265_LEVEL_IDC_4_1), + (150, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_0), + (153, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_1), + (156, vk::video::STD_VIDEO_H265_LEVEL_IDC_5_2), + (180, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_0), + (183, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_1), + (186, vk::video::STD_VIDEO_H265_LEVEL_IDC_6_2), ]; - table + let (_, level) = LEVELS .into_iter() - .find(|&(ps, sr, _)| luma <= ps && luma * fps.0 as u64 <= sr * fps.1 as u64) - .map(|(_, _, level)| level) - .ok_or_else(|| Error::Unsupported(format!("H.265 level for {width}x{height} at {fps:?}"))) + .find(|(value, _)| *value == idc) + .ok_or_else(|| Error::Invalid(format!("H.265 general_level_idc {idc}")))?; + Ok(if level.0 > driver_max.0 { driver_max } else { level }) } fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result { @@ -695,6 +701,7 @@ fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result