From 7368f27762b4c0c52c0345d96268a0b8e637cdf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 18:46:39 +0300 Subject: [PATCH] feat(hw): hardware encoding for H.264 and HEVC, AV1 behind an opt-in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit IDR-then-P with a single reference, CQP or CBR, one frame in and one coded frame out. HEVC encoding is in the tree rather than on a branch, which is the whole point of writing this one: the conformance window is a field of the sequence, so 1916x1080 comes out the size it went in. The packed headers are the application's job here. This driver advertises `SEQUENCE | PICTURE | SLICE` and then writes none of them itself, so the crate writes the H.264 parameter sets and slice headers, and reuses `ec-h265-syntax` for the HEVC ones — the same code that parses them. Two driver behaviours are pinned down by comment where they were found by measurement: the parameter sets only reach the stream when a slice header accompanies them, and the HEVC slice header this driver composes omits `slice_loop_filter_across_slices_enabled_flag`, so the PPS has to say the flag is absent or every P picture decodes as `alignment_bit_equal_to_one = 0`. AV1 encoding is refused unless a caller sets `allow_av1`. That guard is not caution for its own sake: a probe at the driver's own minimum encode size took the GPU down with a hard recovery on 2026-08-14, and there is no error to return from a context that no longer exists. --- crates/ec-hw/src/enc/av1.rs | 101 +++++++ crates/ec-hw/src/enc/h264.rs | 191 ++++++++++++ crates/ec-hw/src/enc/headers.rs | 345 +++++++++++++++++++++ crates/ec-hw/src/enc/hevc.rs | 201 +++++++++++++ crates/ec-hw/src/enc/mod.rs | 518 ++++++++++++++++++++++++++++++++ 5 files changed, 1356 insertions(+) create mode 100644 crates/ec-hw/src/enc/av1.rs create mode 100644 crates/ec-hw/src/enc/h264.rs create mode 100644 crates/ec-hw/src/enc/headers.rs create mode 100644 crates/ec-hw/src/enc/hevc.rs create mode 100644 crates/ec-hw/src/enc/mod.rs diff --git a/crates/ec-hw/src/enc/av1.rs b/crates/ec-hw/src/enc/av1.rs new file mode 100644 index 00000000..220096ec --- /dev/null +++ b/crates/ec-hw/src/enc/av1.rs @@ -0,0 +1,101 @@ +//! AV1 encode parameters — opt-in only. +//! +//! 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. + +use std::sync::Arc; + +use ec_va::Buffer; + +use super::{Encoder, RateControlMode}; +use crate::error::Result; +use crate::params::enc::{ + EncPictureParameterBufferAV1, EncSequenceParameterBufferAV1, EncTileGroupBufferAV1, +}; +use crate::params::param_buffer; +use crate::pool::PooledSurface; + +/// `KEY_FRAME` and `INTER_FRAME` (spec 6.8.2). +const KEY_FRAME: u32 = 0; +const INTER_FRAME: u32 = 1; + +pub(super) fn parameters( + encoder: &Encoder, + recon: &Arc, + coded_buf: u32, + keyframe: bool, + out: &mut Vec, +) -> Result<()> { + let config = *encoder.config(); + let context = encoder.context(); + let (coded_w, coded_h) = encoder.coded_size(); + + let mut seq = EncSequenceParameterBufferAV1 { + seq_profile: 0, + // 0 lets the driver pick the level from the picture size and rate. + seq_level_idx: 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, + ..EncSequenceParameterBufferAV1::default() + }; + seq.seq_fields = seq + .seq_fields + .enable_order_hint(1) + .bit_depth_minus8(0) + .subsampling_x(1) + .subsampling_y(1); + out.push(param_buffer(context, &seq)?); + + let order_hint = (encoder.gop_position() % 128) as u8; + 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, + reconstructed_frame: recon.id(), + coded_buf, + primary_ref_frame: 7, // PRIMARY_REF_NONE + 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, + 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; + 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.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); + out.push(param_buffer(context, &pic)?); + + let tile_group = EncTileGroupBufferAV1 { + tg_start: 0, + tg_end: 0, + ..EncTileGroupBufferAV1::default() + }; + out.push(param_buffer(context, &tile_group)?); + Ok(()) +} diff --git a/crates/ec-hw/src/enc/h264.rs b/crates/ec-hw/src/enc/h264.rs new file mode 100644 index 00000000..70a7cd5e --- /dev/null +++ b/crates/ec-hw/src/enc/h264.rs @@ -0,0 +1,191 @@ +//! H.264 encode parameters. +//! +//! `pic_order_cnt_type` is 2 — decode order *is* output order — because this +//! encoder codes no B frames, and type 2 then costs no picture order count in +//! any slice header. Everything else follows from one reference and one slice +//! per picture. + +use std::sync::Arc; + +use ec_va::Buffer; + +use super::{Encoder, RateControlMode, headers}; +use crate::error::Result; +use crate::params::enc::{ + EncPictureParameterBufferH264, EncSequenceParameterBufferH264, EncSliceParameterBufferH264, +}; +use crate::params::h264::{PICTURE_SHORT_TERM_REFERENCE, VAPictureH264}; +use crate::params::param_buffer; +use crate::pool::PooledSurface; + +/// `log2_max_frame_num_minus4` = 0, i.e. `frame_num` wraps at 16 — far beyond +/// the single reference this encoder keeps. +const LOG2_MAX_FRAME_NUM: u64 = 4; + +pub(super) fn parameters( + encoder: &Encoder, + recon: &Arc, + coded_buf: u32, + keyframe: bool, + out: &mut Vec, +) -> Result<()> { + let config = *encoder.config(); + let context = encoder.context(); + let (coded_w, coded_h) = encoder.coded_size(); + let frame_num = if keyframe { + 0 + } else { + (encoder.coded_count() % (1 << LOG2_MAX_FRAME_NUM)) as u16 + }; + + let mut seq = EncSequenceParameterBufferH264 { + level_idc: level_idc(coded_w, coded_h, config.framerate), + intra_period: config.gop_size.max(1), + intra_idr_period: config.gop_size.max(1), + ip_period: 1, + bits_per_second: match config.rate_control { + RateControlMode::ConstantBitrate => config.bitrate, + RateControlMode::ConstantQp { .. } => 0, + }, + max_num_ref_frames: 1, + picture_width_in_mbs: (coded_w / 16) as u16, + picture_height_in_mbs: (coded_h / 16) as u16, + // 4:2:0 in a crop rectangle of two luma samples per unit (7.4.2.1.1). + frame_cropping_flag: u8::from(coded_w != config.width || coded_h != config.height), + frame_crop_right_offset: (coded_w - config.width) / 2, + frame_crop_bottom_offset: (coded_h - config.height) / 2, + vui_parameters_present_flag: 1, + num_units_in_tick: config.framerate.1.max(1), + // time_scale is twice the frame rate: a "tick" is a field period. + time_scale: config.framerate.0.max(1) * 2, + ..EncSequenceParameterBufferH264::default() + }; + seq.seq_fields = seq + .seq_fields + .chroma_format_idc(1) + .frame_mbs_only_flag(1) + .direct_8x8_inference_flag(1) + .log2_max_frame_num_minus4(0) + .pic_order_cnt_type(2); + seq.vui_fields = seq + .vui_fields + .timing_info_present_flag(1) + .fixed_frame_rate_flag(1); + out.push(param_buffer(context, &seq)?); + + let mut pic = EncPictureParameterBufferH264 { + curr_pic: VAPictureH264::frame( + recon.id(), + u32::from(frame_num), + 2 * encoder.coded_count() as i32, + PICTURE_SHORT_TERM_REFERENCE, + ), + coded_buf, + frame_num, + pic_init_qp: match config.rate_control { + RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, + RateControlMode::ConstantBitrate => 26, + }, + ..EncPictureParameterBufferH264::default() + }; + if let Some(reference) = encoder.reference().filter(|_| !keyframe) { + pic.reference_frames[0] = VAPictureH264::frame( + reference.id(), + u32::from(frame_num.wrapping_sub(1)), + 2 * (encoder.coded_count() as i32 - 1), + PICTURE_SHORT_TERM_REFERENCE, + ); + } + pic.pic_fields = pic + .pic_fields + .idr_pic_flag(u32::from(keyframe)) + .reference_pic_flag(1) + .entropy_coding_mode_flag(1) // CABAC: High profile, and 10% smaller + .deblocking_filter_control_present_flag(1); + out.push(param_buffer(context, &pic)?); + + let mut slice = EncSliceParameterBufferH264 { + macroblock_address: 0, + num_macroblocks: (coded_w / 16) * (coded_h / 16), + slice_type: if keyframe { 2 } else { 0 }, + // idr_pic_id alternates between consecutive IDR pictures (7.4.3). + idr_pic_id: ((encoder.gop_position() / config.gop_size.max(1)) % 2) as u16, + num_ref_idx_active_override_flag: 0, + ..EncSliceParameterBufferH264::default() + }; + if !keyframe && let Some(reference) = encoder.reference() { + slice.ref_pic_list0[0] = VAPictureH264::frame( + reference.id(), + u32::from(frame_num.wrapping_sub(1)), + 2 * (encoder.coded_count() as i32 - 1), + PICTURE_SHORT_TERM_REFERENCE, + ); + } + + // Packed headers, in bitstream order: the parameter sets open every key + // frame (so a stream is seekable and a decoder can start anywhere), and the + // slice header opens every picture. + let header_params = headers::H264Params { + level_idc: seq.level_idc, + mb_width: u32::from(seq.picture_width_in_mbs), + mb_height: u32::from(seq.picture_height_in_mbs), + crop_right: seq.frame_crop_right_offset, + crop_bottom: seq.frame_crop_bottom_offset, + num_units_in_tick: seq.num_units_in_tick, + time_scale: seq.time_scale, + pic_init_qp: pic.pic_init_qp, + }; + if keyframe { + encoder.push_packed(&headers::h264_sps(&header_params), out)?; + encoder.push_packed(&headers::h264_pps(&header_params), out)?; + } + encoder.push_packed( + &headers::h264_slice_header(keyframe, u32::from(frame_num), u32::from(slice.idr_pic_id)), + out, + )?; + out.push(param_buffer(context, &slice)?); + Ok(()) +} + +/// The lowest Annex A level that fits the picture size and rate. +/// +/// Advertising level 6.2 for a 640x480 clip is legal and lazy; a player that +/// checks levels against its decoder budget deserves the real one. +fn level_idc(width: u32, height: u32, framerate: (u32, u32)) -> u8 { + const LEVELS: [(u8, u64, u64); 12] = [ + (10, 1485, 99), + (11, 3000, 396), + (20, 11880, 396), + (21, 19800, 792), + (22, 20250, 1620), + (30, 40500, 1620), + (31, 108000, 3600), + (32, 216000, 5120), + (40, 245760, 8192), + (50, 589824, 22080), + (51, 983040, 36864), + (52, 2073600, 36864), + ]; + let frame_mbs = u64::from(width / 16) * u64::from(height / 16); + let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1)); + let mbps = (frame_mbs as f64 * fps).ceil() as u64; + for &(idc, max_mbps, max_fs) in &LEVELS { + if mbps <= max_mbps && frame_mbs <= max_fs { + return idc; + } + } + 62 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn levels_follow_size_and_rate() { + assert_eq!(level_idc(1920, 1088, (30, 1)), 40); + assert_eq!(level_idc(1920, 1088, (60, 1)), 50); + assert_eq!(level_idc(3840, 2160, (30, 1)), 51); + assert_eq!(level_idc(640, 480, (30, 1)), 30); + } +} diff --git a/crates/ec-hw/src/enc/headers.rs b/crates/ec-hw/src/enc/headers.rs new file mode 100644 index 00000000..2563ae81 --- /dev/null +++ b/crates/ec-hw/src/enc/headers.rs @@ -0,0 +1,345 @@ +//! Packed headers: the parameter sets and slice headers the *application* +//! writes for the driver. +//! +//! This is not optional plumbing. radeonsi advertises +//! `VA_ENC_PACKED_HEADER_SEQUENCE | PICTURE | SLICE` and then writes none of +//! them itself: without these, the coded buffer comes back holding slice data +//! with no parameter sets in front of it — a stream ffmpeg answers with +//! "Invalid data found when processing input" (measured, 2026-08-14). Every +//! field below therefore has to agree with the `VAEnc*ParameterBuffer` the +//! driver was given, or the header describes a picture other than the one the +//! hardware coded. + +use ec_core::BitWriter; + +use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE}; + +/// A header ready to submit: escaped bytes plus its exact length in bits. +/// +/// The bit length matters for slice headers, which do not end on a byte +/// boundary — the driver continues the bitstream from exactly that bit. +pub(crate) struct Packed { + pub(crate) kind: u32, + pub(crate) bytes: Vec, + pub(crate) bits: u32, +} + +/// Wrap a complete NAL: start code, header byte(s), escaped payload. +fn nal(kind: u32, header: &[u8], rbsp: &[u8], padding_bits: u32) -> Packed { + let mut bytes = vec![0, 0, 0, 1]; + bytes.extend_from_slice(header); + let mut escaped = Vec::with_capacity(rbsp.len() + 8); + ec_h264_syntax::escape_rbsp(rbsp, &mut escaped); + bytes.extend_from_slice(&escaped); + let bits = bytes.len() as u32 * 8 - padding_bits; + Packed { kind, bytes, bits } +} + +// --------------------------------------------------------------------------- +// H.264 +// --------------------------------------------------------------------------- + +/// What the H.264 headers need, mirroring the sequence parameter buffer. +pub(super) struct H264Params { + pub(super) level_idc: u8, + pub(super) mb_width: u32, + pub(super) mb_height: u32, + pub(super) crop_right: u32, + pub(super) crop_bottom: u32, + pub(super) num_units_in_tick: u32, + pub(super) time_scale: u32, + pub(super) pic_init_qp: u8, +} + +/// `log2_max_frame_num`, matching `seq_fields.log2_max_frame_num_minus4 = 0`. +pub(super) const H264_LOG2_MAX_FRAME_NUM: u32 = 4; + +/// The sequence parameter set (7.3.2.1), High profile. +pub(super) fn h264_sps(p: &H264Params) -> Packed { + let mut w = BitWriter::with_capacity(64); + w.write_bits(100, 8); // profile_idc: High + w.write_bits(0, 8); // constraint_set flags + reserved_zero_2bits + w.write_bits(u32::from(p.level_idc), 8); + w.write_ue(0); // seq_parameter_set_id + // High profile tail. + w.write_ue(1); // chroma_format_idc: 4:2:0 + w.write_ue(0); // bit_depth_luma_minus8 + w.write_ue(0); // bit_depth_chroma_minus8 + w.write_bit(false); // qpprime_y_zero_transform_bypass_flag + w.write_bit(false); // seq_scaling_matrix_present_flag + w.write_ue(H264_LOG2_MAX_FRAME_NUM - 4); + w.write_ue(2); // pic_order_cnt_type 2: output order is decode order + w.write_ue(1); // max_num_ref_frames + w.write_bit(false); // gaps_in_frame_num_value_allowed_flag + w.write_ue(p.mb_width - 1); + w.write_ue(p.mb_height - 1); + w.write_bit(true); // frame_mbs_only_flag + w.write_bit(true); // direct_8x8_inference_flag + let cropping = p.crop_right != 0 || p.crop_bottom != 0; + w.write_bit(cropping); + if cropping { + // CropUnitX = 2 and CropUnitY = 2 for progressive 4:2:0 (7.4.2.1.1). + w.write_ue(0); + w.write_ue(p.crop_right); + w.write_ue(0); + w.write_ue(p.crop_bottom); + } + w.write_bit(true); // vui_parameters_present_flag + w.write_bit(false); // aspect_ratio_info_present_flag + w.write_bit(false); // overscan_info_present_flag + w.write_bit(false); // video_signal_type_present_flag + w.write_bit(false); // chroma_loc_info_present_flag + w.write_bit(true); // timing_info_present_flag + w.write_bits(p.num_units_in_tick, 32); + w.write_bits(p.time_scale, 32); + w.write_bit(true); // fixed_frame_rate_flag + w.write_bit(false); // nal_hrd_parameters_present_flag + w.write_bit(false); // vcl_hrd_parameters_present_flag + w.write_bit(false); // pic_struct_present_flag + w.write_bit(false); // bitstream_restriction_flag + trailing(&mut w); + nal(PACKED_HEADER_SEQUENCE, &[0x67], &w.into_bytes(), 0) +} + +/// The picture parameter set (7.3.2.2). +pub(super) fn h264_pps(p: &H264Params) -> Packed { + let mut w = BitWriter::with_capacity(16); + w.write_ue(0); // pic_parameter_set_id + w.write_ue(0); // seq_parameter_set_id + w.write_bit(true); // entropy_coding_mode_flag: CABAC + w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag + w.write_ue(0); // num_slice_groups_minus1 + w.write_ue(0); // num_ref_idx_l0_default_active_minus1 + w.write_ue(0); // num_ref_idx_l1_default_active_minus1 + w.write_bit(false); // weighted_pred_flag + w.write_bits(0, 2); // weighted_bipred_idc + w.write_se(i32::from(p.pic_init_qp) - 26); + w.write_se(0); // pic_init_qs_minus26 + w.write_se(0); // chroma_qp_index_offset + w.write_bit(true); // deblocking_filter_control_present_flag + w.write_bit(false); // constrained_intra_pred_flag + w.write_bit(false); // redundant_pic_cnt_present_flag + trailing(&mut w); + nal(PACKED_HEADER_PICTURE, &[0x68], &w.into_bytes(), 0) +} + +/// The slice header (7.3.3), up to but *not* including the slice data. +/// +/// No trailing bits and no alignment: the driver continues the bitstream at the +/// next bit (`cabac_alignment_one_bit` is its business), which is why the +/// returned bit count has to be exact. +pub(super) fn h264_slice_header(idr: bool, frame_num: u32, idr_pic_id: u32) -> Packed { + let mut w = BitWriter::with_capacity(16); + w.write_ue(0); // first_mb_in_slice + // 5..=9 assert that every slice of the picture has this type, which holds: + // one slice per picture. + w.write_ue(if idr { 7 } else { 5 }); + w.write_ue(0); // pic_parameter_set_id + w.write_bits(frame_num, H264_LOG2_MAX_FRAME_NUM); + if idr { + w.write_ue(idr_pic_id); + } + // pic_order_cnt_type 2: no picture order count in the header. + if !idr { + w.write_bit(false); // num_ref_idx_active_override_flag + w.write_bit(false); // ref_pic_list_modification_flag_l0 + } + // Every picture here is a reference (nal_ref_idc != 0). + if idr { + w.write_bit(false); // no_output_of_prior_pics_flag + w.write_bit(false); // long_term_reference_flag + } else { + w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window + } + if !idr { + w.write_ue(0); // cabac_init_idc + } + w.write_se(0); // slice_qp_delta, against pic_init_qp + w.write_ue(0); // disable_deblocking_filter_idc + w.write_se(0); // slice_alpha_c0_offset_div2 + w.write_se(0); // slice_beta_offset_div2 + let bits = w.bit_len() as u32; + let padding = (8 - bits % 8) % 8; + w.align_to_byte(); + let header = if idr { 0x65 } else { 0x61 }; + nal(PACKED_HEADER_SLICE, &[header], &w.into_bytes(), padding) +} + +/// `rbsp_trailing_bits` (7.3.2.11). +fn trailing(w: &mut BitWriter) { + w.write_bit(true); + w.align_to_byte(); +} + +// --------------------------------------------------------------------------- +// HEVC +// --------------------------------------------------------------------------- + +/// Build the HEVC parameter sets, and the slice header for one picture. +/// +/// The syntax crate writes all four structures, so the encoder and the software +/// HEVC path in this family share one definition of what a parameter set is. +pub(super) mod hevc { + use ec_h265_syntax::{ + ConformanceWindow, NalHeader, NalUnitType, Pps, ProfileTierLevel, ShortTermRefPicSet, + SliceHeader, SliceType, Sps, Vps, + }; + + use super::{Packed, nal}; + use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE}; + + /// Geometry and timing for the parameter sets. + pub(in crate::enc) struct Params { + pub(in crate::enc) width: u32, + pub(in crate::enc) height: u32, + pub(in crate::enc) coded_width: u32, + pub(in crate::enc) coded_height: u32, + pub(in crate::enc) level_idc: u8, + pub(in crate::enc) num_units_in_tick: u32, + pub(in crate::enc) time_scale: u32, + pub(in crate::enc) init_qp: u8, + } + + /// The VPS, SPS and PPS, in that order. + pub(in crate::enc) fn parameter_sets(p: &Params) -> (Vps, Sps, Pps) { + let ptl = ProfileTierLevel::main(p.level_idc); + let vps = Vps { + id: 0, + ptl, + max_dec_pic_buffering_minus1: 1, + max_num_reorder_pics: 0, + }; + let sps = Sps { + vps_id: 0, + id: 0, + chroma_format_idc: 1, + separate_colour_plane: false, + pic_width_in_luma_samples: p.coded_width, + pic_height_in_luma_samples: p.coded_height, + // The conformance window is how HEVC crops: the coded size is a + // multiple of the minimum coding block, the displayed size is not. + conf_win: ConformanceWindow { + left: 0, + right: (p.coded_width - p.width) / 2, + top: 0, + bottom: (p.coded_height - p.height) / 2, + }, + bit_depth_luma_minus8: 0, + bit_depth_chroma_minus8: 0, + log2_max_poc_lsb_minus4: 8, + max_dec_pic_buffering_minus1: 1, + max_num_reorder_pics: 0, + log2_min_cb_size_minus3: 0, + log2_diff_max_min_cb_size: 3, + log2_min_tb_size_minus2: 0, + log2_diff_max_min_tb_size: 3, + max_transform_hierarchy_depth_inter: 1, + max_transform_hierarchy_depth_intra: 1, + scaling_list_enabled: false, + amp_enabled: true, + sao_enabled: true, + pcm_enabled: false, + pcm: None, + // No sets in the sequence: this driver writes the reference picture + // set out in each slice header (an inline `st_ref_pic_set` naming + // the previous picture), so declaring one here would leave the two + // descriptions of the same thing free to disagree. + num_short_term_ref_pic_sets: 0, + short_term_ref_pic_sets: Vec::new(), + long_term_ref_pics_present: false, + num_long_term_ref_pics_sps: 0, + long_term_ref_pics_sps: Vec::new(), + temporal_mvp_enabled: false, + strong_intra_smoothing: true, + ptl, + vui: Some(ec_h265_syntax::vui::VuiParameters { + timing: Some((p.num_units_in_tick, p.time_scale)), + ..ec_h265_syntax::vui::VuiParameters::default() + }), + }; + let pps = Pps { + id: 0, + sps_id: 0, + init_qp_minus26: i32::from(p.init_qp) - 26, + num_ref_idx_l0_default_active_minus1: 0, + num_ref_idx_l1_default_active_minus1: 0, + transform_skip_enabled: true, + loop_filter_across_tiles_enabled: false, + loop_filter_across_slices_enabled: false, + ..Pps::default() + }; + (vps, sps, pps) + } + + /// `st_ref_pic_set()`: one negative reference at POC - 1, used by this + /// picture — the single reference this encoder keeps. + fn previous_picture_set() -> ShortTermRefPicSet { + let mut set = ShortTermRefPicSet { + num_negative: 1, + num_positive: 0, + num_used_by_curr: 1, + ..ShortTermRefPicSet::default() + }; + set.delta_poc_s0[0] = -1; + set.used_s0[0] = true; + set + } + + pub(in crate::enc) fn packed_vps(vps: &Vps) -> Packed { + nal( + PACKED_HEADER_SEQUENCE, + &NalHeader::new(NalUnitType::Vps).to_bytes(), + &vps.to_rbsp(), + 0, + ) + } + + pub(in crate::enc) fn packed_sps(sps: &Sps) -> Packed { + nal( + PACKED_HEADER_SEQUENCE, + &NalHeader::new(NalUnitType::Sps).to_bytes(), + &sps.to_rbsp(), + 0, + ) + } + + pub(in crate::enc) fn packed_pps(pps: &Pps) -> Packed { + nal( + PACKED_HEADER_PICTURE, + &NalHeader::new(NalUnitType::Pps).to_bytes(), + &pps.to_rbsp(), + 0, + ) + } + + /// The slice segment header, ending mid-byte like H.264's. + pub(in crate::enc) fn packed_slice(sps: &Sps, pps: &Pps, keyframe: bool, poc: i32) -> Packed { + let nal_type = if keyframe { + NalUnitType::IdrWRadl + } else { + NalUnitType::TrailR + }; + let mut header = SliceHeader::intra(pps, 0); + header.slice_type = if keyframe { SliceType::I } else { SliceType::P }; + header.poc_lsb = (poc as u32) & ((1 << (sps.log2_max_poc_lsb_minus4 + 4)) - 1); + header.sao_luma = sps.sao_enabled; + header.sao_chroma = sps.sao_enabled; + header.five_minus_max_num_merge_cand = 0; + // The set goes in the header rather than the SPS, which is what this + // driver writes when it composes the header itself. + header.short_term_ref_pic_set_sps_flag = false; + header.short_term_ref_pic_set = previous_picture_set(); + header.loop_filter_across_slices_enabled = false; + let mut w = ec_core::BitWriter::with_capacity(16); + // With `byte_alignment()` (7.3.6.1): this driver copies the header it is + // given verbatim and starts the slice data at the next byte, so the + // alignment bit has to be in what it is given. + header.write(&mut w, sps, pps, nal_type); + nal( + PACKED_HEADER_SLICE, + &NalHeader::new(nal_type).to_bytes(), + &w.into_bytes(), + 0, + ) + } +} diff --git a/crates/ec-hw/src/enc/hevc.rs b/crates/ec-hw/src/enc/hevc.rs new file mode 100644 index 00000000..a139afd9 --- /dev/null +++ b/crates/ec-hw/src/enc/hevc.rs @@ -0,0 +1,201 @@ +//! HEVC encode parameters. +//! +//! HEVC encoding in-tree is one of the reasons this crate exists: the incumbent +//! stack carried it on a branch for months. It is the same IDR-then-P structure +//! as the H.264 path, in HEVC's units — CTBs instead of macroblocks, a picture +//! order count instead of `frame_num`, and a conformance window instead of a +//! frame crop, which is what makes 1916x1080 (or any width that is not a +//! multiple of 32) come out the size it went in. + +use std::sync::Arc; + +use ec_va::Buffer; + +use super::headers::hevc as hevc_headers; +use super::{Encoder, RateControlMode}; +use crate::error::Result; +use crate::params::enc::{ + EncPictureParameterBufferHEVC, EncSequenceParameterBufferHEVC, EncSliceParameterBufferHEVC, +}; +use crate::params::hevc::VAPictureHEVC; +use crate::params::param_buffer; +use crate::pool::PooledSurface; + +/// `NAL_IDR_W_RADL`. +const NAL_IDR_W_RADL: u8 = 19; +/// `NAL_TRAIL_R`. +const NAL_TRAIL_R: u8 = 1; + +pub(super) fn parameters( + encoder: &Encoder, + recon: &Arc, + coded_buf: u32, + keyframe: bool, + out: &mut Vec, +) -> Result<()> { + let config = *encoder.config(); + let context = encoder.context(); + let (coded_w, coded_h) = encoder.coded_size(); + let poc = if keyframe { + 0 + } else { + encoder.gop_position() as i32 + }; + + let mut seq = EncSequenceParameterBufferHEVC { + general_profile_idc: 1, // Main + general_level_idc: level_idc(coded_w, coded_h, config.framerate), + general_tier_flag: 0, + intra_period: config.gop_size.max(1), + intra_idr_period: config.gop_size.max(1), + ip_period: 1, + bits_per_second: match config.rate_control { + RateControlMode::ConstantBitrate => config.bitrate, + RateControlMode::ConstantQp { .. } => 0, + }, + pic_width_in_luma_samples: coded_w as u16, + pic_height_in_luma_samples: coded_h as u16, + // 64x64 CTBs from 8x8 minimum CBs: log2_min = 0 (8), diff = 3 (64). + // Not a preference — this driver codes 64x64 CTBs whatever the sequence + // parameters say, and `num_ctu_in_slice` below has to count the same + // blocks the hardware does. + log2_min_luma_coding_block_size_minus3: 0, + log2_diff_max_min_luma_coding_block_size: 3, + log2_min_transform_block_size_minus2: 0, + log2_diff_max_min_transform_block_size: 3, + max_transform_hierarchy_depth_inter: 1, + max_transform_hierarchy_depth_intra: 1, + vui_parameters_present_flag: 1, + vui_num_units_in_tick: config.framerate.1.max(1), + vui_time_scale: config.framerate.0.max(1), + ..EncSequenceParameterBufferHEVC::default() + }; + seq.seq_fields = seq + .seq_fields + .chroma_format_idc(1) + .bit_depth_luma_minus8(0) + .bit_depth_chroma_minus8(0) + .strong_intra_smoothing_enabled_flag(1) + .amp_enabled_flag(1) + .sample_adaptive_offset_enabled_flag(1); + seq.vui_fields = seq.vui_fields.vui_timing_info_present_flag(1); + out.push(param_buffer(context, &seq)?); + + let mut pic = EncPictureParameterBufferHEVC { + decoded_curr_pic: VAPictureHEVC::new(recon.id(), poc, 0), + coded_buf, + collocated_ref_pic_index: 0xff, + pic_init_qp: match config.rate_control { + RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, + RateControlMode::ConstantBitrate => 26, + }, + nal_unit_type: if keyframe { + NAL_IDR_W_RADL + } else { + NAL_TRAIL_R + }, + ..EncPictureParameterBufferHEVC::default() + }; + if let Some(reference) = encoder.reference().filter(|_| !keyframe) { + pic.reference_frames[0] = VAPictureHEVC::new(reference.id(), poc - 1, 0); + } + pic.pic_fields = pic + .pic_fields + .idr_pic_flag(u32::from(keyframe)) + // 1 = I, 2 = P in this driver's coding_type numbering. + .coding_type(if keyframe { 1 } else { 2 }) + .reference_pic_flag(1) + .transform_skip_enabled_flag(1) + // Off, and it has to be off: this driver omits + // `slice_loop_filter_across_slices_enabled_flag` from the slice header + // it writes, so a PPS that says the flag is present describes a header + // that is one bit longer than the one in the stream — every P picture + // then decodes as `alignment_bit_equal_to_one = 0` (measured). + .pps_loop_filter_across_slices_enabled_flag(0); + out.push(param_buffer(context, &pic)?); + + // CTBs are 64x64 by the sequence parameters above. + let ctbs = coded_w.div_ceil(64) * coded_h.div_ceil(64); + let mut slice = EncSliceParameterBufferHEVC { + slice_segment_address: 0, + num_ctu_in_slice: ctbs, + slice_type: if keyframe { 2 } else { 1 }, // 2 = I, 1 = P + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + max_num_merge_cand: 5, + ..EncSliceParameterBufferHEVC::default() + }; + if !keyframe && let Some(reference) = encoder.reference() { + slice.ref_pic_list0[0] = VAPictureHEVC::new(reference.id(), poc - 1, 0); + } + slice.slice_fields = slice + .slice_fields + .last_slice_of_pic_flag(1) + .slice_sao_luma_flag(1) + .slice_sao_chroma_flag(1) + .cabac_init_flag(0) + .num_ref_idx_active_override_flag(u32::from(!keyframe)) + .slice_loop_filter_across_slices_enabled_flag(0); + + let header_params = hevc_headers::Params { + width: config.width, + height: config.height, + coded_width: coded_w, + coded_height: coded_h, + level_idc: seq.general_level_idc, + num_units_in_tick: seq.vui_num_units_in_tick, + time_scale: seq.vui_time_scale, + init_qp: pic.pic_init_qp, + }; + let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params); + if keyframe { + encoder.push_packed(&hevc_headers::packed_vps(&vps), out)?; + encoder.push_packed(&hevc_headers::packed_sps(&sps), out)?; + encoder.push_packed(&hevc_headers::packed_pps(&pps), out)?; + } + // The slice header goes in too. This driver composes its own for HEVC and + // ignores the content of this one — but it emits the parameter sets above + // only when a slice header accompanies them, so dropping it costs the + // stream its VPS, SPS and PPS (measured 2026-08-14). + encoder.push_packed(&hevc_headers::packed_slice(&sps, &pps, keyframe, poc), out)?; + out.push(param_buffer(context, &slice)?); + Ok(()) +} + +/// The lowest level whose luma sample rate and picture size fit (Annex A). +fn level_idc(width: u32, height: u32, framerate: (u32, u32)) -> u8 { + // (general_level_idc = level * 30, MaxLumaPs, MaxLumaSr) + const LEVELS: [(u8, u64, u64); 9] = [ + (30, 36_864, 552_960), + (60, 122_880, 3_686_400), + (63, 245_760, 7_372_800), + (90, 552_960, 16_588_800), + (93, 983_040, 33_177_600), + (120, 2_228_224, 66_846_720), + (123, 2_228_224, 133_693_440), + (150, 8_912_896, 267_386_880), + (153, 8_912_896, 534_773_760), + ]; + let samples = u64::from(width) * u64::from(height); + let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1)); + let rate = (samples as f64 * fps).ceil() as u64; + for &(idc, max_ps, max_sr) in &LEVELS { + if samples <= max_ps && rate <= max_sr { + return idc; + } + } + 186 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn levels_follow_size_and_rate() { + // 1080p30 is level 4.0 (120), 1080p60 level 4.1 (123), 2160p30 5.0 (150). + assert_eq!(level_idc(1920, 1088, (30, 1)), 120); + assert_eq!(level_idc(1920, 1088, (60, 1)), 123); + assert_eq!(level_idc(3840, 2160, (30, 1)), 150); + } +} diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs new file mode 100644 index 00000000..0de67604 --- /dev/null +++ b/crates/ec-hw/src/enc/mod.rs @@ -0,0 +1,518 @@ +//! Hardware encoding: H.264, HEVC, and AV1 behind an explicit opt-in. +//! +//! One frame in, one coded frame out. The GOP is IDR-then-P with a single +//! reference, which is what this GPU advertises (`VAConfigAttribEncMaxRefFrames` +//! reports one list-0 reference for HEVC) and what an editor's export wants: +//! no reordering, so a coded frame comes back in the call that fed it. +//! +//! # 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. + +use std::sync::Arc; + +use ec_va::caps::{Entrypoint, Profile}; +use ec_va::{ + Buffer, CapReport, Config, ConfigAttrib, Context, Display, Image, MappedBuffer, Picture, + Surface, SurfaceSpec, sys, +}; + +use crate::error::{Error, Result}; +use crate::frame::I420; +use crate::params::enc::{ + MISC_FRAME_RATE, MISC_HRD, MISC_RATE_CONTROL, PackedHeaderParameterBuffer, RateControl, + misc_bytes, +}; +use crate::params::param_buffer; +use crate::pool::{PooledSurface, SurfacePool}; + +mod av1; +mod h264; +mod headers; +mod hevc; + +/// The codecs this crate encodes in hardware. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EncCodec { + /// H.264 / AVC, High profile. + H264, + /// H.265 / HEVC, Main profile. + H265, + /// AV1 Profile 0 — opt-in only, see the module docs. + Av1, +} + +/// How the driver should spend bits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RateControlMode { + /// Constant quantiser: `qp` for every picture, bitrate ignored. + ConstantQp { + /// The quantiser, 0..51 for H.264/HEVC, 0..255 for AV1. + qp: u32, + }, + /// Constant bitrate, the driver picking quantisers to hold it. + ConstantBitrate, +} + +/// What can be changed between frames without rebuilding the encoder. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Tunings { + /// Target bitrate in bits per second. + pub bitrate: u32, + /// Frame rate as `(numerator, denominator)`. + pub framerate: (u32, u32), +} + +/// Per-frame instructions from the caller. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct FrameMetadata { + /// Presentation timestamp, carried through to the coded frame. + pub timestamp: i64, + /// Start a new GOP with this frame. + pub force_keyframe: bool, +} + +/// How an encoder is set up. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EncoderConfig { + /// Which codec. + pub codec: EncCodec, + /// Displayed width; the coded size is rounded up for the codec's blocks. + pub width: u32, + /// Displayed height. + pub height: u32, + /// Frame rate as `(numerator, denominator)`. + pub framerate: (u32, u32), + /// Target bitrate in bits per second. + pub bitrate: u32, + /// Pictures per GOP; the first of each is an IDR / key frame. + pub gop_size: u32, + /// Rate control mode. + 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, +} + +impl EncoderConfig { + /// A configuration with sensible defaults for `codec` at `width x height`. + pub fn new(codec: EncCodec, width: u32, height: u32) -> EncoderConfig { + EncoderConfig { + codec, + width, + height, + framerate: (30, 1), + bitrate: 8_000_000, + gop_size: 60, + rate_control: RateControlMode::ConstantBitrate, + quality: 0, + allow_av1: false, + } + } +} + +/// One coded picture. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CodedFrame { + /// The bitstream: an Annex B access unit for H.264/HEVC, an OBU sequence + /// for AV1. + pub data: Vec, + /// The timestamp the caller supplied with the source frame. + pub timestamp: i64, + /// True for an IDR / key frame. + pub is_keyframe: bool, +} + +/// A hardware encoder. +pub struct Encoder { + config: EncoderConfig, + context: Arc, + pool: SurfacePool, + coded_size: (u32, u32), + /// The reconstruction of the previous picture, the single reference. + reference: Option>, + /// Pictures coded since the last key frame. + gop_position: u32, + /// Pictures coded in total, which drives frame_num and order hints. + coded: u64, + tunings: Tunings, + /// Set when the rate control parameters have to be resent. + tunings_dirty: bool, + profile: Profile, + /// An upload image, reused across frames. + upload: Option, +} + +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. + EncCodec::H264 => Profile::H264High, + EncCodec::H265 => Profile::HEVCMain, + EncCodec::Av1 => Profile::AV1Profile0, + }; + let block = match config.codec { + EncCodec::H264 => 16, + EncCodec::H265 => 32, + EncCodec::Av1 => 64, + }; + let coded_size = ( + config.width.next_multiple_of(block), + config.height.next_multiple_of(block), + ); + + let caps = CapReport::probe(display)?; + let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { + Error::unsupported( + format!("{profile:?} encode"), + "the driver advertises no EncSlice entrypoint for this profile", + ) + })?; + if let Some(surfaces) = &entry.surfaces + && !surfaces.allows(coded_size.0, coded_size.1) + { + // The minimum encode size is a driver fact, not a guess: radeonsi + // refuses anything under 96x32 for H.264 and 384x128 for HEVC. + return Err(Error::unsupported( + format!("{}x{} {profile:?} encode", coded_size.0, coded_size.1), + format!( + "the driver accepts {:?}..{:?} x {:?}..{:?}", + surfaces.min_width, + surfaces.max_width, + surfaces.min_height, + surfaces.max_height + ), + )); + } + + // The packed-header attribute is not decoration: a config that does not + // ask for them gets a driver that writes its own headers and silently + // ignores the application's (measured on radeonsi — the parameter sets + // went in, the slice header did not, and every P picture came back + // missing its `byte_alignment()`). + let packed = entry.packed_headers + & (sys::VA_ENC_PACKED_HEADER_SEQUENCE + | sys::VA_ENC_PACKED_HEADER_PICTURE + | sys::VA_ENC_PACKED_HEADER_SLICE); + let config_id = Config::new( + display, + profile, + Entrypoint::EncSlice, + &[ + ConfigAttrib::rt_format(sys::VA_RT_FORMAT_YUV420), + ConfigAttrib { + type_: sys::VAConfigAttribEncPackedHeaders, + value: packed, + }, + ], + )?; + let spec = SurfaceSpec::nv12(coded_size.0, coded_size.1) + .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); + // Input, reconstruction, one reference, and slack for the driver to + // keep a submission in flight. + let pool = SurfacePool::new(display, &spec, 8)?; + let context = Context::new( + &config_id, + coded_size.0, + coded_size.1, + sys::VA_PROGRESSIVE, + pool.targets(), + )?; + + Ok(Encoder { + tunings: Tunings { + bitrate: config.bitrate, + framerate: config.framerate, + }, + config, + context, + pool, + coded_size, + reference: None, + gop_position: 0, + coded: 0, + tunings_dirty: true, + profile, + upload: None, + }) + } + + /// The coded (block-aligned) size the driver works at. + pub fn coded_size(&self) -> (u32, u32) { + self.coded_size + } + + /// Change bitrate or frame rate; takes effect on the next frame. + pub fn tune(&mut self, tunings: Tunings) { + self.tunings = tunings; + self.tunings_dirty = true; + } + + /// Encode one frame and return its coded bytes. + pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { + if frame.width != self.config.width || frame.height != self.config.height { + return Err(Error::config(format!( + "encoder configured for {}x{} was given a {}x{} frame", + self.config.width, self.config.height, frame.width, frame.height + ))); + } + let keyframe = meta.force_keyframe + || self.reference.is_none() + || self.gop_position >= self.config.gop_size.max(1); + + let input = self + .pool + .acquire() + .ok_or_else(|| Error::config("encode: every surface is still in use"))?; + self.upload(frame, &input)?; + let recon = self + .pool + .acquire() + .ok_or_else(|| Error::config("encode: no surface for the reconstruction"))?; + + // 6 bits per pixel of headroom: an intra frame at a low quantiser is the + // worst case, and a coded buffer that overflows loses the picture. + let coded_size = (self.coded_size.0 * self.coded_size.1 * 3 / 4).max(1 << 20); + let coded_buf = Buffer::allocate(&self.context, sys::VAEncCodedBufferType, coded_size)?; + let coded_id = coded_buf.id(); + + let mut buffers = Vec::new(); + match self.config.codec { + EncCodec::H264 => h264::parameters(self, &recon, coded_id, keyframe, &mut buffers)?, + EncCodec::H265 => hevc::parameters(self, &recon, coded_id, keyframe, &mut buffers)?, + EncCodec::Av1 => av1::parameters(self, &recon, coded_id, keyframe, &mut buffers)?, + } + buffers.extend(self.rate_control_buffers()?); + buffers.push(coded_buf); + + let mut picture = Picture::new(&self.context, Arc::clone(input.surface())) + .begin()? + .render_all(buffers)? + .end()? + .sync()?; + + let data = { + let coded = picture + .buffers_mut() + .iter_mut() + .find(|b| b.buffer_type() == sys::VAEncCodedBufferType) + .ok_or_else(|| Error::config("the coded buffer vanished from the picture"))?; + let mapped = coded.map()?; + coded_bytes(&mapped)? + }; + + self.reference = Some(recon); + self.coded += 1; + self.gop_position = if keyframe { 1 } else { self.gop_position + 1 }; + Ok(CodedFrame { + data, + timestamp: meta.timestamp, + is_keyframe: keyframe, + }) + } + + /// Upload one frame into a surface as NV12. + /// + /// One image is created per encoder and reused: `vaCreateImage` per frame + /// would be an allocation per frame, which is exactly the shape of the + /// per-frame cost this crate exists to remove. + fn upload(&mut self, frame: &I420, surface: &Arc) -> Result<()> { + if self.upload.is_none() { + self.upload = Some(Image::create( + surface.display(), + sys::VA_FOURCC_NV12, + self.coded_size.0, + self.coded_size.1, + )?); + } + let image = self + .upload + .as_mut() + .ok_or_else(|| Error::config("no upload image"))?; + let (w, h) = (frame.width as usize, frame.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + { + let mut mapped = image.map()?; + let y_pitch = mapped.pitch(0).unwrap_or(0) as usize; + let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize; + // The two planes are written in turn because a mapping hands out one + // mutable plane at a time; the loops are the interleave `i420_to_nv12` + // does for callers that own both buffers. + if let Some(dst) = mapped.plane_mut(0) { + for row in 0..h { + let (s, d) = (row * w, row * y_pitch); + if d + w > dst.len() { + break; + } + dst[d..d + w].copy_from_slice(&frame.y[s..s + w]); + } + } + if let Some(dst) = mapped.plane_mut(1) { + for row in 0..ch { + let d = row * uv_pitch; + if d + cw * 2 > dst.len() { + break; + } + for col in 0..cw { + dst[d + col * 2] = frame.u[row * cw + col]; + dst[d + col * 2 + 1] = frame.v[row * cw + col]; + } + } + } + } + surface.write_from(image, self.coded_size.0, self.coded_size.1)?; + Ok(()) + } + + /// The misc parameter buffers that carry rate control, resent when tuned. + fn rate_control_buffers(&mut self) -> Result> { + if !self.tunings_dirty { + return Ok(Vec::new()); + } + self.tunings_dirty = false; + let (initial_qp, min_qp, max_qp, bits) = match self.config.rate_control { + RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0), + RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate), + }; + let rc = RateControl { + bits_per_second: bits, + target_percentage: 100, + window_size: 1000, + initial_qp, + min_qp, + max_qp, + }; + let mut out = vec![Buffer::from_bytes( + &self.context, + sys::VAEncMiscParameterBufferType, + &misc_bytes(MISC_RATE_CONTROL, &rc.words()), + )?]; + let fr = crate::params::enc::FrameRate { + num: self.tunings.framerate.0.max(1), + den: self.tunings.framerate.1.max(1), + }; + out.push(Buffer::from_bytes( + &self.context, + sys::VAEncMiscParameterBufferType, + &misc_bytes(MISC_FRAME_RATE, &fr.words()), + )?); + if bits > 0 { + let hrd = crate::params::enc::Hrd { + initial_buffer_fullness: bits, + buffer_size: bits * 2, + }; + out.push(Buffer::from_bytes( + &self.context, + sys::VAEncMiscParameterBufferType, + &misc_bytes(MISC_HRD, &hrd.words()), + )?); + } + Ok(out) + } + + /// Submit one packed header: its parameter buffer, then its bytes. + /// + /// Both go in the same picture, in this order, which is what the driver + /// reads them in (`va.h:2446`). + pub(crate) fn push_packed( + &self, + packed: &headers::Packed, + out: &mut Vec, + ) -> Result<()> { + let param = PackedHeaderParameterBuffer { + type_: packed.kind, + bit_length: packed.bits, + has_emulation_bytes: 1, + ..PackedHeaderParameterBuffer::default() + }; + out.push(param_buffer(&self.context, ¶m)?); + out.push(Buffer::from_bytes( + &self.context, + sys::VAEncPackedHeaderDataBufferType, + &packed.bytes, + )?); + Ok(()) + } + + pub(crate) fn context(&self) -> &Arc { + &self.context + } + + pub(crate) fn config(&self) -> &EncoderConfig { + &self.config + } + + pub(crate) fn reference(&self) -> Option<&Arc> { + self.reference.as_ref() + } + + pub(crate) fn coded_count(&self) -> u64 { + self.coded + } + + pub(crate) fn gop_position(&self) -> u32 { + self.gop_position + } + + /// The VA profile this encoder was configured with. + pub fn profile(&self) -> Profile { + self.profile + } +} + +/// Collect the bytes of a coded buffer's segment list. +/// +/// `VACodedBufferSegment` is a linked list in driver memory: `size`, `bit_offset`, +/// `status`, a `buf` pointer to that segment's bytes and a `next` pointer. There +/// is no safe way to express that in `ec-va`, so this is one of the crate's two +/// unsafe functions. +fn coded_bytes(mapped: &MappedBuffer<'_>) -> Result> { + // Field offsets from `crates/ec-hw/abi-probe.c`: size=0 bit_offset=4 + // status=8 reserved=12 buf=16 next=24, total 48 bytes, align 8. + const BUF_OFFSET: usize = 16; + const NEXT_OFFSET: usize = 24; + let mut out = Vec::new(); + // SAFETY: the mapping is a VACodedBufferSegment as libva defines it + // (va.h:3940); the pointer is valid for the guard's lifetime. + let mut segment = unsafe { mapped.as_ptr() }; + // A driver returning a cyclic list would otherwise hang the export; 4096 + // segments is far beyond any real picture. + for _ in 0..4096 { + if segment.is_null() { + break; + } + // SAFETY: `segment` points at a 48-byte segment header the driver + // wrote; every field is read at its probed offset with an unaligned + // read, and `buf` points at `size` bytes of coded data that stay valid + // until the buffer is unmapped (i.e. for this guard's lifetime). + let (size, data, next) = unsafe { + let size = segment.cast::().read_unaligned() as usize; + let data = segment.add(BUF_OFFSET).cast::<*const u8>().read_unaligned(); + let next = segment.add(NEXT_OFFSET).cast::<*mut u8>().read_unaligned(); + (size, data, next) + }; + if data.is_null() || size == 0 { + break; + } + // SAFETY: as above — `data` is valid for `size` bytes. + out.extend_from_slice(unsafe { std::slice::from_raw_parts(data, size) }); + segment = next; + } + if out.is_empty() { + return Err(Error::config("the encoder produced an empty coded buffer")); + } + Ok(out) +}