forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli6 days ago3927 commits

header.rs341 lines, 9.6 KiBHistoryRawDownload
1//! Sequence, GOP and picture headers and their extensions (ISO/IEC 13818-2 6.2).
2
3use crate::bits::Bits;
4use crate::tables::{DEFAULT_INTRA, ZIGZAG};
5use ec_core::error::{Error, Result};
6
7/// Largest picture the decoder accepts, per side and in samples.
8pub const MAX_DIMENSION: u32 = 8192;
9/// Largest luma area accepted.
10pub const MAX_AREA: u32 = 8192 * 4352;
11
12fn corrupt(msg: &str) -> Error {
13 Error::corrupt(format!("MPEG video: {msg}"))
14}
15
16/// Sequence-level parameters (sequence header plus sequence extension).
17#[derive(Debug, Clone)]
18pub struct SequenceInfo {
19 /// Coded luma width (horizontal_size_value plus extension).
20 pub width: u32,
21 /// Coded luma height.
22 pub height: u32,
23 /// aspect_ratio_information (4 bits).
24 pub aspect_ratio_code: u8,
25 /// frame_rate_code (4 bits).
26 pub frame_rate_code: u8,
27 /// Frame rate extension numerator (MPEG-2 only, 1 when absent).
28 pub frame_rate_ext_n: u32,
29 /// Frame rate extension denominator plus one (MPEG-2 only, 1 when absent).
30 pub frame_rate_ext_d: u32,
31 /// bit_rate (+ extension) in units of 400 bit/s.
32 pub bit_rate: u32,
33 /// MPEG-1 constrained_parameters_flag.
34 pub constrained_parameters: bool,
35 /// True when a sequence_extension followed (MPEG-2 syntax).
36 pub mpeg2: bool,
37 /// profile_and_level_indication (8 bits; 0 for MPEG-1).
38 pub profile_level: u8,
39 /// progressive_sequence.
40 pub progressive_sequence: bool,
41 /// chroma_format: 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4.
42 pub chroma_format: u8,
43 /// low_delay.
44 pub low_delay: bool,
45}
46
47impl SequenceInfo {
48 /// Frame rate as numerator and denominator, when the code is defined.
49 pub fn frame_rate(&self) -> Option<(u32, u32)> {
50 let (n, d) = match self.frame_rate_code {
51 1 => (24000, 1001),
52 2 => (24, 1),
53 3 => (25, 1),
54 4 => (30000, 1001),
55 5 => (30, 1),
56 6 => (50, 1),
57 7 => (60000, 1001),
58 8 => (60, 1),
59 _ => return None,
60 };
61 Some((n * self.frame_rate_ext_n, d * self.frame_rate_ext_d))
62 }
63
64 /// Macroblock columns.
65 pub fn mb_width(&self) -> usize {
66 self.width.div_ceil(16) as usize
67 }
68
69 /// Macroblock rows of a frame.
70 pub fn mb_height(&self) -> usize {
71 if self.progressive_sequence || !self.mpeg2 {
72 self.height.div_ceil(16) as usize
73 } else {
74 (self.height.div_ceil(32) * 2) as usize
75 }
76 }
77}
78
79/// The four quantiser matrices, raster order.
80#[derive(Debug, Clone)]
81pub struct QuantMatrices {
82 pub intra: [u8; 64],
83 pub non_intra: [u8; 64],
84 pub chroma_intra: [u8; 64],
85 pub chroma_non_intra: [u8; 64],
86}
87
88impl Default for QuantMatrices {
89 fn default() -> Self {
90 let mut intra = [0u8; 64];
91 for i in 0..64 {
92 intra[ZIGZAG[i] as usize] = DEFAULT_INTRA[i];
93 }
94 QuantMatrices {
95 intra,
96 non_intra: [16; 64],
97 chroma_intra: intra,
98 chroma_non_intra: [16; 64],
99 }
100 }
101}
102
103fn read_matrix(b: &mut Bits) -> [u8; 64] {
104 let mut m = [0u8; 64];
105 for &z in ZIGZAG.iter() {
106 m[z as usize] = b.read(8) as u8;
107 }
108 m
109}
110
111/// Parse a sequence header (the bytes after the start code).
112pub(crate) fn parse_sequence_header(data: &[u8], q: &mut QuantMatrices) -> Result<SequenceInfo> {
113 let mut b = Bits::new(data);
114 let width = b.read(12);
115 let height = b.read(12);
116 let aspect = b.read(4) as u8;
117 let frc = b.read(4) as u8;
118 let bit_rate = b.read(18);
119 b.skip(1); // marker
120 b.skip(10); // vbv_buffer_size_value
121 let constrained = b.read1();
122 let mut m = QuantMatrices::default();
123 if b.read1() {
124 m.intra = read_matrix(&mut b);
125 m.chroma_intra = m.intra;
126 }
127 if b.read1() {
128 m.non_intra = read_matrix(&mut b);
129 m.chroma_non_intra = m.non_intra;
130 }
131 if b.overrun() {
132 return Err(corrupt("truncated sequence header"));
133 }
134 if width == 0 || height == 0 {
135 return Err(corrupt("zero picture size"));
136 }
137 *q = m;
138 Ok(SequenceInfo {
139 width,
140 height,
141 aspect_ratio_code: aspect,
142 frame_rate_code: frc,
143 frame_rate_ext_n: 1,
144 frame_rate_ext_d: 1,
145 bit_rate,
146 constrained_parameters: constrained,
147 mpeg2: false,
148 profile_level: 0,
149 progressive_sequence: true,
150 chroma_format: 1,
151 low_delay: false,
152 })
153}
154
155/// Parse a sequence_extension (after the 4-bit id) into `seq`.
156pub(crate) fn parse_sequence_extension(b: &mut Bits, seq: &mut SequenceInfo) -> Result<()> {
157 let pl = b.read(8) as u8;
158 let progressive = b.read1();
159 let chroma = b.read(2) as u8;
160 let hext = b.read(2);
161 let vext = b.read(2);
162 let br_ext = b.read(12);
163 b.skip(1);
164 b.skip(8); // vbv_buffer_size_extension
165 let low_delay = b.read1();
166 let n = b.read(2);
167 let d = b.read(5);
168 if b.overrun() {
169 return Err(corrupt("truncated sequence extension"));
170 }
171 seq.width |= hext << 12;
172 seq.height |= vext << 12;
173 seq.bit_rate |= br_ext << 18;
174 seq.mpeg2 = true;
175 seq.profile_level = pl;
176 seq.progressive_sequence = progressive;
177 seq.chroma_format = chroma;
178 seq.low_delay = low_delay;
179 seq.frame_rate_ext_n = n + 1;
180 seq.frame_rate_ext_d = d + 1;
181 Ok(())
182}
183
184pub(crate) fn parse_quant_matrix_extension(
185 b: &mut Bits,
186 q: &mut QuantMatrices,
187 chroma_format: u8,
188) -> Result<()> {
189 if b.read1() {
190 q.intra = read_matrix(b);
191 if chroma_format == 1 {
192 q.chroma_intra = q.intra;
193 }
194 }
195 if b.read1() {
196 q.non_intra = read_matrix(b);
197 if chroma_format == 1 {
198 q.chroma_non_intra = q.non_intra;
199 }
200 }
201 if b.read1() {
202 q.chroma_intra = read_matrix(b);
203 }
204 if b.read1() {
205 q.chroma_non_intra = read_matrix(b);
206 }
207 if b.overrun() {
208 return Err(corrupt("truncated quant matrix extension"));
209 }
210 Ok(())
211}
212
213/// Picture coding type (3 bits in the picture header).
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
215pub enum PictureType {
216 /// Intra.
217 I,
218 /// Predictive.
219 P,
220 /// Bidirectional.
221 B,
222}
223
224/// How a coded picture covers the frame.
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226pub enum Structure {
227 /// A whole frame.
228 Frame,
229 /// The top field.
230 Top,
231 /// The bottom field.
232 Bottom,
233}
234
235/// Picture header plus picture_coding_extension.
236#[derive(Debug, Clone)]
237pub struct PictureHeader {
238 pub temporal_reference: u16,
239 pub picture_type: PictureType,
240 pub full_pel: [bool; 2],
241 /// f_code[s][t]: s = 0 forward / 1 backward, t = 0 horizontal / 1 vertical.
242 pub f_code: [[u8; 2]; 2],
243 pub intra_dc_precision: u8,
244 pub structure: Structure,
245 pub top_field_first: bool,
246 pub frame_pred_frame_dct: bool,
247 pub concealment_motion_vectors: bool,
248 pub q_scale_type: bool,
249 pub intra_vlc_format: bool,
250 pub alternate_scan: bool,
251 pub repeat_first_field: bool,
252 pub chroma_420_type: bool,
253 pub progressive_frame: bool,
254 /// True once a picture_coding_extension was parsed.
255 pub has_extension: bool,
256}
257
258pub(crate) fn parse_picture_header(data: &[u8]) -> Result<PictureHeader> {
259 let mut b = Bits::new(data);
260 let tr = b.read(10) as u16;
261 let t = b.read(3);
262 b.skip(16); // vbv_delay
263 let picture_type = match t {
264 1 => PictureType::I,
265 2 => PictureType::P,
266 3 => PictureType::B,
267 4 => {
268 return Err(Error::unsupported(
269 "MPEG-1 D-picture",
270 "DC-only pictures (picture_coding_type 4) are not decoded",
271 ));
272 }
273 _ => return Err(corrupt("reserved picture_coding_type")),
274 };
275 let mut full_pel = [false; 2];
276 let mut f_code = [[15u8; 2]; 2];
277 if picture_type != PictureType::I {
278 full_pel[0] = b.read1();
279 let f = b.read(3) as u8;
280 f_code[0] = [f, f];
281 if picture_type == PictureType::B {
282 full_pel[1] = b.read1();
283 let f = b.read(3) as u8;
284 f_code[1] = [f, f];
285 }
286 }
287 if b.overrun() {
288 return Err(corrupt("truncated picture header"));
289 }
290 Ok(PictureHeader {
291 temporal_reference: tr,
292 picture_type,
293 full_pel,
294 f_code,
295 intra_dc_precision: 0,
296 structure: Structure::Frame,
297 top_field_first: false,
298 frame_pred_frame_dct: true,
299 concealment_motion_vectors: false,
300 q_scale_type: false,
301 intra_vlc_format: false,
302 alternate_scan: false,
303 repeat_first_field: false,
304 chroma_420_type: true,
305 progressive_frame: true,
306 has_extension: false,
307 })
308}
309
310pub(crate) fn parse_picture_coding_extension(b: &mut Bits, h: &mut PictureHeader) -> Result<()> {
311 let mut f_code = [[0u8; 2]; 2];
312 for s in 0..2 {
313 for t in 0..2 {
314 f_code[s][t] = b.read(4) as u8;
315 }
316 }
317 let dc = b.read(2) as u8;
318 let structure = match b.read(2) {
319 1 => Structure::Top,
320 2 => Structure::Bottom,
321 3 => Structure::Frame,
322 _ => return Err(corrupt("reserved picture_structure")),
323 };
324 h.top_field_first = b.read1();
325 h.frame_pred_frame_dct = b.read1();
326 h.concealment_motion_vectors = b.read1();
327 h.q_scale_type = b.read1();
328 h.intra_vlc_format = b.read1();
329 h.alternate_scan = b.read1();
330 h.repeat_first_field = b.read1();
331 h.chroma_420_type = b.read1();
332 h.progressive_frame = b.read1();
333 if b.overrun() {
334 return Err(corrupt("truncated picture coding extension"));
335 }
336 h.f_code = f_code;
337 h.intra_dc_precision = dc;
338 h.structure = structure;
339 h.has_extension = true;
340 Ok(())
341}