forge
Explore
Log in

Don't you dare go Hollow

Hardware encoding for H.264 and HEVC, AV1 behind an opt-in

Browse files at this commit

7368f27762b4c0c52c0345d96268a0b8e637cdf3Ahmet Kaan GümüşParent: eb589d4
  • feat
    • hardware encoding for H.264 and HEVC, AV1 behind an opt-in
Show full message
feat(hw): hardware encoding for H.264 and HEVC, AV1 behind an opt-in

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.rsadded+101 -0
@@ -0,0 +1,101 @@
1+//! AV1 encode parameters — opt-in only.
2+//!
3+//! Kept deliberately minimal: one tile, one reference, no segmentation, no
4+//! superres, no film grain. The point of this path today is that it exists,
5+//! compiles, and either produces a frame or a typed error — never a panic and
6+//! never a submission this crate cannot describe. See the module docs of
7+//! [`super`] for why it is not on by default.
8+
9+use std::sync::Arc;
10+
11+use ec_va::Buffer;
12+
13+use super::{Encoder, RateControlMode};
14+use crate::error::Result;
15+use crate::params::enc::{
16+ EncPictureParameterBufferAV1, EncSequenceParameterBufferAV1, EncTileGroupBufferAV1,
17+};
18+use crate::params::param_buffer;
19+use crate::pool::PooledSurface;
20+
21+/// `KEY_FRAME` and `INTER_FRAME` (spec 6.8.2).
22+const KEY_FRAME: u32 = 0;
23+const INTER_FRAME: u32 = 1;
24+
25+pub(super) fn parameters(
26+ encoder: &Encoder,
27+ recon: &Arc<PooledSurface>,
28+ coded_buf: u32,
29+ keyframe: bool,
30+ out: &mut Vec<Buffer>,
31+) -> Result<()> {
32+ let config = *encoder.config();
33+ let context = encoder.context();
34+ let (coded_w, coded_h) = encoder.coded_size();
35+
36+ let mut seq = EncSequenceParameterBufferAV1 {
37+ seq_profile: 0,
38+ // 0 lets the driver pick the level from the picture size and rate.
39+ seq_level_idx: 0,
40+ intra_period: config.gop_size.max(1),
41+ ip_period: 1,
42+ bits_per_second: match config.rate_control {
43+ RateControlMode::ConstantBitrate => config.bitrate,
44+ RateControlMode::ConstantQp { .. } => 0,
45+ },
46+ order_hint_bits_minus_1: 6,
47+ ..EncSequenceParameterBufferAV1::default()
48+ };
49+ seq.seq_fields = seq
50+ .seq_fields
51+ .enable_order_hint(1)
52+ .bit_depth_minus8(0)
53+ .subsampling_x(1)
54+ .subsampling_y(1);
55+ out.push(param_buffer(context, &seq)?);
56+
57+ let order_hint = (encoder.gop_position() % 128) as u8;
58+ let mut pic = EncPictureParameterBufferAV1 {
59+ frame_width_minus_1: (config.width.max(1) - 1) as u16,
60+ frame_height_minus_1: (config.height.max(1) - 1) as u16,
61+ reconstructed_frame: recon.id(),
62+ coded_buf,
63+ primary_ref_frame: 7, // PRIMARY_REF_NONE
64+ order_hint,
65+ refresh_frame_flags: 0xff,
66+ base_qindex: match config.rate_control {
67+ RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8,
68+ RateControlMode::ConstantBitrate => 128,
69+ },
70+ min_base_qindex: 1,
71+ max_base_qindex: 255,
72+ tile_cols: 1,
73+ tile_rows: 1,
74+ superres_scale_denominator: 8,
75+ ..EncPictureParameterBufferAV1::default()
76+ };
77+ // One tile covering the whole frame, in 64x64 superblocks.
78+ pic.width_in_sbs_minus_1[0] = (coded_w.div_ceil(64).max(1) - 1) as u16;
79+ pic.height_in_sbs_minus_1[0] = (coded_h.div_ceil(64).max(1) - 1) as u16;
80+ if let Some(reference) = encoder.reference().filter(|_| !keyframe) {
81+ for slot in pic.reference_frames.iter_mut() {
82+ *slot = reference.id();
83+ }
84+ pic.primary_ref_frame = 0;
85+ }
86+ pic.picture_flags = pic
87+ .picture_flags
88+ .frame_type(if keyframe { KEY_FRAME } else { INTER_FRAME })
89+ .disable_cdf_update(1)
90+ .disable_frame_end_update_cdf(1)
91+ .enable_frame_obu(1);
92+ out.push(param_buffer(context, &pic)?);
93+
94+ let tile_group = EncTileGroupBufferAV1 {
95+ tg_start: 0,
96+ tg_end: 0,
97+ ..EncTileGroupBufferAV1::default()
98+ };
99+ out.push(param_buffer(context, &tile_group)?);
100+ Ok(())
101+}
crates/ec-hw/src/enc/h264.rsadded+191 -0
@@ -0,0 +1,191 @@
1+//! H.264 encode parameters.
2+//!
3+//! `pic_order_cnt_type` is 2 — decode order *is* output order — because this
4+//! encoder codes no B frames, and type 2 then costs no picture order count in
5+//! any slice header. Everything else follows from one reference and one slice
6+//! per picture.
7+
8+use std::sync::Arc;
9+
10+use ec_va::Buffer;
11+
12+use super::{Encoder, RateControlMode, headers};
13+use crate::error::Result;
14+use crate::params::enc::{
15+ EncPictureParameterBufferH264, EncSequenceParameterBufferH264, EncSliceParameterBufferH264,
16+};
17+use crate::params::h264::{PICTURE_SHORT_TERM_REFERENCE, VAPictureH264};
18+use crate::params::param_buffer;
19+use crate::pool::PooledSurface;
20+
21+/// `log2_max_frame_num_minus4` = 0, i.e. `frame_num` wraps at 16 — far beyond
22+/// the single reference this encoder keeps.
23+const LOG2_MAX_FRAME_NUM: u64 = 4;
24+
25+pub(super) fn parameters(
26+ encoder: &Encoder,
27+ recon: &Arc<PooledSurface>,
28+ coded_buf: u32,
29+ keyframe: bool,
30+ out: &mut Vec<Buffer>,
31+) -> Result<()> {
32+ let config = *encoder.config();
33+ let context = encoder.context();
34+ let (coded_w, coded_h) = encoder.coded_size();
35+ let frame_num = if keyframe {
36+ 0
37+ } else {
38+ (encoder.coded_count() % (1 << LOG2_MAX_FRAME_NUM)) as u16
39+ };
40+
41+ let mut seq = EncSequenceParameterBufferH264 {
42+ level_idc: level_idc(coded_w, coded_h, config.framerate),
43+ intra_period: config.gop_size.max(1),
44+ intra_idr_period: config.gop_size.max(1),
45+ ip_period: 1,
46+ bits_per_second: match config.rate_control {
47+ RateControlMode::ConstantBitrate => config.bitrate,
48+ RateControlMode::ConstantQp { .. } => 0,
49+ },
50+ max_num_ref_frames: 1,
51+ picture_width_in_mbs: (coded_w / 16) as u16,
52+ picture_height_in_mbs: (coded_h / 16) as u16,
53+ // 4:2:0 in a crop rectangle of two luma samples per unit (7.4.2.1.1).
54+ frame_cropping_flag: u8::from(coded_w != config.width || coded_h != config.height),
55+ frame_crop_right_offset: (coded_w - config.width) / 2,
56+ frame_crop_bottom_offset: (coded_h - config.height) / 2,
57+ vui_parameters_present_flag: 1,
58+ num_units_in_tick: config.framerate.1.max(1),
59+ // time_scale is twice the frame rate: a "tick" is a field period.
60+ time_scale: config.framerate.0.max(1) * 2,
61+ ..EncSequenceParameterBufferH264::default()
62+ };
63+ seq.seq_fields = seq
64+ .seq_fields
65+ .chroma_format_idc(1)
66+ .frame_mbs_only_flag(1)
67+ .direct_8x8_inference_flag(1)
68+ .log2_max_frame_num_minus4(0)
69+ .pic_order_cnt_type(2);
70+ seq.vui_fields = seq
71+ .vui_fields
72+ .timing_info_present_flag(1)
73+ .fixed_frame_rate_flag(1);
74+ out.push(param_buffer(context, &seq)?);
75+
76+ let mut pic = EncPictureParameterBufferH264 {
77+ curr_pic: VAPictureH264::frame(
78+ recon.id(),
79+ u32::from(frame_num),
80+ 2 * encoder.coded_count() as i32,
81+ PICTURE_SHORT_TERM_REFERENCE,
82+ ),
83+ coded_buf,
84+ frame_num,
85+ pic_init_qp: match config.rate_control {
86+ RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8,
87+ RateControlMode::ConstantBitrate => 26,
88+ },
89+ ..EncPictureParameterBufferH264::default()
90+ };
91+ if let Some(reference) = encoder.reference().filter(|_| !keyframe) {
92+ pic.reference_frames[0] = VAPictureH264::frame(
93+ reference.id(),
94+ u32::from(frame_num.wrapping_sub(1)),
95+ 2 * (encoder.coded_count() as i32 - 1),
96+ PICTURE_SHORT_TERM_REFERENCE,
97+ );
98+ }
99+ pic.pic_fields = pic
100+ .pic_fields
101+ .idr_pic_flag(u32::from(keyframe))
102+ .reference_pic_flag(1)
103+ .entropy_coding_mode_flag(1) // CABAC: High profile, and 10% smaller
104+ .deblocking_filter_control_present_flag(1);
105+ out.push(param_buffer(context, &pic)?);
106+
107+ let mut slice = EncSliceParameterBufferH264 {
108+ macroblock_address: 0,
109+ num_macroblocks: (coded_w / 16) * (coded_h / 16),
110+ slice_type: if keyframe { 2 } else { 0 },
111+ // idr_pic_id alternates between consecutive IDR pictures (7.4.3).
112+ idr_pic_id: ((encoder.gop_position() / config.gop_size.max(1)) % 2) as u16,
113+ num_ref_idx_active_override_flag: 0,
114+ ..EncSliceParameterBufferH264::default()
115+ };
116+ if !keyframe && let Some(reference) = encoder.reference() {
117+ slice.ref_pic_list0[0] = VAPictureH264::frame(
118+ reference.id(),
119+ u32::from(frame_num.wrapping_sub(1)),
120+ 2 * (encoder.coded_count() as i32 - 1),
121+ PICTURE_SHORT_TERM_REFERENCE,
122+ );
123+ }
124+
125+ // Packed headers, in bitstream order: the parameter sets open every key
126+ // frame (so a stream is seekable and a decoder can start anywhere), and the
127+ // slice header opens every picture.
128+ let header_params = headers::H264Params {
129+ level_idc: seq.level_idc,
130+ mb_width: u32::from(seq.picture_width_in_mbs),
131+ mb_height: u32::from(seq.picture_height_in_mbs),
132+ crop_right: seq.frame_crop_right_offset,
133+ crop_bottom: seq.frame_crop_bottom_offset,
134+ num_units_in_tick: seq.num_units_in_tick,
135+ time_scale: seq.time_scale,
136+ pic_init_qp: pic.pic_init_qp,
137+ };
138+ if keyframe {
139+ encoder.push_packed(&headers::h264_sps(&header_params), out)?;
140+ encoder.push_packed(&headers::h264_pps(&header_params), out)?;
141+ }
142+ encoder.push_packed(
143+ &headers::h264_slice_header(keyframe, u32::from(frame_num), u32::from(slice.idr_pic_id)),
144+ out,
145+ )?;
146+ out.push(param_buffer(context, &slice)?);
147+ Ok(())
148+}
149+
150+/// The lowest Annex A level that fits the picture size and rate.
151+///
152+/// Advertising level 6.2 for a 640x480 clip is legal and lazy; a player that
153+/// checks levels against its decoder budget deserves the real one.
154+fn level_idc(width: u32, height: u32, framerate: (u32, u32)) -> u8 {
155+ const LEVELS: [(u8, u64, u64); 12] = [
156+ (10, 1485, 99),
157+ (11, 3000, 396),
158+ (20, 11880, 396),
159+ (21, 19800, 792),
160+ (22, 20250, 1620),
161+ (30, 40500, 1620),
162+ (31, 108000, 3600),
163+ (32, 216000, 5120),
164+ (40, 245760, 8192),
165+ (50, 589824, 22080),
166+ (51, 983040, 36864),
167+ (52, 2073600, 36864),
168+ ];
169+ let frame_mbs = u64::from(width / 16) * u64::from(height / 16);
170+ let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1));
171+ let mbps = (frame_mbs as f64 * fps).ceil() as u64;
172+ for &(idc, max_mbps, max_fs) in &LEVELS {
173+ if mbps <= max_mbps && frame_mbs <= max_fs {
174+ return idc;
175+ }
176+ }
177+ 62
178+}
179+
180+#[cfg(test)]
181+mod tests {
182+ use super::*;
183+
184+ #[test]
185+ fn levels_follow_size_and_rate() {
186+ assert_eq!(level_idc(1920, 1088, (30, 1)), 40);
187+ assert_eq!(level_idc(1920, 1088, (60, 1)), 50);
188+ assert_eq!(level_idc(3840, 2160, (30, 1)), 51);
189+ assert_eq!(level_idc(640, 480, (30, 1)), 30);
190+ }
191+}
crates/ec-hw/src/enc/headers.rsadded+345 -0
@@ -0,0 +1,345 @@
1+//! Packed headers: the parameter sets and slice headers the *application*
2+//! writes for the driver.
3+//!
4+//! This is not optional plumbing. radeonsi advertises
5+//! `VA_ENC_PACKED_HEADER_SEQUENCE | PICTURE | SLICE` and then writes none of
6+//! them itself: without these, the coded buffer comes back holding slice data
7+//! with no parameter sets in front of it — a stream ffmpeg answers with
8+//! "Invalid data found when processing input" (measured, 2026-08-14). Every
9+//! field below therefore has to agree with the `VAEnc*ParameterBuffer` the
10+//! driver was given, or the header describes a picture other than the one the
11+//! hardware coded.
12+
13+use ec_core::BitWriter;
14+
15+use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
16+
17+/// A header ready to submit: escaped bytes plus its exact length in bits.
18+///
19+/// The bit length matters for slice headers, which do not end on a byte
20+/// boundary — the driver continues the bitstream from exactly that bit.
21+pub(crate) struct Packed {
22+ pub(crate) kind: u32,
23+ pub(crate) bytes: Vec<u8>,
24+ pub(crate) bits: u32,
25+}
26+
27+/// Wrap a complete NAL: start code, header byte(s), escaped payload.
28+fn nal(kind: u32, header: &[u8], rbsp: &[u8], padding_bits: u32) -> Packed {
29+ let mut bytes = vec![0, 0, 0, 1];
30+ bytes.extend_from_slice(header);
31+ let mut escaped = Vec::with_capacity(rbsp.len() + 8);
32+ ec_h264_syntax::escape_rbsp(rbsp, &mut escaped);
33+ bytes.extend_from_slice(&escaped);
34+ let bits = bytes.len() as u32 * 8 - padding_bits;
35+ Packed { kind, bytes, bits }
36+}
37+
38+// ---------------------------------------------------------------------------
39+// H.264
40+// ---------------------------------------------------------------------------
41+
42+/// What the H.264 headers need, mirroring the sequence parameter buffer.
43+pub(super) struct H264Params {
44+ pub(super) level_idc: u8,
45+ pub(super) mb_width: u32,
46+ pub(super) mb_height: u32,
47+ pub(super) crop_right: u32,
48+ pub(super) crop_bottom: u32,
49+ pub(super) num_units_in_tick: u32,
50+ pub(super) time_scale: u32,
51+ pub(super) pic_init_qp: u8,
52+}
53+
54+/// `log2_max_frame_num`, matching `seq_fields.log2_max_frame_num_minus4 = 0`.
55+pub(super) const H264_LOG2_MAX_FRAME_NUM: u32 = 4;
56+
57+/// The sequence parameter set (7.3.2.1), High profile.
58+pub(super) fn h264_sps(p: &H264Params) -> Packed {
59+ let mut w = BitWriter::with_capacity(64);
60+ w.write_bits(100, 8); // profile_idc: High
61+ w.write_bits(0, 8); // constraint_set flags + reserved_zero_2bits
62+ w.write_bits(u32::from(p.level_idc), 8);
63+ w.write_ue(0); // seq_parameter_set_id
64+ // High profile tail.
65+ w.write_ue(1); // chroma_format_idc: 4:2:0
66+ w.write_ue(0); // bit_depth_luma_minus8
67+ w.write_ue(0); // bit_depth_chroma_minus8
68+ w.write_bit(false); // qpprime_y_zero_transform_bypass_flag
69+ w.write_bit(false); // seq_scaling_matrix_present_flag
70+ w.write_ue(H264_LOG2_MAX_FRAME_NUM - 4);
71+ w.write_ue(2); // pic_order_cnt_type 2: output order is decode order
72+ w.write_ue(1); // max_num_ref_frames
73+ w.write_bit(false); // gaps_in_frame_num_value_allowed_flag
74+ w.write_ue(p.mb_width - 1);
75+ w.write_ue(p.mb_height - 1);
76+ w.write_bit(true); // frame_mbs_only_flag
77+ w.write_bit(true); // direct_8x8_inference_flag
78+ let cropping = p.crop_right != 0 || p.crop_bottom != 0;
79+ w.write_bit(cropping);
80+ if cropping {
81+ // CropUnitX = 2 and CropUnitY = 2 for progressive 4:2:0 (7.4.2.1.1).
82+ w.write_ue(0);
83+ w.write_ue(p.crop_right);
84+ w.write_ue(0);
85+ w.write_ue(p.crop_bottom);
86+ }
87+ w.write_bit(true); // vui_parameters_present_flag
88+ w.write_bit(false); // aspect_ratio_info_present_flag
89+ w.write_bit(false); // overscan_info_present_flag
90+ w.write_bit(false); // video_signal_type_present_flag
91+ w.write_bit(false); // chroma_loc_info_present_flag
92+ w.write_bit(true); // timing_info_present_flag
93+ w.write_bits(p.num_units_in_tick, 32);
94+ w.write_bits(p.time_scale, 32);
95+ w.write_bit(true); // fixed_frame_rate_flag
96+ w.write_bit(false); // nal_hrd_parameters_present_flag
97+ w.write_bit(false); // vcl_hrd_parameters_present_flag
98+ w.write_bit(false); // pic_struct_present_flag
99+ w.write_bit(false); // bitstream_restriction_flag
100+ trailing(&mut w);
101+ nal(PACKED_HEADER_SEQUENCE, &[0x67], &w.into_bytes(), 0)
102+}
103+
104+/// The picture parameter set (7.3.2.2).
105+pub(super) fn h264_pps(p: &H264Params) -> Packed {
106+ let mut w = BitWriter::with_capacity(16);
107+ w.write_ue(0); // pic_parameter_set_id
108+ w.write_ue(0); // seq_parameter_set_id
109+ w.write_bit(true); // entropy_coding_mode_flag: CABAC
110+ w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag
111+ w.write_ue(0); // num_slice_groups_minus1
112+ w.write_ue(0); // num_ref_idx_l0_default_active_minus1
113+ w.write_ue(0); // num_ref_idx_l1_default_active_minus1
114+ w.write_bit(false); // weighted_pred_flag
115+ w.write_bits(0, 2); // weighted_bipred_idc
116+ w.write_se(i32::from(p.pic_init_qp) - 26);
117+ w.write_se(0); // pic_init_qs_minus26
118+ w.write_se(0); // chroma_qp_index_offset
119+ w.write_bit(true); // deblocking_filter_control_present_flag
120+ w.write_bit(false); // constrained_intra_pred_flag
121+ w.write_bit(false); // redundant_pic_cnt_present_flag
122+ trailing(&mut w);
123+ nal(PACKED_HEADER_PICTURE, &[0x68], &w.into_bytes(), 0)
124+}
125+
126+/// The slice header (7.3.3), up to but *not* including the slice data.
127+///
128+/// No trailing bits and no alignment: the driver continues the bitstream at the
129+/// next bit (`cabac_alignment_one_bit` is its business), which is why the
130+/// returned bit count has to be exact.
131+pub(super) fn h264_slice_header(idr: bool, frame_num: u32, idr_pic_id: u32) -> Packed {
132+ let mut w = BitWriter::with_capacity(16);
133+ w.write_ue(0); // first_mb_in_slice
134+ // 5..=9 assert that every slice of the picture has this type, which holds:
135+ // one slice per picture.
136+ w.write_ue(if idr { 7 } else { 5 });
137+ w.write_ue(0); // pic_parameter_set_id
138+ w.write_bits(frame_num, H264_LOG2_MAX_FRAME_NUM);
139+ if idr {
140+ w.write_ue(idr_pic_id);
141+ }
142+ // pic_order_cnt_type 2: no picture order count in the header.
143+ if !idr {
144+ w.write_bit(false); // num_ref_idx_active_override_flag
145+ w.write_bit(false); // ref_pic_list_modification_flag_l0
146+ }
147+ // Every picture here is a reference (nal_ref_idc != 0).
148+ if idr {
149+ w.write_bit(false); // no_output_of_prior_pics_flag
150+ w.write_bit(false); // long_term_reference_flag
151+ } else {
152+ w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window
153+ }
154+ if !idr {
155+ w.write_ue(0); // cabac_init_idc
156+ }
157+ w.write_se(0); // slice_qp_delta, against pic_init_qp
158+ w.write_ue(0); // disable_deblocking_filter_idc
159+ w.write_se(0); // slice_alpha_c0_offset_div2
160+ w.write_se(0); // slice_beta_offset_div2
161+ let bits = w.bit_len() as u32;
162+ let padding = (8 - bits % 8) % 8;
163+ w.align_to_byte();
164+ let header = if idr { 0x65 } else { 0x61 };
165+ nal(PACKED_HEADER_SLICE, &[header], &w.into_bytes(), padding)
166+}
167+
168+/// `rbsp_trailing_bits` (7.3.2.11).
169+fn trailing(w: &mut BitWriter) {
170+ w.write_bit(true);
171+ w.align_to_byte();
172+}
173+
174+// ---------------------------------------------------------------------------
175+// HEVC
176+// ---------------------------------------------------------------------------
177+
178+/// Build the HEVC parameter sets, and the slice header for one picture.
179+///
180+/// The syntax crate writes all four structures, so the encoder and the software
181+/// HEVC path in this family share one definition of what a parameter set is.
182+pub(super) mod hevc {
183+ use ec_h265_syntax::{
184+ ConformanceWindow, NalHeader, NalUnitType, Pps, ProfileTierLevel, ShortTermRefPicSet,
185+ SliceHeader, SliceType, Sps, Vps,
186+ };
187+
188+ use super::{Packed, nal};
189+ use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
190+
191+ /// Geometry and timing for the parameter sets.
192+ pub(in crate::enc) struct Params {
193+ pub(in crate::enc) width: u32,
194+ pub(in crate::enc) height: u32,
195+ pub(in crate::enc) coded_width: u32,
196+ pub(in crate::enc) coded_height: u32,
197+ pub(in crate::enc) level_idc: u8,
198+ pub(in crate::enc) num_units_in_tick: u32,
199+ pub(in crate::enc) time_scale: u32,
200+ pub(in crate::enc) init_qp: u8,
201+ }
202+
203+ /// The VPS, SPS and PPS, in that order.
204+ pub(in crate::enc) fn parameter_sets(p: &Params) -> (Vps, Sps, Pps) {
205+ let ptl = ProfileTierLevel::main(p.level_idc);
206+ let vps = Vps {
207+ id: 0,
208+ ptl,
209+ max_dec_pic_buffering_minus1: 1,
210+ max_num_reorder_pics: 0,
211+ };
212+ let sps = Sps {
213+ vps_id: 0,
214+ id: 0,
215+ chroma_format_idc: 1,
216+ separate_colour_plane: false,
217+ pic_width_in_luma_samples: p.coded_width,
218+ pic_height_in_luma_samples: p.coded_height,
219+ // The conformance window is how HEVC crops: the coded size is a
220+ // multiple of the minimum coding block, the displayed size is not.
221+ conf_win: ConformanceWindow {
222+ left: 0,
223+ right: (p.coded_width - p.width) / 2,
224+ top: 0,
225+ bottom: (p.coded_height - p.height) / 2,
226+ },
227+ bit_depth_luma_minus8: 0,
228+ bit_depth_chroma_minus8: 0,
229+ log2_max_poc_lsb_minus4: 8,
230+ max_dec_pic_buffering_minus1: 1,
231+ max_num_reorder_pics: 0,
232+ log2_min_cb_size_minus3: 0,
233+ log2_diff_max_min_cb_size: 3,
234+ log2_min_tb_size_minus2: 0,
235+ log2_diff_max_min_tb_size: 3,
236+ max_transform_hierarchy_depth_inter: 1,
237+ max_transform_hierarchy_depth_intra: 1,
238+ scaling_list_enabled: false,
239+ amp_enabled: true,
240+ sao_enabled: true,
241+ pcm_enabled: false,
242+ pcm: None,
243+ // No sets in the sequence: this driver writes the reference picture
244+ // set out in each slice header (an inline `st_ref_pic_set` naming
245+ // the previous picture), so declaring one here would leave the two
246+ // descriptions of the same thing free to disagree.
247+ num_short_term_ref_pic_sets: 0,
248+ short_term_ref_pic_sets: Vec::new(),
249+ long_term_ref_pics_present: false,
250+ num_long_term_ref_pics_sps: 0,
251+ long_term_ref_pics_sps: Vec::new(),
252+ temporal_mvp_enabled: false,
253+ strong_intra_smoothing: true,
254+ ptl,
255+ vui: Some(ec_h265_syntax::vui::VuiParameters {
256+ timing: Some((p.num_units_in_tick, p.time_scale)),
257+ ..ec_h265_syntax::vui::VuiParameters::default()
258+ }),
259+ };
260+ let pps = Pps {
261+ id: 0,
262+ sps_id: 0,
263+ init_qp_minus26: i32::from(p.init_qp) - 26,
264+ num_ref_idx_l0_default_active_minus1: 0,
265+ num_ref_idx_l1_default_active_minus1: 0,
266+ transform_skip_enabled: true,
267+ loop_filter_across_tiles_enabled: false,
268+ loop_filter_across_slices_enabled: false,
269+ ..Pps::default()
270+ };
271+ (vps, sps, pps)
272+ }
273+
274+ /// `st_ref_pic_set()`: one negative reference at POC - 1, used by this
275+ /// picture — the single reference this encoder keeps.
276+ fn previous_picture_set() -> ShortTermRefPicSet {
277+ let mut set = ShortTermRefPicSet {
278+ num_negative: 1,
279+ num_positive: 0,
280+ num_used_by_curr: 1,
281+ ..ShortTermRefPicSet::default()
282+ };
283+ set.delta_poc_s0[0] = -1;
284+ set.used_s0[0] = true;
285+ set
286+ }
287+
288+ pub(in crate::enc) fn packed_vps(vps: &Vps) -> Packed {
289+ nal(
290+ PACKED_HEADER_SEQUENCE,
291+ &NalHeader::new(NalUnitType::Vps).to_bytes(),
292+ &vps.to_rbsp(),
293+ 0,
294+ )
295+ }
296+
297+ pub(in crate::enc) fn packed_sps(sps: &Sps) -> Packed {
298+ nal(
299+ PACKED_HEADER_SEQUENCE,
300+ &NalHeader::new(NalUnitType::Sps).to_bytes(),
301+ &sps.to_rbsp(),
302+ 0,
303+ )
304+ }
305+
306+ pub(in crate::enc) fn packed_pps(pps: &Pps) -> Packed {
307+ nal(
308+ PACKED_HEADER_PICTURE,
309+ &NalHeader::new(NalUnitType::Pps).to_bytes(),
310+ &pps.to_rbsp(),
311+ 0,
312+ )
313+ }
314+
315+ /// The slice segment header, ending mid-byte like H.264's.
316+ pub(in crate::enc) fn packed_slice(sps: &Sps, pps: &Pps, keyframe: bool, poc: i32) -> Packed {
317+ let nal_type = if keyframe {
318+ NalUnitType::IdrWRadl
319+ } else {
320+ NalUnitType::TrailR
321+ };
322+ let mut header = SliceHeader::intra(pps, 0);
323+ header.slice_type = if keyframe { SliceType::I } else { SliceType::P };
324+ header.poc_lsb = (poc as u32) & ((1 << (sps.log2_max_poc_lsb_minus4 + 4)) - 1);
325+ header.sao_luma = sps.sao_enabled;
326+ header.sao_chroma = sps.sao_enabled;
327+ header.five_minus_max_num_merge_cand = 0;
328+ // The set goes in the header rather than the SPS, which is what this
329+ // driver writes when it composes the header itself.
330+ header.short_term_ref_pic_set_sps_flag = false;
331+ header.short_term_ref_pic_set = previous_picture_set();
332+ header.loop_filter_across_slices_enabled = false;
333+ let mut w = ec_core::BitWriter::with_capacity(16);
334+ // With `byte_alignment()` (7.3.6.1): this driver copies the header it is
335+ // given verbatim and starts the slice data at the next byte, so the
336+ // alignment bit has to be in what it is given.
337+ header.write(&mut w, sps, pps, nal_type);
338+ nal(
339+ PACKED_HEADER_SLICE,
340+ &NalHeader::new(nal_type).to_bytes(),
341+ &w.into_bytes(),
342+ 0,
343+ )
344+ }
345+}
crates/ec-hw/src/enc/hevc.rsadded+201 -0
@@ -0,0 +1,201 @@
1+//! HEVC encode parameters.
2+//!
3+//! HEVC encoding in-tree is one of the reasons this crate exists: the incumbent
4+//! stack carried it on a branch for months. It is the same IDR-then-P structure
5+//! as the H.264 path, in HEVC's units — CTBs instead of macroblocks, a picture
6+//! order count instead of `frame_num`, and a conformance window instead of a
7+//! frame crop, which is what makes 1916x1080 (or any width that is not a
8+//! multiple of 32) come out the size it went in.
9+
10+use std::sync::Arc;
11+
12+use ec_va::Buffer;
13+
14+use super::headers::hevc as hevc_headers;
15+use super::{Encoder, RateControlMode};
16+use crate::error::Result;
17+use crate::params::enc::{
18+ EncPictureParameterBufferHEVC, EncSequenceParameterBufferHEVC, EncSliceParameterBufferHEVC,
19+};
20+use crate::params::hevc::VAPictureHEVC;
21+use crate::params::param_buffer;
22+use crate::pool::PooledSurface;
23+
24+/// `NAL_IDR_W_RADL`.
25+const NAL_IDR_W_RADL: u8 = 19;
26+/// `NAL_TRAIL_R`.
27+const NAL_TRAIL_R: u8 = 1;
28+
29+pub(super) fn parameters(
30+ encoder: &Encoder,
31+ recon: &Arc<PooledSurface>,
32+ coded_buf: u32,
33+ keyframe: bool,
34+ out: &mut Vec<Buffer>,
35+) -> Result<()> {
36+ let config = *encoder.config();
37+ let context = encoder.context();
38+ let (coded_w, coded_h) = encoder.coded_size();
39+ let poc = if keyframe {
40+ 0
41+ } else {
42+ encoder.gop_position() as i32
43+ };
44+
45+ let mut seq = EncSequenceParameterBufferHEVC {
46+ general_profile_idc: 1, // Main
47+ general_level_idc: level_idc(coded_w, coded_h, config.framerate),
48+ general_tier_flag: 0,
49+ intra_period: config.gop_size.max(1),
50+ intra_idr_period: config.gop_size.max(1),
51+ ip_period: 1,
52+ bits_per_second: match config.rate_control {
53+ RateControlMode::ConstantBitrate => config.bitrate,
54+ RateControlMode::ConstantQp { .. } => 0,
55+ },
56+ pic_width_in_luma_samples: coded_w as u16,
57+ pic_height_in_luma_samples: coded_h as u16,
58+ // 64x64 CTBs from 8x8 minimum CBs: log2_min = 0 (8), diff = 3 (64).
59+ // Not a preference — this driver codes 64x64 CTBs whatever the sequence
60+ // parameters say, and `num_ctu_in_slice` below has to count the same
61+ // blocks the hardware does.
62+ log2_min_luma_coding_block_size_minus3: 0,
63+ log2_diff_max_min_luma_coding_block_size: 3,
64+ log2_min_transform_block_size_minus2: 0,
65+ log2_diff_max_min_transform_block_size: 3,
66+ max_transform_hierarchy_depth_inter: 1,
67+ max_transform_hierarchy_depth_intra: 1,
68+ vui_parameters_present_flag: 1,
69+ vui_num_units_in_tick: config.framerate.1.max(1),
70+ vui_time_scale: config.framerate.0.max(1),
71+ ..EncSequenceParameterBufferHEVC::default()
72+ };
73+ seq.seq_fields = seq
74+ .seq_fields
75+ .chroma_format_idc(1)
76+ .bit_depth_luma_minus8(0)
77+ .bit_depth_chroma_minus8(0)
78+ .strong_intra_smoothing_enabled_flag(1)
79+ .amp_enabled_flag(1)
80+ .sample_adaptive_offset_enabled_flag(1);
81+ seq.vui_fields = seq.vui_fields.vui_timing_info_present_flag(1);
82+ out.push(param_buffer(context, &seq)?);
83+
84+ let mut pic = EncPictureParameterBufferHEVC {
85+ decoded_curr_pic: VAPictureHEVC::new(recon.id(), poc, 0),
86+ coded_buf,
87+ collocated_ref_pic_index: 0xff,
88+ pic_init_qp: match config.rate_control {
89+ RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8,
90+ RateControlMode::ConstantBitrate => 26,
91+ },
92+ nal_unit_type: if keyframe {
93+ NAL_IDR_W_RADL
94+ } else {
95+ NAL_TRAIL_R
96+ },
97+ ..EncPictureParameterBufferHEVC::default()
98+ };
99+ if let Some(reference) = encoder.reference().filter(|_| !keyframe) {
100+ pic.reference_frames[0] = VAPictureHEVC::new(reference.id(), poc - 1, 0);
101+ }
102+ pic.pic_fields = pic
103+ .pic_fields
104+ .idr_pic_flag(u32::from(keyframe))
105+ // 1 = I, 2 = P in this driver's coding_type numbering.
106+ .coding_type(if keyframe { 1 } else { 2 })
107+ .reference_pic_flag(1)
108+ .transform_skip_enabled_flag(1)
109+ // Off, and it has to be off: this driver omits
110+ // `slice_loop_filter_across_slices_enabled_flag` from the slice header
111+ // it writes, so a PPS that says the flag is present describes a header
112+ // that is one bit longer than the one in the stream — every P picture
113+ // then decodes as `alignment_bit_equal_to_one = 0` (measured).
114+ .pps_loop_filter_across_slices_enabled_flag(0);
115+ out.push(param_buffer(context, &pic)?);
116+
117+ // CTBs are 64x64 by the sequence parameters above.
118+ let ctbs = coded_w.div_ceil(64) * coded_h.div_ceil(64);
119+ let mut slice = EncSliceParameterBufferHEVC {
120+ slice_segment_address: 0,
121+ num_ctu_in_slice: ctbs,
122+ slice_type: if keyframe { 2 } else { 1 }, // 2 = I, 1 = P
123+ num_ref_idx_l0_active_minus1: 0,
124+ num_ref_idx_l1_active_minus1: 0,
125+ max_num_merge_cand: 5,
126+ ..EncSliceParameterBufferHEVC::default()
127+ };
128+ if !keyframe && let Some(reference) = encoder.reference() {
129+ slice.ref_pic_list0[0] = VAPictureHEVC::new(reference.id(), poc - 1, 0);
130+ }
131+ slice.slice_fields = slice
132+ .slice_fields
133+ .last_slice_of_pic_flag(1)
134+ .slice_sao_luma_flag(1)
135+ .slice_sao_chroma_flag(1)
136+ .cabac_init_flag(0)
137+ .num_ref_idx_active_override_flag(u32::from(!keyframe))
138+ .slice_loop_filter_across_slices_enabled_flag(0);
139+
140+ let header_params = hevc_headers::Params {
141+ width: config.width,
142+ height: config.height,
143+ coded_width: coded_w,
144+ coded_height: coded_h,
145+ level_idc: seq.general_level_idc,
146+ num_units_in_tick: seq.vui_num_units_in_tick,
147+ time_scale: seq.vui_time_scale,
148+ init_qp: pic.pic_init_qp,
149+ };
150+ let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params);
151+ if keyframe {
152+ encoder.push_packed(&hevc_headers::packed_vps(&vps), out)?;
153+ encoder.push_packed(&hevc_headers::packed_sps(&sps), out)?;
154+ encoder.push_packed(&hevc_headers::packed_pps(&pps), out)?;
155+ }
156+ // The slice header goes in too. This driver composes its own for HEVC and
157+ // ignores the content of this one — but it emits the parameter sets above
158+ // only when a slice header accompanies them, so dropping it costs the
159+ // stream its VPS, SPS and PPS (measured 2026-08-14).
160+ encoder.push_packed(&hevc_headers::packed_slice(&sps, &pps, keyframe, poc), out)?;
161+ out.push(param_buffer(context, &slice)?);
162+ Ok(())
163+}
164+
165+/// The lowest level whose luma sample rate and picture size fit (Annex A).
166+fn level_idc(width: u32, height: u32, framerate: (u32, u32)) -> u8 {
167+ // (general_level_idc = level * 30, MaxLumaPs, MaxLumaSr)
168+ const LEVELS: [(u8, u64, u64); 9] = [
169+ (30, 36_864, 552_960),
170+ (60, 122_880, 3_686_400),
171+ (63, 245_760, 7_372_800),
172+ (90, 552_960, 16_588_800),
173+ (93, 983_040, 33_177_600),
174+ (120, 2_228_224, 66_846_720),
175+ (123, 2_228_224, 133_693_440),
176+ (150, 8_912_896, 267_386_880),
177+ (153, 8_912_896, 534_773_760),
178+ ];
179+ let samples = u64::from(width) * u64::from(height);
180+ let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1));
181+ let rate = (samples as f64 * fps).ceil() as u64;
182+ for &(idc, max_ps, max_sr) in &LEVELS {
183+ if samples <= max_ps && rate <= max_sr {
184+ return idc;
185+ }
186+ }
187+ 186
188+}
189+
190+#[cfg(test)]
191+mod tests {
192+ use super::*;
193+
194+ #[test]
195+ fn levels_follow_size_and_rate() {
196+ // 1080p30 is level 4.0 (120), 1080p60 level 4.1 (123), 2160p30 5.0 (150).
197+ assert_eq!(level_idc(1920, 1088, (30, 1)), 120);
198+ assert_eq!(level_idc(1920, 1088, (60, 1)), 123);
199+ assert_eq!(level_idc(3840, 2160, (30, 1)), 150);
200+ }
201+}
crates/ec-hw/src/enc/mod.rsadded+518 -0
@@ -0,0 +1,518 @@
1+//! Hardware encoding: H.264, HEVC, and AV1 behind an explicit opt-in.
2+//!
3+//! One frame in, one coded frame out. The GOP is IDR-then-P with a single
4+//! reference, which is what this GPU advertises (`VAConfigAttribEncMaxRefFrames`
5+//! reports one list-0 reference for HEVC) and what an editor's export wants:
6+//! no reordering, so a coded frame comes back in the call that fed it.
7+//!
8+//! # AV1
9+//!
10+//! AV1 encoding is off unless [`EncoderConfig::allow_av1`] is set, and never
11+//! reachable from an "auto" codec choice. The reason is on the record rather
12+//! than theoretical: an AV1 encode submission on this driver generation took
13+//! the GPU down hard enough to need a reset. The path is built, typed and
14+//! probed; turning it on is a caller's explicit decision.
15+
16+use std::sync::Arc;
17+
18+use ec_va::caps::{Entrypoint, Profile};
19+use ec_va::{
20+ Buffer, CapReport, Config, ConfigAttrib, Context, Display, Image, MappedBuffer, Picture,
21+ Surface, SurfaceSpec, sys,
22+};
23+
24+use crate::error::{Error, Result};
25+use crate::frame::I420;
26+use crate::params::enc::{
27+ MISC_FRAME_RATE, MISC_HRD, MISC_RATE_CONTROL, PackedHeaderParameterBuffer, RateControl,
28+ misc_bytes,
29+};
30+use crate::params::param_buffer;
31+use crate::pool::{PooledSurface, SurfacePool};
32+
33+mod av1;
34+mod h264;
35+mod headers;
36+mod hevc;
37+
38+/// The codecs this crate encodes in hardware.
39+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40+pub enum EncCodec {
41+ /// H.264 / AVC, High profile.
42+ H264,
43+ /// H.265 / HEVC, Main profile.
44+ H265,
45+ /// AV1 Profile 0 — opt-in only, see the module docs.
46+ Av1,
47+}
48+
49+/// How the driver should spend bits.
50+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51+pub enum RateControlMode {
52+ /// Constant quantiser: `qp` for every picture, bitrate ignored.
53+ ConstantQp {
54+ /// The quantiser, 0..51 for H.264/HEVC, 0..255 for AV1.
55+ qp: u32,
56+ },
57+ /// Constant bitrate, the driver picking quantisers to hold it.
58+ ConstantBitrate,
59+}
60+
61+/// What can be changed between frames without rebuilding the encoder.
62+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63+pub struct Tunings {
64+ /// Target bitrate in bits per second.
65+ pub bitrate: u32,
66+ /// Frame rate as `(numerator, denominator)`.
67+ pub framerate: (u32, u32),
68+}
69+
70+/// Per-frame instructions from the caller.
71+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72+pub struct FrameMetadata {
73+ /// Presentation timestamp, carried through to the coded frame.
74+ pub timestamp: i64,
75+ /// Start a new GOP with this frame.
76+ pub force_keyframe: bool,
77+}
78+
79+/// How an encoder is set up.
80+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81+pub struct EncoderConfig {
82+ /// Which codec.
83+ pub codec: EncCodec,
84+ /// Displayed width; the coded size is rounded up for the codec's blocks.
85+ pub width: u32,
86+ /// Displayed height.
87+ pub height: u32,
88+ /// Frame rate as `(numerator, denominator)`.
89+ pub framerate: (u32, u32),
90+ /// Target bitrate in bits per second.
91+ pub bitrate: u32,
92+ /// Pictures per GOP; the first of each is an IDR / key frame.
93+ pub gop_size: u32,
94+ /// Rate control mode.
95+ pub rate_control: RateControlMode,
96+ /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default.
97+ pub quality: u32,
98+ /// Permit AV1 encoding. Without it, [`EncCodec::Av1`] is refused.
99+ pub allow_av1: bool,
100+}
101+
102+impl EncoderConfig {
103+ /// A configuration with sensible defaults for `codec` at `width x height`.
104+ pub fn new(codec: EncCodec, width: u32, height: u32) -> EncoderConfig {
105+ EncoderConfig {
106+ codec,
107+ width,
108+ height,
109+ framerate: (30, 1),
110+ bitrate: 8_000_000,
111+ gop_size: 60,
112+ rate_control: RateControlMode::ConstantBitrate,
113+ quality: 0,
114+ allow_av1: false,
115+ }
116+ }
117+}
118+
119+/// One coded picture.
120+#[derive(Debug, Clone, PartialEq, Eq)]
121+pub struct CodedFrame {
122+ /// The bitstream: an Annex B access unit for H.264/HEVC, an OBU sequence
123+ /// for AV1.
124+ pub data: Vec<u8>,
125+ /// The timestamp the caller supplied with the source frame.
126+ pub timestamp: i64,
127+ /// True for an IDR / key frame.
128+ pub is_keyframe: bool,
129+}
130+
131+/// A hardware encoder.
132+pub struct Encoder {
133+ config: EncoderConfig,
134+ context: Arc<Context>,
135+ pool: SurfacePool,
136+ coded_size: (u32, u32),
137+ /// The reconstruction of the previous picture, the single reference.
138+ reference: Option<Arc<PooledSurface>>,
139+ /// Pictures coded since the last key frame.
140+ gop_position: u32,
141+ /// Pictures coded in total, which drives frame_num and order hints.
142+ coded: u64,
143+ tunings: Tunings,
144+ /// Set when the rate control parameters have to be resent.
145+ tunings_dirty: bool,
146+ profile: Profile,
147+ /// An upload image, reused across frames.
148+ upload: Option<Image>,
149+}
150+
151+impl Encoder {
152+ /// Build an encoder for `config` on `display`.
153+ pub fn new(display: &Arc<Display>, config: EncoderConfig) -> Result<Encoder> {
154+ if config.codec == EncCodec::Av1 && !config.allow_av1 {
155+ return Err(Error::unsupported(
156+ "AV1 hardware encoding",
157+ "it is opt-in (EncoderConfig::allow_av1) after a GPU recovery incident",
158+ ));
159+ }
160+ let profile = match config.codec {
161+ // High is the profile every H.264 encoder on this driver reports and
162+ // the one a High-profile decoder expects; Main is a strict subset.
163+ EncCodec::H264 => Profile::H264High,
164+ EncCodec::H265 => Profile::HEVCMain,
165+ EncCodec::Av1 => Profile::AV1Profile0,
166+ };
167+ let block = match config.codec {
168+ EncCodec::H264 => 16,
169+ EncCodec::H265 => 32,
170+ EncCodec::Av1 => 64,
171+ };
172+ let coded_size = (
173+ config.width.next_multiple_of(block),
174+ config.height.next_multiple_of(block),
175+ );
176+
177+ let caps = CapReport::probe(display)?;
178+ let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| {
179+ Error::unsupported(
180+ format!("{profile:?} encode"),
181+ "the driver advertises no EncSlice entrypoint for this profile",
182+ )
183+ })?;
184+ if let Some(surfaces) = &entry.surfaces
185+ && !surfaces.allows(coded_size.0, coded_size.1)
186+ {
187+ // The minimum encode size is a driver fact, not a guess: radeonsi
188+ // refuses anything under 96x32 for H.264 and 384x128 for HEVC.
189+ return Err(Error::unsupported(
190+ format!("{}x{} {profile:?} encode", coded_size.0, coded_size.1),
191+ format!(
192+ "the driver accepts {:?}..{:?} x {:?}..{:?}",
193+ surfaces.min_width,
194+ surfaces.max_width,
195+ surfaces.min_height,
196+ surfaces.max_height
197+ ),
198+ ));
199+ }
200+
201+ // The packed-header attribute is not decoration: a config that does not
202+ // ask for them gets a driver that writes its own headers and silently
203+ // ignores the application's (measured on radeonsi — the parameter sets
204+ // went in, the slice header did not, and every P picture came back
205+ // missing its `byte_alignment()`).
206+ let packed = entry.packed_headers
207+ & (sys::VA_ENC_PACKED_HEADER_SEQUENCE
208+ | sys::VA_ENC_PACKED_HEADER_PICTURE
209+ | sys::VA_ENC_PACKED_HEADER_SLICE);
210+ let config_id = Config::new(
211+ display,
212+ profile,
213+ Entrypoint::EncSlice,
214+ &[
215+ ConfigAttrib::rt_format(sys::VA_RT_FORMAT_YUV420),
216+ ConfigAttrib {
217+ type_: sys::VAConfigAttribEncPackedHeaders,
218+ value: packed,
219+ },
220+ ],
221+ )?;
222+ let spec = SurfaceSpec::nv12(coded_size.0, coded_size.1)
223+ .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER);
224+ // Input, reconstruction, one reference, and slack for the driver to
225+ // keep a submission in flight.
226+ let pool = SurfacePool::new(display, &spec, 8)?;
227+ let context = Context::new(
228+ &config_id,
229+ coded_size.0,
230+ coded_size.1,
231+ sys::VA_PROGRESSIVE,
232+ pool.targets(),
233+ )?;
234+
235+ Ok(Encoder {
236+ tunings: Tunings {
237+ bitrate: config.bitrate,
238+ framerate: config.framerate,
239+ },
240+ config,
241+ context,
242+ pool,
243+ coded_size,
244+ reference: None,
245+ gop_position: 0,
246+ coded: 0,
247+ tunings_dirty: true,
248+ profile,
249+ upload: None,
250+ })
251+ }
252+
253+ /// The coded (block-aligned) size the driver works at.
254+ pub fn coded_size(&self) -> (u32, u32) {
255+ self.coded_size
256+ }
257+
258+ /// Change bitrate or frame rate; takes effect on the next frame.
259+ pub fn tune(&mut self, tunings: Tunings) {
260+ self.tunings = tunings;
261+ self.tunings_dirty = true;
262+ }
263+
264+ /// Encode one frame and return its coded bytes.
265+ pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
266+ if frame.width != self.config.width || frame.height != self.config.height {
267+ return Err(Error::config(format!(
268+ "encoder configured for {}x{} was given a {}x{} frame",
269+ self.config.width, self.config.height, frame.width, frame.height
270+ )));
271+ }
272+ let keyframe = meta.force_keyframe
273+ || self.reference.is_none()
274+ || self.gop_position >= self.config.gop_size.max(1);
275+
276+ let input = self
277+ .pool
278+ .acquire()
279+ .ok_or_else(|| Error::config("encode: every surface is still in use"))?;
280+ self.upload(frame, &input)?;
281+ let recon = self
282+ .pool
283+ .acquire()
284+ .ok_or_else(|| Error::config("encode: no surface for the reconstruction"))?;
285+
286+ // 6 bits per pixel of headroom: an intra frame at a low quantiser is the
287+ // worst case, and a coded buffer that overflows loses the picture.
288+ let coded_size = (self.coded_size.0 * self.coded_size.1 * 3 / 4).max(1 << 20);
289+ let coded_buf = Buffer::allocate(&self.context, sys::VAEncCodedBufferType, coded_size)?;
290+ let coded_id = coded_buf.id();
291+
292+ let mut buffers = Vec::new();
293+ match self.config.codec {
294+ EncCodec::H264 => h264::parameters(self, &recon, coded_id, keyframe, &mut buffers)?,
295+ EncCodec::H265 => hevc::parameters(self, &recon, coded_id, keyframe, &mut buffers)?,
296+ EncCodec::Av1 => av1::parameters(self, &recon, coded_id, keyframe, &mut buffers)?,
297+ }
298+ buffers.extend(self.rate_control_buffers()?);
299+ buffers.push(coded_buf);
300+
301+ let mut picture = Picture::new(&self.context, Arc::clone(input.surface()))
302+ .begin()?
303+ .render_all(buffers)?
304+ .end()?
305+ .sync()?;
306+
307+ let data = {
308+ let coded = picture
309+ .buffers_mut()
310+ .iter_mut()
311+ .find(|b| b.buffer_type() == sys::VAEncCodedBufferType)
312+ .ok_or_else(|| Error::config("the coded buffer vanished from the picture"))?;
313+ let mapped = coded.map()?;
314+ coded_bytes(&mapped)?
315+ };
316+
317+ self.reference = Some(recon);
318+ self.coded += 1;
319+ self.gop_position = if keyframe { 1 } else { self.gop_position + 1 };
320+ Ok(CodedFrame {
321+ data,
322+ timestamp: meta.timestamp,
323+ is_keyframe: keyframe,
324+ })
325+ }
326+
327+ /// Upload one frame into a surface as NV12.
328+ ///
329+ /// One image is created per encoder and reused: `vaCreateImage` per frame
330+ /// would be an allocation per frame, which is exactly the shape of the
331+ /// per-frame cost this crate exists to remove.
332+ fn upload(&mut self, frame: &I420, surface: &Arc<Surface>) -> Result<()> {
333+ if self.upload.is_none() {
334+ self.upload = Some(Image::create(
335+ surface.display(),
336+ sys::VA_FOURCC_NV12,
337+ self.coded_size.0,
338+ self.coded_size.1,
339+ )?);
340+ }
341+ let image = self
342+ .upload
343+ .as_mut()
344+ .ok_or_else(|| Error::config("no upload image"))?;
345+ let (w, h) = (frame.width as usize, frame.height as usize);
346+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
347+ {
348+ let mut mapped = image.map()?;
349+ let y_pitch = mapped.pitch(0).unwrap_or(0) as usize;
350+ let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize;
351+ // The two planes are written in turn because a mapping hands out one
352+ // mutable plane at a time; the loops are the interleave `i420_to_nv12`
353+ // does for callers that own both buffers.
354+ if let Some(dst) = mapped.plane_mut(0) {
355+ for row in 0..h {
356+ let (s, d) = (row * w, row * y_pitch);
357+ if d + w > dst.len() {
358+ break;
359+ }
360+ dst[d..d + w].copy_from_slice(&frame.y[s..s + w]);
361+ }
362+ }
363+ if let Some(dst) = mapped.plane_mut(1) {
364+ for row in 0..ch {
365+ let d = row * uv_pitch;
366+ if d + cw * 2 > dst.len() {
367+ break;
368+ }
369+ for col in 0..cw {
370+ dst[d + col * 2] = frame.u[row * cw + col];
371+ dst[d + col * 2 + 1] = frame.v[row * cw + col];
372+ }
373+ }
374+ }
375+ }
376+ surface.write_from(image, self.coded_size.0, self.coded_size.1)?;
377+ Ok(())
378+ }
379+
380+ /// The misc parameter buffers that carry rate control, resent when tuned.
381+ fn rate_control_buffers(&mut self) -> Result<Vec<Buffer>> {
382+ if !self.tunings_dirty {
383+ return Ok(Vec::new());
384+ }
385+ self.tunings_dirty = false;
386+ let (initial_qp, min_qp, max_qp, bits) = match self.config.rate_control {
387+ RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0),
388+ RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate),
389+ };
390+ let rc = RateControl {
391+ bits_per_second: bits,
392+ target_percentage: 100,
393+ window_size: 1000,
394+ initial_qp,
395+ min_qp,
396+ max_qp,
397+ };
398+ let mut out = vec![Buffer::from_bytes(
399+ &self.context,
400+ sys::VAEncMiscParameterBufferType,
401+ &misc_bytes(MISC_RATE_CONTROL, &rc.words()),
402+ )?];
403+ let fr = crate::params::enc::FrameRate {
404+ num: self.tunings.framerate.0.max(1),
405+ den: self.tunings.framerate.1.max(1),
406+ };
407+ out.push(Buffer::from_bytes(
408+ &self.context,
409+ sys::VAEncMiscParameterBufferType,
410+ &misc_bytes(MISC_FRAME_RATE, &fr.words()),
411+ )?);
412+ if bits > 0 {
413+ let hrd = crate::params::enc::Hrd {
414+ initial_buffer_fullness: bits,
415+ buffer_size: bits * 2,
416+ };
417+ out.push(Buffer::from_bytes(
418+ &self.context,
419+ sys::VAEncMiscParameterBufferType,
420+ &misc_bytes(MISC_HRD, &hrd.words()),
421+ )?);
422+ }
423+ Ok(out)
424+ }
425+
426+ /// Submit one packed header: its parameter buffer, then its bytes.
427+ ///
428+ /// Both go in the same picture, in this order, which is what the driver
429+ /// reads them in (`va.h:2446`).
430+ pub(crate) fn push_packed(
431+ &self,
432+ packed: &headers::Packed,
433+ out: &mut Vec<Buffer>,
434+ ) -> Result<()> {
435+ let param = PackedHeaderParameterBuffer {
436+ type_: packed.kind,
437+ bit_length: packed.bits,
438+ has_emulation_bytes: 1,
439+ ..PackedHeaderParameterBuffer::default()
440+ };
441+ out.push(param_buffer(&self.context, &param)?);
442+ out.push(Buffer::from_bytes(
443+ &self.context,
444+ sys::VAEncPackedHeaderDataBufferType,
445+ &packed.bytes,
446+ )?);
447+ Ok(())
448+ }
449+
450+ pub(crate) fn context(&self) -> &Arc<Context> {
451+ &self.context
452+ }
453+
454+ pub(crate) fn config(&self) -> &EncoderConfig {
455+ &self.config
456+ }
457+
458+ pub(crate) fn reference(&self) -> Option<&Arc<PooledSurface>> {
459+ self.reference.as_ref()
460+ }
461+
462+ pub(crate) fn coded_count(&self) -> u64 {
463+ self.coded
464+ }
465+
466+ pub(crate) fn gop_position(&self) -> u32 {
467+ self.gop_position
468+ }
469+
470+ /// The VA profile this encoder was configured with.
471+ pub fn profile(&self) -> Profile {
472+ self.profile
473+ }
474+}
475+
476+/// Collect the bytes of a coded buffer's segment list.
477+///
478+/// `VACodedBufferSegment` is a linked list in driver memory: `size`, `bit_offset`,
479+/// `status`, a `buf` pointer to that segment's bytes and a `next` pointer. There
480+/// is no safe way to express that in `ec-va`, so this is one of the crate's two
481+/// unsafe functions.
482+fn coded_bytes(mapped: &MappedBuffer<'_>) -> Result<Vec<u8>> {
483+ // Field offsets from `crates/ec-hw/abi-probe.c`: size=0 bit_offset=4
484+ // status=8 reserved=12 buf=16 next=24, total 48 bytes, align 8.
485+ const BUF_OFFSET: usize = 16;
486+ const NEXT_OFFSET: usize = 24;
487+ let mut out = Vec::new();
488+ // SAFETY: the mapping is a VACodedBufferSegment as libva defines it
489+ // (va.h:3940); the pointer is valid for the guard's lifetime.
490+ let mut segment = unsafe { mapped.as_ptr() };
491+ // A driver returning a cyclic list would otherwise hang the export; 4096
492+ // segments is far beyond any real picture.
493+ for _ in 0..4096 {
494+ if segment.is_null() {
495+ break;
496+ }
497+ // SAFETY: `segment` points at a 48-byte segment header the driver
498+ // wrote; every field is read at its probed offset with an unaligned
499+ // read, and `buf` points at `size` bytes of coded data that stay valid
500+ // until the buffer is unmapped (i.e. for this guard's lifetime).
501+ let (size, data, next) = unsafe {
502+ let size = segment.cast::<u32>().read_unaligned() as usize;
503+ let data = segment.add(BUF_OFFSET).cast::<*const u8>().read_unaligned();
504+ let next = segment.add(NEXT_OFFSET).cast::<*mut u8>().read_unaligned();
505+ (size, data, next)
506+ };
507+ if data.is_null() || size == 0 {
508+ break;
509+ }
510+ // SAFETY: as above — `data` is valid for `size` bytes.
511+ out.extend_from_slice(unsafe { std::slice::from_raw_parts(data, size) });
512+ segment = next;
513+ }
514+ if out.is_empty() {
515+ return Err(Error::config("the encoder produced an empty coded buffer"));
516+ }
517+ Ok(out)
518+}