forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

headers.rs345 lines, 13.5 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 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
13use ec_core::BitWriter;
14
15use 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.
21pub(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.
28fn 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.
43pub(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`.
55pub(super) const H264_LOG2_MAX_FRAME_NUM: u32 = 4;
56
57/// The sequence parameter set (7.3.2.1), High profile.
58pub(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).
105pub(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.
131pub(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).
169fn 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.
182pub(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}