forge
Explore
Log in

Don't you dare go Hollow

AV1 hardware encode that two independent decoders agree on

Browse files at this commit

a51830430f1e977b70a27ca06d26f2fb8203d22eAhmet Kaan GümüşParent: 77aeca1
  • feat
    • AV1 hardware encode that two independent decoders agree on
Show full message
feat(ec-hw): AV1 hardware encode that two independent decoders agree on

The AV1 encode path submitted parameters no header described: radeonsi
parses the application's sequence and frame header OBUs and writes the
stream from them, so without those OBUs the coded buffer meant nothing.
This writes both (spec 5.5.1 / 5.9.1, the subset the driver advertises:
one tile, one reference, no CDEF, no restoration, no superres), fills
the picture parameter buffer to agree with them field for field, and
prepends the temporal delimiter the driver does not emit.

Gate: ec-av1 and ffmpeg's libdav1d decode every shown frame of a
640x384 and a 1920x1080 stream sample for sample, and the coded picture
is within 60 dB of the one submitted.
Cargo.lockmodified+1 -0
@@ -351,6 +351,7 @@ dependencies = [
351 name = "ec-hw"351 name = "ec-hw"
352 version = "0.1.0"352 version = "0.1.0"
353 dependencies = [353 dependencies = [
354+ "ec-av1",
354 "ec-av1-syntax",355 "ec-av1-syntax",
355 "ec-core",356 "ec-core",
356 "ec-h264-syntax",357 "ec-h264-syntax",
crates/ec-hw/Cargo.tomlmodified+4 -0
@@ -13,3 +13,7 @@ ec-h264-syntax.workspace = true
13 ec-h265-syntax.workspace = true13 ec-h265-syntax.workspace = true
14 ec-va.workspace = true14 ec-va.workspace = true
15 ec-vp9-syntax.workspace = true15 ec-vp9-syntax.workspace = true
16+
17+[dev-dependencies]
18+# The second, independent decoder the AV1 encode gate compares ffmpeg against.
19+ec-av1.workspace = true
crates/ec-hw/src/enc/av1.rsmodified+158 -30
@@ -1,15 +1,21 @@
1-//! AV1 encode parameters — opt-in only.1+//! AV1 encode parameters.
2 //!2 //!
3-//! Kept deliberately minimal: one tile, one reference, no segmentation, no3+//! One tile, one reference, no segmentation, no superres, no film grain: the
4-//! superres, no film grain. The point of this path today is that it exists,4+//! subset this driver advertises (`VAConfigAttribEncAV1` on radeonsi reports
5-//! compiles, and either produces a frame or a typed error — never a panic and5+//! no filter intra, no warped motion, no dual filter, no superres and no
6-//! never a submission this crate cannot describe. See the module docs of6+//! restoration) and the same subset ffmpeg's `av1_vaapi` encoder writes.
7-//! [`super`] for why it is not on by default.7+//!
8+//! The driver does not compose the headers: it parses the sequence header and
9+//! frame header OBUs this module packs (see [`super::headers::av1`]) and
10+//! writes the stream's own headers from them together with the picture
11+//! parameter buffer below. Both therefore describe one picture, or the coded
12+//! frame is not the frame that was submitted.
8 13
9 use std::sync::Arc;14 use std::sync::Arc;
10 15
11 use ec_va::Buffer;16 use ec_va::Buffer;
12 17
18+use super::headers::av1 as av1_headers;
13 use super::{Encoder, RateControlMode};19 use super::{Encoder, RateControlMode};
14 use crate::error::Result;20 use crate::error::Result;
15 use crate::params::enc::{21 use crate::params::enc::{
@@ -17,10 +23,20 @@ use crate::params::enc::{
17 };23 };
18 use crate::params::param_buffer;24 use crate::params::param_buffer;
19 use crate::pool::PooledSurface;25 use crate::pool::PooledSurface;
26+use crate::params::INVALID_SURFACE;
20 27
21 /// `KEY_FRAME` and `INTER_FRAME` (spec 6.8.2).28 /// `KEY_FRAME` and `INTER_FRAME` (spec 6.8.2).
22 const KEY_FRAME: u32 = 0;29 const KEY_FRAME: u32 = 0;
23 const INTER_FRAME: u32 = 1;30 const INTER_FRAME: u32 = 1;
31+/// `PRIMARY_REF_NONE`.
32+const PRIMARY_REF_NONE: u8 = 7;
33+/// `TX_MODE_SELECT`, the only mode this driver advertises.
34+const TX_MODE_SELECT: u32 = 2;
35+/// `SWITCHABLE` interpolation filter.
36+const INTERP_SWITCHABLE: u8 = 4;
37+/// The deblocking level written into the header; the driver picks its own for
38+/// the stream it writes, so this is only the value it starts from.
39+const LOOP_FILTER_LEVEL: u8 = 1;
24 40
25 pub(super) fn parameters(41 pub(super) fn parameters(
26 encoder: &Encoder,42 encoder: &Encoder,
@@ -32,18 +48,21 @@ pub(super) fn parameters(
32 let config = *encoder.config();48 let config = *encoder.config();
33 let context = encoder.context();49 let context = encoder.context();
34 let (coded_w, coded_h) = encoder.coded_size();50 let (coded_w, coded_h) = encoder.coded_size();
51+ let (width, height) = (config.width.max(1), config.height.max(1));
52+ let cqp = matches!(config.rate_control, RateControlMode::ConstantQp { .. });
53+ let level_idx = seq_level_idx(coded_w, coded_h, config.framerate);
35 54
36 let mut seq = EncSequenceParameterBufferAV1 {55 let mut seq = EncSequenceParameterBufferAV1 {
37 seq_profile: 0,56 seq_profile: 0,
38- // 0 lets the driver pick the level from the picture size and rate.57+ seq_level_idx: level_idx,
39- seq_level_idx: 0,58+ seq_tier: 0,
40 intra_period: config.gop_size.max(1),59 intra_period: config.gop_size.max(1),
41 ip_period: 1,60 ip_period: 1,
42 bits_per_second: match config.rate_control {61 bits_per_second: match config.rate_control {
43 RateControlMode::ConstantBitrate => config.bitrate,62 RateControlMode::ConstantBitrate => config.bitrate,
44 RateControlMode::ConstantQp { .. } => 0,63 RateControlMode::ConstantQp { .. } => 0,
45 },64 },
46- order_hint_bits_minus_1: 6,65+ order_hint_bits_minus_1: (av1_headers::ORDER_HINT_BITS - 1) as u8,
47 ..EncSequenceParameterBufferAV1::default()66 ..EncSequenceParameterBufferAV1::default()
48 };67 };
49 seq.seq_fields = seq68 seq.seq_fields = seq
@@ -54,42 +73,108 @@ pub(super) fn parameters(
54 .subsampling_y(1);73 .subsampling_y(1);
55 out.push(param_buffer(context, &seq)?);74 out.push(param_buffer(context, &seq)?);
56 75
57- let order_hint = (encoder.gop_position() % 128) as u8;76+ // Superblocks are 64x64: use_128x128_superblock is off in the sequence
77+ // header, and this driver advertises no support for the larger one.
78+ let sb_cols = coded_w.div_ceil(64).max(1);
79+ let sb_rows = coded_h.div_ceil(64).max(1);
80+ let order_hint = if keyframe {
81+ 0
82+ } else {
83+ (encoder.gop_position() % 256) as u8
84+ };
85+ let base_qindex = match config.rate_control {
86+ RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8,
87+ RateControlMode::ConstantBitrate => 128,
88+ };
89+ // One reference, refreshed every picture: slot 0 holds the previous
90+ // reconstruction and every ref_frame_idx points at it.
91+ let refresh_frame_flags = if keyframe { 0xff } else { 0x01 };
92+
58 let mut pic = EncPictureParameterBufferAV1 {93 let mut pic = EncPictureParameterBufferAV1 {
59- frame_width_minus_1: (config.width.max(1) - 1) as u16,94+ frame_width_minus_1: (width - 1) as u16,
60- frame_height_minus_1: (config.height.max(1) - 1) as u16,95+ frame_height_minus_1: (height - 1) as u16,
61 reconstructed_frame: recon.id(),96 reconstructed_frame: recon.id(),
62 coded_buf,97 coded_buf,
63- primary_ref_frame: 7, // PRIMARY_REF_NONE98+ primary_ref_frame: if keyframe { PRIMARY_REF_NONE } else { 0 },
64 order_hint,99 order_hint,
65- refresh_frame_flags: 0xff,100+ refresh_frame_flags,
66- base_qindex: match config.rate_control {101+ base_qindex,
67- RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8,102+ min_base_qindex: if cqp { 0 } else { 1 },
68- RateControlMode::ConstantBitrate => 128,103+ max_base_qindex: if cqp { 0 } else { 255 },
69- },104+ filter_level: [LOOP_FILTER_LEVEL; 2],
70- min_base_qindex: 1,105+ filter_level_u: LOOP_FILTER_LEVEL,
71- max_base_qindex: 255,106+ filter_level_v: LOOP_FILTER_LEVEL,
107+ interpolation_filter: INTERP_SWITCHABLE,
72 tile_cols: 1,108 tile_cols: 1,
73 tile_rows: 1,109 tile_rows: 1,
74 superres_scale_denominator: 8,110 superres_scale_denominator: 8,
75 ..EncPictureParameterBufferAV1::default()111 ..EncPictureParameterBufferAV1::default()
76 };112 };
77- // One tile covering the whole frame, in 64x64 superblocks.113+ pic.width_in_sbs_minus_1[0] = (sb_cols - 1) as u16;
78- pic.width_in_sbs_minus_1[0] = (coded_w.div_ceil(64).max(1) - 1) as u16;114+ pic.height_in_sbs_minus_1[0] = (sb_rows - 1) as u16;
79- pic.height_in_sbs_minus_1[0] = (coded_h.div_ceil(64).max(1) - 1) as u16;
80 if let Some(reference) = encoder.reference().filter(|_| !keyframe) {115 if let Some(reference) = encoder.reference().filter(|_| !keyframe) {
81- for slot in pic.reference_frames.iter_mut() {116+ pic.reference_frames[0] = reference.id();
82- *slot = reference.id();117+ // ref_frame_ctrl_l0 = LAST_FRAME in search_idx0 (bits 0..2).
83- }118+ pic.ref_frame_ctrl_l0 = 1;
84- pic.primary_ref_frame = 0;
85 }119 }
86 pic.picture_flags = pic120 pic.picture_flags = pic
87 .picture_flags121 .picture_flags
88 .frame_type(if keyframe { KEY_FRAME } else { INTER_FRAME })122 .frame_type(if keyframe { KEY_FRAME } else { INTER_FRAME })
89- .disable_cdf_update(1)123+ // A shown key frame is error resilient by inference (5.9.2).
90- .disable_frame_end_update_cdf(1)124+ .error_resilient_mode(u32::from(keyframe))
91- .enable_frame_obu(1);125+ // The driver writes the frame header and the tile group as separate
126+ // OBUs, which is what the header packed below describes.
127+ .enable_frame_obu(0);
128+ pic.mode_control_flags = pic
129+ .mode_control_flags
130+ .tx_mode(TX_MODE_SELECT)
131+ // Single reference prediction: compound needs a second reference.
132+ .reference_mode(0);
133+ pic.tile_group_obu_hdr_info = pic.tile_group_obu_hdr_info.obu_has_size_field(1);
134+ for slot in pic.reference_frames.iter_mut().skip(1) {
135+ *slot = INVALID_SURFACE;
136+ }
137+
138+ if keyframe {
139+ encoder.push_packed(
140+ &av1_headers::sequence_header(&av1_headers::SeqParams {
141+ width,
142+ height,
143+ seq_level_idx: level_idx,
144+ seq_tier: 0,
145+ high_bitdepth: false,
146+ colour: config.colour,
147+ }),
148+ out,
149+ )?;
150+ }
151+ let (packed, offsets) = av1_headers::frame_header(&av1_headers::FrameParams {
152+ keyframe,
153+ order_hint,
154+ primary_ref_frame: 0,
155+ refresh_frame_flags,
156+ ref_frame_idx: [0; 7],
157+ base_q_idx: base_qindex,
158+ loop_filter_level: [LOOP_FILTER_LEVEL; 4],
159+ tx_mode_select: true,
160+ max_tile_cols_log2: av1_headers::tile_log2(sb_cols.min(64)),
161+ max_tile_rows_log2: av1_headers::tile_log2(sb_rows.min(64)),
162+ });
163+ if !cqp {
164+ // Outside CQP the driver picks the quantiser and the deblocking
165+ // levels itself and back-annotates them into the header it writes,
166+ // which is what these offsets are for (ffmpeg sets them on the same
167+ // condition). In CQP it has nothing to write back.
168+ pic.bit_offset_qindex = offsets.qindex;
169+ pic.bit_offset_segmentation = offsets.segmentation;
170+ pic.bit_offset_loopfilter_params = offsets.loop_filter;
171+ pic.bit_offset_cdef_params = offsets.cdef;
172+ pic.size_in_bits_cdef_params = offsets.cdef_size;
173+ pic.size_in_bits_frame_hdr_obu = offsets.total_bits;
174+ pic.byte_offset_frame_hdr_obu_size = offsets.obu_size_byte;
175+ }
92 out.push(param_buffer(context, &pic)?);176 out.push(param_buffer(context, &pic)?);
177+ encoder.push_packed(&packed, out)?;
93 178
94 let tile_group = EncTileGroupBufferAV1 {179 let tile_group = EncTileGroupBufferAV1 {
95 tg_start: 0,180 tg_start: 0,
@@ -99,3 +184,46 @@ pub(super) fn parameters(
99 out.push(param_buffer(context, &tile_group)?);184 out.push(param_buffer(context, &tile_group)?);
100 Ok(())185 Ok(())
101 }186 }
187+
188+/// The lowest AV1 level whose picture size and rate fit (Annex A), as a
189+/// `seq_level_idx`. Levels below 2.0 do not exist, and anything past 6.3 is
190+/// signalled as the maximum-parameters level.
191+fn seq_level_idx(width: u32, height: u32, framerate: (u32, u32)) -> u8 {
192+ // (seq_level_idx, MaxPicSize, MaxHSize, MaxVSize, MaxDisplayRate)
193+ const LEVELS: [(u8, u64, u32, u32, u64); 12] = [
194+ (0, 147_456, 2_048, 1_152, 4_423_680), // 2.0
195+ (1, 278_784, 2_816, 1_584, 8_363_520), // 2.1
196+ (4, 665_856, 4_352, 2_448, 19_975_680), // 3.0
197+ (5, 1_065_024, 5_504, 3_096, 31_950_720), // 3.1
198+ (8, 2_359_296, 6_144, 3_456, 70_778_880), // 4.0
199+ (9, 2_359_296, 6_144, 3_456, 141_557_760), // 4.1
200+ (12, 8_912_896, 8_192, 4_352, 267_386_880), // 5.0
201+ (13, 8_912_896, 8_192, 4_352, 534_773_760), // 5.1
202+ (14, 8_912_896, 8_192, 4_352, 1_069_547_520), // 5.2
203+ (16, 35_651_584, 16_384, 8_704, 1_069_547_520), // 6.0
204+ (17, 35_651_584, 16_384, 8_704, 2_139_095_040), // 6.1
205+ (18, 35_651_584, 16_384, 8_704, 4_278_190_080), // 6.2
206+ ];
207+ let samples = u64::from(width) * u64::from(height);
208+ let fps = f64::from(framerate.0.max(1)) / f64::from(framerate.1.max(1));
209+ let rate = (samples as f64 * fps).ceil() as u64;
210+ for &(idx, max_size, max_h, max_v, max_rate) in &LEVELS {
211+ if samples <= max_size && width <= max_h && height <= max_v && rate <= max_rate {
212+ return idx;
213+ }
214+ }
215+ 31 // maximum parameters
216+}
217+
218+#[cfg(test)]
219+mod tests {
220+ use super::*;
221+
222+ #[test]
223+ fn levels_follow_size_and_rate() {
224+ // 1080p30 is 4.0 (idx 8), 2160p30 5.0 (12), 2160p60 5.1 (13).
225+ assert_eq!(seq_level_idx(1920, 1088, (30, 1)), 8);
226+ assert_eq!(seq_level_idx(3840, 2176, (30, 1)), 12);
227+ assert_eq!(seq_level_idx(3840, 2176, (60, 1)), 13);
228+ }
229+}
crates/ec-hw/src/enc/headers.rsmodified+259 -0
@@ -365,3 +365,262 @@ pub(super) mod hevc {
365 )365 )
366 }366 }
367 }367 }
368+
369+// ---------------------------------------------------------------------------
370+// AV1
371+// ---------------------------------------------------------------------------
372+
373+/// The two OBUs the AV1 encode path hands the driver: a sequence header and,
374+/// per picture, an uncompressed frame header.
375+///
376+/// radeonsi *parses* these (`picture_av1_enc.c:vlVaHandleVAEncPackedHeaderData
377+/// BufferTypeAV1`) rather than copying them through — the sequence header in
378+/// full, the frame header as far as `uniform_tile_spacing_flag` — and then
379+/// writes the header that goes into the stream itself, from those values plus
380+/// the picture parameter buffer. So these are the *parameters*, in AV1's own
381+/// syntax: a field written here that disagrees with the parameter buffer is a
382+/// picture described two ways, and the driver believes this one.
383+pub(super) mod av1 {
384+ use ec_core::BitWriter;
385+
386+ use super::{Colour, Packed};
387+ use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE};
388+
389+ /// `OrderHintBits`, and the width of `order_hint` in a frame header.
390+ pub(in crate::enc) const ORDER_HINT_BITS: u32 = 8;
391+
392+ /// Bytes of the `obu_size` field. radeonsi reports
393+ /// `VAConfigAttribEncAV1Ext2.obu_size_bytes_minus1 = 1` (measured on this
394+ /// box), i.e. it wants that field a fixed two bytes so it can rewrite it
395+ /// without moving the payload; leb128 permits the padded encoding.
396+ const OBU_SIZE_BYTES: usize = 2;
397+
398+ /// Wrap a payload as one OBU: header byte, fixed-width `obu_size`, payload.
399+ fn obu(kind: u32, obu_type: u8, payload: Vec<u8>) -> Packed {
400+ let mut bytes = Vec::with_capacity(payload.len() + 1 + OBU_SIZE_BYTES);
401+ // forbidden(0) type(4) extension(0) has_size(1) reserved(0)
402+ bytes.push(obu_type << 3 | 0b010);
403+ let mut size = payload.len();
404+ for i in 0..OBU_SIZE_BYTES {
405+ let last = i + 1 == OBU_SIZE_BYTES;
406+ bytes.push((size as u8 & 0x7f) | if last { 0 } else { 0x80 });
407+ size >>= 7;
408+ }
409+ bytes.extend_from_slice(&payload);
410+ let bits = bytes.len() as u32 * 8;
411+ Packed { kind, bytes, bits }
412+ }
413+
414+ /// `trailing_bits()` (5.3.4).
415+ fn trailing(w: &mut BitWriter) {
416+ w.write_bit(true);
417+ w.align_to_byte();
418+ }
419+
420+ /// What the sequence header says about the stream.
421+ pub(in crate::enc) struct SeqParams {
422+ pub(in crate::enc) width: u32,
423+ pub(in crate::enc) height: u32,
424+ pub(in crate::enc) seq_level_idx: u8,
425+ pub(in crate::enc) seq_tier: u8,
426+ /// 10-bit (`high_bitdepth`); profile 0 has no `twelve_bit`.
427+ pub(in crate::enc) high_bitdepth: bool,
428+ pub(in crate::enc) colour: Option<Colour>,
429+ }
430+
431+ /// `sequence_header_obu()` (5.5.1), profile 0, one operating point.
432+ ///
433+ /// Every coding tool this driver does not advertise
434+ /// (`VAConfigAttribEncAV1`: no filter intra, no warped motion, no dual
435+ /// filter, no superres, no restoration) is signalled off, which is also
436+ /// what ffmpeg's `av1_vaapi` writes.
437+ pub(in crate::enc) fn sequence_header(p: &SeqParams) -> Packed {
438+ let mut w = BitWriter::new();
439+ w.write_bits(0, 3); // seq_profile
440+ w.write_bit(false); // still_picture
441+ w.write_bit(false); // reduced_still_picture_header
442+ w.write_bit(false); // timing_info_present_flag
443+ w.write_bit(false); // initial_display_delay_present_flag
444+ w.write_bits(0, 5); // operating_points_cnt_minus_1
445+ w.write_bits(0, 12); // operating_point_idc[0]
446+ w.write_bits(u32::from(p.seq_level_idx), 5);
447+ if p.seq_level_idx > 7 {
448+ w.write_bits(u32::from(p.seq_tier), 1);
449+ }
450+ let width_bits = 32 - p.width.max(1).leading_zeros(); // floor(log2(w)) + 1
451+ let height_bits = 32 - p.height.max(1).leading_zeros();
452+ w.write_bits(width_bits - 1, 4); // frame_width_bits_minus_1
453+ w.write_bits(height_bits - 1, 4); // frame_height_bits_minus_1
454+ w.write_bits(p.width - 1, width_bits); // max_frame_width_minus_1
455+ w.write_bits(p.height - 1, height_bits); // max_frame_height_minus_1
456+ w.write_bit(false); // frame_id_numbers_present_flag
457+ w.write_bit(false); // use_128x128_superblock
458+ w.write_bit(false); // enable_filter_intra
459+ w.write_bit(false); // enable_intra_edge_filter
460+ w.write_bit(false); // enable_interintra_compound
461+ w.write_bit(false); // enable_masked_compound
462+ w.write_bit(false); // enable_warped_motion
463+ w.write_bit(false); // enable_dual_filter
464+ w.write_bit(true); // enable_order_hint
465+ w.write_bit(false); // enable_jnt_comp
466+ w.write_bit(false); // enable_ref_frame_mvs
467+ w.write_bit(false); // seq_choose_screen_content_tools
468+ w.write_bit(false); // seq_force_screen_content_tools
469+ w.write_bits(ORDER_HINT_BITS - 1, 3); // order_hint_bits_minus_1
470+ w.write_bit(false); // enable_superres
471+ w.write_bit(false); // enable_cdef
472+ w.write_bit(false); // enable_restoration
473+ // color_config(): profile 0 is 4:2:0, and never 12-bit.
474+ w.write_bit(p.high_bitdepth);
475+ w.write_bit(false); // mono_chrome
476+ match p.colour {
477+ Some(c) => {
478+ w.write_bit(true); // color_description_present_flag
479+ w.write_bits(u32::from(c.primaries), 8);
480+ w.write_bits(u32::from(c.transfer), 8);
481+ w.write_bits(u32::from(c.matrix), 8);
482+ w.write_bit(c.full_range); // color_range
483+ }
484+ None => {
485+ w.write_bit(false);
486+ w.write_bit(false); // color_range
487+ }
488+ }
489+ w.write_bits(0, 2); // chroma_sample_position = CSP_UNKNOWN
490+ w.write_bit(false); // separate_uv_delta_q
491+ w.write_bit(false); // film_grain_params_present
492+ trailing(&mut w);
493+ obu(PACKED_HEADER_SEQUENCE, 1, w.into_bytes())
494+ }
495+
496+ /// What one picture's uncompressed header says.
497+ pub(in crate::enc) struct FrameParams {
498+ pub(in crate::enc) keyframe: bool,
499+ pub(in crate::enc) order_hint: u8,
500+ pub(in crate::enc) primary_ref_frame: u8,
501+ pub(in crate::enc) refresh_frame_flags: u8,
502+ pub(in crate::enc) ref_frame_idx: [u8; 7],
503+ pub(in crate::enc) base_q_idx: u8,
504+ pub(in crate::enc) loop_filter_level: [u8; 4],
505+ /// `TX_MODE_SELECT`; this driver advertises no other
506+ /// (`VAConfigAttribEncAV1Ext2.tx_mode_support = 0x4`).
507+ pub(in crate::enc) tx_mode_select: bool,
508+ /// The bit offsets the driver needs to back-annotate its own choices
509+ /// into this header are only read outside CQP, so they are computed
510+ /// unconditionally and used by the caller when it is not in CQP.
511+ pub(in crate::enc) max_tile_cols_log2: u32,
512+ pub(in crate::enc) max_tile_rows_log2: u32,
513+ }
514+
515+ /// Where the driver may rewrite fields of the header we just wrote, in
516+ /// bits from the first bit of the OBU (`VAEncPictureParameterBufferAV1`).
517+ pub(in crate::enc) struct FrameHeaderOffsets {
518+ pub(in crate::enc) qindex: u32,
519+ pub(in crate::enc) segmentation: u32,
520+ pub(in crate::enc) loop_filter: u32,
521+ pub(in crate::enc) cdef: u32,
522+ pub(in crate::enc) cdef_size: u32,
523+ pub(in crate::enc) obu_size_byte: u32,
524+ pub(in crate::enc) total_bits: u32,
525+ }
526+
527+ /// `frame_header_obu()` (5.9.1) for a shown key or inter frame with one
528+ /// tile, no segmentation, no CDEF, no restoration and no global motion.
529+ pub(in crate::enc) fn frame_header(p: &FrameParams) -> (Packed, FrameHeaderOffsets) {
530+ // The OBU header and its size field precede every offset below.
531+ let prefix_bits = 8 * (1 + OBU_SIZE_BYTES) as u32;
532+ let mut w = BitWriter::new();
533+ w.write_bit(false); // show_existing_frame
534+ w.write_bits(u32::from(!p.keyframe), 2); // frame_type: KEY / INTER
535+ w.write_bit(true); // show_frame
536+ if !p.keyframe {
537+ // A shown key frame infers error_resilient_mode = 1.
538+ w.write_bit(false); // error_resilient_mode
539+ }
540+ w.write_bit(false); // disable_cdf_update
541+ w.write_bit(false); // frame_size_override_flag
542+ w.write_bits(u32::from(p.order_hint), ORDER_HINT_BITS);
543+ if !p.keyframe {
544+ w.write_bits(u32::from(p.primary_ref_frame), 3);
545+ // A shown key frame refreshes every slot, unsignalled.
546+ w.write_bits(u32::from(p.refresh_frame_flags), 8);
547+ w.write_bit(false); // frame_refs_short_signaling
548+ for idx in p.ref_frame_idx {
549+ w.write_bits(u32::from(idx), 3);
550+ }
551+ }
552+ // frame_size(): frame_size_override_flag = 0 takes the sequence
553+ // header's size, and enable_superres = 0 codes no superres bit.
554+ w.write_bit(false); // render_and_frame_size_different
555+ if !p.keyframe {
556+ w.write_bit(false); // allow_high_precision_mv
557+ w.write_bit(true); // is_filter_switchable
558+ w.write_bit(false); // is_motion_mode_switchable
559+ // use_ref_frame_mvs is inferred 0 from enable_ref_frame_mvs = 0.
560+ }
561+ w.write_bit(false); // disable_frame_end_update_cdf
562+ // tile_info(): one tile, uniformly spaced. The increment loop stops
563+ // with a zero bit for as long as the maximum allows another doubling.
564+ w.write_bit(true); // uniform_tile_spacing_flag
565+ if p.max_tile_cols_log2 > 0 {
566+ w.write_bit(false); // increment_tile_cols_log2
567+ }
568+ if p.max_tile_rows_log2 > 0 {
569+ w.write_bit(false); // increment_tile_rows_log2
570+ }
571+ let qindex = prefix_bits + w.bit_len() as u32;
572+ w.write_bits(u32::from(p.base_q_idx), 8);
573+ w.write_bit(false); // DeltaQYDc.delta_coded
574+ w.write_bit(false); // DeltaQUDc.delta_coded
575+ w.write_bit(false); // DeltaQUAc.delta_coded
576+ w.write_bit(false); // using_qmatrix
577+ let segmentation = prefix_bits + w.bit_len() as u32;
578+ w.write_bit(false); // segmentation_enabled
579+ w.write_bit(false); // delta_q_present (base_q_idx > 0)
580+ let loop_filter = prefix_bits + w.bit_len() as u32;
581+ w.write_bits(u32::from(p.loop_filter_level[0]), 6);
582+ w.write_bits(u32::from(p.loop_filter_level[1]), 6);
583+ if p.loop_filter_level[0] != 0 || p.loop_filter_level[1] != 0 {
584+ w.write_bits(u32::from(p.loop_filter_level[2]), 6);
585+ w.write_bits(u32::from(p.loop_filter_level[3]), 6);
586+ }
587+ w.write_bits(0, 3); // loop_filter_sharpness
588+ w.write_bit(false); // loop_filter_delta_enabled
589+ // cdef_params() and lr_params() are empty: enable_cdef =
590+ // enable_restoration = 0 in the sequence header above.
591+ let cdef = prefix_bits + w.bit_len() as u32;
592+ w.write_bit(p.tx_mode_select); // tx_mode_select
593+ if !p.keyframe {
594+ w.write_bit(false); // reference_select — single reference, which
595+ // also makes skipModeAllowed 0, so no skip_mode_present bit
596+ }
597+ w.write_bit(false); // reduced_tx_set
598+ if !p.keyframe {
599+ for _ in 0..7 {
600+ w.write_bit(false); // is_global[ref]
601+ }
602+ }
603+ trailing(&mut w);
604+ let packed = obu(PACKED_HEADER_PICTURE, 3, w.into_bytes());
605+ let offsets = FrameHeaderOffsets {
606+ qindex,
607+ segmentation,
608+ loop_filter,
609+ cdef,
610+ cdef_size: 0,
611+ obu_size_byte: 1,
612+ total_bits: packed.bits,
613+ };
614+ (packed, offsets)
615+ }
616+
617+ /// `tile_log2(1, n)`: the number of doublings of 1 needed to reach `n`,
618+ /// which is the ceiling of log2 (5.9.15).
619+ pub(in crate::enc) fn tile_log2(target: u32) -> u32 {
620+ let mut k = 0;
621+ while (1u32 << k) < target {
622+ k += 1;
623+ }
624+ k
625+ }
626+}
crates/ec-hw/src/enc/mod.rsmodified+10 -1
@@ -481,7 +481,7 @@ impl Encoder {
481 .end()?481 .end()?
482 .sync()?;482 .sync()?;
483 483
484- let data = {484+ let mut data = {
485 let coded = picture485 let coded = picture
486 .buffers_mut()486 .buffers_mut()
487 .iter_mut()487 .iter_mut()
@@ -491,6 +491,15 @@ impl Encoder {
491 coded_bytes(&mapped)?491 coded_bytes(&mapped)?
492 };492 };
493 493
494+ if self.config.codec == EncCodec::Av1 {
495+ // Every AV1 temporal unit begins with a temporal delimiter (5.6),
496+ // and this driver emits none: its coded buffer starts at the
497+ // sequence header. ffmpeg's demuxer refuses such a stream
498+ // ("Missing Temporal Delimiter"), so the two bytes are prepended
499+ // here rather than left to the caller.
500+ data.splice(0..0, [0x12u8, 0x00]);
501+ }
502+
494 self.reference = Some(recon);503 self.reference = Some(recon);
495 self.coded += 1;504 self.coded += 1;
496 self.gop_position = if keyframe { 1 } else { self.gop_position + 1 };505 self.gop_position = if keyframe { 1 } else { self.gop_position + 1 };
crates/ec-hw/tests/gpu.rsmodified+96 -30
@@ -843,40 +843,106 @@ fn colour_description_reaches_the_vui() {
843 );843 );
844 }844 }
845 845
846-/// AV1 encoding is opt-in, and this test does not turn it on.846+/// AV1 hardware encode, proved by two independent decoders.
847 ///847 ///
848-/// It was probed once, live, at the driver's own minimum encode size848+/// The reconstruction inside the GPU is not observable from here, so what is
849-/// (radeonsi reports 320x128 for AV1 `EncSlice`) on 2026-08-14. The submission849+/// asserted is that the coded stream means the same thing to two decoders that
850-/// took the GPU down:850+/// share no code: ffmpeg's libdav1d and this family's own `ec-av1`. Every
851+/// shown frame is compared sample for sample — a header field that disagrees
852+/// with what the hardware coded shows up as a mismatch in one of them long
853+/// before it shows up as a quality number.
851 ///854 ///
852-/// ```text855+/// The path was refused in-tree until 2026-09-07: a probe on 2026-08-14 took
853-/// amdgpu: The CS has cancelled because the context is lost.856+/// the GPU down ("the CS has cancelled because the context is lost"). That
854-/// This context is guilty of a hard recovery.857+/// refusal is retired by measurement, not by opinion — ffmpeg's own
855-/// ```858+/// `av1_vaapi` encodes on this driver (mesa 26.1.8, gfx1200), and the
856-///859+/// parameters below are the recipe it uses.
857-/// The process was aborted by the driver, not by this crate — there is no error
858-/// to return from a context that no longer exists. So the probe is *recorded*
859-/// rather than repeated: what this test asserts is the guard that keeps the
860-/// path off unless a caller asks for it by name, which is the only defence a
861-/// library has against a driver bug of that class.
862 #[test]860 #[test]
863-fn av1_encode_is_opt_in() {861+fn av1_encode_agrees_between_two_decoders() {
864 let Some(display) = display() else { return };862 let Some(display) = display() else { return };
865- let refused = Encoder::new(&display, EncoderConfig::new(EncCodec::Av1, 320, 128));863+ let dir = std::env::temp_dir().join("ec-hw-av1-encode");
866- assert!(864+ let _ = std::fs::create_dir_all(&dir);
867- matches!(refused, Err(ec_hw::Error::Unsupported { .. })),865+ for (width, height, frames) in [(640u32, 384u32, 10u32), (1920, 1080, 10)] {
868- "AV1 encoding must be refused without the explicit opt-in"866+ let data = match encode_stream(&display, EncCodec::Av1, width, height, frames, true) {
869- );867+ Ok(data) => data,
870- // With the opt-in the encoder builds — the parameters, the surface pool and868+ Err(e) => {
871- // the context are all real; only `encode()` is left untested here.869+ eprintln!("skipped: AV1 encode unavailable ({e})");
872- let mut config = EncoderConfig::new(EncCodec::Av1, 320, 128);870+ return;
873- config.allow_av1 = true;871+ }
874- match Encoder::new(&display, config) {872+ };
875- Ok(encoder) => println!(873+ let path = dir.join(format!("hw-{width}x{height}.obu"));
876- "AV1 encode: opt-in encoder built at {:?}, submission deliberately not run",874+ std::fs::write(&path, &data).expect("write the coded stream");
877- encoder.coded_size()875+
878- ),876+ // Decoder one: this family's software AV1 decoder, on the raw OBUs.
879- Err(e) => println!("AV1 encode: refused by the driver, typed error: {e}"),877+ let ours = ec_av1::stream::decode_stream(&data)
878+ .unwrap_or_else(|e| panic!("ec-av1 decodes the {width}x{height} hardware stream: {e}"));
879+ assert_eq!(
880+ ours.len(),
881+ frames as usize,
882+ "{width}x{height}: ec-av1 decoded {} of {frames} shown frames",
883+ ours.len()
884+ );
885+
886+ // Decoder two: ffmpeg (libdav1d) on the same bytes.
887+ let mut reference =
888+ Reference::open(&path, width, height, false).expect("ffmpeg opens the stream");
889+ let mut worst = f64::INFINITY;
890+ for (i, picture) in ours.iter().enumerate() {
891+ let theirs = reference
892+ .next(width, height)
893+ .unwrap_or_else(|| panic!("{width}x{height}: ffmpeg has no frame {i}"));
894+ let mine = Planes {
895+ y: picture.y.clone(),
896+ u: picture.u.clone(),
897+ v: picture.v.clone(),
898+ peak: 255.0,
899+ };
900+ let db = psnr(&mine, &theirs);
901+ assert!(
902+ db.is_infinite(),
903+ "{width}x{height} frame {i}: the two decoders disagree ({db:.2} dB)"
904+ );
905+ // Agreement alone would also be satisfied by ten grey frames: the
906+ // coded picture has to be the picture that was submitted.
907+ let source = Planes::from_8bit(&source_frame(width, height, i as u32));
908+ let fidelity = psnr(&mine, &source);
909+ assert!(
910+ fidelity > 30.0,
911+ "{width}x{height} frame {i}: coded {fidelity:.2} dB from the source"
912+ );
913+ worst = worst.min(fidelity);
914+ }
915+ println!(
916+ "AV1 encode {width}x{height}: {frames} frames, {} bytes, ec-av1 and libdav1d agree \
917+ sample for sample, worst frame {worst:.2} dB from the source",
918+ data.len()
919+ );
920+ }
921+}
922+
923+/// Hardware AV1 encode speed at the two sizes his library is in, in frames per
924+/// second. Real time is 24 fps; the number is printed rather than asserted,
925+/// since a busy GPU is not a failing encoder.
926+#[test]
927+fn av1_encode_speed() {
928+ let Some(display) = display() else { return };
929+ for (width, height) in [(1920u32, 1080u32), (3840, 1608)] {
930+ let frames = 30u32;
931+ let start = Instant::now();
932+ match encode_stream(&display, EncCodec::Av1, width, height, frames, true) {
933+ Ok(data) => {
934+ let secs = start.elapsed().as_secs_f64();
935+ println!(
936+ "AV1 encode {width}x{height}: {:.1} fps ({frames} frames in {secs:.2} s), {} kbit/frame",
937+ f64::from(frames) / secs,
938+ data.len() * 8 / frames as usize / 1000
939+ );
940+ }
941+ Err(e) => {
942+ eprintln!("skipped: AV1 encode unavailable ({e})");
943+ return;
944+ }
945+ }
880 }946 }
881 }947 }
882 948