diff --git a/Cargo.lock b/Cargo.lock index 23d6ee1d..c535ff8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -285,12 +285,14 @@ dependencies = [ "ec-h264", "ec-h264-syntax", "ec-h265", + "ec-hw", "ec-image", "ec-inflate", "ec-mp3", "ec-opus", "ec-probe", "ec-truehd", + "ec-va", "ec-vorbis", ] @@ -351,6 +353,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..c0bc0fbf 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -1,4 +1,4 @@ -//! Hardware encoding: H.264, HEVC, and AV1 behind an explicit opt-in. +//! Hardware encoding: H.264, HEVC and AV1. //! //! One frame in, one coded frame out. The GOP is IDR-then-P with a single //! reference, which is what this GPU advertises (`VAConfigAttribEncMaxRefFrames` @@ -7,11 +7,15 @@ //! //! # AV1 //! -//! AV1 encoding is off unless [`EncoderConfig::allow_av1`] is set, and never -//! reachable from an "auto" codec choice. The reason is on the record rather -//! than theoretical: an AV1 encode submission on this driver generation took -//! the GPU down hard enough to need a reset. The path is built, typed and -//! probed; turning it on is a caller's explicit decision. +//! AV1 encode was opt-in until 2026-09-07, after a submission on an older +//! driver took the GPU down. It is on by default now because the refusal was +//! retired by measurement, not by opinion: on mesa 26.1.8 (gfx1200) ffmpeg's +//! own `av1_vaapi` encodes, this path encodes, and `gpu.rs`'s +//! `av1_encode_agrees_between_two_decoders` proves every coded frame decodes +//! identically through `ec-av1` and libdav1d. Unlike H.264 and HEVC, the +//! driver composes no headers of its own from thin air: it parses the +//! sequence and frame header OBUs this crate packs (see `enc::headers::av1`) +//! and writes the stream's headers from them. use std::sync::Arc; @@ -42,7 +46,7 @@ pub enum EncCodec { H264, /// H.265 / HEVC, Main profile. H265, - /// AV1 Profile 0 — opt-in only, see the module docs. + /// AV1 Profile 0. Av1, } @@ -95,8 +99,6 @@ pub struct EncoderConfig { pub rate_control: RateControlMode, /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default. pub quality: u32, - /// Permit AV1 encoding. Without it, [`EncCodec::Av1`] is refused. - pub allow_av1: bool, /// The colour description to write into the VUI, or `None` to leave it /// unsignalled (`video_signal_type_present_flag = 0`) as before. pub colour: Option, @@ -132,7 +134,6 @@ impl EncoderConfig { gop_size: 60, rate_control: RateControlMode::ConstantBitrate, quality: 0, - allow_av1: false, colour: None, } } @@ -199,12 +200,6 @@ pub struct Encoder { impl Encoder { /// Build an encoder for `config` on `display`. pub fn new(display: &Arc, config: EncoderConfig) -> Result { - if config.codec == EncCodec::Av1 && !config.allow_av1 { - return Err(Error::unsupported( - "AV1 hardware encoding", - "it is opt-in (EncoderConfig::allow_av1) after a GPU recovery incident", - )); - } let profile = match config.codec { // High is the profile every H.264 encoder on this driver reports and // the one a High-profile decoder expects; Main is a strict subset. @@ -481,7 +476,7 @@ impl Encoder { .end()? .sync()?; - let data = { + let mut data = { let coded = picture .buffers_mut() .iter_mut() @@ -491,6 +486,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/src/lib.rs b/crates/ec-hw/src/lib.rs index 4087024e..5beceec5 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -30,7 +30,7 @@ //! * [`params`] — the `#[repr(C)]` codec parameter buffers, each checked //! against the system headers by a `const` assertion. //! * [`dec`] — one stateless decoder per codec behind [`Decoder`]. -//! * [`enc`] — H.264 and HEVC encoders, and an opt-in AV1 one. +//! * [`enc`] — H.264, HEVC and AV1 encoders. //! * [`SurfacePool`] / [`Frame`] — surface recycling and pixel access. //! //! # Unsafe diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 5b31c713..bd64d4c8 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -532,13 +532,11 @@ fn encode_stream( width: u32, height: u32, frames: u32, - allow_av1: bool, ) -> Result, ec_hw::Error> { let mut config = EncoderConfig::new(codec, width, height); config.gop_size = 30; config.framerate = (30, 1); config.rate_control = RateControlMode::ConstantQp { qp: 26 }; - config.allow_av1 = allow_av1; let mut encoder = Encoder::new(display, config)?; let mut out = Vec::new(); for t in 0..frames { @@ -559,7 +557,7 @@ fn encode_stream( fn round_trip(codec: EncCodec, width: u32, height: u32, min_db: f64) { let Some(display) = display() else { return }; let frames = 12u32; - let stream = match encode_stream(&display, codec, width, height, frames, false) { + let stream = match encode_stream(&display, codec, width, height, frames) { Ok(stream) => stream, Err(e) => panic!("{codec:?} encode failed: {e}"), }; @@ -649,7 +647,7 @@ fn hevc_encode_honours_the_conformance_window() { fn our_encoder_and_our_decoder_agree() { let Some(display) = display() else { return }; for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { - let stream = encode_stream(&display, enc, 640, 480, 12, false).expect("encode"); + let stream = encode_stream(&display, enc, 640, 480, 12).expect("encode"); let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); let mut worst = f64::INFINITY; let mut count = 0u32; @@ -843,40 +841,411 @@ 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 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_agrees_between_two_decoders() { + let Some(display) = display() else { return }; + 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) { + 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() + ); + } +} + +/// What the GPU's AV1 costs against software, on his own content. /// -/// 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. +/// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen +/// capture, PSNR from ffmpeg, BD-rate over the overlapping quality range +/// against librav1e speed 6 and libaom cpu-used 6. Nothing is asserted about +/// the number — a fixed-function encoder is not a search — but it is measured +/// and printed rather than assumed, and the ladder itself is asserted to be +/// monotone, which is the part a broken parameter set would break. #[test] -fn av1_encode_is_opt_in() { +fn av1_encode_bd_row_vs_software() { 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 clips = real_clips(); + if clips.is_empty() { + eprintln!("skipped: no real-library manifest"); + return; + } + // A ladder compared with itself saves nothing: the check on the metric. + let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)]; + assert!(bd_rate(&same, &same).abs() < 1e-9, "bd_rate is not self-zero"); + + let dir = std::env::temp_dir().join("ec-hw-av1-bd"); + let _ = std::fs::create_dir_all(&dir); + for (label, source) in clips { + let y4m = dir.join(format!("{label}.y4m")); + let (width, height, frames) = (1920u32, 1080u32, 12u32); + if !extract_y4m(&source, &y4m, width, height, frames) { + eprintln!("skipped {label}: extraction failed"); + continue; + } + let planes = match raw_frames(&y4m, width, height, frames) { + Some(planes) => planes, + None => { + eprintln!("skipped {label}: no frames extracted"); + continue; + } + }; + + let mut ours = Vec::new(); + // Descending quantiser: every ladder here is ordered by rising rate. + for qp in [180u32, 140, 100, 60] { + let mut config = EncoderConfig::new(EncCodec::Av1, width, height); + config.framerate = (24, 1); + config.gop_size = 60; + config.rate_control = RateControlMode::ConstantQp { qp }; + let mut encoder = match Encoder::new(&display, config) { + Ok(encoder) => encoder, + Err(e) => { + eprintln!("skipped: AV1 encode unavailable ({e})"); + return; + } + }; + let mut bytes = Vec::new(); + for (i, frame) in planes.iter().enumerate() { + let coded = encoder + .encode( + frame, + FrameMetadata { + timestamp: i as i64, + force_keyframe: false, + }, + ) + .expect("hardware AV1 encode"); + bytes.extend_from_slice(&coded.data); + } + let path = dir.join(format!("{label}-hw-{qp}.obu")); + std::fs::write(&path, &bytes).expect("write"); + if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { + ours.push((bytes.len() as f64 * 8.0 / f64::from(frames), db)); + } + } + let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] + .iter() + .filter_map(|q| { + software_point( + &dir, + &y4m, + label, + "librav1e", + &["-rav1e-params", &format!("speed=6:quantizer={q}"), "-g", "60"], + *q, + frames, + ) + }) + .collect(); + let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] + .iter() + .filter_map(|crf| { + software_point( + &dir, + &y4m, + label, + "libaom-av1", + &[ + "-cpu-used", "6", "-crf", &crf.to_string(), "-b:v", "0", "-g", "60", + ], + *crf, + frames, + ) + }) + .collect(); + + for (name, ladder) in [("hw AV1", &ours), ("librav1e", &rav1e), ("libaom", &libaom)] { + println!("{label} {name}: {ladder:?}"); + for pair in ladder.windows(2) { + assert!( + pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, + "{label} {name}: ladder is not monotone at {pair:?}" + ); + } + } + if ours.len() >= 3 && rav1e.len() >= 3 { + println!( + "BD-rate row: {label}, hw AV1 vs librav1e speed 6: {:+.1}%", + bd_rate(&rav1e, &ours) * 100.0 + ); + } + if ours.len() >= 3 && libaom.len() >= 3 { + println!( + "BD-rate row: {label}, hw AV1 vs libaom cpu-used 6: {:+.1}%", + bd_rate(&libaom, &ours) * 100.0 + ); + } + } +} + +/// One software encoder's rate/PSNR point, or `None` when that encoder is not +/// built into this ffmpeg. +fn software_point( + dir: &Path, + y4m: &Path, + label: &str, + encoder: &str, + args: &[&str], + point: u32, + frames: u32, +) -> Option<(f64, f64)> { + let out = dir.join(format!("{label}-{encoder}-{point}.ivf")); + let _ = std::fs::remove_file(&out); + let status = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-y", "-i"]) + .arg(y4m) + .args(["-c:v", encoder]) + .args(args) + .arg(&out) + .status() + .ok()?; + if !status.success() { + return None; + } + let bytes = std::fs::metadata(&out).ok()?.len() as f64; + let db = ffmpeg_psnr(&out, y4m, false)?; + Some((bytes * 8.0 / f64::from(frames), db)) +} + +/// PSNR of a coded stream against the source, from ffmpeg's own filter. +fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option { + let mut cmd = Command::new("ffmpeg"); + cmd.args(["-nostdin", "-v", "info"]); + if raw_obu { + cmd.args(["-f", "obu"]); + } + // Both inputs are pinned to the same rate: a raw OBU stream carries no + // timing, so ffmpeg would otherwise call it 25 fps against a 24 fps + // source and the filter would compare frame i with frame i+k. + let out = cmd + .args(["-r", "24"]) + .arg("-i") + .arg(coded) + .args(["-r", "24"]) + .arg("-i") + .arg(source) + .args(["-lavfi", "psnr", "-f", "null", "-"]) + .output() + .ok()?; + let text = String::from_utf8_lossy(&out.stderr); + let field = text.split("average:").nth(1)?; + field + .split_whitespace() + .next()? + .parse::() + .ok() + .filter(|v| v.is_finite()) +} + +/// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. +fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { + let _ = std::fs::remove_file(out); + Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-y", "-ss", "60", "-i"]) + .arg(source) + .args([ + "-frames:v", + &frames.to_string(), + "-vf", + &format!("scale={width}:{height}"), + "-pix_fmt", + "yuv420p", + ]) + .arg(out) + .status() + .is_ok_and(|s| s.success()) +} + +/// The same pictures as planes, for the hardware encoder's own input. +fn raw_frames(y4m: &Path, width: u32, height: u32, frames: u32) -> Option> { + let out = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-i"]) + .arg(y4m) + .args(["-pix_fmt", "yuv420p", "-f", "rawvideo", "-"]) + .stderr(Stdio::null()) + .output() + .ok()?; + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let frame_len = w * h + 2 * cw * ch; + let mut pictures = Vec::new(); + for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { + let (y, rest) = chunk.split_at(w * h); + let (u, v) = rest.split_at(cw * ch); + pictures.push(I420 { + y: y.to_vec(), + u: u.to_vec(), + v: v.to_vec(), + width, + height, + }); + } + (!pictures.is_empty()).then_some(pictures) +} + +/// One film and one screen capture from the real-library manifest, labelled +/// rather than named: the titles are his, not this suite's. +fn real_clips() -> Vec<(&'static str, PathBuf)> { + let manifest = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); + let Ok(text) = std::fs::read_to_string(&manifest) else { + return Vec::new(); + }; + let mut film = None; + let mut screen = None; + for line in text.lines().skip(1) { + let f: Vec<&str> = line.split('\t').collect(); + if f.len() < 7 || f[2] != "h264" { + continue; + } + let width: u32 = f[3].parse().unwrap_or(0); + // Long enough that the extraction's 60 s seek lands inside the file. + let duration: f64 = f.get(8).and_then(|d| d.parse().ok()).unwrap_or(0.0); + if width < 1280 || duration < 90.0 { + continue; + } + let path = PathBuf::from(f[0]); + if f[0].contains("/Films/") && film.is_none() { + film = Some(("film A", path)); + } else if f[0].contains("/OBS/") && screen.is_none() { + screen = Some(("screen capture", path)); + } + } + film.into_iter().chain(screen).collect() +} + +/// BD-rate of `test` against `reference`, as a fraction (negative = fewer +/// bits for the same quality), integrated piecewise-linearly in +/// `log10(bits per frame)` over the PSNR range the two ladders share. +/// +/// The cubic fit of the original method needs four well-spread points and +/// misbehaves outside them; a trapezoid over the overlap is the honest +/// version of the same integral for ladders this short. +fn bd_rate(reference: &[(f64, f64)], test: &[(f64, f64)]) -> f64 { + let low = reference[0].1.max(test[0].1); + let high = reference[reference.len() - 1].1.min(test[test.len() - 1].1); + if !(high > low) { + return f64::NAN; + } + // log-rate at a PSNR, linearly interpolated inside the ladder. + let at = |ladder: &[(f64, f64)], db: f64| -> f64 { + for pair in ladder.windows(2) { + let ((r0, d0), (r1, d1)) = (pair[0], pair[1]); + if db >= d0 && db <= d1 { + let t = if (d1 - d0).abs() < f64::EPSILON { + 0.0 + } else { + (db - d0) / (d1 - d0) + }; + return r0.log10() + t * (r1.log10() - r0.log10()); + } + } + if db < ladder[0].1 { + ladder[0].0.log10() + } else { + ladder[ladder.len() - 1].0.log10() + } + }; + let steps = 100; + let mut integral = 0.0; + for i in 0..steps { + let a = low + (high - low) * f64::from(i) / f64::from(steps); + let b = low + (high - low) * f64::from(i + 1) / f64::from(steps); + let da = at(test, a) - at(reference, a); + let db = at(test, b) - at(reference, b); + integral += (da + db) / 2.0 * (b - a); + } + 10f64.powf(integral / (high - low)) - 1.0 +} + +/// 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) { + 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; + } + } } } diff --git a/tools/ec-bench/Cargo.toml b/tools/ec-bench/Cargo.toml index b6193d2c..f1cffa3b 100644 --- a/tools/ec-bench/Cargo.toml +++ b/tools/ec-bench/Cargo.toml @@ -18,6 +18,8 @@ ec-core = { workspace = true } ec-h264 = { workspace = true } ec-h265 = { workspace = true } ec-av1 = { workspace = true } +ec-hw = { workspace = true } +ec-va = { workspace = true } ec-probe = { workspace = true } ec-h264-syntax = { workspace = true } ec-image = { workspace = true } diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index 6260b649..e2d2d862 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -42,6 +42,7 @@ fn main() { bench_h264(&mut rows); bench_h265_encode(&mut rows); bench_av1_encode(&mut rows); + bench_hw_av1_encode(&mut rows); bench_audio_decode(&mut rows); bench_audio_encode(&mut rows); bench_truehd(&mut rows); @@ -328,6 +329,77 @@ fn bench_h265_encode(rows: &mut Vec) { }); } +// --------------------------------------------------------------------------- +// hardware av1: the GPU encoder, at the size his library is in. +// --------------------------------------------------------------------------- + +/// AV1 encode on the GPU (`ec-hw`, VA-API). Skips as a row rather than a +/// failure when there is no VA device or the driver has no AV1 encode +/// entrypoint -- a machine without one is not a slow machine. +fn bench_hw_av1_encode(rows: &mut Vec) { + let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else { + rows.push(missing("ec-hw av1", "encode")); + return; + }; + let display = match ec_va::Display::open() { + Ok(display) => display, + Err(e) => { + rows.push(missing_direction("ec-hw av1", "encode", &format!("no VA display ({e})"))); + return; + } + }; + let (planes, w, h, n) = extract_yuv420p(&src, 1920, 1080, 30); + if n == 0 { + rows.push(missing("ec-hw av1", "encode")); + return; + } + let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h); + cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 }; + let mut enc = match ec_hw::Encoder::new(&display, cfg) { + Ok(enc) => enc, + Err(e) => { + rows.push(missing_direction("ec-hw av1", "encode", &format!("driver refused ({e})"))); + return; + } + }; + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let frame_len = (w * h + 2 * cw * ch) as usize; + let start = Instant::now(); + let mut coded = 0usize; + for (i, frame) in planes.chunks_exact(frame_len).enumerate() { + let (y, rest) = frame.split_at((w * h) as usize); + let (u, v) = rest.split_at(rest.len() / 2); + let picture = ec_hw::I420 { + y: y.to_vec(), + u: u.to_vec(), + v: v.to_vec(), + width: w, + height: h, + }; + let meta = ec_hw::FrameMetadata { + timestamp: i as i64, + force_keyframe: false, + }; + match enc.encode(&picture, meta) { + Ok(out) => coded += out.data.len(), + Err(e) => { + rows.push(missing_direction("ec-hw av1", "encode", &format!("encode failed ({e})"))); + return; + } + } + } + let wall = start.elapsed().as_secs_f64(); + let media_s = n as f64 / 30.0; + rows.push(Row { + component: "ec-hw av1", + direction: "encode", + content: format!("{w}x{h}, {n} frames, CQP 120, {} kB", coded / 1000), + media: format!("{media_s:.1}s"), + wall_ms: wall * 1000.0, + rtf: (wall > 0.0).then_some(media_s / wall), + }); +} + // --------------------------------------------------------------------------- // av1: encode only -- same shape as h265. // ---------------------------------------------------------------------------