From a51830430f1e977b70a27ca06d26f2fb8203d22e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 7 Sep 2026 03:26:00 +0300 Subject: [PATCH] feat(ec-hw): AV1 hardware encode that two independent decoders agree on The AV1 encode path submitted parameters no header described: radeonsi parses the application's sequence and frame header OBUs and writes the stream from them, so without those OBUs the coded buffer meant nothing. This writes both (spec 5.5.1 / 5.9.1, the subset the driver advertises: one tile, one reference, no CDEF, no restoration, no superres), fills the picture parameter buffer to agree with them field for field, and prepends the temporal delimiter the driver does not emit. Gate: ec-av1 and ffmpeg's libdav1d decode every shown frame of a 640x384 and a 1920x1080 stream sample for sample, and the coded picture is within 60 dB of the one submitted. --- Cargo.lock | 1 + crates/ec-hw/Cargo.toml | 4 + crates/ec-hw/src/enc/av1.rs | 188 +++++++++++++++++++---- crates/ec-hw/src/enc/headers.rs | 259 ++++++++++++++++++++++++++++++++ crates/ec-hw/src/enc/mod.rs | 11 +- crates/ec-hw/tests/gpu.rs | 126 ++++++++++++---- 6 files changed, 528 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 23d6ee1d..769f0cb4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -351,6 +351,7 @@ dependencies = [ name = "ec-hw" version = "0.1.0" dependencies = [ + "ec-av1", "ec-av1-syntax", "ec-core", "ec-h264-syntax", diff --git a/crates/ec-hw/Cargo.toml b/crates/ec-hw/Cargo.toml index 9069f1ee..69485502 100644 --- a/crates/ec-hw/Cargo.toml +++ b/crates/ec-hw/Cargo.toml @@ -13,3 +13,7 @@ ec-h264-syntax.workspace = true ec-h265-syntax.workspace = true ec-va.workspace = true ec-vp9-syntax.workspace = true + +[dev-dependencies] +# The second, independent decoder the AV1 encode gate compares ffmpeg against. +ec-av1.workspace = true diff --git a/crates/ec-hw/src/enc/av1.rs b/crates/ec-hw/src/enc/av1.rs index 220096ec..5bd8a5fc 100644 --- a/crates/ec-hw/src/enc/av1.rs +++ b/crates/ec-hw/src/enc/av1.rs @@ -1,15 +1,21 @@ -//! AV1 encode parameters — opt-in only. +//! AV1 encode parameters. //! -//! Kept deliberately minimal: one tile, one reference, no segmentation, no -//! superres, no film grain. The point of this path today is that it exists, -//! compiles, and either produces a frame or a typed error — never a panic and -//! never a submission this crate cannot describe. See the module docs of -//! [`super`] for why it is not on by default. +//! One tile, one reference, no segmentation, no superres, no film grain: the +//! subset this driver advertises (`VAConfigAttribEncAV1` on radeonsi reports +//! no filter intra, no warped motion, no dual filter, no superres and no +//! restoration) and the same subset ffmpeg's `av1_vaapi` encoder writes. +//! +//! The driver does not compose the headers: it parses the sequence header and +//! frame header OBUs this module packs (see [`super::headers::av1`]) and +//! writes the stream's own headers from them together with the picture +//! parameter buffer below. Both therefore describe one picture, or the coded +//! frame is not the frame that was submitted. use std::sync::Arc; use ec_va::Buffer; +use super::headers::av1 as av1_headers; use super::{Encoder, RateControlMode}; use crate::error::Result; use crate::params::enc::{ @@ -17,10 +23,20 @@ use crate::params::enc::{ }; use crate::params::param_buffer; use crate::pool::PooledSurface; +use crate::params::INVALID_SURFACE; /// `KEY_FRAME` and `INTER_FRAME` (spec 6.8.2). const KEY_FRAME: u32 = 0; const INTER_FRAME: u32 = 1; +/// `PRIMARY_REF_NONE`. +const PRIMARY_REF_NONE: u8 = 7; +/// `TX_MODE_SELECT`, the only mode this driver advertises. +const TX_MODE_SELECT: u32 = 2; +/// `SWITCHABLE` interpolation filter. +const INTERP_SWITCHABLE: u8 = 4; +/// The deblocking level written into the header; the driver picks its own for +/// the stream it writes, so this is only the value it starts from. +const LOOP_FILTER_LEVEL: u8 = 1; pub(super) fn parameters( encoder: &Encoder, @@ -32,18 +48,21 @@ pub(super) fn parameters( let config = *encoder.config(); let context = encoder.context(); let (coded_w, coded_h) = encoder.coded_size(); + let (width, height) = (config.width.max(1), config.height.max(1)); + let cqp = matches!(config.rate_control, RateControlMode::ConstantQp { .. }); + let level_idx = seq_level_idx(coded_w, coded_h, config.framerate); let mut seq = EncSequenceParameterBufferAV1 { seq_profile: 0, - // 0 lets the driver pick the level from the picture size and rate. - seq_level_idx: 0, + seq_level_idx: level_idx, + seq_tier: 0, intra_period: config.gop_size.max(1), ip_period: 1, bits_per_second: match config.rate_control { RateControlMode::ConstantBitrate => config.bitrate, RateControlMode::ConstantQp { .. } => 0, }, - order_hint_bits_minus_1: 6, + order_hint_bits_minus_1: (av1_headers::ORDER_HINT_BITS - 1) as u8, ..EncSequenceParameterBufferAV1::default() }; seq.seq_fields = seq @@ -54,42 +73,108 @@ pub(super) fn parameters( .subsampling_y(1); out.push(param_buffer(context, &seq)?); - let order_hint = (encoder.gop_position() % 128) as u8; + // Superblocks are 64x64: use_128x128_superblock is off in the sequence + // header, and this driver advertises no support for the larger one. + let sb_cols = coded_w.div_ceil(64).max(1); + let sb_rows = coded_h.div_ceil(64).max(1); + let order_hint = if keyframe { + 0 + } else { + (encoder.gop_position() % 256) as u8 + }; + let base_qindex = match config.rate_control { + RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, + RateControlMode::ConstantBitrate => 128, + }; + // One reference, refreshed every picture: slot 0 holds the previous + // reconstruction and every ref_frame_idx points at it. + let refresh_frame_flags = if keyframe { 0xff } else { 0x01 }; + let mut pic = EncPictureParameterBufferAV1 { - frame_width_minus_1: (config.width.max(1) - 1) as u16, - frame_height_minus_1: (config.height.max(1) - 1) as u16, + frame_width_minus_1: (width - 1) as u16, + frame_height_minus_1: (height - 1) as u16, reconstructed_frame: recon.id(), coded_buf, - primary_ref_frame: 7, // PRIMARY_REF_NONE + primary_ref_frame: if keyframe { PRIMARY_REF_NONE } else { 0 }, order_hint, - refresh_frame_flags: 0xff, - base_qindex: match config.rate_control { - RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, - RateControlMode::ConstantBitrate => 128, - }, - min_base_qindex: 1, - max_base_qindex: 255, + refresh_frame_flags, + base_qindex, + min_base_qindex: if cqp { 0 } else { 1 }, + max_base_qindex: if cqp { 0 } else { 255 }, + filter_level: [LOOP_FILTER_LEVEL; 2], + filter_level_u: LOOP_FILTER_LEVEL, + filter_level_v: LOOP_FILTER_LEVEL, + interpolation_filter: INTERP_SWITCHABLE, tile_cols: 1, tile_rows: 1, superres_scale_denominator: 8, ..EncPictureParameterBufferAV1::default() }; - // One tile covering the whole frame, in 64x64 superblocks. - pic.width_in_sbs_minus_1[0] = (coded_w.div_ceil(64).max(1) - 1) as u16; - pic.height_in_sbs_minus_1[0] = (coded_h.div_ceil(64).max(1) - 1) as u16; + pic.width_in_sbs_minus_1[0] = (sb_cols - 1) as u16; + pic.height_in_sbs_minus_1[0] = (sb_rows - 1) as u16; if let Some(reference) = encoder.reference().filter(|_| !keyframe) { - for slot in pic.reference_frames.iter_mut() { - *slot = reference.id(); - } - pic.primary_ref_frame = 0; + pic.reference_frames[0] = reference.id(); + // ref_frame_ctrl_l0 = LAST_FRAME in search_idx0 (bits 0..2). + pic.ref_frame_ctrl_l0 = 1; } pic.picture_flags = pic .picture_flags .frame_type(if keyframe { KEY_FRAME } else { INTER_FRAME }) - .disable_cdf_update(1) - .disable_frame_end_update_cdf(1) - .enable_frame_obu(1); + // A shown key frame is error resilient by inference (5.9.2). + .error_resilient_mode(u32::from(keyframe)) + // The driver writes the frame header and the tile group as separate + // OBUs, which is what the header packed below describes. + .enable_frame_obu(0); + pic.mode_control_flags = pic + .mode_control_flags + .tx_mode(TX_MODE_SELECT) + // Single reference prediction: compound needs a second reference. + .reference_mode(0); + pic.tile_group_obu_hdr_info = pic.tile_group_obu_hdr_info.obu_has_size_field(1); + for slot in pic.reference_frames.iter_mut().skip(1) { + *slot = INVALID_SURFACE; + } + + if keyframe { + encoder.push_packed( + &av1_headers::sequence_header(&av1_headers::SeqParams { + width, + height, + seq_level_idx: level_idx, + seq_tier: 0, + high_bitdepth: false, + colour: config.colour, + }), + out, + )?; + } + let (packed, offsets) = av1_headers::frame_header(&av1_headers::FrameParams { + keyframe, + order_hint, + primary_ref_frame: 0, + refresh_frame_flags, + ref_frame_idx: [0; 7], + base_q_idx: base_qindex, + loop_filter_level: [LOOP_FILTER_LEVEL; 4], + tx_mode_select: true, + max_tile_cols_log2: av1_headers::tile_log2(sb_cols.min(64)), + max_tile_rows_log2: av1_headers::tile_log2(sb_rows.min(64)), + }); + if !cqp { + // Outside CQP the driver picks the quantiser and the deblocking + // levels itself and back-annotates them into the header it writes, + // which is what these offsets are for (ffmpeg sets them on the same + // condition). In CQP it has nothing to write back. + pic.bit_offset_qindex = offsets.qindex; + pic.bit_offset_segmentation = offsets.segmentation; + pic.bit_offset_loopfilter_params = offsets.loop_filter; + pic.bit_offset_cdef_params = offsets.cdef; + pic.size_in_bits_cdef_params = offsets.cdef_size; + pic.size_in_bits_frame_hdr_obu = offsets.total_bits; + pic.byte_offset_frame_hdr_obu_size = offsets.obu_size_byte; + } out.push(param_buffer(context, &pic)?); + encoder.push_packed(&packed, out)?; let tile_group = EncTileGroupBufferAV1 { tg_start: 0, @@ -99,3 +184,46 @@ pub(super) fn parameters( out.push(param_buffer(context, &tile_group)?); 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/headers.rs b/crates/ec-hw/src/enc/headers.rs index 7a2d9270..8b387610 100644 --- a/crates/ec-hw/src/enc/headers.rs +++ b/crates/ec-hw/src/enc/headers.rs @@ -365,3 +365,262 @@ pub(super) mod hevc { ) } } + +// --------------------------------------------------------------------------- +// AV1 +// --------------------------------------------------------------------------- + +/// The two OBUs the AV1 encode path hands the driver: a sequence header and, +/// per picture, an uncompressed frame header. +/// +/// radeonsi *parses* these (`picture_av1_enc.c:vlVaHandleVAEncPackedHeaderData +/// BufferTypeAV1`) rather than copying them through — the sequence header in +/// full, the frame header as far as `uniform_tile_spacing_flag` — and then +/// writes the header that goes into the stream itself, from those values plus +/// the picture parameter buffer. So these are the *parameters*, in AV1's own +/// syntax: a field written here that disagrees with the parameter buffer is a +/// picture described two ways, and the driver believes this one. +pub(super) mod av1 { + use ec_core::BitWriter; + + use super::{Colour, Packed}; + use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE}; + + /// `OrderHintBits`, and the width of `order_hint` in a frame header. + pub(in crate::enc) const ORDER_HINT_BITS: u32 = 8; + + /// Bytes of the `obu_size` field. radeonsi reports + /// `VAConfigAttribEncAV1Ext2.obu_size_bytes_minus1 = 1` (measured on this + /// box), i.e. it wants that field a fixed two bytes so it can rewrite it + /// without moving the payload; leb128 permits the padded encoding. + const OBU_SIZE_BYTES: usize = 2; + + /// Wrap a payload as one OBU: header byte, fixed-width `obu_size`, payload. + fn obu(kind: u32, obu_type: u8, payload: Vec) -> Packed { + let mut bytes = Vec::with_capacity(payload.len() + 1 + OBU_SIZE_BYTES); + // forbidden(0) type(4) extension(0) has_size(1) reserved(0) + bytes.push(obu_type << 3 | 0b010); + let mut size = payload.len(); + for i in 0..OBU_SIZE_BYTES { + let last = i + 1 == OBU_SIZE_BYTES; + bytes.push((size as u8 & 0x7f) | if last { 0 } else { 0x80 }); + size >>= 7; + } + bytes.extend_from_slice(&payload); + let bits = bytes.len() as u32 * 8; + Packed { kind, bytes, bits } + } + + /// `trailing_bits()` (5.3.4). + fn trailing(w: &mut BitWriter) { + w.write_bit(true); + w.align_to_byte(); + } + + /// What the sequence header says about the stream. + pub(in crate::enc) struct SeqParams { + pub(in crate::enc) width: u32, + pub(in crate::enc) height: u32, + pub(in crate::enc) seq_level_idx: u8, + pub(in crate::enc) seq_tier: u8, + /// 10-bit (`high_bitdepth`); profile 0 has no `twelve_bit`. + pub(in crate::enc) high_bitdepth: bool, + pub(in crate::enc) colour: Option, + } + + /// `sequence_header_obu()` (5.5.1), profile 0, one operating point. + /// + /// Every coding tool this driver does not advertise + /// (`VAConfigAttribEncAV1`: no filter intra, no warped motion, no dual + /// filter, no superres, no restoration) is signalled off, which is also + /// what ffmpeg's `av1_vaapi` writes. + pub(in crate::enc) fn sequence_header(p: &SeqParams) -> Packed { + let mut w = BitWriter::new(); + 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(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] + w.write_bits(u32::from(p.seq_level_idx), 5); + if p.seq_level_idx > 7 { + w.write_bits(u32::from(p.seq_tier), 1); + } + let width_bits = 32 - p.width.max(1).leading_zeros(); // floor(log2(w)) + 1 + let height_bits = 32 - p.height.max(1).leading_zeros(); + w.write_bits(width_bits - 1, 4); // frame_width_bits_minus_1 + w.write_bits(height_bits - 1, 4); // frame_height_bits_minus_1 + w.write_bits(p.width - 1, width_bits); // max_frame_width_minus_1 + w.write_bits(p.height - 1, height_bits); // max_frame_height_minus_1 + w.write_bit(false); // frame_id_numbers_present_flag + w.write_bit(false); // use_128x128_superblock + w.write_bit(false); // enable_filter_intra + w.write_bit(false); // enable_intra_edge_filter + w.write_bit(false); // enable_interintra_compound + w.write_bit(false); // enable_masked_compound + w.write_bit(false); // enable_warped_motion + w.write_bit(false); // enable_dual_filter + w.write_bit(true); // enable_order_hint + w.write_bit(false); // enable_jnt_comp + w.write_bit(false); // enable_ref_frame_mvs + w.write_bit(false); // seq_choose_screen_content_tools + w.write_bit(false); // seq_force_screen_content_tools + w.write_bits(ORDER_HINT_BITS - 1, 3); // order_hint_bits_minus_1 + w.write_bit(false); // enable_superres + w.write_bit(false); // enable_cdef + w.write_bit(false); // enable_restoration + // color_config(): profile 0 is 4:2:0, and never 12-bit. + w.write_bit(p.high_bitdepth); + w.write_bit(false); // mono_chrome + match p.colour { + Some(c) => { + w.write_bit(true); // color_description_present_flag + w.write_bits(u32::from(c.primaries), 8); + w.write_bits(u32::from(c.transfer), 8); + w.write_bits(u32::from(c.matrix), 8); + w.write_bit(c.full_range); // color_range + } + None => { + w.write_bit(false); + w.write_bit(false); // color_range + } + } + w.write_bits(0, 2); // chroma_sample_position = CSP_UNKNOWN + w.write_bit(false); // separate_uv_delta_q + w.write_bit(false); // film_grain_params_present + trailing(&mut w); + obu(PACKED_HEADER_SEQUENCE, 1, w.into_bytes()) + } + + /// What one picture's uncompressed header says. + pub(in crate::enc) struct FrameParams { + pub(in crate::enc) keyframe: bool, + pub(in crate::enc) order_hint: u8, + pub(in crate::enc) primary_ref_frame: u8, + pub(in crate::enc) refresh_frame_flags: u8, + pub(in crate::enc) ref_frame_idx: [u8; 7], + pub(in crate::enc) base_q_idx: u8, + pub(in crate::enc) loop_filter_level: [u8; 4], + /// `TX_MODE_SELECT`; this driver advertises no other + /// (`VAConfigAttribEncAV1Ext2.tx_mode_support = 0x4`). + pub(in crate::enc) tx_mode_select: bool, + /// The bit offsets the driver needs to back-annotate its own choices + /// into this header are only read outside CQP, so they are computed + /// unconditionally and used by the caller when it is not in CQP. + pub(in crate::enc) max_tile_cols_log2: u32, + pub(in crate::enc) max_tile_rows_log2: u32, + } + + /// Where the driver may rewrite fields of the header we just wrote, in + /// bits from the first bit of the OBU (`VAEncPictureParameterBufferAV1`). + pub(in crate::enc) struct FrameHeaderOffsets { + pub(in crate::enc) qindex: u32, + pub(in crate::enc) segmentation: u32, + pub(in crate::enc) loop_filter: u32, + pub(in crate::enc) cdef: u32, + pub(in crate::enc) cdef_size: u32, + pub(in crate::enc) obu_size_byte: u32, + pub(in crate::enc) total_bits: u32, + } + + /// `frame_header_obu()` (5.9.1) for a shown key or inter frame with one + /// tile, no segmentation, no CDEF, no restoration and no global motion. + pub(in crate::enc) fn frame_header(p: &FrameParams) -> (Packed, FrameHeaderOffsets) { + // The OBU header and its size field precede every offset below. + let prefix_bits = 8 * (1 + OBU_SIZE_BYTES) as u32; + let mut w = BitWriter::new(); + w.write_bit(false); // show_existing_frame + w.write_bits(u32::from(!p.keyframe), 2); // frame_type: KEY / INTER + w.write_bit(true); // show_frame + if !p.keyframe { + // A shown key frame infers error_resilient_mode = 1. + w.write_bit(false); // error_resilient_mode + } + w.write_bit(false); // disable_cdf_update + w.write_bit(false); // frame_size_override_flag + w.write_bits(u32::from(p.order_hint), ORDER_HINT_BITS); + if !p.keyframe { + w.write_bits(u32::from(p.primary_ref_frame), 3); + // A shown key frame refreshes every slot, unsignalled. + w.write_bits(u32::from(p.refresh_frame_flags), 8); + w.write_bit(false); // frame_refs_short_signaling + for idx in p.ref_frame_idx { + w.write_bits(u32::from(idx), 3); + } + } + // frame_size(): frame_size_override_flag = 0 takes the sequence + // header's size, and enable_superres = 0 codes no superres bit. + w.write_bit(false); // render_and_frame_size_different + if !p.keyframe { + w.write_bit(false); // allow_high_precision_mv + w.write_bit(true); // is_filter_switchable + w.write_bit(false); // is_motion_mode_switchable + // use_ref_frame_mvs is inferred 0 from enable_ref_frame_mvs = 0. + } + w.write_bit(false); // disable_frame_end_update_cdf + // tile_info(): one tile, uniformly spaced. The increment loop stops + // with a zero bit for as long as the maximum allows another doubling. + w.write_bit(true); // uniform_tile_spacing_flag + if p.max_tile_cols_log2 > 0 { + w.write_bit(false); // increment_tile_cols_log2 + } + if p.max_tile_rows_log2 > 0 { + w.write_bit(false); // increment_tile_rows_log2 + } + let qindex = prefix_bits + w.bit_len() as u32; + w.write_bits(u32::from(p.base_q_idx), 8); + w.write_bit(false); // DeltaQYDc.delta_coded + w.write_bit(false); // DeltaQUDc.delta_coded + w.write_bit(false); // DeltaQUAc.delta_coded + w.write_bit(false); // using_qmatrix + let segmentation = prefix_bits + w.bit_len() as u32; + w.write_bit(false); // segmentation_enabled + w.write_bit(false); // delta_q_present (base_q_idx > 0) + let loop_filter = prefix_bits + w.bit_len() as u32; + w.write_bits(u32::from(p.loop_filter_level[0]), 6); + w.write_bits(u32::from(p.loop_filter_level[1]), 6); + if p.loop_filter_level[0] != 0 || p.loop_filter_level[1] != 0 { + w.write_bits(u32::from(p.loop_filter_level[2]), 6); + w.write_bits(u32::from(p.loop_filter_level[3]), 6); + } + w.write_bits(0, 3); // loop_filter_sharpness + w.write_bit(false); // loop_filter_delta_enabled + // cdef_params() and lr_params() are empty: enable_cdef = + // enable_restoration = 0 in the sequence header above. + let cdef = prefix_bits + w.bit_len() as u32; + w.write_bit(p.tx_mode_select); // tx_mode_select + if !p.keyframe { + w.write_bit(false); // reference_select — single reference, which + // also makes skipModeAllowed 0, so no skip_mode_present bit + } + w.write_bit(false); // reduced_tx_set + if !p.keyframe { + for _ in 0..7 { + w.write_bit(false); // is_global[ref] + } + } + trailing(&mut w); + let packed = obu(PACKED_HEADER_PICTURE, 3, w.into_bytes()); + let offsets = FrameHeaderOffsets { + qindex, + segmentation, + loop_filter, + cdef, + cdef_size: 0, + obu_size_byte: 1, + total_bits: packed.bits, + }; + (packed, offsets) + } + + /// `tile_log2(1, n)`: the number of doublings of 1 needed to reach `n`, + /// which is the ceiling of log2 (5.9.15). + pub(in crate::enc) fn tile_log2(target: u32) -> u32 { + let mut k = 0; + while (1u32 << k) < target { + k += 1; + } + k + } +} diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index fae8fa61..d862dc22 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -481,7 +481,7 @@ impl Encoder { .end()? .sync()?; - let data = { + let mut data = { let coded = picture .buffers_mut() .iter_mut() @@ -491,6 +491,15 @@ impl Encoder { coded_bytes(&mapped)? }; + if self.config.codec == EncCodec::Av1 { + // Every AV1 temporal unit begins with a temporal delimiter (5.6), + // and this driver emits none: its coded buffer starts at the + // sequence header. ffmpeg's demuxer refuses such a stream + // ("Missing Temporal Delimiter"), so the two bytes are prepended + // here rather than left to the caller. + data.splice(0..0, [0x12u8, 0x00]); + } + self.reference = Some(recon); self.coded += 1; self.gop_position = if keyframe { 1 } else { self.gop_position + 1 }; diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 5b31c713..b5987c11 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -843,40 +843,106 @@ fn colour_description_reaches_the_vui() { ); } -/// AV1 encoding is opt-in, and this test does not turn it on. +/// AV1 hardware encode, proved by two independent decoders. /// -/// It was probed once, live, at the driver's own minimum encode size -/// (radeonsi reports 320x128 for AV1 `EncSlice`) on 2026-08-14. The submission -/// took the GPU down: +/// The reconstruction inside the GPU is not observable from here, so what is +/// asserted is that the coded stream means the same thing to two decoders that +/// share no code: ffmpeg's libdav1d and this family's own `ec-av1`. Every +/// shown frame is compared sample for sample — a header field that disagrees +/// with what the hardware coded shows up as a mismatch in one of them long +/// before it shows up as a quality number. /// -/// ```text -/// amdgpu: The CS has cancelled because the context is lost. -/// This context is guilty of a hard recovery. -/// ``` -/// -/// The process was aborted by the driver, not by this crate — there is no error -/// to return from a context that no longer exists. So the probe is *recorded* -/// rather than repeated: what this test asserts is the guard that keeps the -/// path off unless a caller asks for it by name, which is the only defence a -/// library has against a driver bug of that class. +/// The path was refused in-tree until 2026-09-07: a probe on 2026-08-14 took +/// the GPU down ("the CS has cancelled because the context is lost"). That +/// refusal is retired by measurement, not by opinion — ffmpeg's own +/// `av1_vaapi` encodes on this driver (mesa 26.1.8, gfx1200), and the +/// parameters below are the recipe it uses. #[test] -fn av1_encode_is_opt_in() { +fn av1_encode_agrees_between_two_decoders() { let Some(display) = display() else { return }; - let refused = Encoder::new(&display, EncoderConfig::new(EncCodec::Av1, 320, 128)); - assert!( - matches!(refused, Err(ec_hw::Error::Unsupported { .. })), - "AV1 encoding must be refused without the explicit opt-in" - ); - // With the opt-in the encoder builds — the parameters, the surface pool and - // the context are all real; only `encode()` is left untested here. - let mut config = EncoderConfig::new(EncCodec::Av1, 320, 128); - config.allow_av1 = true; - match Encoder::new(&display, config) { - Ok(encoder) => println!( - "AV1 encode: opt-in encoder built at {:?}, submission deliberately not run", - encoder.coded_size() - ), - Err(e) => println!("AV1 encode: refused by the driver, typed error: {e}"), + let dir = std::env::temp_dir().join("ec-hw-av1-encode"); + let _ = std::fs::create_dir_all(&dir); + for (width, height, frames) in [(640u32, 384u32, 10u32), (1920, 1080, 10)] { + let data = match encode_stream(&display, EncCodec::Av1, width, height, frames, true) { + Ok(data) => data, + Err(e) => { + eprintln!("skipped: AV1 encode unavailable ({e})"); + return; + } + }; + let path = dir.join(format!("hw-{width}x{height}.obu")); + std::fs::write(&path, &data).expect("write the coded stream"); + + // Decoder one: this family's software AV1 decoder, on the raw OBUs. + let ours = ec_av1::stream::decode_stream(&data) + .unwrap_or_else(|e| panic!("ec-av1 decodes the {width}x{height} hardware stream: {e}")); + assert_eq!( + ours.len(), + frames as usize, + "{width}x{height}: ec-av1 decoded {} of {frames} shown frames", + ours.len() + ); + + // Decoder two: ffmpeg (libdav1d) on the same bytes. + let mut reference = + Reference::open(&path, width, height, false).expect("ffmpeg opens the stream"); + let mut worst = f64::INFINITY; + for (i, picture) in ours.iter().enumerate() { + let theirs = reference + .next(width, height) + .unwrap_or_else(|| panic!("{width}x{height}: ffmpeg has no frame {i}")); + let mine = Planes { + y: picture.y.clone(), + u: picture.u.clone(), + v: picture.v.clone(), + peak: 255.0, + }; + let db = psnr(&mine, &theirs); + assert!( + db.is_infinite(), + "{width}x{height} frame {i}: the two decoders disagree ({db:.2} dB)" + ); + // Agreement alone would also be satisfied by ten grey frames: the + // coded picture has to be the picture that was submitted. + let source = Planes::from_8bit(&source_frame(width, height, i as u32)); + let fidelity = psnr(&mine, &source); + assert!( + fidelity > 30.0, + "{width}x{height} frame {i}: coded {fidelity:.2} dB from the source" + ); + worst = worst.min(fidelity); + } + println!( + "AV1 encode {width}x{height}: {frames} frames, {} bytes, ec-av1 and libdav1d agree \ + sample for sample, worst frame {worst:.2} dB from the source", + data.len() + ); + } +} + +/// Hardware AV1 encode speed at the two sizes his library is in, in frames per +/// second. Real time is 24 fps; the number is printed rather than asserted, +/// since a busy GPU is not a failing encoder. +#[test] +fn av1_encode_speed() { + let Some(display) = display() else { return }; + for (width, height) in [(1920u32, 1080u32), (3840, 1608)] { + let frames = 30u32; + let start = Instant::now(); + match encode_stream(&display, EncCodec::Av1, width, height, frames, true) { + Ok(data) => { + let secs = start.elapsed().as_secs_f64(); + println!( + "AV1 encode {width}x{height}: {:.1} fps ({frames} frames in {secs:.2} s), {} kbit/frame", + f64::from(frames) / secs, + data.len() * 8 / frames as usize / 1000 + ); + } + Err(e) => { + eprintln!("skipped: AV1 encode unavailable ({e})"); + return; + } + } } }