forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

headers.rs340 lines, 13.0 KiBHistoryRawDownload
1//! Parameter sets and slice headers on the writing side (spec 7.3.2, 7.3.3).
2//!
3//! Only the subset this encoder emits is written: 8-bit 4:2:0 progressive,
4//! CAVLC, one slice group, one reference, `pic_order_cnt_type` 2 — which is
5//! the type that says decode order *is* output order, and costs no bits in
6//! any slice header. The test at the bottom parses everything back through
7//! [`ec_h264_syntax`], which is the same parser the decoder uses.
8
9use ec_core::BitWriter;
10use ec_h264_syntax::SliceType;
11
12/// Geometry and timing of the sequence, everything the parameter sets need.
13#[derive(Debug, Clone, Copy)]
14pub(crate) struct SeqParams {
15 /// Displayed luma width.
16 pub width: u32,
17 /// Displayed luma height.
18 pub height: u32,
19 /// Coded width in macroblocks.
20 pub mb_w: u32,
21 /// Coded height in macroblocks.
22 pub mb_h: u32,
23 /// `(num_units_in_tick, time_scale)`; `time_scale` is twice the frame rate.
24 pub timing: (u32, u32),
25 /// Bits per second the level has to carry.
26 pub bitrate: u32,
27 /// CABAC, which Baseline does not allow: the sequence is then Main.
28 pub cabac: bool,
29 /// 8x8 transform (High profile). Forces `profile_idc` 100 with no
30 /// constraint flags, and the High-profile SPS tail (7.3.2.1.1 subset:
31 /// 4:2:0 8-bit, no scaling matrices, no transform bypass).
32 pub transform_8x8: bool,
33}
34
35/// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one
36/// reference picture this encoder keeps.
37pub(crate) const LOG2_MAX_FRAME_NUM: u32 = 8;
38
39/// Annex A levels as `(level_idc, MaxMBPS, MaxFS, MaxBR in kbit/s)`, in
40/// ascending order; the first one that fits is what the SPS advertises.
41const LEVELS: [(u8, u64, u64, u64); 16] = [
42 (10, 1485, 99, 64),
43 (11, 3000, 396, 192),
44 (12, 6000, 396, 384),
45 (13, 11880, 396, 768),
46 (20, 11880, 396, 2000),
47 (21, 19800, 792, 4000),
48 (22, 20250, 1620, 4000),
49 (30, 40500, 1620, 10000),
50 (31, 108000, 3600, 14000),
51 (32, 216000, 5120, 20000),
52 (40, 245760, 8192, 20000),
53 (42, 522240, 8704, 50000),
54 (50, 589824, 22080, 135000),
55 (51, 983040, 36864, 240000),
56 (52, 2073600, 36864, 240000),
57 (62, 16711680, 139264, 800000),
58];
59
60fn level_idc(p: &SeqParams) -> u8 {
61 let frame_mbs = u64::from(p.mb_w) * u64::from(p.mb_h);
62 let fps = f64::from(p.timing.1) / (2.0 * f64::from(p.timing.0).max(1.0));
63 let mbps = (frame_mbs as f64 * fps).ceil() as u64;
64 let kbps = u64::from(p.bitrate) / 1000;
65 for &(idc, max_mbps, max_fs, max_br) in &LEVELS {
66 if mbps <= max_mbps && frame_mbs <= max_fs && kbps <= max_br {
67 return idc;
68 }
69 }
70 62
71}
72
73/// Write the sequence parameter set RBSP (7.3.2.1), Baseline profile with the
74/// Main-profile constraint flag set: this encoder emits nothing (no FMO, no
75/// ASO, no redundant slices, no interlace) that either profile forbids.
76pub(crate) fn write_sps(p: &SeqParams) -> Vec<u8> {
77 let mut w = BitWriter::with_capacity(32);
78 // Main when CABAC is in force (Baseline has no CABAC), Baseline otherwise;
79 // constraint_set1_flag says the stream also obeys the Main constraints.
80 // 8x8 transform needs High profile (100), which sets no constraint flags.
81 if p.transform_8x8 {
82 w.write_bits(100, 8);
83 w.write_bits(0, 8);
84 } else {
85 w.write_bits(if p.cabac { 77 } else { 66 }, 8);
86 w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8);
87 }
88 w.write_bits(u32::from(level_idc(p)), 8);
89 w.write_ue(0); // seq_parameter_set_id
90 if p.transform_8x8 {
91 w.write_ue(1); // chroma_format_idc: 4:2:0
92 w.write_ue(0); // bit_depth_luma_minus8
93 w.write_ue(0); // bit_depth_chroma_minus8
94 w.write_bit(false); // qpprime_y_zero_transform_bypass_flag
95 w.write_bit(false); // seq_scaling_matrix_present_flag
96 }
97 w.write_ue(LOG2_MAX_FRAME_NUM - 4);
98 w.write_ue(2); // pic_order_cnt_type 2: output order is decode order
99 w.write_ue(1); // max_num_ref_frames
100 w.write_bit(false); // gaps_in_frame_num_value_allowed_flag
101 w.write_ue(p.mb_w - 1);
102 w.write_ue(p.mb_h - 1);
103 w.write_bit(true); // frame_mbs_only_flag
104 w.write_bit(true); // direct_8x8_inference_flag
105 let crop_right = (p.mb_w * 16 - p.width) / 2; // CropUnitX = 2 for 4:2:0
106 let crop_bottom = (p.mb_h * 16 - p.height) / 2; // CropUnitY = 2, frame only
107 let cropping = crop_right != 0 || crop_bottom != 0;
108 w.write_bit(cropping);
109 if cropping {
110 w.write_ue(0);
111 w.write_ue(crop_right);
112 w.write_ue(0);
113 w.write_ue(crop_bottom);
114 }
115 // VUI: timing only, so a container-less stream still states its frame rate.
116 w.write_bit(true); // vui_parameters_present_flag
117 w.write_bit(false); // aspect_ratio_info_present_flag
118 w.write_bit(false); // overscan_info_present_flag
119 w.write_bit(false); // video_signal_type_present_flag
120 w.write_bit(false); // chroma_loc_info_present_flag
121 w.write_bit(true); // timing_info_present_flag
122 w.write_bits(p.timing.0, 32);
123 w.write_bits(p.timing.1, 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 w.into_bytes()
138}
139
140/// Write the picture parameter set RBSP (7.3.2.2).
141pub(crate) fn write_pps(cabac: bool, transform_8x8: bool, cqo: i32) -> Vec<u8> {
142 let mut w = BitWriter::with_capacity(8);
143 w.write_ue(0); // pic_parameter_set_id
144 w.write_ue(0); // seq_parameter_set_id
145 w.write_bit(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(0); // pic_init_qp_minus26
153 w.write_se(0); // pic_init_qs_minus26
154 w.write_se(cqo); // chroma_qp_index_offset
155 w.write_bit(false); // 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 transform_8x8 {
159 w.write_bit(true); // transform_8x8_mode_flag
160 w.write_bit(false); // pic_scaling_matrix_present_flag
161 w.write_se(cqo); // second_chroma_qp_index_offset
162 }
163 trailing(&mut w);
164 w.into_bytes()
165}
166
167/// What one slice header says about the picture it opens.
168#[derive(Debug, Clone, Copy)]
169pub(crate) struct SliceParams {
170 pub first_mb: u32,
171 pub slice_type: SliceType,
172 pub frame_num: u32,
173 pub idr: bool,
174 /// `idr_pic_id`, alternating between consecutive IDR pictures.
175 pub idr_pic_id: u32,
176 pub qp: i32,
177 /// CABAC is in force, so a P slice carries cabac_init_idc.
178 pub cabac: bool,
179}
180
181/// Write a slice header (7.3.3) into `w`; slice data follows immediately.
182pub(crate) fn write_slice_header(w: &mut BitWriter, s: &SliceParams) {
183 w.write_ue(s.first_mb);
184 // 5..=9 assert that every slice of this picture has the same type, which
185 // is true here: the picture is coded in one pass at one type.
186 w.write_ue(if s.slice_type == SliceType::I { 7 } else { 5 });
187 w.write_ue(0); // pic_parameter_set_id
188 w.write_bits(s.frame_num, LOG2_MAX_FRAME_NUM);
189 if s.idr {
190 w.write_ue(s.idr_pic_id);
191 }
192 // pic_order_cnt_type 2: no picture order count in the header at all.
193 if s.slice_type == SliceType::P {
194 w.write_bit(false); // num_ref_idx_active_override_flag
195 w.write_bit(false); // ref_pic_list_modification_flag_l0
196 }
197 // Every picture here is a reference picture (nal_ref_idc != 0).
198 if s.idr {
199 w.write_bit(false); // no_output_of_prior_pics_flag
200 w.write_bit(false); // long_term_reference_flag
201 } else {
202 w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window
203 }
204 if s.cabac && s.slice_type != SliceType::I {
205 w.write_ue(0); // cabac_init_idc
206 }
207 w.write_se(s.qp - 26); // slice_qp_delta, pic_init_qp_minus26 being 0
208 // deblocking_filter_control_present_flag is 0: the filter is on, offsets 0.
209}
210
211/// `rbsp_trailing_bits` (7.3.2.11).
212pub(crate) fn trailing(w: &mut BitWriter) {
213 w.write_bit(true);
214 w.align_to_byte();
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use ec_h264_syntax::{Pps, Sps};
221
222 fn params(width: u32, height: u32) -> SeqParams {
223 SeqParams {
224 width,
225 height,
226 mb_w: width.div_ceil(16),
227 mb_h: height.div_ceil(16),
228 timing: (1000, 60000),
229 bitrate: 8_000_000,
230 cabac: true,
231 transform_8x8: false,
232 }
233 }
234
235 /// The parameter sets this encoder writes are the ones the decoder's own
236 /// parser reads back, geometry, cropping, profile and entropy coder alike.
237 #[test]
238 fn parameter_sets_parse_back() {
239 for (w, h, cabac, t8x8) in [
240 (1920, 1080, true, false),
241 (1920, 1080, false, false),
242 (640, 480, true, false),
243 (854, 482, false, false),
244 (16, 16, true, false),
245 (640, 480, true, true),
246 (640, 480, false, true),
247 ] {
248 let mut p = params(w, h);
249 p.cabac = cabac;
250 p.transform_8x8 = t8x8;
251 let sps = Sps::parse(&write_sps(&p)).expect("SPS parses");
252 assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop");
253 assert_eq!(sps.mb_width, p.mb_w);
254 assert_eq!(sps.mb_height, p.mb_h);
255 assert_eq!(sps.pic_order_cnt_type, 2);
256 assert_eq!(sps.max_num_ref_frames, 1);
257 assert!(sps.frame_mbs_only);
258 let vui = sps.vui.as_ref().expect("VUI present");
259 assert_eq!(vui.timing_info, Some((1000, 60000, true)));
260 assert_eq!(
261 sps.profile_idc,
262 if t8x8 {
263 100
264 } else if cabac {
265 77
266 } else {
267 66
268 }
269 );
270 if t8x8 {
271 assert_eq!(sps.chroma_format_idc, 1);
272 assert_eq!(sps.bit_depth_luma, 8);
273 }
274 let pps = Pps::parse(&write_pps(cabac, t8x8, -2), |_| Some(&sps)).expect("PPS parses");
275 assert_eq!(pps.entropy_coding_mode, cabac);
276 assert_eq!(pps.pic_init_qp, 26);
277 assert_eq!(pps.transform_8x8_mode, t8x8);
278 assert_eq!(pps.chroma_qp_index_offset, -2);
279 // Absent, it is inferred equal to chroma_qp_index_offset (7.4.2.2).
280 assert_eq!(pps.second_chroma_qp_index_offset, -2);
281 }
282 }
283
284 /// 1080p60 at 8 Mbit/s needs level 4.0; a small clip needs far less.
285 #[test]
286 fn level_follows_the_load() {
287 assert_eq!(level_idc(&params(1920, 1080)), 40);
288 let mut small = params(320, 240);
289 small.timing = (1000, 30000);
290 small.bitrate = 300_000;
291 assert!(level_idc(&small) <= 21);
292 }
293
294 /// A slice header reads back at the values that were written.
295 #[test]
296 fn slice_header_parses_back() {
297 let p = params(320, 240);
298 let sps = Sps::parse(&write_sps(&p)).unwrap();
299 let pps = Pps::parse(&write_pps(true, false, 0), |_| Some(&sps)).unwrap();
300 for (idr, slice_type, first_mb, qp) in [
301 (true, SliceType::I, 0u32, 30i32),
302 (false, SliceType::P, 40, 18),
303 ] {
304 let mut w = BitWriter::new();
305 write_slice_header(
306 &mut w,
307 &SliceParams {
308 first_mb,
309 slice_type,
310 frame_num: 7,
311 idr,
312 idr_pic_id: 1,
313 qp,
314 cabac: true,
315 },
316 );
317 trailing(&mut w);
318 let rbsp = w.into_bytes();
319 let header = ec_h264_syntax::SliceHeader::parse(
320 &rbsp,
321 ec_h264_syntax::nal::NalHeader {
322 ref_idc: 1,
323 unit_type: if idr {
324 ec_h264_syntax::nal::NalUnitType::SliceIdr
325 } else {
326 ec_h264_syntax::nal::NalUnitType::Slice
327 },
328 },
329 &sps,
330 &pps,
331 )
332 .expect("slice header parses");
333 assert_eq!(header.first_mb_in_slice, first_mb);
334 assert_eq!(header.slice_type, slice_type);
335 assert!(header.all_slices_same_type);
336 assert_eq!(header.frame_num, 7);
337 assert_eq!(header.slice_qp, qp);
338 }
339 }
340}