forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB5c8eff8Tahinli2 months ago2949 commits

headers.rs626 lines, 26.2 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}
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.
383pub(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}