forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

headers.rs367 lines, 14.6 KiBHistoryRawDownload
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 the oracle 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
13use ec_core::BitWriter;
14
15use super::Colour;
16use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
17
18/// A header ready to submit: escaped bytes plus its exact length in bits.
19///
20/// The bit length matters for slice headers, which do not end on a byte
21/// boundary — the driver continues the bitstream from exactly that bit.
22pub(crate) struct Packed {
23 pub(crate) kind: u32,
24 pub(crate) bytes: Vec<u8>,
25 pub(crate) bits: u32,
26}
27
28/// Wrap a complete NAL: start code, header byte(s), escaped payload.
29fn nal(kind: u32, header: &[u8], rbsp: &[u8], padding_bits: u32) -> Packed {
30 let mut bytes = vec![0, 0, 0, 1];
31 bytes.extend_from_slice(header);
32 let mut escaped = Vec::with_capacity(rbsp.len() + 8);
33 ec_h264_syntax::escape_rbsp(rbsp, &mut escaped);
34 bytes.extend_from_slice(&escaped);
35 let bits = bytes.len() as u32 * 8 - padding_bits;
36 Packed { kind, bytes, bits }
37}
38
39// ---------------------------------------------------------------------------
40// H.264
41// ---------------------------------------------------------------------------
42
43/// What the H.264 headers need, mirroring the sequence parameter buffer.
44pub(super) struct H264Params {
45 pub(super) level_idc: u8,
46 pub(super) mb_width: u32,
47 pub(super) mb_height: u32,
48 pub(super) crop_right: u32,
49 pub(super) crop_bottom: u32,
50 pub(super) num_units_in_tick: u32,
51 pub(super) time_scale: u32,
52 pub(super) pic_init_qp: u8,
53 pub(super) colour: Option<Colour>,
54}
55
56/// `log2_max_frame_num`, matching `seq_fields.log2_max_frame_num_minus4 = 0`.
57pub(super) const H264_LOG2_MAX_FRAME_NUM: u32 = 4;
58
59/// The sequence parameter set (7.3.2.1), High profile.
60pub(super) fn h264_sps(p: &H264Params) -> Packed {
61 let mut w = BitWriter::with_capacity(64);
62 w.write_bits(100, 8); // profile_idc: High
63 w.write_bits(0, 8); // constraint_set flags + reserved_zero_2bits
64 w.write_bits(u32::from(p.level_idc), 8);
65 w.write_ue(0); // seq_parameter_set_id
66 // High profile tail.
67 w.write_ue(1); // chroma_format_idc: 4:2:0
68 w.write_ue(0); // bit_depth_luma_minus8
69 w.write_ue(0); // bit_depth_chroma_minus8
70 w.write_bit(false); // qpprime_y_zero_transform_bypass_flag
71 w.write_bit(false); // seq_scaling_matrix_present_flag
72 w.write_ue(H264_LOG2_MAX_FRAME_NUM - 4);
73 w.write_ue(2); // pic_order_cnt_type 2: output order is decode order
74 w.write_ue(1); // max_num_ref_frames
75 w.write_bit(false); // gaps_in_frame_num_value_allowed_flag
76 w.write_ue(p.mb_width - 1);
77 w.write_ue(p.mb_height - 1);
78 w.write_bit(true); // frame_mbs_only_flag
79 w.write_bit(true); // direct_8x8_inference_flag
80 let cropping = p.crop_right != 0 || p.crop_bottom != 0;
81 w.write_bit(cropping);
82 if cropping {
83 // CropUnitX = 2 and CropUnitY = 2 for progressive 4:2:0 (7.4.2.1.1).
84 w.write_ue(0);
85 w.write_ue(p.crop_right);
86 w.write_ue(0);
87 w.write_ue(p.crop_bottom);
88 }
89 w.write_bit(true); // vui_parameters_present_flag
90 w.write_bit(false); // aspect_ratio_info_present_flag
91 w.write_bit(false); // overscan_info_present_flag
92 w.write_bit(p.colour.is_some()); // video_signal_type_present_flag
93 if let Some(colour) = p.colour {
94 w.write_bits(5, 3); // video_format: unspecified
95 w.write_bit(colour.full_range);
96 w.write_bit(true); // colour_description_present_flag
97 w.write_bits(u32::from(colour.primaries), 8);
98 w.write_bits(u32::from(colour.transfer), 8);
99 w.write_bits(u32::from(colour.matrix), 8);
100 }
101 w.write_bit(false); // chroma_loc_info_present_flag
102 w.write_bit(true); // timing_info_present_flag
103 w.write_bits(p.num_units_in_tick, 32);
104 w.write_bits(p.time_scale, 32);
105 w.write_bit(true); // fixed_frame_rate_flag
106 w.write_bit(false); // nal_hrd_parameters_present_flag
107 w.write_bit(false); // vcl_hrd_parameters_present_flag
108 w.write_bit(false); // pic_struct_present_flag
109 w.write_bit(false); // bitstream_restriction_flag
110 trailing(&mut w);
111 nal(PACKED_HEADER_SEQUENCE, &[0x67], &w.into_bytes(), 0)
112}
113
114/// The picture parameter set (7.3.2.2).
115pub(super) fn h264_pps(p: &H264Params) -> Packed {
116 let mut w = BitWriter::with_capacity(16);
117 w.write_ue(0); // pic_parameter_set_id
118 w.write_ue(0); // seq_parameter_set_id
119 w.write_bit(true); // entropy_coding_mode_flag: CABAC
120 w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag
121 w.write_ue(0); // num_slice_groups_minus1
122 w.write_ue(0); // num_ref_idx_l0_default_active_minus1
123 w.write_ue(0); // num_ref_idx_l1_default_active_minus1
124 w.write_bit(false); // weighted_pred_flag
125 w.write_bits(0, 2); // weighted_bipred_idc
126 w.write_se(i32::from(p.pic_init_qp) - 26);
127 w.write_se(0); // pic_init_qs_minus26
128 w.write_se(0); // chroma_qp_index_offset
129 w.write_bit(true); // deblocking_filter_control_present_flag
130 w.write_bit(false); // constrained_intra_pred_flag
131 w.write_bit(false); // redundant_pic_cnt_present_flag
132 trailing(&mut w);
133 nal(PACKED_HEADER_PICTURE, &[0x68], &w.into_bytes(), 0)
134}
135
136/// The slice header (7.3.3), up to but *not* including the slice data.
137///
138/// No trailing bits and no alignment: the driver continues the bitstream at the
139/// next bit (`cabac_alignment_one_bit` is its business), which is why the
140/// returned bit count has to be exact.
141pub(super) fn h264_slice_header(idr: bool, frame_num: u32, idr_pic_id: u32) -> Packed {
142 let mut w = BitWriter::with_capacity(16);
143 w.write_ue(0); // first_mb_in_slice
144 // 5..=9 assert that every slice of the picture has this type, which holds:
145 // one slice per picture.
146 w.write_ue(if idr { 7 } else { 5 });
147 w.write_ue(0); // pic_parameter_set_id
148 w.write_bits(frame_num, H264_LOG2_MAX_FRAME_NUM);
149 if idr {
150 w.write_ue(idr_pic_id);
151 }
152 // pic_order_cnt_type 2: no picture order count in the header.
153 if !idr {
154 w.write_bit(false); // num_ref_idx_active_override_flag
155 w.write_bit(false); // ref_pic_list_modification_flag_l0
156 }
157 // Every picture here is a reference (nal_ref_idc != 0).
158 if idr {
159 w.write_bit(false); // no_output_of_prior_pics_flag
160 w.write_bit(false); // long_term_reference_flag
161 } else {
162 w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window
163 }
164 if !idr {
165 w.write_ue(0); // cabac_init_idc
166 }
167 w.write_se(0); // slice_qp_delta, against pic_init_qp
168 w.write_ue(0); // disable_deblocking_filter_idc
169 w.write_se(0); // slice_alpha_c0_offset_div2
170 w.write_se(0); // slice_beta_offset_div2
171 let bits = w.bit_len() as u32;
172 let padding = (8 - bits % 8) % 8;
173 w.align_to_byte();
174 let header = if idr { 0x65 } else { 0x61 };
175 nal(PACKED_HEADER_SLICE, &[header], &w.into_bytes(), padding)
176}
177
178/// `rbsp_trailing_bits` (7.3.2.11).
179fn trailing(w: &mut BitWriter) {
180 w.write_bit(true);
181 w.align_to_byte();
182}
183
184// ---------------------------------------------------------------------------
185// HEVC
186// ---------------------------------------------------------------------------
187
188/// Build the HEVC parameter sets, and the slice header for one picture.
189///
190/// The syntax crate writes all four structures, so the encoder and the software
191/// HEVC path in this family share one definition of what a parameter set is.
192pub(super) mod hevc {
193 use ec_h265_syntax::{
194 ConformanceWindow, NalHeader, NalUnitType, Pps, ProfileTierLevel, ShortTermRefPicSet,
195 SliceHeader, SliceType, Sps, Vps,
196 };
197
198 use super::{Colour, Packed, nal};
199 use crate::params::enc::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
200
201 /// Geometry and timing for the parameter sets.
202 pub(in crate::enc) struct Params {
203 pub(in crate::enc) width: u32,
204 pub(in crate::enc) height: u32,
205 pub(in crate::enc) coded_width: u32,
206 pub(in crate::enc) coded_height: u32,
207 pub(in crate::enc) level_idc: u8,
208 pub(in crate::enc) num_units_in_tick: u32,
209 pub(in crate::enc) time_scale: u32,
210 pub(in crate::enc) init_qp: u8,
211 pub(in crate::enc) colour: Option<Colour>,
212 }
213
214 /// The VPS, SPS and PPS, in that order.
215 pub(in crate::enc) fn parameter_sets(p: &Params) -> (Vps, Sps, Pps) {
216 let ptl = ProfileTierLevel::main(p.level_idc);
217 let vps = Vps {
218 id: 0,
219 ptl,
220 max_dec_pic_buffering_minus1: 1,
221 max_num_reorder_pics: 0,
222 };
223 let sps = Sps {
224 vps_id: 0,
225 id: 0,
226 chroma_format_idc: 1,
227 separate_colour_plane: false,
228 pic_width_in_luma_samples: p.coded_width,
229 pic_height_in_luma_samples: p.coded_height,
230 // The conformance window is how HEVC crops: the coded size is a
231 // multiple of the minimum coding block, the displayed size is not.
232 conf_win: ConformanceWindow {
233 left: 0,
234 right: (p.coded_width - p.width) / 2,
235 top: 0,
236 bottom: (p.coded_height - p.height) / 2,
237 },
238 bit_depth_luma_minus8: 0,
239 bit_depth_chroma_minus8: 0,
240 log2_max_poc_lsb_minus4: 8,
241 max_dec_pic_buffering_minus1: 1,
242 max_num_reorder_pics: 0,
243 log2_min_cb_size_minus3: 0,
244 log2_diff_max_min_cb_size: 3,
245 log2_min_tb_size_minus2: 0,
246 log2_diff_max_min_tb_size: 3,
247 max_transform_hierarchy_depth_inter: 1,
248 max_transform_hierarchy_depth_intra: 1,
249 scaling_list_enabled: false,
250 amp_enabled: true,
251 sao_enabled: true,
252 pcm_enabled: false,
253 pcm: None,
254 // No sets in the sequence: this driver writes the reference picture
255 // set out in each slice header (an inline `st_ref_pic_set` naming
256 // the previous picture), so declaring one here would leave the two
257 // descriptions of the same thing free to disagree.
258 num_short_term_ref_pic_sets: 0,
259 short_term_ref_pic_sets: Vec::new(),
260 long_term_ref_pics_present: false,
261 num_long_term_ref_pics_sps: 0,
262 long_term_ref_pics_sps: Vec::new(),
263 temporal_mvp_enabled: false,
264 strong_intra_smoothing: true,
265 ptl,
266 vui: Some(ec_h265_syntax::vui::VuiParameters {
267 timing: Some((p.num_units_in_tick, p.time_scale)),
268 video_signal_type: p.colour.map(|colour| {
269 ec_h265_syntax::vui::VideoSignalType {
270 video_format: 5, // unspecified
271 video_full_range_flag: colour.full_range,
272 colour_description: Some(ec_h265_syntax::vui::ColourDescription {
273 colour_primaries: colour.primaries,
274 transfer_characteristics: colour.transfer,
275 matrix_coeffs: colour.matrix,
276 }),
277 }
278 }),
279 ..ec_h265_syntax::vui::VuiParameters::default()
280 }),
281 };
282 let pps = Pps {
283 id: 0,
284 sps_id: 0,
285 init_qp_minus26: i32::from(p.init_qp) - 26,
286 num_ref_idx_l0_default_active_minus1: 0,
287 num_ref_idx_l1_default_active_minus1: 0,
288 transform_skip_enabled: true,
289 loop_filter_across_tiles_enabled: false,
290 loop_filter_across_slices_enabled: false,
291 ..Pps::default()
292 };
293 (vps, sps, pps)
294 }
295
296 /// `st_ref_pic_set()`: one negative reference at POC - 1, used by this
297 /// picture — the single reference this encoder keeps.
298 fn previous_picture_set() -> ShortTermRefPicSet {
299 let mut set = ShortTermRefPicSet {
300 num_negative: 1,
301 num_positive: 0,
302 num_used_by_curr: 1,
303 ..ShortTermRefPicSet::default()
304 };
305 set.delta_poc_s0[0] = -1;
306 set.used_s0[0] = true;
307 set
308 }
309
310 pub(in crate::enc) fn packed_vps(vps: &Vps) -> Packed {
311 nal(
312 PACKED_HEADER_SEQUENCE,
313 &NalHeader::new(NalUnitType::Vps).to_bytes(),
314 &vps.to_rbsp(),
315 0,
316 )
317 }
318
319 pub(in crate::enc) fn packed_sps(sps: &Sps) -> Packed {
320 nal(
321 PACKED_HEADER_SEQUENCE,
322 &NalHeader::new(NalUnitType::Sps).to_bytes(),
323 &sps.to_rbsp(),
324 0,
325 )
326 }
327
328 pub(in crate::enc) fn packed_pps(pps: &Pps) -> Packed {
329 nal(
330 PACKED_HEADER_PICTURE,
331 &NalHeader::new(NalUnitType::Pps).to_bytes(),
332 &pps.to_rbsp(),
333 0,
334 )
335 }
336
337 /// The slice segment header, ending mid-byte like H.264's.
338 pub(in crate::enc) fn packed_slice(sps: &Sps, pps: &Pps, keyframe: bool, poc: i32) -> Packed {
339 let nal_type = if keyframe {
340 NalUnitType::IdrWRadl
341 } else {
342 NalUnitType::TrailR
343 };
344 let mut header = SliceHeader::intra(pps, 0);
345 header.slice_type = if keyframe { SliceType::I } else { SliceType::P };
346 header.poc_lsb = (poc as u32) & ((1 << (sps.log2_max_poc_lsb_minus4 + 4)) - 1);
347 header.sao_luma = sps.sao_enabled;
348 header.sao_chroma = sps.sao_enabled;
349 header.five_minus_max_num_merge_cand = 0;
350 // The set goes in the header rather than the SPS, which is what this
351 // driver writes when it composes the header itself.
352 header.short_term_ref_pic_set_sps_flag = false;
353 header.short_term_ref_pic_set = previous_picture_set();
354 header.loop_filter_across_slices_enabled = false;
355 let mut w = ec_core::BitWriter::with_capacity(16);
356 // With `byte_alignment()` (7.3.6.1): this driver copies the header it is
357 // given verbatim and starts the slice data at the next byte, so the
358 // alignment bit has to be in what it is given.
359 header.write(&mut w, sps, pps, nal_type);
360 nal(
361 PACKED_HEADER_SLICE,
362 &NalHeader::new(nal_type).to_bytes(),
363 &w.into_bytes(),
364 0,
365 )
366 }
367}