forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

headers.rs333 lines, 12.6 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(false); // bitstream_restriction_flag
129 trailing(&mut w);
130 w.into_bytes()
131}
132
133/// Write the picture parameter set RBSP (7.3.2.2).
134pub(crate) fn write_pps(cabac: bool, transform_8x8: bool, cqo: i32) -> Vec<u8> {
135 let mut w = BitWriter::with_capacity(8);
136 w.write_ue(0); // pic_parameter_set_id
137 w.write_ue(0); // seq_parameter_set_id
138 w.write_bit(cabac); // entropy_coding_mode_flag
139 w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag
140 w.write_ue(0); // num_slice_groups_minus1
141 w.write_ue(0); // num_ref_idx_l0_default_active_minus1
142 w.write_ue(0); // num_ref_idx_l1_default_active_minus1
143 w.write_bit(false); // weighted_pred_flag
144 w.write_bits(0, 2); // weighted_bipred_idc
145 w.write_se(0); // pic_init_qp_minus26
146 w.write_se(0); // pic_init_qs_minus26
147 w.write_se(cqo); // chroma_qp_index_offset
148 w.write_bit(false); // deblocking_filter_control_present_flag
149 w.write_bit(false); // constrained_intra_pred_flag
150 w.write_bit(false); // redundant_pic_cnt_present_flag
151 if transform_8x8 {
152 w.write_bit(true); // transform_8x8_mode_flag
153 w.write_bit(false); // pic_scaling_matrix_present_flag
154 w.write_se(cqo); // second_chroma_qp_index_offset
155 }
156 trailing(&mut w);
157 w.into_bytes()
158}
159
160/// What one slice header says about the picture it opens.
161#[derive(Debug, Clone, Copy)]
162pub(crate) struct SliceParams {
163 pub first_mb: u32,
164 pub slice_type: SliceType,
165 pub frame_num: u32,
166 pub idr: bool,
167 /// `idr_pic_id`, alternating between consecutive IDR pictures.
168 pub idr_pic_id: u32,
169 pub qp: i32,
170 /// CABAC is in force, so a P slice carries cabac_init_idc.
171 pub cabac: bool,
172}
173
174/// Write a slice header (7.3.3) into `w`; slice data follows immediately.
175pub(crate) fn write_slice_header(w: &mut BitWriter, s: &SliceParams) {
176 w.write_ue(s.first_mb);
177 // 5..=9 assert that every slice of this picture has the same type, which
178 // is true here: the picture is coded in one pass at one type.
179 w.write_ue(if s.slice_type == SliceType::I { 7 } else { 5 });
180 w.write_ue(0); // pic_parameter_set_id
181 w.write_bits(s.frame_num, LOG2_MAX_FRAME_NUM);
182 if s.idr {
183 w.write_ue(s.idr_pic_id);
184 }
185 // pic_order_cnt_type 2: no picture order count in the header at all.
186 if s.slice_type == SliceType::P {
187 w.write_bit(false); // num_ref_idx_active_override_flag
188 w.write_bit(false); // ref_pic_list_modification_flag_l0
189 }
190 // Every picture here is a reference picture (nal_ref_idc != 0).
191 if s.idr {
192 w.write_bit(false); // no_output_of_prior_pics_flag
193 w.write_bit(false); // long_term_reference_flag
194 } else {
195 w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window
196 }
197 if s.cabac && s.slice_type != SliceType::I {
198 w.write_ue(0); // cabac_init_idc
199 }
200 w.write_se(s.qp - 26); // slice_qp_delta, pic_init_qp_minus26 being 0
201 // deblocking_filter_control_present_flag is 0: the filter is on, offsets 0.
202}
203
204/// `rbsp_trailing_bits` (7.3.2.11).
205pub(crate) fn trailing(w: &mut BitWriter) {
206 w.write_bit(true);
207 w.align_to_byte();
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use ec_h264_syntax::{Pps, Sps};
214
215 fn params(width: u32, height: u32) -> SeqParams {
216 SeqParams {
217 width,
218 height,
219 mb_w: width.div_ceil(16),
220 mb_h: height.div_ceil(16),
221 timing: (1000, 60000),
222 bitrate: 8_000_000,
223 cabac: true,
224 transform_8x8: false,
225 }
226 }
227
228 /// The parameter sets this encoder writes are the ones the decoder's own
229 /// parser reads back, geometry, cropping, profile and entropy coder alike.
230 #[test]
231 fn parameter_sets_parse_back() {
232 for (w, h, cabac, t8x8) in [
233 (1920, 1080, true, false),
234 (1920, 1080, false, false),
235 (640, 480, true, false),
236 (854, 482, false, false),
237 (16, 16, true, false),
238 (640, 480, true, true),
239 (640, 480, false, true),
240 ] {
241 let mut p = params(w, h);
242 p.cabac = cabac;
243 p.transform_8x8 = t8x8;
244 let sps = Sps::parse(&write_sps(&p)).expect("SPS parses");
245 assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop");
246 assert_eq!(sps.mb_width, p.mb_w);
247 assert_eq!(sps.mb_height, p.mb_h);
248 assert_eq!(sps.pic_order_cnt_type, 2);
249 assert_eq!(sps.max_num_ref_frames, 1);
250 assert!(sps.frame_mbs_only);
251 let vui = sps.vui.as_ref().expect("VUI present");
252 assert_eq!(vui.timing_info, Some((1000, 60000, true)));
253 assert_eq!(
254 sps.profile_idc,
255 if t8x8 {
256 100
257 } else if cabac {
258 77
259 } else {
260 66
261 }
262 );
263 if t8x8 {
264 assert_eq!(sps.chroma_format_idc, 1);
265 assert_eq!(sps.bit_depth_luma, 8);
266 }
267 let pps = Pps::parse(&write_pps(cabac, t8x8, -2), |_| Some(&sps)).expect("PPS parses");
268 assert_eq!(pps.entropy_coding_mode, cabac);
269 assert_eq!(pps.pic_init_qp, 26);
270 assert_eq!(pps.transform_8x8_mode, t8x8);
271 assert_eq!(pps.chroma_qp_index_offset, -2);
272 // Absent, it is inferred equal to chroma_qp_index_offset (7.4.2.2).
273 assert_eq!(pps.second_chroma_qp_index_offset, -2);
274 }
275 }
276
277 /// 1080p60 at 8 Mbit/s needs level 4.0; a small clip needs far less.
278 #[test]
279 fn level_follows_the_load() {
280 assert_eq!(level_idc(&params(1920, 1080)), 40);
281 let mut small = params(320, 240);
282 small.timing = (1000, 30000);
283 small.bitrate = 300_000;
284 assert!(level_idc(&small) <= 21);
285 }
286
287 /// A slice header reads back at the values that were written.
288 #[test]
289 fn slice_header_parses_back() {
290 let p = params(320, 240);
291 let sps = Sps::parse(&write_sps(&p)).unwrap();
292 let pps = Pps::parse(&write_pps(true, false, 0), |_| Some(&sps)).unwrap();
293 for (idr, slice_type, first_mb, qp) in [
294 (true, SliceType::I, 0u32, 30i32),
295 (false, SliceType::P, 40, 18),
296 ] {
297 let mut w = BitWriter::new();
298 write_slice_header(
299 &mut w,
300 &SliceParams {
301 first_mb,
302 slice_type,
303 frame_num: 7,
304 idr,
305 idr_pic_id: 1,
306 qp,
307 cabac: true,
308 },
309 );
310 trailing(&mut w);
311 let rbsp = w.into_bytes();
312 let header = ec_h264_syntax::SliceHeader::parse(
313 &rbsp,
314 ec_h264_syntax::nal::NalHeader {
315 ref_idc: 1,
316 unit_type: if idr {
317 ec_h264_syntax::nal::NalUnitType::SliceIdr
318 } else {
319 ec_h264_syntax::nal::NalUnitType::Slice
320 },
321 },
322 &sps,
323 &pps,
324 )
325 .expect("slice header parses");
326 assert_eq!(header.first_mb_in_slice, first_mb);
327 assert_eq!(header.slice_type, slice_type);
328 assert!(header.all_slices_same_type);
329 assert_eq!(header.frame_num, 7);
330 assert_eq!(header.slice_qp, qp);
331 }
332 }
333}