forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB58b009bTahinli2 months ago2045 commits

sequence.rs341 lines, 12.1 KiBHistoryRawDownload
1//! Sequence-header OBU writer (spec 5.5) — bit-exact inverse of
2//! [`ec_av1_syntax::sequence::SequenceHeader::parse`], for the
3//! stateless-decoder subset.
4
5use ec_av1_syntax::obu::{ObuHeader, ObuType};
6#[cfg(test)]
7use ec_av1_syntax::sequence::OperatingPoint;
8use ec_av1_syntax::sequence::{
9 ChromaSamplePosition, ColorConfig, SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS,
10 SequenceHeader,
11};
12use ec_core::{BitWriter, Error, Result};
13
14use crate::bits::write_trailing_bits;
15use crate::obu::wrap_obu;
16
17/// Map a [`ChromaSamplePosition`] to its 2-bit code (spec 6.4.2).
18fn chroma_sample_position_code(p: ChromaSamplePosition) -> u32 {
19 match p {
20 ChromaSamplePosition::Unknown => 0,
21 ChromaSamplePosition::Vertical => 1,
22 ChromaSamplePosition::Colocated => 2,
23 ChromaSamplePosition::Reserved => 3,
24 }
25}
26
27/// Write `color_config()` (spec 5.5.2) — the inverse of
28/// `ec_av1_syntax::sequence::read_color_config`.
29fn write_color_config(w: &mut BitWriter, c: &ColorConfig, seq_profile: u8) -> Result<()> {
30 let high_bitdepth = c.bit_depth >= 10;
31 w.write_bit(high_bitdepth);
32 if seq_profile == 2 && high_bitdepth {
33 // The extra `twelve_bit` flag: 1 for 12-bit, 0 for 10-bit.
34 w.write_bit(c.bit_depth == 12);
35 }
36
37 if seq_profile == 1 {
38 // Profile 1 forces mono_chrome = false; the bit is not coded.
39 if c.mono_chrome {
40 return Err(Error::unsupported(
41 "AV1 color_config mono_chrome",
42 "profile 1 is 4:4:4 and cannot be monochrome",
43 ));
44 }
45 } else {
46 w.write_bit(c.mono_chrome);
47 }
48
49 // color_description_present_flag: absent when all three are the
50 // unspecified default (H.273 code 2), which the parser then assumes.
51 let present =
52 c.color_primaries != 2 || c.transfer_characteristics != 2 || c.matrix_coefficients != 2;
53 w.write_bit(present);
54 if present {
55 w.write_bits(c.color_primaries as u32, 8);
56 w.write_bits(c.transfer_characteristics as u32, 8);
57 w.write_bits(c.matrix_coefficients as u32, 8);
58 }
59
60 if c.mono_chrome {
61 w.write_bit(c.color_range);
62 // subsampling is forced 1,1 and separate_uv_delta_q is not coded.
63 return Ok(());
64 }
65
66 // sRGB identity (BT.709 primaries, sRGB transfer, identity matrix) forces
67 // full-range 4:4:4; none of color_range, subsampling or position is coded.
68 let srgb =
69 c.color_primaries == 1 && c.transfer_characteristics == 13 && c.matrix_coefficients == 0;
70 if !srgb {
71 w.write_bit(c.color_range);
72 match seq_profile {
73 0 => {} // subsampling forced 1,1 (4:2:0), not coded
74 1 => {} // subsampling forced 0,0 (4:4:4), not coded
75 _ => {
76 if c.bit_depth == 12 {
77 w.write_bits(c.subsampling_x as u32, 1);
78 if c.subsampling_x == 1 {
79 w.write_bits(c.subsampling_y as u32, 1);
80 }
81 }
82 // Profile 2 below 12-bit: subsampling forced 1,0 (4:2:2).
83 }
84 }
85 if c.subsampling_x == 1 && c.subsampling_y == 1 {
86 w.write_bits(chroma_sample_position_code(c.chroma_sample_position), 2);
87 }
88 }
89 w.write_bit(c.separate_uv_delta_q);
90 Ok(())
91}
92
93/// Write a sequence-header OBU payload (spec 5.5.1) — the inverse of
94/// [`SequenceHeader::parse`], ending with `trailing_bits()`.
95///
96/// Supported subset (anything else returns [`Error::Unsupported`]):
97/// `reduced_still_picture_header == false`, no `timing_info`, no
98/// `decoder_model_info`, and exactly one operating point — the normal
99/// single-layer video case. Still-image, timed and buffered-decoder-model
100/// streams are refused rather than mis-written.
101pub fn write_sequence_header(w: &mut BitWriter, s: &SequenceHeader) -> Result<()> {
102 if s.reduced_still_picture_header {
103 return Err(Error::unsupported(
104 "AV1 reduced_still_picture_header",
105 "the cut-down still-image header is not implemented",
106 ));
107 }
108 if s.timing_info.is_some() {
109 return Err(Error::unsupported(
110 "AV1 timing_info",
111 "timing info is not implemented",
112 ));
113 }
114 if s.decoder_model_info.is_some() {
115 return Err(Error::unsupported(
116 "AV1 decoder_model_info",
117 "the decoder model is not implemented",
118 ));
119 }
120 if s.operating_points.len() != 1 {
121 return Err(Error::unsupported(
122 "AV1 operating_points",
123 "only one operating point is supported",
124 ));
125 }
126
127 w.write_bits(s.seq_profile as u32, 3);
128 w.write_bit(s.still_picture);
129 w.write_bit(s.reduced_still_picture_header);
130 // timing_info_present_flag = false (the subset above guarantees it).
131 w.write_bit(false);
132 w.write_bit(s.initial_display_delay_present_flag);
133 // operating_points_cnt_minus_1 = 0.
134 w.write_bits(0, 5);
135
136 let op = &s.operating_points[0];
137 w.write_bits(op.idc, 12);
138 w.write_bits(op.seq_level_idx as u32, 5);
139 if op.seq_level_idx > 7 {
140 w.write_bit(op.seq_tier != 0);
141 }
142 // No decoder model: decoder_model_present_for_this_op is not coded.
143 if s.initial_display_delay_present_flag {
144 if op.initial_display_delay > 0 {
145 w.write_bit(true);
146 w.write_bits(op.initial_display_delay as u32 - 1, 4);
147 } else {
148 w.write_bit(false);
149 }
150 }
151
152 w.write_bits(s.frame_width_bits - 1, 4);
153 w.write_bits(s.frame_height_bits - 1, 4);
154 w.write_bits(s.max_frame_width - 1, s.frame_width_bits);
155 w.write_bits(s.max_frame_height - 1, s.frame_height_bits);
156
157 // reduced_still_picture_header is false, so the flag is always coded.
158 w.write_bit(s.frame_id_numbers_present_flag);
159 if s.frame_id_numbers_present_flag {
160 w.write_bits(s.delta_frame_id_length - 2, 4);
161 w.write_bits(s.additional_frame_id_length - 1, 3);
162 }
163
164 w.write_bit(s.use_128x128_superblock);
165 w.write_bit(s.enable_filter_intra);
166 w.write_bit(s.enable_intra_edge_filter);
167
168 // The !reduced_still_picture_header block (spec 5.5.1).
169 w.write_bit(s.enable_interintra_compound);
170 w.write_bit(s.enable_masked_compound);
171 w.write_bit(s.enable_warped_motion);
172 w.write_bit(s.enable_dual_filter);
173 w.write_bit(s.enable_order_hint);
174 if s.enable_order_hint {
175 w.write_bit(s.enable_jnt_comp);
176 w.write_bit(s.enable_ref_frame_mvs);
177 }
178 // seq_force_screen_content_tools: SELECT (2) is the single-bit form.
179 if s.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS {
180 w.write_bit(true);
181 } else if s.seq_force_screen_content_tools <= 1 {
182 w.write_bit(false);
183 w.write_bits(s.seq_force_screen_content_tools as u32, 1);
184 } else {
185 return Err(Error::unsupported(
186 "AV1 seq_force_screen_content_tools",
187 "value must be 0, 1 or SELECT (2)",
188 ));
189 }
190 // seq_force_integer_mv: only coded when screen content tools are on.
191 if s.seq_force_screen_content_tools > 0 {
192 if s.seq_force_integer_mv == SELECT_INTEGER_MV {
193 w.write_bit(true);
194 } else if s.seq_force_integer_mv <= 1 {
195 w.write_bit(false);
196 w.write_bits(s.seq_force_integer_mv as u32, 1);
197 } else {
198 return Err(Error::unsupported(
199 "AV1 seq_force_integer_mv",
200 "value must be 0, 1 or SELECT (2)",
201 ));
202 }
203 }
204 if s.enable_order_hint {
205 w.write_bits(s.order_hint_bits - 1, 3);
206 }
207
208 w.write_bit(s.enable_superres);
209 w.write_bit(s.enable_cdef);
210 w.write_bit(s.enable_restoration);
211 write_color_config(w, &s.color_config, s.seq_profile)?;
212 w.write_bit(s.film_grain_params_present);
213 write_trailing_bits(w);
214 Ok(())
215}
216
217/// Build a complete sequence-header OBU (spec 5.5.1): the payload from
218/// [`write_sequence_header`] wrapped by [`wrap_obu`] with
219/// [`ObuType::SequenceHeader`], `has_size_field` set and no extension header.
220pub fn sequence_header_obu(s: &SequenceHeader) -> Result<Vec<u8>> {
221 let mut w = BitWriter::new();
222 write_sequence_header(&mut w, s)?;
223 let payload = w.into_bytes();
224 Ok(wrap_obu(
225 &ObuHeader {
226 obu_type: ObuType::SequenceHeader,
227 extension_flag: false,
228 has_size_field: true,
229 temporal_id: 0,
230 spatial_id: 0,
231 },
232 &payload,
233 ))
234}
235
236#[cfg(test)]
237pub(crate) mod tests {
238 use super::*;
239 use ec_av1_syntax::obu::{ObuHeader, read_leb128};
240 use ec_av1_syntax::sequence::SequenceHeader;
241 use ec_core::{BitReader, BitWriter};
242
243 /// A realistic 1920x1080 8-bit 4:2:0 main-profile sequence header.
244 pub(crate) fn sample_1080p() -> SequenceHeader {
245 SequenceHeader {
246 seq_profile: 0,
247 still_picture: false,
248 reduced_still_picture_header: false,
249 timing_info: None,
250 decoder_model_info: None,
251 initial_display_delay_present_flag: false,
252 operating_points: vec![OperatingPoint {
253 idc: 0,
254 seq_level_idx: 8, // level 4.0; > 7 so seq_tier is coded
255 seq_tier: 0,
256 decoder_model_present: false,
257 decoder_buffer_delay: 0,
258 encoder_buffer_delay: 0,
259 low_delay_mode_flag: false,
260 initial_display_delay: 0,
261 }],
262 operating_point: 0,
263 operating_point_idc: 0,
264 frame_width_bits: 11,
265 frame_height_bits: 11,
266 max_frame_width: 1920,
267 max_frame_height: 1080,
268 frame_id_numbers_present_flag: false,
269 delta_frame_id_length: 0,
270 additional_frame_id_length: 0,
271 use_128x128_superblock: true,
272 enable_filter_intra: true,
273 enable_intra_edge_filter: true,
274 enable_interintra_compound: false,
275 enable_masked_compound: false,
276 enable_warped_motion: false,
277 enable_dual_filter: true,
278 enable_order_hint: true,
279 enable_jnt_comp: false,
280 enable_ref_frame_mvs: false,
281 seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS,
282 seq_force_integer_mv: SELECT_INTEGER_MV,
283 order_hint_bits: 7,
284 enable_superres: false,
285 enable_cdef: true,
286 enable_restoration: false,
287 color_config: ColorConfig {
288 bit_depth: 8,
289 mono_chrome: false,
290 num_planes: 3,
291 color_primaries: 2,
292 transfer_characteristics: 2,
293 matrix_coefficients: 2,
294 color_range: false,
295 subsampling_x: 1,
296 subsampling_y: 1,
297 chroma_sample_position: ChromaSamplePosition::Unknown,
298 separate_uv_delta_q: false,
299 },
300 film_grain_params_present: false,
301 }
302 }
303
304 #[test]
305 fn sequence_header_roundtrip() {
306 let original = sample_1080p();
307 let mut w = BitWriter::new();
308 write_sequence_header(&mut w, &original).unwrap();
309 let payload = w.into_bytes();
310
311 let mut r = BitReader::new(&payload);
312 let parsed = SequenceHeader::parse(&mut r).unwrap();
313 assert_eq!(parsed, original);
314 }
315
316 #[test]
317 fn sequence_header_obu_size_matches_payload() {
318 let s = sample_1080p();
319
320 // The payload the OBU must carry.
321 let mut w = BitWriter::new();
322 write_sequence_header(&mut w, &s).unwrap();
323 let payload = w.into_bytes();
324
325 let obu = sequence_header_obu(&s).unwrap();
326
327 // Header (no extension) → leb128 size → payload.
328 let mut r = BitReader::new(&obu);
329 let h = ObuHeader::parse(&mut r).unwrap();
330 assert_eq!(h.obu_type, ObuType::SequenceHeader);
331 assert!(h.has_size_field);
332 let size = read_leb128(&mut r).unwrap();
333 assert_eq!(size as usize, payload.len());
334
335 // The trailing slice re-parses to the same header.
336 let body = &obu[obu.len() - payload.len()..];
337 let mut r2 = BitReader::new(body);
338 let parsed = SequenceHeader::parse(&mut r2).unwrap();
339 assert_eq!(parsed, s);
340 }
341}