forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

vui.rs366 lines, 13.3 KiBHistoryRawDownload
1//! VUI parameters — the part of an SPS that says what the samples *mean*.
2
3use crate::ps::check_range;
4use ec_core::bitio::{BitReader, BitWriter};
5use ec_core::color::ColorDescription;
6use ec_core::error::Result;
7
8/// `colour_primaries`, `transfer_characteristics`, `matrix_coeffs` (H.273 code
9/// points), carried verbatim.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub struct ColourDescription {
12 /// `colour_primaries`: 1 = BT.709, 9 = BT.2020.
13 pub colour_primaries: u8,
14 /// `transfer_characteristics`: 1 = BT.709, 16 = PQ, 18 = HLG.
15 pub transfer_characteristics: u8,
16 /// `matrix_coeffs`: 1 = BT.709, 9 = BT.2020 non-constant luminance.
17 pub matrix_coeffs: u8,
18}
19
20impl ColourDescription {
21 /// The three code points a [`ColorDescription`] resolves to.
22 ///
23 /// This is the bridge that keeps the bitstream and the container from
24 /// drifting apart: both sides come from the same H.273 resolution in
25 /// [`ec_core::color`].
26 pub fn from_color(color: ColorDescription) -> ColourDescription {
27 let (primaries, transfer, matrix) = color.codes();
28 ColourDescription {
29 colour_primaries: primaries as u8,
30 transfer_characteristics: transfer as u8,
31 matrix_coeffs: matrix as u8,
32 }
33 }
34}
35
36/// `video_signal_type` and the colour description under it.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct VideoSignalType {
39 /// The analogue system a picture came off; 5 ("unspecified") for anything
40 /// this family encodes, because none of it did.
41 pub video_format: u8,
42 /// False = limited range (16..235), true = full range.
43 pub video_full_range_flag: bool,
44 /// The H.273 code points, when stated.
45 pub colour_description: Option<ColourDescription>,
46}
47
48impl Default for VideoSignalType {
49 fn default() -> Self {
50 VideoSignalType {
51 video_format: 5,
52 video_full_range_flag: false,
53 colour_description: None,
54 }
55 }
56}
57
58/// The VUI fields this family writes and reads (E.2.1).
59///
60/// Everything absent here is written as "not present"; an HRD block in
61/// particular is deliberately never written, since nothing downstream reads one
62/// and a wrong one is worse than none.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct VuiParameters {
65 /// Sample aspect ratio as `aspect_ratio_idc`, or `Some((w, h))` for the
66 /// extended form.
67 pub sample_aspect_ratio: Option<(u16, u16)>,
68 /// What the samples mean.
69 pub video_signal_type: Option<VideoSignalType>,
70 /// `(chroma_sample_loc_type_top_field, chroma_sample_loc_type_bottom_field)`,
71 /// each 0..=5. 4:2:0 BT.2020 material is normally type 2 (top-left).
72 pub chroma_sample_loc: Option<(u8, u8)>,
73 /// `(num_units_in_tick, time_scale)`: a rational frame rate, exact.
74 pub timing: Option<(u32, u32)>,
75}
76
77impl VuiParameters {
78 /// Write `vui_parameters()`.
79 pub fn write(&self, w: &mut BitWriter) {
80 match self.sample_aspect_ratio {
81 Some((sw, sh)) => {
82 w.write_bit(true);
83 w.write_bits(255, 8); // EXTENDED_SAR
84 w.write_bits(u32::from(sw), 16);
85 w.write_bits(u32::from(sh), 16);
86 }
87 None => w.write_bit(false),
88 }
89 w.write_bit(false); // overscan_info_present_flag
90 match self.video_signal_type {
91 Some(vst) => {
92 w.write_bit(true);
93 w.write_bits(u32::from(vst.video_format), 3);
94 w.write_bit(vst.video_full_range_flag);
95 match vst.colour_description {
96 Some(cd) => {
97 w.write_bit(true);
98 w.write_bits(u32::from(cd.colour_primaries), 8);
99 w.write_bits(u32::from(cd.transfer_characteristics), 8);
100 w.write_bits(u32::from(cd.matrix_coeffs), 8);
101 }
102 None => w.write_bit(false),
103 }
104 }
105 None => w.write_bit(false),
106 }
107 match self.chroma_sample_loc {
108 Some((top, bottom)) => {
109 w.write_bit(true);
110 w.write_ue(u32::from(top));
111 w.write_ue(u32::from(bottom));
112 }
113 None => w.write_bit(false),
114 }
115 w.write_bit(false); // neutral_chroma_indication_flag
116 w.write_bit(false); // field_seq_flag
117 w.write_bit(false); // frame_field_info_present_flag
118 w.write_bit(false); // default_display_window_flag
119 match self.timing {
120 Some((units, scale)) => {
121 w.write_bit(true);
122 w.write_bits(units, 32);
123 w.write_bits(scale, 32);
124 w.write_bit(false); // vui_poc_proportional_to_timing_flag
125 w.write_bit(false); // vui_hrd_parameters_present_flag
126 }
127 None => w.write_bit(false),
128 }
129 w.write_bit(false); // bitstream_restriction_flag
130 }
131
132 /// Parse `vui_parameters()`, skipping past the parts not modelled.
133 pub fn parse(r: &mut BitReader, max_sub_layers_minus1: u32) -> Result<VuiParameters> {
134 let mut vui = VuiParameters::default();
135 if r.read_bit()? {
136 let idc = r.read_bits(8)?;
137 if idc == 255 {
138 let sw = r.read_bits(16)? as u16;
139 let sh = r.read_bits(16)? as u16;
140 vui.sample_aspect_ratio = Some((sw, sh));
141 }
142 }
143 if r.read_bit()? {
144 r.read_bit()?; // overscan_appropriate_flag
145 }
146 if r.read_bit()? {
147 let video_format = r.read_bits(3)? as u8;
148 let video_full_range_flag = r.read_bit()?;
149 let colour_description = if r.read_bit()? {
150 Some(ColourDescription {
151 colour_primaries: r.read_bits(8)? as u8,
152 transfer_characteristics: r.read_bits(8)? as u8,
153 matrix_coeffs: r.read_bits(8)? as u8,
154 })
155 } else {
156 None
157 };
158 vui.video_signal_type = Some(VideoSignalType {
159 video_format,
160 video_full_range_flag,
161 colour_description,
162 });
163 }
164 if r.read_bit()? {
165 let top = r.read_ue()?;
166 let bottom = r.read_ue()?;
167 vui.chroma_sample_loc = Some((top as u8, bottom as u8));
168 }
169 r.read_bit()?; // neutral_chroma_indication_flag
170 r.read_bit()?; // field_seq_flag
171 r.read_bit()?; // frame_field_info_present_flag
172 if r.read_bit()? {
173 for _ in 0..4 {
174 r.read_ue()?;
175 }
176 }
177 if r.read_bit()? {
178 let units = r.read_bits(32)?;
179 let scale = r.read_bits(32)?;
180 vui.timing = Some((units, scale));
181 if r.read_bit()? {
182 r.read_ue()?;
183 }
184 if r.read_bit()? {
185 skip_hrd_parameters(r, true, max_sub_layers_minus1)?;
186 }
187 }
188 if r.read_bit()? {
189 r.read_bit()?;
190 r.read_bit()?;
191 r.read_bit()?;
192 for _ in 0..5 {
193 r.read_ue()?;
194 }
195 }
196 Ok(vui)
197 }
198}
199
200/// Walk past an `hrd_parameters()` block (E.2.2) without modelling it.
201fn skip_hrd_parameters(
202 r: &mut BitReader,
203 common_inf_present: bool,
204 max_sub_layers_minus1: u32,
205) -> Result<()> {
206 let mut nal_hrd = false;
207 let mut vcl_hrd = false;
208 let mut sub_pic_hrd = false;
209 if common_inf_present {
210 nal_hrd = r.read_bit()?;
211 vcl_hrd = r.read_bit()?;
212 if nal_hrd || vcl_hrd {
213 sub_pic_hrd = r.read_bit()?;
214 if sub_pic_hrd {
215 r.read_bits(8)?; // tick_divisor_minus2
216 r.read_bits(5)?; // du_cpb_removal_delay_increment_length_minus1
217 r.read_bit()?; // sub_pic_cpb_params_in_pic_timing_sei_flag
218 r.read_bits(5)?; // dpb_output_delay_du_length_minus1
219 }
220 r.read_bits(4)?; // bit_rate_scale
221 r.read_bits(4)?; // cpb_size_scale
222 if sub_pic_hrd {
223 r.read_bits(4)?; // cpb_size_du_scale
224 }
225 r.read_bits(5)?; // initial_cpb_removal_delay_length_minus1
226 r.read_bits(5)?; // au_cpb_removal_delay_length_minus1
227 r.read_bits(5)?; // dpb_output_delay_length_minus1
228 }
229 }
230 for _ in 0..=max_sub_layers_minus1 {
231 let fixed_pic_rate_general = r.read_bit()?;
232 let mut fixed_pic_rate_within_cvs = fixed_pic_rate_general;
233 if !fixed_pic_rate_general {
234 fixed_pic_rate_within_cvs = r.read_bit()?;
235 }
236 let mut low_delay = false;
237 if fixed_pic_rate_within_cvs {
238 r.read_ue()?; // elemental_duration_in_tc_minus1
239 } else {
240 low_delay = r.read_bit()?;
241 }
242 let mut cpb_cnt = 1u32;
243 if !low_delay {
244 // E.2.2: cpb_cnt_minus1 is 0 to 31. Widened before the +1 so it cannot wrap.
245 let cpb_cnt_minus1 = r.read_ue()?;
246 check_range(
247 "HEVC VUI",
248 "cpb_cnt_minus1",
249 i64::from(cpb_cnt_minus1),
250 0,
251 31,
252 )?;
253 cpb_cnt = cpb_cnt_minus1 + 1;
254 }
255 for present in [nal_hrd, vcl_hrd] {
256 if !present {
257 continue;
258 }
259 for _ in 0..cpb_cnt {
260 r.read_ue()?; // bit_rate_value_minus1
261 r.read_ue()?; // cpb_size_value_minus1
262 if sub_pic_hrd {
263 r.read_ue()?; // cpb_size_du_value_minus1
264 r.read_ue()?; // bit_rate_du_value_minus1
265 }
266 r.read_bit()?; // cbr_flag
267 }
268 }
269 }
270 Ok(())
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276
277 /// A VUI with only the HRD block set: one sub-layer, NAL HRD, no sub-picture
278 /// parameters, and the given `cpb_cnt_minus1`.
279 fn vui_with_cpb_cnt(cpb_cnt_minus1: u32) -> Vec<u8> {
280 let mut w = BitWriter::new();
281 for _ in 0..8 {
282 w.write_bit(false); // aspect ratio .. default display window, all absent
283 }
284 w.write_bit(true); // vui_timing_info_present_flag
285 w.write_bits(1001, 32);
286 w.write_bits(60_000, 32);
287 w.write_bit(false); // vui_poc_proportional_to_timing_flag
288 w.write_bit(true); // vui_hrd_parameters_present_flag
289 w.write_bit(true); // nal_hrd_parameters_present_flag
290 w.write_bit(false); // vcl_hrd_parameters_present_flag
291 w.write_bit(false); // sub_pic_hrd_params_present_flag
292 w.write_bits(0, 4); // bit_rate_scale
293 w.write_bits(0, 4); // cpb_size_scale
294 w.write_bits(0, 15); // initial, au and dpb delay lengths
295 w.write_bit(false); // fixed_pic_rate_general_flag
296 w.write_bit(false); // fixed_pic_rate_within_cvs_flag
297 w.write_bit(false); // low_delay_hrd_flag
298 w.write_ue(cpb_cnt_minus1);
299 // One NAL entry per CPB (the refused count never gets this far): bit rate,
300 // CPB size, CBR flag. Then bitstream_restriction_flag, so the parse ends cleanly.
301 for _ in 0..=cpb_cnt_minus1.min(31) {
302 w.write_ue(0);
303 w.write_ue(0);
304 w.write_bit(false);
305 }
306 w.write_bit(false); // bitstream_restriction_flag
307 w.align_to_byte();
308 w.into_bytes()
309 }
310
311 #[test]
312 fn cpb_count_past_31_is_refused_and_31_is_not() {
313 let bytes = vui_with_cpb_cnt(31);
314 let mut r = BitReader::new(&bytes);
315 assert_eq!(
316 VuiParameters::parse(&mut r, 0).unwrap().timing,
317 Some((1001, 60_000))
318 );
319
320 let bytes = vui_with_cpb_cnt(32);
321 let mut r = BitReader::new(&bytes);
322 let err = VuiParameters::parse(&mut r, 0).unwrap_err();
323 assert!(err.to_string().contains("cpb_cnt_minus1"), "{err}");
324 }
325
326 #[test]
327 fn vui_round_trips() {
328 let vui = VuiParameters {
329 sample_aspect_ratio: Some((1, 1)),
330 video_signal_type: Some(VideoSignalType {
331 video_format: 5,
332 video_full_range_flag: false,
333 colour_description: Some(ColourDescription {
334 colour_primaries: 1,
335 transfer_characteristics: 1,
336 matrix_coeffs: 1,
337 }),
338 }),
339 chroma_sample_loc: Some((2, 2)),
340 timing: Some((1001, 60_000)),
341 };
342 let mut w = BitWriter::new();
343 vui.write(&mut w);
344 w.align_to_byte();
345 let bytes = w.into_bytes();
346 let mut r = BitReader::new(&bytes);
347 assert_eq!(VuiParameters::parse(&mut r, 0).unwrap(), vui);
348
349 // Every export this family writes declares itself SDR: 709 above 720
350 // lines and 601 below, which is the rule ec-core states, not a guess
351 // made here.
352 for height in [1080, 2160] {
353 let cd = ColourDescription::from_color(ColorDescription::output(height));
354 assert_eq!(
355 (
356 cd.colour_primaries,
357 cd.transfer_characteristics,
358 cd.matrix_coeffs
359 ),
360 (1, 1, 1)
361 );
362 }
363 let cd = ColourDescription::from_color(ColorDescription::output(480));
364 assert_eq!((cd.colour_primaries, cd.matrix_coeffs), (6, 6));
365 }
366}