forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

headers.rs290 lines, 10.9 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}
30
31/// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one
32/// reference picture this encoder keeps.
33pub(crate) const LOG2_MAX_FRAME_NUM: u32 = 8;
34
35/// Annex A levels as `(level_idc, MaxMBPS, MaxFS, MaxBR in kbit/s)`, in
36/// ascending order; the first one that fits is what the SPS advertises.
37const LEVELS: [(u8, u64, u64, u64); 16] = [
38 (10, 1485, 99, 64),
39 (11, 3000, 396, 192),
40 (12, 6000, 396, 384),
41 (13, 11880, 396, 768),
42 (20, 11880, 396, 2000),
43 (21, 19800, 792, 4000),
44 (22, 20250, 1620, 4000),
45 (30, 40500, 1620, 10000),
46 (31, 108000, 3600, 14000),
47 (32, 216000, 5120, 20000),
48 (40, 245760, 8192, 20000),
49 (42, 522240, 8704, 50000),
50 (50, 589824, 22080, 135000),
51 (51, 983040, 36864, 240000),
52 (52, 2073600, 36864, 240000),
53 (62, 16711680, 139264, 800000),
54];
55
56fn level_idc(p: &SeqParams) -> u8 {
57 let frame_mbs = u64::from(p.mb_w) * u64::from(p.mb_h);
58 let fps = f64::from(p.timing.1) / (2.0 * f64::from(p.timing.0).max(1.0));
59 let mbps = (frame_mbs as f64 * fps).ceil() as u64;
60 let kbps = u64::from(p.bitrate) / 1000;
61 for &(idc, max_mbps, max_fs, max_br) in &LEVELS {
62 if mbps <= max_mbps && frame_mbs <= max_fs && kbps <= max_br {
63 return idc;
64 }
65 }
66 62
67}
68
69/// Write the sequence parameter set RBSP (7.3.2.1), Baseline profile with the
70/// Main-profile constraint flag set: this encoder emits nothing (no FMO, no
71/// ASO, no redundant slices, no interlace) that either profile forbids.
72pub(crate) fn write_sps(p: &SeqParams) -> Vec<u8> {
73 let mut w = BitWriter::with_capacity(32);
74 // Main when CABAC is in force (Baseline has no CABAC), Baseline otherwise;
75 // constraint_set1_flag says the stream also obeys the Main constraints.
76 w.write_bits(if p.cabac { 77 } else { 66 }, 8);
77 w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8);
78 w.write_bits(u32::from(level_idc(p)), 8);
79 w.write_ue(0); // seq_parameter_set_id
80 w.write_ue(LOG2_MAX_FRAME_NUM - 4);
81 w.write_ue(2); // pic_order_cnt_type 2: output order is decode order
82 w.write_ue(1); // max_num_ref_frames
83 w.write_bit(false); // gaps_in_frame_num_value_allowed_flag
84 w.write_ue(p.mb_w - 1);
85 w.write_ue(p.mb_h - 1);
86 w.write_bit(true); // frame_mbs_only_flag
87 w.write_bit(true); // direct_8x8_inference_flag
88 let crop_right = (p.mb_w * 16 - p.width) / 2; // CropUnitX = 2 for 4:2:0
89 let crop_bottom = (p.mb_h * 16 - p.height) / 2; // CropUnitY = 2, frame only
90 let cropping = crop_right != 0 || crop_bottom != 0;
91 w.write_bit(cropping);
92 if cropping {
93 w.write_ue(0);
94 w.write_ue(crop_right);
95 w.write_ue(0);
96 w.write_ue(crop_bottom);
97 }
98 // VUI: timing only, so a container-less stream still states its frame rate.
99 w.write_bit(true); // vui_parameters_present_flag
100 w.write_bit(false); // aspect_ratio_info_present_flag
101 w.write_bit(false); // overscan_info_present_flag
102 w.write_bit(false); // video_signal_type_present_flag
103 w.write_bit(false); // chroma_loc_info_present_flag
104 w.write_bit(true); // timing_info_present_flag
105 w.write_bits(p.timing.0, 32);
106 w.write_bits(p.timing.1, 32);
107 w.write_bit(true); // fixed_frame_rate_flag
108 w.write_bit(false); // nal_hrd_parameters_present_flag
109 w.write_bit(false); // vcl_hrd_parameters_present_flag
110 w.write_bit(false); // pic_struct_present_flag
111 w.write_bit(false); // bitstream_restriction_flag
112 trailing(&mut w);
113 w.into_bytes()
114}
115
116/// Write the picture parameter set RBSP (7.3.2.2).
117pub(crate) fn write_pps(cabac: bool) -> Vec<u8> {
118 let mut w = BitWriter::with_capacity(8);
119 w.write_ue(0); // pic_parameter_set_id
120 w.write_ue(0); // seq_parameter_set_id
121 w.write_bit(cabac); // entropy_coding_mode_flag
122 w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag
123 w.write_ue(0); // num_slice_groups_minus1
124 w.write_ue(0); // num_ref_idx_l0_default_active_minus1
125 w.write_ue(0); // num_ref_idx_l1_default_active_minus1
126 w.write_bit(false); // weighted_pred_flag
127 w.write_bits(0, 2); // weighted_bipred_idc
128 w.write_se(0); // pic_init_qp_minus26
129 w.write_se(0); // pic_init_qs_minus26
130 w.write_se(0); // chroma_qp_index_offset
131 w.write_bit(false); // deblocking_filter_control_present_flag
132 w.write_bit(false); // constrained_intra_pred_flag
133 w.write_bit(false); // redundant_pic_cnt_present_flag
134 trailing(&mut w);
135 w.into_bytes()
136}
137
138/// What one slice header says about the picture it opens.
139#[derive(Debug, Clone, Copy)]
140pub(crate) struct SliceParams {
141 pub first_mb: u32,
142 pub slice_type: SliceType,
143 pub frame_num: u32,
144 pub idr: bool,
145 /// `idr_pic_id`, alternating between consecutive IDR pictures.
146 pub idr_pic_id: u32,
147 pub qp: i32,
148 /// CABAC is in force, so a P slice carries cabac_init_idc.
149 pub cabac: bool,
150}
151
152/// Write a slice header (7.3.3) into `w`; slice data follows immediately.
153pub(crate) fn write_slice_header(w: &mut BitWriter, s: &SliceParams) {
154 w.write_ue(s.first_mb);
155 // 5..=9 assert that every slice of this picture has the same type, which
156 // is true here: the picture is coded in one pass at one type.
157 w.write_ue(if s.slice_type == SliceType::I { 7 } else { 5 });
158 w.write_ue(0); // pic_parameter_set_id
159 w.write_bits(s.frame_num, LOG2_MAX_FRAME_NUM);
160 if s.idr {
161 w.write_ue(s.idr_pic_id);
162 }
163 // pic_order_cnt_type 2: no picture order count in the header at all.
164 if s.slice_type == SliceType::P {
165 w.write_bit(false); // num_ref_idx_active_override_flag
166 w.write_bit(false); // ref_pic_list_modification_flag_l0
167 }
168 // Every picture here is a reference picture (nal_ref_idc != 0).
169 if s.idr {
170 w.write_bit(false); // no_output_of_prior_pics_flag
171 w.write_bit(false); // long_term_reference_flag
172 } else {
173 w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window
174 }
175 if s.cabac && s.slice_type != SliceType::I {
176 w.write_ue(0); // cabac_init_idc
177 }
178 w.write_se(s.qp - 26); // slice_qp_delta, pic_init_qp_minus26 being 0
179 // deblocking_filter_control_present_flag is 0: the filter is on, offsets 0.
180}
181
182/// `rbsp_trailing_bits` (7.3.2.11).
183pub(crate) fn trailing(w: &mut BitWriter) {
184 w.write_bit(true);
185 w.align_to_byte();
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191 use ec_h264_syntax::{Pps, Sps};
192
193 fn params(width: u32, height: u32) -> SeqParams {
194 SeqParams {
195 width,
196 height,
197 mb_w: width.div_ceil(16),
198 mb_h: height.div_ceil(16),
199 timing: (1000, 60000),
200 bitrate: 8_000_000,
201 cabac: true,
202 }
203 }
204
205 /// The parameter sets this encoder writes are the ones the decoder's own
206 /// parser reads back, geometry, cropping, profile and entropy coder alike.
207 #[test]
208 fn parameter_sets_parse_back() {
209 for (w, h, cabac) in [
210 (1920, 1080, true),
211 (1920, 1080, false),
212 (640, 480, true),
213 (854, 482, false),
214 (16, 16, true),
215 ] {
216 let mut p = params(w, h);
217 p.cabac = cabac;
218 let sps = Sps::parse(&write_sps(&p)).expect("SPS parses");
219 assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop");
220 assert_eq!(sps.mb_width, p.mb_w);
221 assert_eq!(sps.mb_height, p.mb_h);
222 assert_eq!(sps.pic_order_cnt_type, 2);
223 assert_eq!(sps.max_num_ref_frames, 1);
224 assert!(sps.frame_mbs_only);
225 let vui = sps.vui.as_ref().expect("VUI present");
226 assert_eq!(vui.timing_info, Some((1000, 60000, true)));
227 assert_eq!(sps.profile_idc, if cabac { 77 } else { 66 });
228 let pps = Pps::parse(&write_pps(cabac), |_| Some(&sps)).expect("PPS parses");
229 assert_eq!(pps.entropy_coding_mode, cabac);
230 assert_eq!(pps.pic_init_qp, 26);
231 }
232 }
233
234 /// 1080p60 at 8 Mbit/s needs level 4.0; a small clip needs far less.
235 #[test]
236 fn level_follows_the_load() {
237 assert_eq!(level_idc(&params(1920, 1080)), 40);
238 let mut small = params(320, 240);
239 small.timing = (1000, 30000);
240 small.bitrate = 300_000;
241 assert!(level_idc(&small) <= 21);
242 }
243
244 /// A slice header reads back at the values that were written.
245 #[test]
246 fn slice_header_parses_back() {
247 let p = params(320, 240);
248 let sps = Sps::parse(&write_sps(&p)).unwrap();
249 let pps = Pps::parse(&write_pps(true), |_| Some(&sps)).unwrap();
250 for (idr, slice_type, first_mb, qp) in [
251 (true, SliceType::I, 0u32, 30i32),
252 (false, SliceType::P, 40, 18),
253 ] {
254 let mut w = BitWriter::new();
255 write_slice_header(
256 &mut w,
257 &SliceParams {
258 first_mb,
259 slice_type,
260 frame_num: 7,
261 idr,
262 idr_pic_id: 1,
263 qp,
264 cabac: true,
265 },
266 );
267 trailing(&mut w);
268 let rbsp = w.into_bytes();
269 let header = ec_h264_syntax::SliceHeader::parse(
270 &rbsp,
271 ec_h264_syntax::nal::NalHeader {
272 ref_idc: 1,
273 unit_type: if idr {
274 ec_h264_syntax::nal::NalUnitType::SliceIdr
275 } else {
276 ec_h264_syntax::nal::NalUnitType::Slice
277 },
278 },
279 &sps,
280 &pps,
281 )
282 .expect("slice header parses");
283 assert_eq!(header.first_mb_in_slice, first_mb);
284 assert_eq!(header.slice_type, slice_type);
285 assert!(header.all_slices_same_type);
286 assert_eq!(header.frame_num, 7);
287 assert_eq!(header.slice_qp, qp);
288 }
289 }
290}