Merge branch 'lane-hwav1enc' (eda549f4): VAAPI AV1 hardware encode, on by default, agreed by two decoders
Browse files at this commit9 changed files +922 -81
- Cargo.lock +3 -0
- crates/ec-hw/Cargo.toml +4 -0
- crates/ec-hw/src/enc/av1.rs +158 -30
- crates/ec-hw/src/enc/headers.rs +259 -0
- crates/ec-hw/src/enc/mod.rs +21 -17
- crates/ec-hw/src/lib.rs +1 -1
- crates/ec-hw/tests/gpu.rs +402 -33
- tools/ec-bench/Cargo.toml +2 -0
- tools/ec-bench/src/main.rs +72 -0
Cargo.lockmodified+3 -0
| @@ -285,12 +285,14 @@ dependencies = [ | |||
| 285 | "ec-h264", | 285 | "ec-h264", |
| 286 | "ec-h264-syntax", | 286 | "ec-h264-syntax", |
| 287 | "ec-h265", | 287 | "ec-h265", |
| 288 | + "ec-hw", | ||
| 288 | "ec-image", | 289 | "ec-image", |
| 289 | "ec-inflate", | 290 | "ec-inflate", |
| 290 | "ec-mp3", | 291 | "ec-mp3", |
| 291 | "ec-opus", | 292 | "ec-opus", |
| 292 | "ec-probe", | 293 | "ec-probe", |
| 293 | "ec-truehd", | 294 | "ec-truehd", |
| 295 | + "ec-va", | ||
| 294 | "ec-vorbis", | 296 | "ec-vorbis", |
| 295 | ] | 297 | ] |
| 296 | 298 | ||
| @@ -351,6 +353,7 @@ dependencies = [ | |||
| 351 | name = "ec-hw" | 353 | name = "ec-hw" |
| 352 | version = "0.1.0" | 354 | version = "0.1.0" |
| 353 | dependencies = [ | 355 | dependencies = [ |
| 356 | + "ec-av1", | ||
| 354 | "ec-av1-syntax", | 357 | "ec-av1-syntax", |
| 355 | "ec-core", | 358 | "ec-core", |
| 356 | "ec-h264-syntax", | 359 | "ec-h264-syntax", |
crates/ec-hw/Cargo.tomlmodified+4 -0
| @@ -13,3 +13,7 @@ ec-h264-syntax.workspace = true | |||
| 13 | ec-h265-syntax.workspace = true | 13 | ec-h265-syntax.workspace = true |
| 14 | ec-va.workspace = true | 14 | ec-va.workspace = true |
| 15 | ec-vp9-syntax.workspace = true | 15 | ec-vp9-syntax.workspace = true |
| 16 | + | ||
| 17 | +[dev-dependencies] | ||
| 18 | +# The second, independent decoder the AV1 encode gate compares ffmpeg against. | ||
| 19 | +ec-av1.workspace = true | ||
crates/ec-hw/src/enc/av1.rsmodified+158 -30
| @@ -1,15 +1,21 @@ | |||
| 1 | -//! AV1 encode parameters — opt-in only. | 1 | +//! AV1 encode parameters. |
| 2 | //! | 2 | //! |
| 3 | -//! Kept deliberately minimal: one tile, one reference, no segmentation, no | 3 | +//! One tile, one reference, no segmentation, no superres, no film grain: the |
| 4 | -//! superres, no film grain. The point of this path today is that it exists, | 4 | +//! subset this driver advertises (`VAConfigAttribEncAV1` on radeonsi reports |
| 5 | -//! compiles, and either produces a frame or a typed error — never a panic and | 5 | +//! no filter intra, no warped motion, no dual filter, no superres and no |
| 6 | -//! never a submission this crate cannot describe. See the module docs of | 6 | +//! restoration) and the same subset ffmpeg's `av1_vaapi` encoder writes. |
| 7 | -//! [`super`] for why it is not on by default. | 7 | +//! |
| 8 | +//! The driver does not compose the headers: it parses the sequence header and | ||
| 9 | +//! frame header OBUs this module packs (see [`super::headers::av1`]) and | ||
| 10 | +//! writes the stream's own headers from them together with the picture | ||
| 11 | +//! parameter buffer below. Both therefore describe one picture, or the coded | ||
| 12 | +//! frame is not the frame that was submitted. | ||
| 8 | 13 | ||
| 9 | use std::sync::Arc; | 14 | use std::sync::Arc; |
| 10 | 15 | ||
| 11 | use ec_va::Buffer; | 16 | use ec_va::Buffer; |
| 12 | 17 | ||
| 18 | +use super::headers::av1 as av1_headers; | ||
| 13 | use super::{Encoder, RateControlMode}; | 19 | use super::{Encoder, RateControlMode}; |
| 14 | use crate::error::Result; | 20 | use crate::error::Result; |
| 15 | use crate::params::enc::{ | 21 | use crate::params::enc::{ |
| @@ -17,10 +23,20 @@ use crate::params::enc::{ | |||
| 17 | }; | 23 | }; |
| 18 | use crate::params::param_buffer; | 24 | use crate::params::param_buffer; |
| 19 | use crate::pool::PooledSurface; | 25 | use crate::pool::PooledSurface; |
| 26 | +use crate::params::INVALID_SURFACE; | ||
| 20 | 27 | ||
| 21 | /// `KEY_FRAME` and `INTER_FRAME` (spec 6.8.2). | 28 | /// `KEY_FRAME` and `INTER_FRAME` (spec 6.8.2). |
| 22 | const KEY_FRAME: u32 = 0; | 29 | const KEY_FRAME: u32 = 0; |
| 23 | const INTER_FRAME: u32 = 1; | 30 | const INTER_FRAME: u32 = 1; |
| 31 | +/// `PRIMARY_REF_NONE`. | ||
| 32 | +const PRIMARY_REF_NONE: u8 = 7; | ||
| 33 | +/// `TX_MODE_SELECT`, the only mode this driver advertises. | ||
| 34 | +const TX_MODE_SELECT: u32 = 2; | ||
| 35 | +/// `SWITCHABLE` interpolation filter. | ||
| 36 | +const INTERP_SWITCHABLE: u8 = 4; | ||
| 37 | +/// The deblocking level written into the header; the driver picks its own for | ||
| 38 | +/// the stream it writes, so this is only the value it starts from. | ||
| 39 | +const LOOP_FILTER_LEVEL: u8 = 1; | ||
| 24 | 40 | ||
| 25 | pub(super) fn parameters( | 41 | pub(super) fn parameters( |
| 26 | encoder: &Encoder, | 42 | encoder: &Encoder, |
| @@ -32,18 +48,21 @@ pub(super) fn parameters( | |||
| 32 | let config = *encoder.config(); | 48 | let config = *encoder.config(); |
| 33 | let context = encoder.context(); | 49 | let context = encoder.context(); |
| 34 | let (coded_w, coded_h) = encoder.coded_size(); | 50 | let (coded_w, coded_h) = encoder.coded_size(); |
| 51 | + let (width, height) = (config.width.max(1), config.height.max(1)); | ||
| 52 | + let cqp = matches!(config.rate_control, RateControlMode::ConstantQp { .. }); | ||
| 53 | + let level_idx = seq_level_idx(coded_w, coded_h, config.framerate); | ||
| 35 | 54 | ||
| 36 | let mut seq = EncSequenceParameterBufferAV1 { | 55 | let mut seq = EncSequenceParameterBufferAV1 { |
| 37 | seq_profile: 0, | 56 | seq_profile: 0, |
| 38 | - // 0 lets the driver pick the level from the picture size and rate. | 57 | + seq_level_idx: level_idx, |
| 39 | - seq_level_idx: 0, | 58 | + seq_tier: 0, |
| 40 | intra_period: config.gop_size.max(1), | 59 | intra_period: config.gop_size.max(1), |
| 41 | ip_period: 1, | 60 | ip_period: 1, |
| 42 | bits_per_second: match config.rate_control { | 61 | bits_per_second: match config.rate_control { |
| 43 | RateControlMode::ConstantBitrate => config.bitrate, | 62 | RateControlMode::ConstantBitrate => config.bitrate, |
| 44 | RateControlMode::ConstantQp { .. } => 0, | 63 | RateControlMode::ConstantQp { .. } => 0, |
| 45 | }, | 64 | }, |
| 46 | - order_hint_bits_minus_1: 6, | 65 | + order_hint_bits_minus_1: (av1_headers::ORDER_HINT_BITS - 1) as u8, |
| 47 | ..EncSequenceParameterBufferAV1::default() | 66 | ..EncSequenceParameterBufferAV1::default() |
| 48 | }; | 67 | }; |
| 49 | seq.seq_fields = seq | 68 | seq.seq_fields = seq |
| @@ -54,42 +73,108 @@ pub(super) fn parameters( | |||
| 54 | .subsampling_y(1); | 73 | .subsampling_y(1); |
| 55 | out.push(param_buffer(context, &seq)?); | 74 | out.push(param_buffer(context, &seq)?); |
| 56 | 75 | ||
| 57 | - let order_hint = (encoder.gop_position() % 128) as u8; | 76 | + // Superblocks are 64x64: use_128x128_superblock is off in the sequence |
| 77 | + // header, and this driver advertises no support for the larger one. | ||
| 78 | + let sb_cols = coded_w.div_ceil(64).max(1); | ||
| 79 | + let sb_rows = coded_h.div_ceil(64).max(1); | ||
| 80 | + let order_hint = if keyframe { | ||
| 81 | + 0 | ||
| 82 | + } else { | ||
| 83 | + (encoder.gop_position() % 256) as u8 | ||
| 84 | + }; | ||
| 85 | + let base_qindex = match config.rate_control { | ||
| 86 | + RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, | ||
| 87 | + RateControlMode::ConstantBitrate => 128, | ||
| 88 | + }; | ||
| 89 | + // One reference, refreshed every picture: slot 0 holds the previous | ||
| 90 | + // reconstruction and every ref_frame_idx points at it. | ||
| 91 | + let refresh_frame_flags = if keyframe { 0xff } else { 0x01 }; | ||
| 92 | + | ||
| 58 | let mut pic = EncPictureParameterBufferAV1 { | 93 | let mut pic = EncPictureParameterBufferAV1 { |
| 59 | - frame_width_minus_1: (config.width.max(1) - 1) as u16, | 94 | + frame_width_minus_1: (width - 1) as u16, |
| 60 | - frame_height_minus_1: (config.height.max(1) - 1) as u16, | 95 | + frame_height_minus_1: (height - 1) as u16, |
| 61 | reconstructed_frame: recon.id(), | 96 | reconstructed_frame: recon.id(), |
| 62 | coded_buf, | 97 | coded_buf, |
| 63 | - primary_ref_frame: 7, // PRIMARY_REF_NONE | 98 | + primary_ref_frame: if keyframe { PRIMARY_REF_NONE } else { 0 }, |
| 64 | order_hint, | 99 | order_hint, |
| 65 | - refresh_frame_flags: 0xff, | 100 | + refresh_frame_flags, |
| 66 | - base_qindex: match config.rate_control { | 101 | + base_qindex, |
| 67 | - RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, | 102 | + min_base_qindex: if cqp { 0 } else { 1 }, |
| 68 | - RateControlMode::ConstantBitrate => 128, | 103 | + max_base_qindex: if cqp { 0 } else { 255 }, |
| 69 | - }, | 104 | + filter_level: [LOOP_FILTER_LEVEL; 2], |
| 70 | - min_base_qindex: 1, | 105 | + filter_level_u: LOOP_FILTER_LEVEL, |
| 71 | - max_base_qindex: 255, | 106 | + filter_level_v: LOOP_FILTER_LEVEL, |
| 107 | + interpolation_filter: INTERP_SWITCHABLE, | ||
| 72 | tile_cols: 1, | 108 | tile_cols: 1, |
| 73 | tile_rows: 1, | 109 | tile_rows: 1, |
| 74 | superres_scale_denominator: 8, | 110 | superres_scale_denominator: 8, |
| 75 | ..EncPictureParameterBufferAV1::default() | 111 | ..EncPictureParameterBufferAV1::default() |
| 76 | }; | 112 | }; |
| 77 | - // One tile covering the whole frame, in 64x64 superblocks. | 113 | + pic.width_in_sbs_minus_1[0] = (sb_cols - 1) as u16; |
| 78 | - pic.width_in_sbs_minus_1[0] = (coded_w.div_ceil(64).max(1) - 1) as u16; | 114 | + pic.height_in_sbs_minus_1[0] = (sb_rows - 1) as u16; |
| 79 | - pic.height_in_sbs_minus_1[0] = (coded_h.div_ceil(64).max(1) - 1) as u16; | ||
| 80 | if let Some(reference) = encoder.reference().filter(|_| !keyframe) { | 115 | if let Some(reference) = encoder.reference().filter(|_| !keyframe) { |
| 81 | - for slot in pic.reference_frames.iter_mut() { | 116 | + pic.reference_frames[0] = reference.id(); |
| 82 | - *slot = reference.id(); | 117 | + // ref_frame_ctrl_l0 = LAST_FRAME in search_idx0 (bits 0..2). |
| 83 | - } | 118 | + pic.ref_frame_ctrl_l0 = 1; |
| 84 | - pic.primary_ref_frame = 0; | ||
| 85 | } | 119 | } |
| 86 | pic.picture_flags = pic | 120 | pic.picture_flags = pic |
| 87 | .picture_flags | 121 | .picture_flags |
| 88 | .frame_type(if keyframe { KEY_FRAME } else { INTER_FRAME }) | 122 | .frame_type(if keyframe { KEY_FRAME } else { INTER_FRAME }) |
| 89 | - .disable_cdf_update(1) | 123 | + // A shown key frame is error resilient by inference (5.9.2). |
| 90 | - .disable_frame_end_update_cdf(1) | 124 | + .error_resilient_mode(u32::from(keyframe)) |
| 91 | - .enable_frame_obu(1); | 125 | + // The driver writes the frame header and the tile group as separate |
| 126 | + // OBUs, which is what the header packed below describes. | ||
| 127 | + .enable_frame_obu(0); | ||
| 128 | + pic.mode_control_flags = pic | ||
| 129 | + .mode_control_flags | ||
| 130 | + .tx_mode(TX_MODE_SELECT) | ||
| 131 | + // Single reference prediction: compound needs a second reference. | ||
| 132 | + .reference_mode(0); | ||
| 133 | + pic.tile_group_obu_hdr_info = pic.tile_group_obu_hdr_info.obu_has_size_field(1); | ||
| 134 | + for slot in pic.reference_frames.iter_mut().skip(1) { | ||
| 135 | + *slot = INVALID_SURFACE; | ||
| 136 | + } | ||
| 137 | + | ||
| 138 | + if keyframe { | ||
| 139 | + encoder.push_packed( | ||
| 140 | + &av1_headers::sequence_header(&av1_headers::SeqParams { | ||
| 141 | + width, | ||
| 142 | + height, | ||
| 143 | + seq_level_idx: level_idx, | ||
| 144 | + seq_tier: 0, | ||
| 145 | + high_bitdepth: false, | ||
| 146 | + colour: config.colour, | ||
| 147 | + }), | ||
| 148 | + out, | ||
| 149 | + )?; | ||
| 150 | + } | ||
| 151 | + let (packed, offsets) = av1_headers::frame_header(&av1_headers::FrameParams { | ||
| 152 | + keyframe, | ||
| 153 | + order_hint, | ||
| 154 | + primary_ref_frame: 0, | ||
| 155 | + refresh_frame_flags, | ||
| 156 | + ref_frame_idx: [0; 7], | ||
| 157 | + base_q_idx: base_qindex, | ||
| 158 | + loop_filter_level: [LOOP_FILTER_LEVEL; 4], | ||
| 159 | + tx_mode_select: true, | ||
| 160 | + max_tile_cols_log2: av1_headers::tile_log2(sb_cols.min(64)), | ||
| 161 | + max_tile_rows_log2: av1_headers::tile_log2(sb_rows.min(64)), | ||
| 162 | + }); | ||
| 163 | + if !cqp { | ||
| 164 | + // Outside CQP the driver picks the quantiser and the deblocking | ||
| 165 | + // levels itself and back-annotates them into the header it writes, | ||
| 166 | + // which is what these offsets are for (ffmpeg sets them on the same | ||
| 167 | + // condition). In CQP it has nothing to write back. | ||
| 168 | + pic.bit_offset_qindex = offsets.qindex; | ||
| 169 | + pic.bit_offset_segmentation = offsets.segmentation; | ||
| 170 | + pic.bit_offset_loopfilter_params = offsets.loop_filter; | ||
| 171 | + pic.bit_offset_cdef_params = offsets.cdef; | ||
| 172 | + pic.size_in_bits_cdef_params = offsets.cdef_size; | ||
| 173 | + pic.size_in_bits_frame_hdr_obu = offsets.total_bits; | ||
| 174 | + pic.byte_offset_frame_hdr_obu_size = offsets.obu_size_byte; | ||
| 175 | + } | ||
| 92 | out.push(param_buffer(context, &pic)?); | 176 | out.push(param_buffer(context, &pic)?); |
| 177 | + encoder.push_packed(&packed, out)?; | ||
| 93 | 178 | ||
| 94 | let tile_group = EncTileGroupBufferAV1 { | 179 | let tile_group = EncTileGroupBufferAV1 { |
| 95 | tg_start: 0, | 180 | tg_start: 0, |
| @@ -99,3 +184,46 @@ pub(super) fn parameters( | |||
| 99 | out.push(param_buffer(context, &tile_group)?); | 184 | out.push(param_buffer(context, &tile_group)?); |
| 100 | Ok(()) | 185 | Ok(()) |
| 101 | } | 186 | } |
| 187 | + | ||
| 188 | +/// The lowest AV1 level whose picture size and rate fit (Annex A), as a | ||
| 189 | +/// `seq_level_idx`. Levels below 2.0 do not exist, and anything past 6.3 is | ||
| 190 | +/// signalled as the maximum-parameters level. | ||
| 191 | +fn seq_level_idx(width: u32, height: u32, framerate: (u32, u32)) -> u8 { | ||
| 192 | + // (seq_level_idx, MaxPicSize, MaxHSize, MaxVSize, MaxDisplayRate) | ||
| 193 | + const LEVELS: [(u8, u64, u32, u32, u64); 12] = [ | ||
| 194 | + (0, 147_456, 2_048, 1_152, 4_423_680), // 2.0 | ||
| 195 | + (1, 278_784, 2_816, 1_584, 8_363_520), // 2.1 | ||
| 196 | + (4, 665_856, 4_352, 2_448, 19_975_680), // 3.0 | ||
| 197 | + (5, 1_065_024, 5_504, 3_096, 31_950_720), // 3.1 | ||
| 198 | + (8, 2_359_296, 6_144, 3_456, 70_778_880), // 4.0 | ||
| 199 | + (9, 2_359_296, 6_144, 3_456, 141_557_760), // 4.1 | ||
| 200 | + (12, 8_912_896, 8_192, 4_352, 267_386_880), // 5.0 | ||
| 201 | + (13, 8_912_896, 8_192, 4_352, 534_773_760), // 5.1 | ||
| 202 | + (14, 8_912_896, 8_192, 4_352, 1_069_547_520), // 5.2 | ||
| 203 | + (16, 35_651_584, 16_384, 8_704, 1_069_547_520), // 6.0 | ||
| 204 | + (17, 35_651_584, 16_384, 8_704, 2_139_095_040), // 6.1 | ||
| 205 | + (18, 35_651_584, 16_384, 8_704, 4_278_190_080), // 6.2 | ||
| 206 | + ]; | ||
| 207 | + let samples = u64::from(width) * u64::from(height); | ||
| 208 | + let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1)); | ||
| 209 | + let rate = (samples as f64 * fps).ceil() as u64; | ||
| 210 | + for &(idx, max_size, max_h, max_v, max_rate) in &LEVELS { | ||
| 211 | + if samples <= max_size && width <= max_h && height <= max_v && rate <= max_rate { | ||
| 212 | + return idx; | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | + 31 // maximum parameters | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +#[cfg(test)] | ||
| 219 | +mod tests { | ||
| 220 | + use super::*; | ||
| 221 | + | ||
| 222 | + #[test] | ||
| 223 | + fn levels_follow_size_and_rate() { | ||
| 224 | + // 1080p30 is 4.0 (idx 8), 2160p30 5.0 (12), 2160p60 5.1 (13). | ||
| 225 | + assert_eq!(seq_level_idx(1920, 1088, (30, 1)), 8); | ||
| 226 | + assert_eq!(seq_level_idx(3840, 2176, (30, 1)), 12); | ||
| 227 | + assert_eq!(seq_level_idx(3840, 2176, (60, 1)), 13); | ||
| 228 | + } | ||
| 229 | +} | ||
crates/ec-hw/src/enc/headers.rsmodified+259 -0
| @@ -365,3 +365,262 @@ pub(super) mod hevc { | |||
| 365 | ) | 365 | ) |
| 366 | } | 366 | } |
| 367 | } | 367 | } |
| 368 | + | ||
| 369 | +// --------------------------------------------------------------------------- | ||
| 370 | +// AV1 | ||
| 371 | +// --------------------------------------------------------------------------- | ||
| 372 | + | ||
| 373 | +/// The two OBUs the AV1 encode path hands the driver: a sequence header and, | ||
| 374 | +/// per picture, an uncompressed frame header. | ||
| 375 | +/// | ||
| 376 | +/// radeonsi *parses* these (`picture_av1_enc.c:vlVaHandleVAEncPackedHeaderData | ||
| 377 | +/// BufferTypeAV1`) rather than copying them through — the sequence header in | ||
| 378 | +/// full, the frame header as far as `uniform_tile_spacing_flag` — and then | ||
| 379 | +/// writes the header that goes into the stream itself, from those values plus | ||
| 380 | +/// the picture parameter buffer. So these are the *parameters*, in AV1's own | ||
| 381 | +/// syntax: a field written here that disagrees with the parameter buffer is a | ||
| 382 | +/// picture described two ways, and the driver believes this one. | ||
| 383 | +pub(super) mod av1 { | ||
| 384 | + use ec_core::BitWriter; | ||
| 385 | + | ||
| 386 | + use super::{Colour, Packed}; | ||
| 387 | + use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE}; | ||
| 388 | + | ||
| 389 | + /// `OrderHintBits`, and the width of `order_hint` in a frame header. | ||
| 390 | + pub(in crate::enc) const ORDER_HINT_BITS: u32 = 8; | ||
| 391 | + | ||
| 392 | + /// Bytes of the `obu_size` field. radeonsi reports | ||
| 393 | + /// `VAConfigAttribEncAV1Ext2.obu_size_bytes_minus1 = 1` (measured on this | ||
| 394 | + /// box), i.e. it wants that field a fixed two bytes so it can rewrite it | ||
| 395 | + /// without moving the payload; leb128 permits the padded encoding. | ||
| 396 | + const OBU_SIZE_BYTES: usize = 2; | ||
| 397 | + | ||
| 398 | + /// Wrap a payload as one OBU: header byte, fixed-width `obu_size`, payload. | ||
| 399 | + fn obu(kind: u32, obu_type: u8, payload: Vec<u8>) -> Packed { | ||
| 400 | + let mut bytes = Vec::with_capacity(payload.len() + 1 + OBU_SIZE_BYTES); | ||
| 401 | + // forbidden(0) type(4) extension(0) has_size(1) reserved(0) | ||
| 402 | + bytes.push(obu_type << 3 | 0b010); | ||
| 403 | + let mut size = payload.len(); | ||
| 404 | + for i in 0..OBU_SIZE_BYTES { | ||
| 405 | + let last = i + 1 == OBU_SIZE_BYTES; | ||
| 406 | + bytes.push((size as u8 & 0x7f) | if last { 0 } else { 0x80 }); | ||
| 407 | + size >>= 7; | ||
| 408 | + } | ||
| 409 | + bytes.extend_from_slice(&payload); | ||
| 410 | + let bits = bytes.len() as u32 * 8; | ||
| 411 | + Packed { kind, bytes, bits } | ||
| 412 | + } | ||
| 413 | + | ||
| 414 | + /// `trailing_bits()` (5.3.4). | ||
| 415 | + fn trailing(w: &mut BitWriter) { | ||
| 416 | + w.write_bit(true); | ||
| 417 | + w.align_to_byte(); | ||
| 418 | + } | ||
| 419 | + | ||
| 420 | + /// What the sequence header says about the stream. | ||
| 421 | + pub(in crate::enc) struct SeqParams { | ||
| 422 | + pub(in crate::enc) width: u32, | ||
| 423 | + pub(in crate::enc) height: u32, | ||
| 424 | + pub(in crate::enc) seq_level_idx: u8, | ||
| 425 | + pub(in crate::enc) seq_tier: u8, | ||
| 426 | + /// 10-bit (`high_bitdepth`); profile 0 has no `twelve_bit`. | ||
| 427 | + pub(in crate::enc) high_bitdepth: bool, | ||
| 428 | + pub(in crate::enc) colour: Option<Colour>, | ||
| 429 | + } | ||
| 430 | + | ||
| 431 | + /// `sequence_header_obu()` (5.5.1), profile 0, one operating point. | ||
| 432 | + /// | ||
| 433 | + /// Every coding tool this driver does not advertise | ||
| 434 | + /// (`VAConfigAttribEncAV1`: no filter intra, no warped motion, no dual | ||
| 435 | + /// filter, no superres, no restoration) is signalled off, which is also | ||
| 436 | + /// what ffmpeg's `av1_vaapi` writes. | ||
| 437 | + pub(in crate::enc) fn sequence_header(p: &SeqParams) -> Packed { | ||
| 438 | + let mut w = BitWriter::new(); | ||
| 439 | + w.write_bits(0, 3); // seq_profile | ||
| 440 | + w.write_bit(false); // still_picture | ||
| 441 | + w.write_bit(false); // reduced_still_picture_header | ||
| 442 | + w.write_bit(false); // timing_info_present_flag | ||
| 443 | + w.write_bit(false); // initial_display_delay_present_flag | ||
| 444 | + w.write_bits(0, 5); // operating_points_cnt_minus_1 | ||
| 445 | + w.write_bits(0, 12); // operating_point_idc[0] | ||
| 446 | + w.write_bits(u32::from(p.seq_level_idx), 5); | ||
| 447 | + if p.seq_level_idx > 7 { | ||
| 448 | + w.write_bits(u32::from(p.seq_tier), 1); | ||
| 449 | + } | ||
| 450 | + let width_bits = 32 - p.width.max(1).leading_zeros(); // floor(log2(w)) + 1 | ||
| 451 | + let height_bits = 32 - p.height.max(1).leading_zeros(); | ||
| 452 | + w.write_bits(width_bits - 1, 4); // frame_width_bits_minus_1 | ||
| 453 | + w.write_bits(height_bits - 1, 4); // frame_height_bits_minus_1 | ||
| 454 | + w.write_bits(p.width - 1, width_bits); // max_frame_width_minus_1 | ||
| 455 | + w.write_bits(p.height - 1, height_bits); // max_frame_height_minus_1 | ||
| 456 | + w.write_bit(false); // frame_id_numbers_present_flag | ||
| 457 | + w.write_bit(false); // use_128x128_superblock | ||
| 458 | + w.write_bit(false); // enable_filter_intra | ||
| 459 | + w.write_bit(false); // enable_intra_edge_filter | ||
| 460 | + w.write_bit(false); // enable_interintra_compound | ||
| 461 | + w.write_bit(false); // enable_masked_compound | ||
| 462 | + w.write_bit(false); // enable_warped_motion | ||
| 463 | + w.write_bit(false); // enable_dual_filter | ||
| 464 | + w.write_bit(true); // enable_order_hint | ||
| 465 | + w.write_bit(false); // enable_jnt_comp | ||
| 466 | + w.write_bit(false); // enable_ref_frame_mvs | ||
| 467 | + w.write_bit(false); // seq_choose_screen_content_tools | ||
| 468 | + w.write_bit(false); // seq_force_screen_content_tools | ||
| 469 | + w.write_bits(ORDER_HINT_BITS - 1, 3); // order_hint_bits_minus_1 | ||
| 470 | + w.write_bit(false); // enable_superres | ||
| 471 | + w.write_bit(false); // enable_cdef | ||
| 472 | + w.write_bit(false); // enable_restoration | ||
| 473 | + // color_config(): profile 0 is 4:2:0, and never 12-bit. | ||
| 474 | + w.write_bit(p.high_bitdepth); | ||
| 475 | + w.write_bit(false); // mono_chrome | ||
| 476 | + match p.colour { | ||
| 477 | + Some(c) => { | ||
| 478 | + w.write_bit(true); // color_description_present_flag | ||
| 479 | + w.write_bits(u32::from(c.primaries), 8); | ||
| 480 | + w.write_bits(u32::from(c.transfer), 8); | ||
| 481 | + w.write_bits(u32::from(c.matrix), 8); | ||
| 482 | + w.write_bit(c.full_range); // color_range | ||
| 483 | + } | ||
| 484 | + None => { | ||
| 485 | + w.write_bit(false); | ||
| 486 | + w.write_bit(false); // color_range | ||
| 487 | + } | ||
| 488 | + } | ||
| 489 | + w.write_bits(0, 2); // chroma_sample_position = CSP_UNKNOWN | ||
| 490 | + w.write_bit(false); // separate_uv_delta_q | ||
| 491 | + w.write_bit(false); // film_grain_params_present | ||
| 492 | + trailing(&mut w); | ||
| 493 | + obu(PACKED_HEADER_SEQUENCE, 1, w.into_bytes()) | ||
| 494 | + } | ||
| 495 | + | ||
| 496 | + /// What one picture's uncompressed header says. | ||
| 497 | + pub(in crate::enc) struct FrameParams { | ||
| 498 | + pub(in crate::enc) keyframe: bool, | ||
| 499 | + pub(in crate::enc) order_hint: u8, | ||
| 500 | + pub(in crate::enc) primary_ref_frame: u8, | ||
| 501 | + pub(in crate::enc) refresh_frame_flags: u8, | ||
| 502 | + pub(in crate::enc) ref_frame_idx: [u8; 7], | ||
| 503 | + pub(in crate::enc) base_q_idx: u8, | ||
| 504 | + pub(in crate::enc) loop_filter_level: [u8; 4], | ||
| 505 | + /// `TX_MODE_SELECT`; this driver advertises no other | ||
| 506 | + /// (`VAConfigAttribEncAV1Ext2.tx_mode_support = 0x4`). | ||
| 507 | + pub(in crate::enc) tx_mode_select: bool, | ||
| 508 | + /// The bit offsets the driver needs to back-annotate its own choices | ||
| 509 | + /// into this header are only read outside CQP, so they are computed | ||
| 510 | + /// unconditionally and used by the caller when it is not in CQP. | ||
| 511 | + pub(in crate::enc) max_tile_cols_log2: u32, | ||
| 512 | + pub(in crate::enc) max_tile_rows_log2: u32, | ||
| 513 | + } | ||
| 514 | + | ||
| 515 | + /// Where the driver may rewrite fields of the header we just wrote, in | ||
| 516 | + /// bits from the first bit of the OBU (`VAEncPictureParameterBufferAV1`). | ||
| 517 | + pub(in crate::enc) struct FrameHeaderOffsets { | ||
| 518 | + pub(in crate::enc) qindex: u32, | ||
| 519 | + pub(in crate::enc) segmentation: u32, | ||
| 520 | + pub(in crate::enc) loop_filter: u32, | ||
| 521 | + pub(in crate::enc) cdef: u32, | ||
| 522 | + pub(in crate::enc) cdef_size: u32, | ||
| 523 | + pub(in crate::enc) obu_size_byte: u32, | ||
| 524 | + pub(in crate::enc) total_bits: u32, | ||
| 525 | + } | ||
| 526 | + | ||
| 527 | + /// `frame_header_obu()` (5.9.1) for a shown key or inter frame with one | ||
| 528 | + /// tile, no segmentation, no CDEF, no restoration and no global motion. | ||
| 529 | + pub(in crate::enc) fn frame_header(p: &FrameParams) -> (Packed, FrameHeaderOffsets) { | ||
| 530 | + // The OBU header and its size field precede every offset below. | ||
| 531 | + let prefix_bits = 8 * (1 + OBU_SIZE_BYTES) as u32; | ||
| 532 | + let mut w = BitWriter::new(); | ||
| 533 | + w.write_bit(false); // show_existing_frame | ||
| 534 | + w.write_bits(u32::from(!p.keyframe), 2); // frame_type: KEY / INTER | ||
| 535 | + w.write_bit(true); // show_frame | ||
| 536 | + if !p.keyframe { | ||
| 537 | + // A shown key frame infers error_resilient_mode = 1. | ||
| 538 | + w.write_bit(false); // error_resilient_mode | ||
| 539 | + } | ||
| 540 | + w.write_bit(false); // disable_cdf_update | ||
| 541 | + w.write_bit(false); // frame_size_override_flag | ||
| 542 | + w.write_bits(u32::from(p.order_hint), ORDER_HINT_BITS); | ||
| 543 | + if !p.keyframe { | ||
| 544 | + w.write_bits(u32::from(p.primary_ref_frame), 3); | ||
| 545 | + // A shown key frame refreshes every slot, unsignalled. | ||
| 546 | + w.write_bits(u32::from(p.refresh_frame_flags), 8); | ||
| 547 | + w.write_bit(false); // frame_refs_short_signaling | ||
| 548 | + for idx in p.ref_frame_idx { | ||
| 549 | + w.write_bits(u32::from(idx), 3); | ||
| 550 | + } | ||
| 551 | + } | ||
| 552 | + // frame_size(): frame_size_override_flag = 0 takes the sequence | ||
| 553 | + // header's size, and enable_superres = 0 codes no superres bit. | ||
| 554 | + w.write_bit(false); // render_and_frame_size_different | ||
| 555 | + if !p.keyframe { | ||
| 556 | + w.write_bit(false); // allow_high_precision_mv | ||
| 557 | + w.write_bit(true); // is_filter_switchable | ||
| 558 | + w.write_bit(false); // is_motion_mode_switchable | ||
| 559 | + // use_ref_frame_mvs is inferred 0 from enable_ref_frame_mvs = 0. | ||
| 560 | + } | ||
| 561 | + w.write_bit(false); // disable_frame_end_update_cdf | ||
| 562 | + // tile_info(): one tile, uniformly spaced. The increment loop stops | ||
| 563 | + // with a zero bit for as long as the maximum allows another doubling. | ||
| 564 | + w.write_bit(true); // uniform_tile_spacing_flag | ||
| 565 | + if p.max_tile_cols_log2 > 0 { | ||
| 566 | + w.write_bit(false); // increment_tile_cols_log2 | ||
| 567 | + } | ||
| 568 | + if p.max_tile_rows_log2 > 0 { | ||
| 569 | + w.write_bit(false); // increment_tile_rows_log2 | ||
| 570 | + } | ||
| 571 | + let qindex = prefix_bits + w.bit_len() as u32; | ||
| 572 | + w.write_bits(u32::from(p.base_q_idx), 8); | ||
| 573 | + w.write_bit(false); // DeltaQYDc.delta_coded | ||
| 574 | + w.write_bit(false); // DeltaQUDc.delta_coded | ||
| 575 | + w.write_bit(false); // DeltaQUAc.delta_coded | ||
| 576 | + w.write_bit(false); // using_qmatrix | ||
| 577 | + let segmentation = prefix_bits + w.bit_len() as u32; | ||
| 578 | + w.write_bit(false); // segmentation_enabled | ||
| 579 | + w.write_bit(false); // delta_q_present (base_q_idx > 0) | ||
| 580 | + let loop_filter = prefix_bits + w.bit_len() as u32; | ||
| 581 | + w.write_bits(u32::from(p.loop_filter_level[0]), 6); | ||
| 582 | + w.write_bits(u32::from(p.loop_filter_level[1]), 6); | ||
| 583 | + if p.loop_filter_level[0] != 0 || p.loop_filter_level[1] != 0 { | ||
| 584 | + w.write_bits(u32::from(p.loop_filter_level[2]), 6); | ||
| 585 | + w.write_bits(u32::from(p.loop_filter_level[3]), 6); | ||
| 586 | + } | ||
| 587 | + w.write_bits(0, 3); // loop_filter_sharpness | ||
| 588 | + w.write_bit(false); // loop_filter_delta_enabled | ||
| 589 | + // cdef_params() and lr_params() are empty: enable_cdef = | ||
| 590 | + // enable_restoration = 0 in the sequence header above. | ||
| 591 | + let cdef = prefix_bits + w.bit_len() as u32; | ||
| 592 | + w.write_bit(p.tx_mode_select); // tx_mode_select | ||
| 593 | + if !p.keyframe { | ||
| 594 | + w.write_bit(false); // reference_select — single reference, which | ||
| 595 | + // also makes skipModeAllowed 0, so no skip_mode_present bit | ||
| 596 | + } | ||
| 597 | + w.write_bit(false); // reduced_tx_set | ||
| 598 | + if !p.keyframe { | ||
| 599 | + for _ in 0..7 { | ||
| 600 | + w.write_bit(false); // is_global[ref] | ||
| 601 | + } | ||
| 602 | + } | ||
| 603 | + trailing(&mut w); | ||
| 604 | + let packed = obu(PACKED_HEADER_PICTURE, 3, w.into_bytes()); | ||
| 605 | + let offsets = FrameHeaderOffsets { | ||
| 606 | + qindex, | ||
| 607 | + segmentation, | ||
| 608 | + loop_filter, | ||
| 609 | + cdef, | ||
| 610 | + cdef_size: 0, | ||
| 611 | + obu_size_byte: 1, | ||
| 612 | + total_bits: packed.bits, | ||
| 613 | + }; | ||
| 614 | + (packed, offsets) | ||
| 615 | + } | ||
| 616 | + | ||
| 617 | + /// `tile_log2(1, n)`: the number of doublings of 1 needed to reach `n`, | ||
| 618 | + /// which is the ceiling of log2 (5.9.15). | ||
| 619 | + pub(in crate::enc) fn tile_log2(target: u32) -> u32 { | ||
| 620 | + let mut k = 0; | ||
| 621 | + while (1u32 << k) < target { | ||
| 622 | + k += 1; | ||
| 623 | + } | ||
| 624 | + k | ||
| 625 | + } | ||
| 626 | +} | ||
crates/ec-hw/src/enc/mod.rsmodified+21 -17
| @@ -1,4 +1,4 @@ | |||
| 1 | -//! Hardware encoding: H.264, HEVC, and AV1 behind an explicit opt-in. | 1 | +//! Hardware encoding: H.264, HEVC and AV1. |
| 2 | //! | 2 | //! |
| 3 | //! One frame in, one coded frame out. The GOP is IDR-then-P with a single | 3 | //! One frame in, one coded frame out. The GOP is IDR-then-P with a single |
| 4 | //! reference, which is what this GPU advertises (`VAConfigAttribEncMaxRefFrames` | 4 | //! reference, which is what this GPU advertises (`VAConfigAttribEncMaxRefFrames` |
| @@ -7,11 +7,15 @@ | |||
| 7 | //! | 7 | //! |
| 8 | //! # AV1 | 8 | //! # AV1 |
| 9 | //! | 9 | //! |
| 10 | -//! AV1 encoding is off unless [`EncoderConfig::allow_av1`] is set, and never | 10 | +//! AV1 encode was opt-in until 2026-09-07, after a submission on an older |
| 11 | -//! reachable from an "auto" codec choice. The reason is on the record rather | 11 | +//! driver took the GPU down. It is on by default now because the refusal was |
| 12 | -//! than theoretical: an AV1 encode submission on this driver generation took | 12 | +//! retired by measurement, not by opinion: on mesa 26.1.8 (gfx1200) ffmpeg's |
| 13 | -//! the GPU down hard enough to need a reset. The path is built, typed and | 13 | +//! own `av1_vaapi` encodes, this path encodes, and `gpu.rs`'s |
| 14 | -//! probed; turning it on is a caller's explicit decision. | 14 | +//! `av1_encode_agrees_between_two_decoders` proves every coded frame decodes |
| 15 | +//! identically through `ec-av1` and libdav1d. Unlike H.264 and HEVC, the | ||
| 16 | +//! driver composes no headers of its own from thin air: it parses the | ||
| 17 | +//! sequence and frame header OBUs this crate packs (see `enc::headers::av1`) | ||
| 18 | +//! and writes the stream's headers from them. | ||
| 15 | 19 | ||
| 16 | use std::sync::Arc; | 20 | use std::sync::Arc; |
| 17 | 21 | ||
| @@ -42,7 +46,7 @@ pub enum EncCodec { | |||
| 42 | H264, | 46 | H264, |
| 43 | /// H.265 / HEVC, Main profile. | 47 | /// H.265 / HEVC, Main profile. |
| 44 | H265, | 48 | H265, |
| 45 | - /// AV1 Profile 0 — opt-in only, see the module docs. | 49 | + /// AV1 Profile 0. |
| 46 | Av1, | 50 | Av1, |
| 47 | } | 51 | } |
| 48 | 52 | ||
| @@ -95,8 +99,6 @@ pub struct EncoderConfig { | |||
| 95 | pub rate_control: RateControlMode, | 99 | pub rate_control: RateControlMode, |
| 96 | /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default. | 100 | /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default. |
| 97 | pub quality: u32, | 101 | pub quality: u32, |
| 98 | - /// Permit AV1 encoding. Without it, [`EncCodec::Av1`] is refused. | ||
| 99 | - pub allow_av1: bool, | ||
| 100 | /// The colour description to write into the VUI, or `None` to leave it | 102 | /// The colour description to write into the VUI, or `None` to leave it |
| 101 | /// unsignalled (`video_signal_type_present_flag = 0`) as before. | 103 | /// unsignalled (`video_signal_type_present_flag = 0`) as before. |
| 102 | pub colour: Option<Colour>, | 104 | pub colour: Option<Colour>, |
| @@ -132,7 +134,6 @@ impl EncoderConfig { | |||
| 132 | gop_size: 60, | 134 | gop_size: 60, |
| 133 | rate_control: RateControlMode::ConstantBitrate, | 135 | rate_control: RateControlMode::ConstantBitrate, |
| 134 | quality: 0, | 136 | quality: 0, |
| 135 | - allow_av1: false, | ||
| 136 | colour: None, | 137 | colour: None, |
| 137 | } | 138 | } |
| 138 | } | 139 | } |
| @@ -199,12 +200,6 @@ pub struct Encoder { | |||
| 199 | impl Encoder { | 200 | impl Encoder { |
| 200 | /// Build an encoder for `config` on `display`. | 201 | /// Build an encoder for `config` on `display`. |
| 201 | pub fn new(display: &Arc<Display>, config: EncoderConfig) -> Result<Encoder> { | 202 | pub fn new(display: &Arc<Display>, config: EncoderConfig) -> Result<Encoder> { |
| 202 | - if config.codec == EncCodec::Av1 && !config.allow_av1 { | ||
| 203 | - return Err(Error::unsupported( | ||
| 204 | - "AV1 hardware encoding", | ||
| 205 | - "it is opt-in (EncoderConfig::allow_av1) after a GPU recovery incident", | ||
| 206 | - )); | ||
| 207 | - } | ||
| 208 | let profile = match config.codec { | 203 | let profile = match config.codec { |
| 209 | // High is the profile every H.264 encoder on this driver reports and | 204 | // High is the profile every H.264 encoder on this driver reports and |
| 210 | // the one a High-profile decoder expects; Main is a strict subset. | 205 | // the one a High-profile decoder expects; Main is a strict subset. |
| @@ -481,7 +476,7 @@ impl Encoder { | |||
| 481 | .end()? | 476 | .end()? |
| 482 | .sync()?; | 477 | .sync()?; |
| 483 | 478 | ||
| 484 | - let data = { | 479 | + let mut data = { |
| 485 | let coded = picture | 480 | let coded = picture |
| 486 | .buffers_mut() | 481 | .buffers_mut() |
| 487 | .iter_mut() | 482 | .iter_mut() |
| @@ -491,6 +486,15 @@ impl Encoder { | |||
| 491 | coded_bytes(&mapped)? | 486 | coded_bytes(&mapped)? |
| 492 | }; | 487 | }; |
| 493 | 488 | ||
| 489 | + if self.config.codec == EncCodec::Av1 { | ||
| 490 | + // Every AV1 temporal unit begins with a temporal delimiter (5.6), | ||
| 491 | + // and this driver emits none: its coded buffer starts at the | ||
| 492 | + // sequence header. ffmpeg's demuxer refuses such a stream | ||
| 493 | + // ("Missing Temporal Delimiter"), so the two bytes are prepended | ||
| 494 | + // here rather than left to the caller. | ||
| 495 | + data.splice(0..0, [0x12u8, 0x00]); | ||
| 496 | + } | ||
| 497 | + | ||
| 494 | self.reference = Some(recon); | 498 | self.reference = Some(recon); |
| 495 | self.coded += 1; | 499 | self.coded += 1; |
| 496 | self.gop_position = if keyframe { 1 } else { self.gop_position + 1 }; | 500 | self.gop_position = if keyframe { 1 } else { self.gop_position + 1 }; |
crates/ec-hw/src/lib.rsmodified+1 -1
| @@ -30,7 +30,7 @@ | |||
| 30 | //! * [`params`] — the `#[repr(C)]` codec parameter buffers, each checked | 30 | //! * [`params`] — the `#[repr(C)]` codec parameter buffers, each checked |
| 31 | //! against the system headers by a `const` assertion. | 31 | //! against the system headers by a `const` assertion. |
| 32 | //! * [`dec`] — one stateless decoder per codec behind [`Decoder`]. | 32 | //! * [`dec`] — one stateless decoder per codec behind [`Decoder`]. |
| 33 | -//! * [`enc`] — H.264 and HEVC encoders, and an opt-in AV1 one. | 33 | +//! * [`enc`] — H.264, HEVC and AV1 encoders. |
| 34 | //! * [`SurfacePool`] / [`Frame`] — surface recycling and pixel access. | 34 | //! * [`SurfacePool`] / [`Frame`] — surface recycling and pixel access. |
| 35 | //! | 35 | //! |
| 36 | //! # Unsafe | 36 | //! # Unsafe |
crates/ec-hw/tests/gpu.rsmodified+402 -33
| @@ -532,13 +532,11 @@ fn encode_stream( | |||
| 532 | width: u32, | 532 | width: u32, |
| 533 | height: u32, | 533 | height: u32, |
| 534 | frames: u32, | 534 | frames: u32, |
| 535 | - allow_av1: bool, | ||
| 536 | ) -> Result<Vec<u8>, ec_hw::Error> { | 535 | ) -> Result<Vec<u8>, ec_hw::Error> { |
| 537 | let mut config = EncoderConfig::new(codec, width, height); | 536 | let mut config = EncoderConfig::new(codec, width, height); |
| 538 | config.gop_size = 30; | 537 | config.gop_size = 30; |
| 539 | config.framerate = (30, 1); | 538 | config.framerate = (30, 1); |
| 540 | config.rate_control = RateControlMode::ConstantQp { qp: 26 }; | 539 | config.rate_control = RateControlMode::ConstantQp { qp: 26 }; |
| 541 | - config.allow_av1 = allow_av1; | ||
| 542 | let mut encoder = Encoder::new(display, config)?; | 540 | let mut encoder = Encoder::new(display, config)?; |
| 543 | let mut out = Vec::new(); | 541 | let mut out = Vec::new(); |
| 544 | for t in 0..frames { | 542 | for t in 0..frames { |
| @@ -559,7 +557,7 @@ fn encode_stream( | |||
| 559 | fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) { | 557 | fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) { |
| 560 | let Some(display) = display() else { return }; | 558 | let Some(display) = display() else { return }; |
| 561 | let frames = 12u32; | 559 | let frames = 12u32; |
| 562 | - let stream = match encode_stream(&display, codec, width, height, frames, false) { | 560 | + let stream = match encode_stream(&display, codec, width, height, frames) { |
| 563 | Ok(stream) => stream, | 561 | Ok(stream) => stream, |
| 564 | Err(e) => panic!("{codec:?} encode failed: {e}"), | 562 | Err(e) => panic!("{codec:?} encode failed: {e}"), |
| 565 | }; | 563 | }; |
| @@ -649,7 +647,7 @@ fn hevc_encode_honours_the_conformance_window() { | |||
| 649 | fn our_encoder_and_our_decoder_agree() { | 647 | fn our_encoder_and_our_decoder_agree() { |
| 650 | let Some(display) = display() else { return }; | 648 | let Some(display) = display() else { return }; |
| 651 | for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { | 649 | for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { |
| 652 | - let stream = encode_stream(&display, enc, 640, 480, 12, false).expect("encode"); | 650 | + let stream = encode_stream(&display, enc, 640, 480, 12).expect("encode"); |
| 653 | let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); | 651 | let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); |
| 654 | let mut worst = f64::INFINITY; | 652 | let mut worst = f64::INFINITY; |
| 655 | let mut count = 0u32; | 653 | let mut count = 0u32; |
| @@ -843,40 +841,411 @@ fn colour_description_reaches_the_vui() { | |||
| 843 | ); | 841 | ); |
| 844 | } | 842 | } |
| 845 | 843 | ||
| 846 | -/// AV1 encoding is opt-in, and this test does not turn it on. | 844 | +/// AV1 hardware encode, proved by two independent decoders. |
| 847 | /// | 845 | /// |
| 848 | -/// It was probed once, live, at the driver's own minimum encode size | 846 | +/// The reconstruction inside the GPU is not observable from here, so what is |
| 849 | -/// (radeonsi reports 320x128 for AV1 `EncSlice`) on 2026-08-14. The submission | 847 | +/// asserted is that the coded stream means the same thing to two decoders that |
| 850 | -/// took the GPU down: | 848 | +/// share no code: ffmpeg's libdav1d and this family's own `ec-av1`. Every |
| 849 | +/// shown frame is compared sample for sample — a header field that disagrees | ||
| 850 | +/// with what the hardware coded shows up as a mismatch in one of them long | ||
| 851 | +/// before it shows up as a quality number. | ||
| 851 | /// | 852 | /// |
| 852 | -/// ```text | 853 | +/// The path was refused in-tree until 2026-09-07: a probe on 2026-08-14 took |
| 853 | -/// amdgpu: The CS has cancelled because the context is lost. | 854 | +/// the GPU down ("the CS has cancelled because the context is lost"). That |
| 854 | -/// This context is guilty of a hard recovery. | 855 | +/// refusal is retired by measurement, not by opinion — ffmpeg's own |
| 855 | -/// ``` | 856 | +/// `av1_vaapi` encodes on this driver (mesa 26.1.8, gfx1200), and the |
| 857 | +/// parameters below are the recipe it uses. | ||
| 858 | +#[test] | ||
| 859 | +fn av1_encode_agrees_between_two_decoders() { | ||
| 860 | + let Some(display) = display() else { return }; | ||
| 861 | + let dir = std::env::temp_dir().join("ec-hw-av1-encode"); | ||
| 862 | + let _ = std::fs::create_dir_all(&dir); | ||
| 863 | + for (width, height, frames) in [(640u32, 384u32, 10u32), (1920, 1080, 10)] { | ||
| 864 | + let data = match encode_stream(&display, EncCodec::Av1, width, height, frames) { | ||
| 865 | + Ok(data) => data, | ||
| 866 | + Err(e) => { | ||
| 867 | + eprintln!("skipped: AV1 encode unavailable ({e})"); | ||
| 868 | + return; | ||
| 869 | + } | ||
| 870 | + }; | ||
| 871 | + let path = dir.join(format!("hw-{width}x{height}.obu")); | ||
| 872 | + std::fs::write(&path, &data).expect("write the coded stream"); | ||
| 873 | + | ||
| 874 | + // Decoder one: this family's software AV1 decoder, on the raw OBUs. | ||
| 875 | + let ours = ec_av1::stream::decode_stream(&data) | ||
| 876 | + .unwrap_or_else(|e| panic!("ec-av1 decodes the {width}x{height} hardware stream: {e}")); | ||
| 877 | + assert_eq!( | ||
| 878 | + ours.len(), | ||
| 879 | + frames as usize, | ||
| 880 | + "{width}x{height}: ec-av1 decoded {} of {frames} shown frames", | ||
| 881 | + ours.len() | ||
| 882 | + ); | ||
| 883 | + | ||
| 884 | + // Decoder two: ffmpeg (libdav1d) on the same bytes. | ||
| 885 | + let mut reference = | ||
| 886 | + Reference::open(&path, width, height, false).expect("ffmpeg opens the stream"); | ||
| 887 | + let mut worst = f64::INFINITY; | ||
| 888 | + for (i, picture) in ours.iter().enumerate() { | ||
| 889 | + let theirs = reference | ||
| 890 | + .next(width, height) | ||
| 891 | + .unwrap_or_else(|| panic!("{width}x{height}: ffmpeg has no frame {i}")); | ||
| 892 | + let mine = Planes { | ||
| 893 | + y: picture.y.clone(), | ||
| 894 | + u: picture.u.clone(), | ||
| 895 | + v: picture.v.clone(), | ||
| 896 | + peak: 255.0, | ||
| 897 | + }; | ||
| 898 | + let db = psnr(&mine, &theirs); | ||
| 899 | + assert!( | ||
| 900 | + db.is_infinite(), | ||
| 901 | + "{width}x{height} frame {i}: the two decoders disagree ({db:.2} dB)" | ||
| 902 | + ); | ||
| 903 | + // Agreement alone would also be satisfied by ten grey frames: the | ||
| 904 | + // coded picture has to be the picture that was submitted. | ||
| 905 | + let source = Planes::from_8bit(&source_frame(width, height, i as u32)); | ||
| 906 | + let fidelity = psnr(&mine, &source); | ||
| 907 | + assert!( | ||
| 908 | + fidelity > 30.0, | ||
| 909 | + "{width}x{height} frame {i}: coded {fidelity:.2} dB from the source" | ||
| 910 | + ); | ||
| 911 | + worst = worst.min(fidelity); | ||
| 912 | + } | ||
| 913 | + println!( | ||
| 914 | + "AV1 encode {width}x{height}: {frames} frames, {} bytes, ec-av1 and libdav1d agree \ | ||
| 915 | + sample for sample, worst frame {worst:.2} dB from the source", | ||
| 916 | + data.len() | ||
| 917 | + ); | ||
| 918 | + } | ||
| 919 | +} | ||
| 920 | + | ||
| 921 | +/// What the GPU's AV1 costs against software, on his own content. | ||
| 856 | /// | 922 | /// |
| 857 | -/// The process was aborted by the driver, not by this crate — there is no error | 923 | +/// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen |
| 858 | -/// to return from a context that no longer exists. So the probe is *recorded* | 924 | +/// capture, PSNR from ffmpeg, BD-rate over the overlapping quality range |
| 859 | -/// rather than repeated: what this test asserts is the guard that keeps the | 925 | +/// against librav1e speed 6 and libaom cpu-used 6. Nothing is asserted about |
| 860 | -/// path off unless a caller asks for it by name, which is the only defence a | 926 | +/// the number — a fixed-function encoder is not a search — but it is measured |
| 861 | -/// library has against a driver bug of that class. | 927 | +/// and printed rather than assumed, and the ladder itself is asserted to be |
| 928 | +/// monotone, which is the part a broken parameter set would break. | ||
| 862 | #[test] | 929 | #[test] |
| 863 | -fn av1_encode_is_opt_in() { | 930 | +fn av1_encode_bd_row_vs_software() { |
| 864 | let Some(display) = display() else { return }; | 931 | let Some(display) = display() else { return }; |
| 865 | - let refused = Encoder::new(&display, EncoderConfig::new(EncCodec::Av1, 320, 128)); | 932 | + let clips = real_clips(); |
| 866 | - assert!( | 933 | + if clips.is_empty() { |
| 867 | - matches!(refused, Err(ec_hw::Error::Unsupported { .. })), | 934 | + eprintln!("skipped: no real-library manifest"); |
| 868 | - "AV1 encoding must be refused without the explicit opt-in" | 935 | + return; |
| 869 | - ); | 936 | + } |
| 870 | - // With the opt-in the encoder builds — the parameters, the surface pool and | 937 | + // A ladder compared with itself saves nothing: the check on the metric. |
| 871 | - // the context are all real; only `encode()` is left untested here. | 938 | + let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)]; |
| 872 | - let mut config = EncoderConfig::new(EncCodec::Av1, 320, 128); | 939 | + assert!(bd_rate(&same, &same).abs() < 1e-9, "bd_rate is not self-zero"); |
| 873 | - config.allow_av1 = true; | 940 | + |
| 874 | - match Encoder::new(&display, config) { | 941 | + let dir = std::env::temp_dir().join("ec-hw-av1-bd"); |
| 875 | - Ok(encoder) => println!( | 942 | + let _ = std::fs::create_dir_all(&dir); |
| 876 | - "AV1 encode: opt-in encoder built at {:?}, submission deliberately not run", | 943 | + for (label, source) in clips { |
| 877 | - encoder.coded_size() | 944 | + let y4m = dir.join(format!("{label}.y4m")); |
| 878 | - ), | 945 | + let (width, height, frames) = (1920u32, 1080u32, 12u32); |
| 879 | - Err(e) => println!("AV1 encode: refused by the driver, typed error: {e}"), | 946 | + if !extract_y4m(&source, &y4m, width, height, frames) { |
| 947 | + eprintln!("skipped {label}: extraction failed"); | ||
| 948 | + continue; | ||
| 949 | + } | ||
| 950 | + let planes = match raw_frames(&y4m, width, height, frames) { | ||
| 951 | + Some(planes) => planes, | ||
| 952 | + None => { | ||
| 953 | + eprintln!("skipped {label}: no frames extracted"); | ||
| 954 | + continue; | ||
| 955 | + } | ||
| 956 | + }; | ||
| 957 | + | ||
| 958 | + let mut ours = Vec::new(); | ||
| 959 | + // Descending quantiser: every ladder here is ordered by rising rate. | ||
| 960 | + for qp in [180u32, 140, 100, 60] { | ||
| 961 | + let mut config = EncoderConfig::new(EncCodec::Av1, width, height); | ||
| 962 | + config.framerate = (24, 1); | ||
| 963 | + config.gop_size = 60; | ||
| 964 | + config.rate_control = RateControlMode::ConstantQp { qp }; | ||
| 965 | + let mut encoder = match Encoder::new(&display, config) { | ||
| 966 | + Ok(encoder) => encoder, | ||
| 967 | + Err(e) => { | ||
| 968 | + eprintln!("skipped: AV1 encode unavailable ({e})"); | ||
| 969 | + return; | ||
| 970 | + } | ||
| 971 | + }; | ||
| 972 | + let mut bytes = Vec::new(); | ||
| 973 | + for (i, frame) in planes.iter().enumerate() { | ||
| 974 | + let coded = encoder | ||
| 975 | + .encode( | ||
| 976 | + frame, | ||
| 977 | + FrameMetadata { | ||
| 978 | + timestamp: i as i64, | ||
| 979 | + force_keyframe: false, | ||
| 980 | + }, | ||
| 981 | + ) | ||
| 982 | + .expect("hardware AV1 encode"); | ||
| 983 | + bytes.extend_from_slice(&coded.data); | ||
| 984 | + } | ||
| 985 | + let path = dir.join(format!("{label}-hw-{qp}.obu")); | ||
| 986 | + std::fs::write(&path, &bytes).expect("write"); | ||
| 987 | + if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { | ||
| 988 | + ours.push((bytes.len() as f64 * 8.0 / f64::from(frames), db)); | ||
| 989 | + } | ||
| 990 | + } | ||
| 991 | + let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] | ||
| 992 | + .iter() | ||
| 993 | + .filter_map(|q| { | ||
| 994 | + software_point( | ||
| 995 | + &dir, | ||
| 996 | + &y4m, | ||
| 997 | + label, | ||
| 998 | + "librav1e", | ||
| 999 | + &["-rav1e-params", &format!("speed=6:quantizer={q}"), "-g", "60"], | ||
| 1000 | + *q, | ||
| 1001 | + frames, | ||
| 1002 | + ) | ||
| 1003 | + }) | ||
| 1004 | + .collect(); | ||
| 1005 | + let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] | ||
| 1006 | + .iter() | ||
| 1007 | + .filter_map(|crf| { | ||
| 1008 | + software_point( | ||
| 1009 | + &dir, | ||
| 1010 | + &y4m, | ||
| 1011 | + label, | ||
| 1012 | + "libaom-av1", | ||
| 1013 | + &[ | ||
| 1014 | + "-cpu-used", "6", "-crf", &crf.to_string(), "-b:v", "0", "-g", "60", | ||
| 1015 | + ], | ||
| 1016 | + *crf, | ||
| 1017 | + frames, | ||
| 1018 | + ) | ||
| 1019 | + }) | ||
| 1020 | + .collect(); | ||
| 1021 | + | ||
| 1022 | + for (name, ladder) in [("hw AV1", &ours), ("librav1e", &rav1e), ("libaom", &libaom)] { | ||
| 1023 | + println!("{label} {name}: {ladder:?}"); | ||
| 1024 | + for pair in ladder.windows(2) { | ||
| 1025 | + assert!( | ||
| 1026 | + pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, | ||
| 1027 | + "{label} {name}: ladder is not monotone at {pair:?}" | ||
| 1028 | + ); | ||
| 1029 | + } | ||
| 1030 | + } | ||
| 1031 | + if ours.len() >= 3 && rav1e.len() >= 3 { | ||
| 1032 | + println!( | ||
| 1033 | + "BD-rate row: {label}, hw AV1 vs librav1e speed 6: {:+.1}%", | ||
| 1034 | + bd_rate(&rav1e, &ours) * 100.0 | ||
| 1035 | + ); | ||
| 1036 | + } | ||
| 1037 | + if ours.len() >= 3 && libaom.len() >= 3 { | ||
| 1038 | + println!( | ||
| 1039 | + "BD-rate row: {label}, hw AV1 vs libaom cpu-used 6: {:+.1}%", | ||
| 1040 | + bd_rate(&libaom, &ours) * 100.0 | ||
| 1041 | + ); | ||
| 1042 | + } | ||
| 1043 | + } | ||
| 1044 | +} | ||
| 1045 | + | ||
| 1046 | +/// One software encoder's rate/PSNR point, or `None` when that encoder is not | ||
| 1047 | +/// built into this ffmpeg. | ||
| 1048 | +fn software_point( | ||
| 1049 | + dir: &Path, | ||
| 1050 | + y4m: &Path, | ||
| 1051 | + label: &str, | ||
| 1052 | + encoder: &str, | ||
| 1053 | + args: &[&str], | ||
| 1054 | + point: u32, | ||
| 1055 | + frames: u32, | ||
| 1056 | +) -> Option<(f64, f64)> { | ||
| 1057 | + let out = dir.join(format!("{label}-{encoder}-{point}.ivf")); | ||
| 1058 | + let _ = std::fs::remove_file(&out); | ||
| 1059 | + let status = Command::new("ffmpeg") | ||
| 1060 | + .args(["-nostdin", "-v", "error", "-y", "-i"]) | ||
| 1061 | + .arg(y4m) | ||
| 1062 | + .args(["-c:v", encoder]) | ||
| 1063 | + .args(args) | ||
| 1064 | + .arg(&out) | ||
| 1065 | + .status() | ||
| 1066 | + .ok()?; | ||
| 1067 | + if !status.success() { | ||
| 1068 | + return None; | ||
| 1069 | + } | ||
| 1070 | + let bytes = std::fs::metadata(&out).ok()?.len() as f64; | ||
| 1071 | + let db = ffmpeg_psnr(&out, y4m, false)?; | ||
| 1072 | + Some((bytes * 8.0 / f64::from(frames), db)) | ||
| 1073 | +} | ||
| 1074 | + | ||
| 1075 | +/// PSNR of a coded stream against the source, from ffmpeg's own filter. | ||
| 1076 | +fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option<f64> { | ||
| 1077 | + let mut cmd = Command::new("ffmpeg"); | ||
| 1078 | + cmd.args(["-nostdin", "-v", "info"]); | ||
| 1079 | + if raw_obu { | ||
| 1080 | + cmd.args(["-f", "obu"]); | ||
| 1081 | + } | ||
| 1082 | + // Both inputs are pinned to the same rate: a raw OBU stream carries no | ||
| 1083 | + // timing, so ffmpeg would otherwise call it 25 fps against a 24 fps | ||
| 1084 | + // source and the filter would compare frame i with frame i+k. | ||
| 1085 | + let out = cmd | ||
| 1086 | + .args(["-r", "24"]) | ||
| 1087 | + .arg("-i") | ||
| 1088 | + .arg(coded) | ||
| 1089 | + .args(["-r", "24"]) | ||
| 1090 | + .arg("-i") | ||
| 1091 | + .arg(source) | ||
| 1092 | + .args(["-lavfi", "psnr", "-f", "null", "-"]) | ||
| 1093 | + .output() | ||
| 1094 | + .ok()?; | ||
| 1095 | + let text = String::from_utf8_lossy(&out.stderr); | ||
| 1096 | + let field = text.split("average:").nth(1)?; | ||
| 1097 | + field | ||
| 1098 | + .split_whitespace() | ||
| 1099 | + .next()? | ||
| 1100 | + .parse::<f64>() | ||
| 1101 | + .ok() | ||
| 1102 | + .filter(|v| v.is_finite()) | ||
| 1103 | +} | ||
| 1104 | + | ||
| 1105 | +/// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. | ||
| 1106 | +fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { | ||
| 1107 | + let _ = std::fs::remove_file(out); | ||
| 1108 | + Command::new("ffmpeg") | ||
| 1109 | + .args(["-nostdin", "-v", "error", "-y", "-ss", "60", "-i"]) | ||
| 1110 | + .arg(source) | ||
| 1111 | + .args([ | ||
| 1112 | + "-frames:v", | ||
| 1113 | + &frames.to_string(), | ||
| 1114 | + "-vf", | ||
| 1115 | + &format!("scale={width}:{height}"), | ||
| 1116 | + "-pix_fmt", | ||
| 1117 | + "yuv420p", | ||
| 1118 | + ]) | ||
| 1119 | + .arg(out) | ||
| 1120 | + .status() | ||
| 1121 | + .is_ok_and(|s| s.success()) | ||
| 1122 | +} | ||
| 1123 | + | ||
| 1124 | +/// The same pictures as planes, for the hardware encoder's own input. | ||
| 1125 | +fn raw_frames(y4m: &Path, width: u32, height: u32, frames: u32) -> Option<Vec<I420>> { | ||
| 1126 | + let out = Command::new("ffmpeg") | ||
| 1127 | + .args(["-nostdin", "-v", "error", "-i"]) | ||
| 1128 | + .arg(y4m) | ||
| 1129 | + .args(["-pix_fmt", "yuv420p", "-f", "rawvideo", "-"]) | ||
| 1130 | + .stderr(Stdio::null()) | ||
| 1131 | + .output() | ||
| 1132 | + .ok()?; | ||
| 1133 | + let (w, h) = (width as usize, height as usize); | ||
| 1134 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | ||
| 1135 | + let frame_len = w * h + 2 * cw * ch; | ||
| 1136 | + let mut pictures = Vec::new(); | ||
| 1137 | + for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { | ||
| 1138 | + let (y, rest) = chunk.split_at(w * h); | ||
| 1139 | + let (u, v) = rest.split_at(cw * ch); | ||
| 1140 | + pictures.push(I420 { | ||
| 1141 | + y: y.to_vec(), | ||
| 1142 | + u: u.to_vec(), | ||
| 1143 | + v: v.to_vec(), | ||
| 1144 | + width, | ||
| 1145 | + height, | ||
| 1146 | + }); | ||
| 1147 | + } | ||
| 1148 | + (!pictures.is_empty()).then_some(pictures) | ||
| 1149 | +} | ||
| 1150 | + | ||
| 1151 | +/// One film and one screen capture from the real-library manifest, labelled | ||
| 1152 | +/// rather than named: the titles are his, not this suite's. | ||
| 1153 | +fn real_clips() -> Vec<(&'static str, PathBuf)> { | ||
| 1154 | + let manifest = | ||
| 1155 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); | ||
| 1156 | + let Ok(text) = std::fs::read_to_string(&manifest) else { | ||
| 1157 | + return Vec::new(); | ||
| 1158 | + }; | ||
| 1159 | + let mut film = None; | ||
| 1160 | + let mut screen = None; | ||
| 1161 | + for line in text.lines().skip(1) { | ||
| 1162 | + let f: Vec<&str> = line.split('\t').collect(); | ||
| 1163 | + if f.len() < 7 || f[2] != "h264" { | ||
| 1164 | + continue; | ||
| 1165 | + } | ||
| 1166 | + let width: u32 = f[3].parse().unwrap_or(0); | ||
| 1167 | + // Long enough that the extraction's 60 s seek lands inside the file. | ||
| 1168 | + let duration: f64 = f.get(8).and_then(|d| d.parse().ok()).unwrap_or(0.0); | ||
| 1169 | + if width < 1280 || duration < 90.0 { | ||
| 1170 | + continue; | ||
| 1171 | + } | ||
| 1172 | + let path = PathBuf::from(f[0]); | ||
| 1173 | + if f[0].contains("/Films/") && film.is_none() { | ||
| 1174 | + film = Some(("film A", path)); | ||
| 1175 | + } else if f[0].contains("/OBS/") && screen.is_none() { | ||
| 1176 | + screen = Some(("screen capture", path)); | ||
| 1177 | + } | ||
| 1178 | + } | ||
| 1179 | + film.into_iter().chain(screen).collect() | ||
| 1180 | +} | ||
| 1181 | + | ||
| 1182 | +/// BD-rate of `test` against `reference`, as a fraction (negative = fewer | ||
| 1183 | +/// bits for the same quality), integrated piecewise-linearly in | ||
| 1184 | +/// `log10(bits per frame)` over the PSNR range the two ladders share. | ||
| 1185 | +/// | ||
| 1186 | +/// The cubic fit of the original method needs four well-spread points and | ||
| 1187 | +/// misbehaves outside them; a trapezoid over the overlap is the honest | ||
| 1188 | +/// version of the same integral for ladders this short. | ||
| 1189 | +fn bd_rate(reference: &[(f64, f64)], test: &[(f64, f64)]) -> f64 { | ||
| 1190 | + let low = reference[0].1.max(test[0].1); | ||
| 1191 | + let high = reference[reference.len() - 1].1.min(test[test.len() - 1].1); | ||
| 1192 | + if !(high > low) { | ||
| 1193 | + return f64::NAN; | ||
| 1194 | + } | ||
| 1195 | + // log-rate at a PSNR, linearly interpolated inside the ladder. | ||
| 1196 | + let at = |ladder: &[(f64, f64)], db: f64| -> f64 { | ||
| 1197 | + for pair in ladder.windows(2) { | ||
| 1198 | + let ((r0, d0), (r1, d1)) = (pair[0], pair[1]); | ||
| 1199 | + if db >= d0 && db <= d1 { | ||
| 1200 | + let t = if (d1 - d0).abs() < f64::EPSILON { | ||
| 1201 | + 0.0 | ||
| 1202 | + } else { | ||
| 1203 | + (db - d0) / (d1 - d0) | ||
| 1204 | + }; | ||
| 1205 | + return r0.log10() + t * (r1.log10() - r0.log10()); | ||
| 1206 | + } | ||
| 1207 | + } | ||
| 1208 | + if db < ladder[0].1 { | ||
| 1209 | + ladder[0].0.log10() | ||
| 1210 | + } else { | ||
| 1211 | + ladder[ladder.len() - 1].0.log10() | ||
| 1212 | + } | ||
| 1213 | + }; | ||
| 1214 | + let steps = 100; | ||
| 1215 | + let mut integral = 0.0; | ||
| 1216 | + for i in 0..steps { | ||
| 1217 | + let a = low + (high - low) * f64::from(i) / f64::from(steps); | ||
| 1218 | + let b = low + (high - low) * f64::from(i + 1) / f64::from(steps); | ||
| 1219 | + let da = at(test, a) - at(reference, a); | ||
| 1220 | + let db = at(test, b) - at(reference, b); | ||
| 1221 | + integral += (da + db) / 2.0 * (b - a); | ||
| 1222 | + } | ||
| 1223 | + 10f64.powf(integral / (high - low)) - 1.0 | ||
| 1224 | +} | ||
| 1225 | + | ||
| 1226 | +/// Hardware AV1 encode speed at the two sizes his library is in, in frames per | ||
| 1227 | +/// second. Real time is 24 fps; the number is printed rather than asserted, | ||
| 1228 | +/// since a busy GPU is not a failing encoder. | ||
| 1229 | +#[test] | ||
| 1230 | +fn av1_encode_speed() { | ||
| 1231 | + let Some(display) = display() else { return }; | ||
| 1232 | + for (width, height) in [(1920u32, 1080u32), (3840, 1608)] { | ||
| 1233 | + let frames = 30u32; | ||
| 1234 | + let start = Instant::now(); | ||
| 1235 | + match encode_stream(&display, EncCodec::Av1, width, height, frames) { | ||
| 1236 | + Ok(data) => { | ||
| 1237 | + let secs = start.elapsed().as_secs_f64(); | ||
| 1238 | + println!( | ||
| 1239 | + "AV1 encode {width}x{height}: {:.1} fps ({frames} frames in {secs:.2} s), {} kbit/frame", | ||
| 1240 | + f64::from(frames) / secs, | ||
| 1241 | + data.len() * 8 / frames as usize / 1000 | ||
| 1242 | + ); | ||
| 1243 | + } | ||
| 1244 | + Err(e) => { | ||
| 1245 | + eprintln!("skipped: AV1 encode unavailable ({e})"); | ||
| 1246 | + return; | ||
| 1247 | + } | ||
| 1248 | + } | ||
| 880 | } | 1249 | } |
| 881 | } | 1250 | } |
| 882 | 1251 | ||
tools/ec-bench/Cargo.tomlmodified+2 -0
| @@ -18,6 +18,8 @@ ec-core = { workspace = true } | |||
| 18 | ec-h264 = { workspace = true } | 18 | ec-h264 = { workspace = true } |
| 19 | ec-h265 = { workspace = true } | 19 | ec-h265 = { workspace = true } |
| 20 | ec-av1 = { workspace = true } | 20 | ec-av1 = { workspace = true } |
| 21 | +ec-hw = { workspace = true } | ||
| 22 | +ec-va = { workspace = true } | ||
| 21 | ec-probe = { workspace = true } | 23 | ec-probe = { workspace = true } |
| 22 | ec-h264-syntax = { workspace = true } | 24 | ec-h264-syntax = { workspace = true } |
| 23 | ec-image = { workspace = true } | 25 | ec-image = { workspace = true } |
tools/ec-bench/src/main.rsmodified+72 -0
| @@ -42,6 +42,7 @@ fn main() { | |||
| 42 | bench_h264(&mut rows); | 42 | bench_h264(&mut rows); |
| 43 | bench_h265_encode(&mut rows); | 43 | bench_h265_encode(&mut rows); |
| 44 | bench_av1_encode(&mut rows); | 44 | bench_av1_encode(&mut rows); |
| 45 | + bench_hw_av1_encode(&mut rows); | ||
| 45 | bench_audio_decode(&mut rows); | 46 | bench_audio_decode(&mut rows); |
| 46 | bench_audio_encode(&mut rows); | 47 | bench_audio_encode(&mut rows); |
| 47 | bench_truehd(&mut rows); | 48 | bench_truehd(&mut rows); |
| @@ -328,6 +329,77 @@ fn bench_h265_encode(rows: &mut Vec<Row>) { | |||
| 328 | }); | 329 | }); |
| 329 | } | 330 | } |
| 330 | 331 | ||
| 332 | +// --------------------------------------------------------------------------- | ||
| 333 | +// hardware av1: the GPU encoder, at the size his library is in. | ||
| 334 | +// --------------------------------------------------------------------------- | ||
| 335 | + | ||
| 336 | +/// AV1 encode on the GPU (`ec-hw`, VA-API). Skips as a row rather than a | ||
| 337 | +/// failure when there is no VA device or the driver has no AV1 encode | ||
| 338 | +/// entrypoint -- a machine without one is not a slow machine. | ||
| 339 | +fn bench_hw_av1_encode(rows: &mut Vec<Row>) { | ||
| 340 | + let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else { | ||
| 341 | + rows.push(missing("ec-hw av1", "encode")); | ||
| 342 | + return; | ||
| 343 | + }; | ||
| 344 | + let display = match ec_va::Display::open() { | ||
| 345 | + Ok(display) => display, | ||
| 346 | + Err(e) => { | ||
| 347 | + rows.push(missing_direction("ec-hw av1", "encode", &format!("no VA display ({e})"))); | ||
| 348 | + return; | ||
| 349 | + } | ||
| 350 | + }; | ||
| 351 | + let (planes, w, h, n) = extract_yuv420p(&src, 1920, 1080, 30); | ||
| 352 | + if n == 0 { | ||
| 353 | + rows.push(missing("ec-hw av1", "encode")); | ||
| 354 | + return; | ||
| 355 | + } | ||
| 356 | + let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h); | ||
| 357 | + cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 }; | ||
| 358 | + let mut enc = match ec_hw::Encoder::new(&display, cfg) { | ||
| 359 | + Ok(enc) => enc, | ||
| 360 | + Err(e) => { | ||
| 361 | + rows.push(missing_direction("ec-hw av1", "encode", &format!("driver refused ({e})"))); | ||
| 362 | + return; | ||
| 363 | + } | ||
| 364 | + }; | ||
| 365 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | ||
| 366 | + let frame_len = (w * h + 2 * cw * ch) as usize; | ||
| 367 | + let start = Instant::now(); | ||
| 368 | + let mut coded = 0usize; | ||
| 369 | + for (i, frame) in planes.chunks_exact(frame_len).enumerate() { | ||
| 370 | + let (y, rest) = frame.split_at((w * h) as usize); | ||
| 371 | + let (u, v) = rest.split_at(rest.len() / 2); | ||
| 372 | + let picture = ec_hw::I420 { | ||
| 373 | + y: y.to_vec(), | ||
| 374 | + u: u.to_vec(), | ||
| 375 | + v: v.to_vec(), | ||
| 376 | + width: w, | ||
| 377 | + height: h, | ||
| 378 | + }; | ||
| 379 | + let meta = ec_hw::FrameMetadata { | ||
| 380 | + timestamp: i as i64, | ||
| 381 | + force_keyframe: false, | ||
| 382 | + }; | ||
| 383 | + match enc.encode(&picture, meta) { | ||
| 384 | + Ok(out) => coded += out.data.len(), | ||
| 385 | + Err(e) => { | ||
| 386 | + rows.push(missing_direction("ec-hw av1", "encode", &format!("encode failed ({e})"))); | ||
| 387 | + return; | ||
| 388 | + } | ||
| 389 | + } | ||
| 390 | + } | ||
| 391 | + let wall = start.elapsed().as_secs_f64(); | ||
| 392 | + let media_s = n as f64 / 30.0; | ||
| 393 | + rows.push(Row { | ||
| 394 | + component: "ec-hw av1", | ||
| 395 | + direction: "encode", | ||
| 396 | + content: format!("{w}x{h}, {n} frames, CQP 120, {} kB", coded / 1000), | ||
| 397 | + media: format!("{media_s:.1}s"), | ||
| 398 | + wall_ms: wall * 1000.0, | ||
| 399 | + rtf: (wall > 0.0).then_some(media_s / wall), | ||
| 400 | + }); | ||
| 401 | +} | ||
| 402 | + | ||
| 331 | // --------------------------------------------------------------------------- | 403 | // --------------------------------------------------------------------------- |
| 332 | // av1: encode only -- same shape as h265. | 404 | // av1: encode only -- same shape as h265. |
| 333 | // --------------------------------------------------------------------------- | 405 | // --------------------------------------------------------------------------- |