forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

headers.rs737 lines, 30.7 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#![allow(dead_code)] // parked with the encoder: the writers return when it is ported
13
14/// `VAEncPackedHeaderSequence`: packed sequence-level header bits.
15pub const PACKED_HEADER_SEQUENCE: u32 = 1;
16/// `VAEncPackedHeaderPicture`: packed picture-level header bits.
17pub const PACKED_HEADER_PICTURE: u32 = 2;
18/// `VAEncPackedHeaderSlice`: packed slice-level header bits.
19pub const PACKED_HEADER_SLICE: u32 = 3;
20
21use ec_core::BitWriter;
22
23use super::Colour;
24
25/// A header ready to submit: escaped bytes plus its exact length in bits.
26///
27/// The bit length matters for slice headers, which do not end on a byte
28/// boundary — the driver continues the bitstream from exactly that bit.
29pub(crate) struct Packed {
30 pub(crate) kind: u32,
31 pub(crate) bytes: Vec<u8>,
32 pub(crate) bits: u32,
33}
34
35/// Wrap a complete NAL: start code, header byte(s), escaped payload.
36fn nal(kind: u32, header: &[u8], rbsp: &[u8], padding_bits: u32) -> Packed {
37 let mut bytes = vec![0, 0, 0, 1];
38 bytes.extend_from_slice(header);
39 let mut escaped = Vec::with_capacity(rbsp.len() + 8);
40 ec_h264_syntax::escape_rbsp(rbsp, &mut escaped);
41 bytes.extend_from_slice(&escaped);
42 let bits = bytes.len() as u32 * 8 - padding_bits;
43 Packed { kind, bytes, bits }
44}
45
46// ---------------------------------------------------------------------------
47// H.264
48// ---------------------------------------------------------------------------
49
50/// What the H.264 headers need, mirroring the sequence parameter buffer.
51pub(super) struct H264Params {
52 pub(super) level_idc: u8,
53 pub(super) mb_width: u32,
54 pub(super) mb_height: u32,
55 pub(super) crop_right: u32,
56 pub(super) crop_bottom: u32,
57 pub(super) num_units_in_tick: u32,
58 pub(super) time_scale: u32,
59 pub(super) pic_init_qp: u8,
60 pub(super) colour: Option<Colour>,
61 pub(super) profile: super::H264Profile,
62}
63
64/// `log2_max_frame_num`, matching `seq_fields.log2_max_frame_num_minus4 = 0`.
65pub(super) const H264_LOG2_MAX_FRAME_NUM: u32 = 4;
66
67/// The sequence parameter set (7.3.2.1) for the profile in `p`.
68///
69/// Only High (`profile_idc` 100) carries the chroma/bit-depth/scaling tail; Main
70/// (77) and Constrained Baseline (66) end the profile-specific part after
71/// `seq_parameter_set_id`, and Constrained Baseline sets `constraint_set1_flag`.
72pub(super) fn h264_sps(p: &H264Params) -> Packed {
73 let mut w = BitWriter::with_capacity(64);
74 let (profile_idc, constraints) = match p.profile {
75 super::H264Profile::ConstrainedBaseline => (66, 0x40), // constraint_set1_flag
76 super::H264Profile::Main => (77, 0),
77 super::H264Profile::High => (100, 0),
78 };
79 w.write_bits(profile_idc, 8);
80 w.write_bits(constraints, 8); // constraint_set flags + reserved_zero_2bits
81 w.write_bits(u32::from(p.level_idc), 8);
82 w.write_ue(0); // seq_parameter_set_id
83 if p.profile == super::H264Profile::High {
84 // High profile tail.
85 w.write_ue(1); // chroma_format_idc: 4:2:0
86 w.write_ue(0); // bit_depth_luma_minus8
87 w.write_ue(0); // bit_depth_chroma_minus8
88 w.write_bit(false); // qpprime_y_zero_transform_bypass_flag
89 w.write_bit(false); // seq_scaling_matrix_present_flag
90 }
91 w.write_ue(H264_LOG2_MAX_FRAME_NUM - 4);
92 w.write_ue(2); // pic_order_cnt_type 2: output order is decode order
93 w.write_ue(1); // max_num_ref_frames
94 w.write_bit(false); // gaps_in_frame_num_value_allowed_flag
95 w.write_ue(p.mb_width - 1);
96 w.write_ue(p.mb_height - 1);
97 w.write_bit(true); // frame_mbs_only_flag
98 w.write_bit(true); // direct_8x8_inference_flag
99 let cropping = p.crop_right != 0 || p.crop_bottom != 0;
100 w.write_bit(cropping);
101 if cropping {
102 // CropUnitX = 2 and CropUnitY = 2 for progressive 4:2:0 (7.4.2.1.1).
103 w.write_ue(0);
104 w.write_ue(p.crop_right);
105 w.write_ue(0);
106 w.write_ue(p.crop_bottom);
107 }
108 w.write_bit(true); // vui_parameters_present_flag
109 w.write_bit(false); // aspect_ratio_info_present_flag
110 w.write_bit(false); // overscan_info_present_flag
111 w.write_bit(p.colour.is_some()); // video_signal_type_present_flag
112 if let Some(colour) = p.colour {
113 w.write_bits(5, 3); // video_format: unspecified
114 w.write_bit(colour.full_range);
115 w.write_bit(true); // colour_description_present_flag
116 w.write_bits(u32::from(colour.primaries), 8);
117 w.write_bits(u32::from(colour.transfer), 8);
118 w.write_bits(u32::from(colour.matrix), 8);
119 }
120 w.write_bit(false); // chroma_loc_info_present_flag
121 w.write_bit(true); // timing_info_present_flag
122 w.write_bits(p.num_units_in_tick, 32);
123 w.write_bits(p.time_scale, 32);
124 w.write_bit(true); // fixed_frame_rate_flag
125 w.write_bit(false); // nal_hrd_parameters_present_flag
126 w.write_bit(false); // vcl_hrd_parameters_present_flag
127 w.write_bit(false); // pic_struct_present_flag
128 w.write_bit(true); // bitstream_restriction_flag
129 w.write_bit(true); // motion_vectors_over_pic_boundaries_flag
130 w.write_ue(2); // max_bytes_per_pic_denom
131 w.write_ue(1); // max_bits_per_mb_denom
132 w.write_ue(15); // log2_max_mv_length_horizontal
133 w.write_ue(15); // log2_max_mv_length_vertical
134 w.write_ue(0); // max_num_reorder_frames
135 w.write_ue(1); // max_dec_frame_buffering = max_num_ref_frames
136 trailing(&mut w);
137 nal(PACKED_HEADER_SEQUENCE, &[0x67], &w.into_bytes(), 0)
138}
139
140/// The picture parameter set (7.3.2.2).
141pub(super) fn h264_pps(p: &H264Params) -> Packed {
142 let mut w = BitWriter::with_capacity(16);
143 w.write_ue(0); // pic_parameter_set_id
144 w.write_ue(0); // seq_parameter_set_id
145 w.write_bit(p.profile.cabac()); // entropy_coding_mode_flag
146 w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag
147 w.write_ue(0); // num_slice_groups_minus1
148 w.write_ue(0); // num_ref_idx_l0_default_active_minus1
149 w.write_ue(0); // num_ref_idx_l1_default_active_minus1
150 w.write_bit(false); // weighted_pred_flag
151 w.write_bits(0, 2); // weighted_bipred_idc
152 w.write_se(i32::from(p.pic_init_qp) - 26);
153 w.write_se(0); // pic_init_qs_minus26
154 w.write_se(0); // chroma_qp_index_offset
155 w.write_bit(true); // deblocking_filter_control_present_flag
156 w.write_bit(false); // constrained_intra_pred_flag
157 w.write_bit(false); // redundant_pic_cnt_present_flag
158 if p.profile == super::H264Profile::High {
159 w.write_bit(true); // transform_8x8_mode_flag
160 w.write_bit(false); // pic_scaling_matrix_present_flag
161 w.write_se(0); // second_chroma_qp_index_offset
162 }
163 trailing(&mut w);
164 nal(PACKED_HEADER_PICTURE, &[0x68], &w.into_bytes(), 0)
165}
166
167/// The slice header (7.3.3), up to but *not* including the slice data.
168///
169/// No trailing bits and no alignment: the driver continues the bitstream at the
170/// next bit (`cabac_alignment_one_bit` is its business), which is why the
171/// returned bit count has to be exact.
172pub(super) fn h264_slice_header(idr: bool, frame_num: u32, idr_pic_id: u32) -> Packed {
173 let mut w = BitWriter::with_capacity(16);
174 w.write_ue(0); // first_mb_in_slice
175 // 5..=9 assert that every slice of the picture has this type, which holds:
176 // one slice per picture.
177 w.write_ue(if idr { 7 } else { 5 });
178 w.write_ue(0); // pic_parameter_set_id
179 w.write_bits(frame_num, H264_LOG2_MAX_FRAME_NUM);
180 if idr {
181 w.write_ue(idr_pic_id);
182 }
183 // pic_order_cnt_type 2: no picture order count in the header.
184 if !idr {
185 w.write_bit(false); // num_ref_idx_active_override_flag
186 w.write_bit(false); // ref_pic_list_modification_flag_l0
187 }
188 // Every picture here is a reference (nal_ref_idc != 0).
189 if idr {
190 w.write_bit(false); // no_output_of_prior_pics_flag
191 w.write_bit(false); // long_term_reference_flag
192 } else {
193 w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window
194 }
195 if !idr {
196 w.write_ue(0); // cabac_init_idc
197 }
198 w.write_se(0); // slice_qp_delta, against pic_init_qp
199 w.write_ue(0); // disable_deblocking_filter_idc
200 w.write_se(0); // slice_alpha_c0_offset_div2
201 w.write_se(0); // slice_beta_offset_div2
202 let bits = w.bit_len() as u32;
203 let padding = (8 - bits % 8) % 8;
204 w.align_to_byte();
205 let header = if idr { 0x65 } else { 0x61 };
206 nal(PACKED_HEADER_SLICE, &[header], &w.into_bytes(), padding)
207}
208
209/// `rbsp_trailing_bits` (7.3.2.11).
210fn trailing(w: &mut BitWriter) {
211 w.write_bit(true);
212 w.align_to_byte();
213}
214
215// ---------------------------------------------------------------------------
216// HEVC
217// ---------------------------------------------------------------------------
218
219/// Build the HEVC parameter sets, and the slice header for one picture.
220///
221/// The syntax crate writes all four structures, so the encoder and the software
222/// HEVC path in this family share one definition of what a parameter set is.
223pub(super) mod hevc {
224 #[allow(unused_imports)]
225 use super::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
226 use ec_h265_syntax::{
227 ConformanceWindow, NalHeader, NalUnitType, Pps, ProfileTierLevel, ShortTermRefPicSet,
228 SliceHeader, SliceType, Sps, Vps,
229 };
230
231 use super::{Colour, Packed, nal};
232
233 /// Geometry and timing for the parameter sets.
234 pub(in crate::enc) struct Params {
235 pub(in crate::enc) width: u32,
236 pub(in crate::enc) height: u32,
237 pub(in crate::enc) coded_width: u32,
238 pub(in crate::enc) coded_height: u32,
239 pub(in crate::enc) level_idc: u8,
240 pub(in crate::enc) num_units_in_tick: u32,
241 pub(in crate::enc) time_scale: u32,
242 pub(in crate::enc) init_qp: u8,
243 pub(in crate::enc) colour: Option<Colour>,
244 pub(in crate::enc) bit_depth: u8,
245 }
246
247 /// The VPS, SPS and PPS, in that order.
248 pub(in crate::enc) fn parameter_sets(p: &Params) -> (Vps, Sps, Pps) {
249 let ptl = if p.bit_depth == 10 {
250 ProfileTierLevel::main10(p.level_idc)
251 } else {
252 ProfileTierLevel::main(p.level_idc)
253 };
254 let vps = Vps {
255 id: 0,
256 ptl,
257 max_dec_pic_buffering_minus1: 1,
258 max_num_reorder_pics: 0,
259 timing: Some((p.num_units_in_tick, p.time_scale)),
260 };
261 let sps = Sps {
262 vps_id: 0,
263 id: 0,
264 chroma_format_idc: 1,
265 separate_colour_plane: false,
266 pic_width_in_luma_samples: p.coded_width,
267 pic_height_in_luma_samples: p.coded_height,
268 // The conformance window is how HEVC crops: the coded size is a
269 // multiple of the minimum coding block, the displayed size is not.
270 conf_win: ConformanceWindow {
271 left: 0,
272 right: (p.coded_width - p.width) / 2,
273 top: 0,
274 bottom: (p.coded_height - p.height) / 2,
275 },
276 bit_depth_luma_minus8: u32::from(p.bit_depth - 8),
277 bit_depth_chroma_minus8: u32::from(p.bit_depth - 8),
278 log2_max_poc_lsb_minus4: 8,
279 max_dec_pic_buffering_minus1: 1,
280 max_num_reorder_pics: 0,
281 max_latency_increase_plus1: 0,
282 extension_flags: 0,
283 range: Default::default(),
284 log2_min_cb_size_minus3: 0,
285 log2_diff_max_min_cb_size: 3,
286 log2_min_tb_size_minus2: 0,
287 log2_diff_max_min_tb_size: 3,
288 max_transform_hierarchy_depth_inter: 1,
289 max_transform_hierarchy_depth_intra: 1,
290 scaling_list_enabled: false,
291 scaling_list: None,
292 amp_enabled: true,
293 sao_enabled: true,
294 pcm_enabled: false,
295 pcm: None,
296 // No sets in the sequence: this driver writes the reference picture
297 // set out in each slice header (an inline `st_ref_pic_set` naming
298 // the previous picture), so declaring one here would leave the two
299 // descriptions of the same thing free to disagree.
300 num_short_term_ref_pic_sets: 0,
301 short_term_ref_pic_sets: Vec::new(),
302 long_term_ref_pics_present: false,
303 num_long_term_ref_pics_sps: 0,
304 long_term_ref_pics_sps: Vec::new(),
305 temporal_mvp_enabled: false,
306 strong_intra_smoothing: true,
307 ptl,
308 vui: Some(ec_h265_syntax::vui::VuiParameters {
309 timing: Some((p.num_units_in_tick, p.time_scale)),
310 video_signal_type: p.colour.map(|colour| {
311 ec_h265_syntax::vui::VideoSignalType {
312 video_format: 5, // unspecified
313 video_full_range_flag: colour.full_range,
314 colour_description: Some(ec_h265_syntax::vui::ColourDescription {
315 colour_primaries: colour.primaries,
316 transfer_characteristics: colour.transfer,
317 matrix_coeffs: colour.matrix,
318 }),
319 }
320 }),
321 ..ec_h265_syntax::vui::VuiParameters::default()
322 }),
323 };
324 let pps = Pps {
325 id: 0,
326 sps_id: 0,
327 init_qp_minus26: i32::from(p.init_qp) - 26,
328 num_ref_idx_l0_default_active_minus1: 0,
329 num_ref_idx_l1_default_active_minus1: 0,
330 transform_skip_enabled: true,
331 loop_filter_across_tiles_enabled: false,
332 loop_filter_across_slices_enabled: false,
333 ..Pps::default()
334 };
335 (vps, sps, pps)
336 }
337
338 /// `st_ref_pic_set()`: one negative reference at POC - 1, used by this
339 /// picture — the single reference this encoder keeps.
340 fn previous_picture_set() -> ShortTermRefPicSet {
341 let mut set = ShortTermRefPicSet {
342 num_negative: 1,
343 num_positive: 0,
344 num_used_by_curr: 1,
345 ..ShortTermRefPicSet::default()
346 };
347 set.delta_poc_s0[0] = -1;
348 set.used_s0[0] = true;
349 set
350 }
351
352 pub(in crate::enc) fn packed_vps(vps: &Vps) -> Packed {
353 nal(
354 PACKED_HEADER_SEQUENCE,
355 &NalHeader::new(NalUnitType::Vps).to_bytes(),
356 &vps.to_rbsp(),
357 0,
358 )
359 }
360
361 pub(in crate::enc) fn packed_sps(sps: &Sps) -> Packed {
362 nal(
363 PACKED_HEADER_SEQUENCE,
364 &NalHeader::new(NalUnitType::Sps).to_bytes(),
365 &sps.to_rbsp(),
366 0,
367 )
368 }
369
370 pub(in crate::enc) fn packed_pps(pps: &Pps) -> Packed {
371 nal(
372 PACKED_HEADER_PICTURE,
373 &NalHeader::new(NalUnitType::Pps).to_bytes(),
374 &pps.to_rbsp(),
375 0,
376 )
377 }
378
379 /// The slice segment header, ending mid-byte like H.264's.
380 pub(in crate::enc) fn packed_slice(sps: &Sps, pps: &Pps, keyframe: bool, poc: i32) -> Packed {
381 let nal_type = if keyframe {
382 NalUnitType::IdrWRadl
383 } else {
384 NalUnitType::TrailR
385 };
386 let mut header = SliceHeader::intra(pps, 0);
387 header.slice_type = if keyframe { SliceType::I } else { SliceType::P };
388 header.poc_lsb = (poc as u32) & ((1 << (sps.log2_max_poc_lsb_minus4 + 4)) - 1);
389 header.sao_luma = sps.sao_enabled;
390 header.sao_chroma = sps.sao_enabled;
391 header.five_minus_max_num_merge_cand = 0;
392 // The set goes in the header rather than the SPS, which is what this
393 // driver writes when it composes the header itself.
394 header.short_term_ref_pic_set_sps_flag = false;
395 header.short_term_ref_pic_set = previous_picture_set();
396 header.loop_filter_across_slices_enabled = false;
397 let mut w = ec_core::BitWriter::with_capacity(16);
398 // With `byte_alignment()` (7.3.6.1): this driver copies the header it is
399 // given verbatim and starts the slice data at the next byte, so the
400 // alignment bit has to be in what it is given.
401 header.write(&mut w, sps, pps, nal_type);
402 nal(
403 PACKED_HEADER_SLICE,
404 &NalHeader::new(nal_type).to_bytes(),
405 &w.into_bytes(),
406 0,
407 )
408 }
409}
410
411// ---------------------------------------------------------------------------
412// AV1
413// ---------------------------------------------------------------------------
414
415/// The two OBUs the AV1 encode path hands the driver: a sequence header and,
416/// per picture, an uncompressed frame header.
417///
418/// radeonsi *parses* these (`picture_av1_enc.c:vlVaHandleVAEncPackedHeaderData
419/// BufferTypeAV1`) rather than copying them through — the sequence header in
420/// full, the frame header as far as `uniform_tile_spacing_flag` — and then
421/// writes the header that goes into the stream itself, from those values plus
422/// the picture parameter buffer. So these are the *parameters*, in AV1's own
423/// syntax: a field written here that disagrees with the parameter buffer is a
424/// picture described two ways, and the driver believes this one.
425pub(super) mod av1 {
426 #[allow(unused_imports)]
427 use super::{PACKED_HEADER_PICTURE, PACKED_HEADER_SEQUENCE, PACKED_HEADER_SLICE};
428 use ec_core::BitWriter;
429
430 use super::{Colour, Packed};
431
432 /// `OrderHintBits`, and the width of `order_hint` in a frame header.
433 pub(in crate::enc) const ORDER_HINT_BITS: u32 = 8;
434
435 /// Bytes of the `obu_size` field. radeonsi reports
436 /// `VAConfigAttribEncAV1Ext2.obu_size_bytes_minus1 = 1` (measured on this
437 /// box), i.e. it wants that field a fixed two bytes so it can rewrite it
438 /// without moving the payload; leb128 permits the padded encoding.
439 const OBU_SIZE_BYTES: usize = 2;
440
441 /// Wrap a payload as one OBU: header byte, fixed-width `obu_size`, payload.
442 fn obu(kind: u32, obu_type: u8, payload: Vec<u8>) -> Packed {
443 let mut bytes = Vec::with_capacity(payload.len() + 1 + OBU_SIZE_BYTES);
444 // forbidden(0) type(4) extension(0) has_size(1) reserved(0)
445 bytes.push(obu_type << 3 | 0b010);
446 let mut size = payload.len();
447 for i in 0..OBU_SIZE_BYTES {
448 let last = i + 1 == OBU_SIZE_BYTES;
449 bytes.push((size as u8 & 0x7f) | if last { 0 } else { 0x80 });
450 size >>= 7;
451 }
452 bytes.extend_from_slice(&payload);
453 let bits = bytes.len() as u32 * 8;
454 Packed { kind, bytes, bits }
455 }
456
457 /// `trailing_bits()` (5.3.4).
458 fn trailing(w: &mut BitWriter) {
459 w.write_bit(true);
460 w.align_to_byte();
461 }
462
463 /// What the sequence header says about the stream.
464 pub(in crate::enc) struct SeqParams {
465 pub(in crate::enc) width: u32,
466 pub(in crate::enc) height: u32,
467 pub(in crate::enc) seq_level_idx: u8,
468 pub(in crate::enc) seq_tier: u8,
469 pub(in crate::enc) framerate: (u32, u32),
470 /// 10-bit (`high_bitdepth`); profile 0 has no `twelve_bit`.
471 pub(in crate::enc) high_bitdepth: bool,
472 pub(in crate::enc) colour: Option<Colour>,
473 }
474
475 /// `sequence_header_obu()` (5.5.1), profile 0, one operating point.
476 ///
477 /// Every coding tool this driver does not advertise
478 /// (`VAConfigAttribEncAV1`: no filter intra, no warped motion, no dual
479 /// filter, no superres, no restoration) is signalled off, which is also
480 /// what ffmpeg's `av1_vaapi` writes.
481 pub(in crate::enc) fn sequence_header(p: &SeqParams) -> Packed {
482 let mut w = BitWriter::new();
483 w.write_bits(0, 3); // seq_profile
484 w.write_bit(false); // still_picture
485 w.write_bit(false); // reduced_still_picture_header
486 w.write_bit(true); // timing_info_present_flag
487 w.write_bits(p.framerate.1.max(1), 32); // num_units_in_display_tick
488 w.write_bits(p.framerate.0.max(1), 32); // time_scale
489 w.write_bit(true); // equal_picture_interval
490 w.write_bit(true); // num_ticks_per_picture_minus_1 = 0, as uvlc
491 w.write_bit(false); // decoder_model_info_present_flag
492 w.write_bit(false); // initial_display_delay_present_flag
493 w.write_bits(0, 5); // operating_points_cnt_minus_1
494 w.write_bits(0, 12); // operating_point_idc[0]
495 w.write_bits(u32::from(p.seq_level_idx), 5);
496 if p.seq_level_idx > 7 {
497 w.write_bits(u32::from(p.seq_tier), 1);
498 }
499 let width_bits = 32 - p.width.max(1).leading_zeros(); // floor(log2(w)) + 1
500 let height_bits = 32 - p.height.max(1).leading_zeros();
501 w.write_bits(width_bits - 1, 4); // frame_width_bits_minus_1
502 w.write_bits(height_bits - 1, 4); // frame_height_bits_minus_1
503 w.write_bits(p.width - 1, width_bits); // max_frame_width_minus_1
504 w.write_bits(p.height - 1, height_bits); // max_frame_height_minus_1
505 w.write_bit(false); // frame_id_numbers_present_flag
506 w.write_bit(false); // use_128x128_superblock
507 w.write_bit(false); // enable_filter_intra
508 w.write_bit(false); // enable_intra_edge_filter
509 w.write_bit(false); // enable_interintra_compound
510 w.write_bit(false); // enable_masked_compound
511 w.write_bit(false); // enable_warped_motion
512 w.write_bit(false); // enable_dual_filter
513 w.write_bit(true); // enable_order_hint
514 w.write_bit(false); // enable_jnt_comp
515 w.write_bit(false); // enable_ref_frame_mvs
516 w.write_bit(false); // seq_choose_screen_content_tools
517 w.write_bit(false); // seq_force_screen_content_tools
518 w.write_bits(ORDER_HINT_BITS - 1, 3); // order_hint_bits_minus_1
519 w.write_bit(false); // enable_superres
520 w.write_bit(false); // enable_cdef
521 w.write_bit(false); // enable_restoration
522 // color_config(): profile 0 is 4:2:0, and never 12-bit.
523 w.write_bit(p.high_bitdepth);
524 w.write_bit(false); // mono_chrome
525 match p.colour {
526 Some(c) => {
527 w.write_bit(true); // color_description_present_flag
528 w.write_bits(u32::from(c.primaries), 8);
529 w.write_bits(u32::from(c.transfer), 8);
530 w.write_bits(u32::from(c.matrix), 8);
531 w.write_bit(c.full_range); // color_range
532 }
533 None => {
534 w.write_bit(false);
535 w.write_bit(false); // color_range
536 }
537 }
538 w.write_bits(0, 2); // chroma_sample_position = CSP_UNKNOWN
539 w.write_bit(false); // separate_uv_delta_q
540 w.write_bit(false); // film_grain_params_present
541 trailing(&mut w);
542 obu(PACKED_HEADER_SEQUENCE, 1, w.into_bytes())
543 }
544
545 /// What one picture's uncompressed header says.
546 pub(in crate::enc) struct FrameParams {
547 pub(in crate::enc) keyframe: bool,
548 pub(in crate::enc) order_hint: u8,
549 pub(in crate::enc) primary_ref_frame: u8,
550 pub(in crate::enc) refresh_frame_flags: u8,
551 pub(in crate::enc) ref_frame_idx: [u8; 7],
552 pub(in crate::enc) base_q_idx: u8,
553 pub(in crate::enc) loop_filter_level: [u8; 4],
554 /// `TX_MODE_SELECT`; this driver advertises no other
555 /// (`VAConfigAttribEncAV1Ext2.tx_mode_support = 0x4`).
556 pub(in crate::enc) tx_mode_select: bool,
557 /// The bit offsets the driver needs to back-annotate its own choices
558 /// into this header are only read outside CQP, so they are computed
559 /// unconditionally and used by the caller when it is not in CQP.
560 pub(in crate::enc) max_tile_cols_log2: u32,
561 pub(in crate::enc) max_tile_rows_log2: u32,
562 }
563
564 /// Where the driver may rewrite fields of the header we just wrote, in
565 /// bits from the first bit of the OBU (`VAEncPictureParameterBufferAV1`).
566 pub(in crate::enc) struct FrameHeaderOffsets {
567 pub(in crate::enc) qindex: u32,
568 pub(in crate::enc) segmentation: u32,
569 pub(in crate::enc) loop_filter: u32,
570 pub(in crate::enc) cdef: u32,
571 pub(in crate::enc) cdef_size: u32,
572 pub(in crate::enc) obu_size_byte: u32,
573 pub(in crate::enc) total_bits: u32,
574 }
575
576 /// `frame_header_obu()` (5.9.1) for a shown key or inter frame with one
577 /// tile, no segmentation, no CDEF, no restoration and no global motion.
578 pub(in crate::enc) fn frame_header(p: &FrameParams) -> (Packed, FrameHeaderOffsets) {
579 // The OBU header and its size field precede every offset below.
580 let prefix_bits = 8 * (1 + OBU_SIZE_BYTES) as u32;
581 let mut w = BitWriter::new();
582 w.write_bit(false); // show_existing_frame
583 w.write_bits(u32::from(!p.keyframe), 2); // frame_type: KEY / INTER
584 w.write_bit(true); // show_frame
585 if !p.keyframe {
586 // A shown key frame infers error_resilient_mode = 1.
587 w.write_bit(false); // error_resilient_mode
588 }
589 w.write_bit(false); // disable_cdf_update
590 w.write_bit(false); // frame_size_override_flag
591 w.write_bits(u32::from(p.order_hint), ORDER_HINT_BITS);
592 if !p.keyframe {
593 w.write_bits(u32::from(p.primary_ref_frame), 3);
594 // A shown key frame refreshes every slot, unsignalled.
595 w.write_bits(u32::from(p.refresh_frame_flags), 8);
596 w.write_bit(false); // frame_refs_short_signaling
597 for idx in p.ref_frame_idx {
598 w.write_bits(u32::from(idx), 3);
599 }
600 }
601 // frame_size(): frame_size_override_flag = 0 takes the sequence
602 // header's size, and enable_superres = 0 codes no superres bit.
603 w.write_bit(false); // render_and_frame_size_different
604 if !p.keyframe {
605 w.write_bit(false); // allow_high_precision_mv
606 w.write_bit(true); // is_filter_switchable
607 w.write_bit(false); // is_motion_mode_switchable
608 // use_ref_frame_mvs is inferred 0 from enable_ref_frame_mvs = 0.
609 }
610 w.write_bit(false); // disable_frame_end_update_cdf
611 // tile_info(): one tile, uniformly spaced. The increment loop stops
612 // with a zero bit for as long as the maximum allows another doubling.
613 w.write_bit(true); // uniform_tile_spacing_flag
614 if p.max_tile_cols_log2 > 0 {
615 w.write_bit(false); // increment_tile_cols_log2
616 }
617 if p.max_tile_rows_log2 > 0 {
618 w.write_bit(false); // increment_tile_rows_log2
619 }
620 let qindex = prefix_bits + w.bit_len() as u32;
621 w.write_bits(u32::from(p.base_q_idx), 8);
622 w.write_bit(false); // DeltaQYDc.delta_coded
623 w.write_bit(false); // DeltaQUDc.delta_coded
624 w.write_bit(false); // DeltaQUAc.delta_coded
625 w.write_bit(false); // using_qmatrix
626 let segmentation = prefix_bits + w.bit_len() as u32;
627 w.write_bit(false); // segmentation_enabled
628 w.write_bit(false); // delta_q_present (base_q_idx > 0)
629 let loop_filter = prefix_bits + w.bit_len() as u32;
630 w.write_bits(u32::from(p.loop_filter_level[0]), 6);
631 w.write_bits(u32::from(p.loop_filter_level[1]), 6);
632 if p.loop_filter_level[0] != 0 || p.loop_filter_level[1] != 0 {
633 w.write_bits(u32::from(p.loop_filter_level[2]), 6);
634 w.write_bits(u32::from(p.loop_filter_level[3]), 6);
635 }
636 w.write_bits(0, 3); // loop_filter_sharpness
637 w.write_bit(false); // loop_filter_delta_enabled
638 // cdef_params() and lr_params() are empty: enable_cdef =
639 // enable_restoration = 0 in the sequence header above.
640 let cdef = prefix_bits + w.bit_len() as u32;
641 w.write_bit(p.tx_mode_select); // tx_mode_select
642 if !p.keyframe {
643 w.write_bit(false); // reference_select — single reference, which
644 // also makes skipModeAllowed 0, so no skip_mode_present bit
645 }
646 w.write_bit(false); // reduced_tx_set
647 if !p.keyframe {
648 for _ in 0..7 {
649 w.write_bit(false); // is_global[ref]
650 }
651 }
652 trailing(&mut w);
653 let packed = obu(PACKED_HEADER_PICTURE, 3, w.into_bytes());
654 let offsets = FrameHeaderOffsets {
655 qindex,
656 segmentation,
657 loop_filter,
658 cdef,
659 cdef_size: 0,
660 obu_size_byte: 1,
661 total_bits: packed.bits,
662 };
663 (packed, offsets)
664 }
665
666 /// `tile_log2(1, n)`: the number of doublings of 1 needed to reach `n`,
667 /// which is the ceiling of log2 (5.9.15).
668 pub(in crate::enc) fn tile_log2(target: u32) -> u32 {
669 let mut k = 0;
670 while (1u32 << k) < target {
671 k += 1;
672 }
673 k
674 }
675}
676
677#[cfg(test)]
678mod h264_profile_tests {
679 use super::*;
680
681 fn params(profile: super::super::H264Profile) -> H264Params {
682 H264Params {
683 level_idc: 40,
684 mb_width: 40,
685 mb_height: 30,
686 crop_right: 0,
687 crop_bottom: 0,
688 num_units_in_tick: 1,
689 time_scale: 60,
690 pic_init_qp: 26,
691 colour: None,
692 profile,
693 }
694 }
695
696 /// The SPS NAL payload after the one-byte NAL header: `profile_idc`,
697 /// constraint byte, level, then the RBSP.
698 fn sps_profile(profile: super::super::H264Profile) -> (u8, u8, usize) {
699 let packed = h264_sps(&params(profile));
700 // Start code (4 bytes) then the NAL header (0x67).
701 (packed.bytes[5], packed.bytes[6], packed.bits as usize)
702 }
703
704 #[test]
705 fn each_profile_writes_its_profile_idc_and_constraints() {
706 use super::super::H264Profile::*;
707 assert_eq!(sps_profile(ConstrainedBaseline).0, 66);
708 assert_eq!(sps_profile(ConstrainedBaseline).1, 0x40);
709 assert_eq!(sps_profile(Main).0, 77);
710 assert_eq!(sps_profile(Main).1, 0);
711 assert_eq!(sps_profile(High).0, 100);
712 }
713
714 #[test]
715 fn main_and_baseline_omit_the_high_only_tail() {
716 use super::super::H264Profile::*;
717 // The High tail is chroma_format_idc, two bit depths, the bypass flag
718 // and the scaling-list flag. Main and Baseline must not carry them, so
719 // their SPS is shorter than High's for the same picture.
720 let high = sps_profile(High).2;
721 assert_eq!(sps_profile(Main).2, sps_profile(ConstrainedBaseline).2);
722 // ue(1) chroma_format_idc is 3 bits, two ue(0) depths are 1 bit each,
723 // then the two flags: 7 bits, rounded by rbsp_trailing_bits to 0 or 8.
724 assert!([0, 8].contains(&(high - sps_profile(Main).2)));
725 let sps = h264_sps(&params(High)).bytes;
726 let main = h264_sps(&params(Main)).bytes;
727 assert_ne!(sps[8], main[8]);
728 }
729
730 #[test]
731 fn profile_selects_cabac_only_above_baseline() {
732 use super::super::H264Profile::*;
733 assert!(!ConstrainedBaseline.cabac());
734 assert!(Main.cabac());
735 assert!(High.cabac());
736 }
737}