forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

decoder.rs621 lines, 20.7 KiBHistoryRawDownload
1//! Frame header parsing, macroblock-row decoding and picture assembly.
2
3use ec_core::error::{Error, Result};
4use ec_core::frame::{ColorInfo, Interlace, PixelFormat, Plane, VideoFrame};
5
6use crate::bits::BitReader;
7use crate::idct::{Block, IdctPut, idct_for};
8use crate::tables::{CodeSet, FLAG_MBAFF, ZIGZAG, cid_entry};
9
10/// Chroma layout of a decoded picture.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Chroma {
13 /// 4:2:2 (half-width chroma).
14 C422,
15 /// 4:4:4.
16 C444,
17}
18
19/// What the frame header said about a picture.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct FrameInfo {
22 /// Compression id (1235-1260 DNxHD, 1270-1274 DNxHR).
23 pub cid: u32,
24 /// Coded sample depth: 8, 10 or 12.
25 pub bit_depth: u32,
26 /// Chroma layout.
27 pub chroma: Chroma,
28 /// Picture width in pixels (after the CID's own width override).
29 pub width: u32,
30 /// Picture height in pixels.
31 pub height: u32,
32 /// Two coded fields.
33 pub interlaced: bool,
34 /// The top field comes first (meaningful when `interlaced`).
35 pub top_field_first: bool,
36 /// Adaptive macroblock interlace (CID 1260).
37 pub mbaff: bool,
38 /// Sample aspect ratio implied by a CID that stores fewer columns than the
39 /// header's width (1440 of 1920, 960 of 1280), as `(num, den)`.
40 pub sample_aspect_ratio: Option<(u32, u32)>,
41 /// `matrix_coefficients` code point of the header's colour field.
42 pub matrix: u8,
43}
44
45/// A decoded picture at its coded bit depth: three tightly packed planes of
46/// `u16` samples.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Picture {
49 /// Header facts.
50 pub info: FrameInfo,
51 /// Y, Cb, Cr; `info.width` (or half, rounded up, for 4:2:2 chroma) samples per row.
52 pub planes: [Vec<u16>; 3],
53 /// Samples per row of each plane.
54 pub strides: [usize; 3],
55}
56
57/// Largest picture area decoded (8192x4608).
58const MAX_PIXELS: u64 = 8192 * 4608;
59
60struct Header {
61 info: FrameInfo,
62 cur_field: usize,
63 mb_width: usize,
64 mb_height: usize,
65 data_offset: usize,
66 coding_unit_size: usize,
67 scan: Vec<u32>,
68 code_set_key: (u32, u32),
69 hqx: bool,
70}
71
72fn be16(b: &[u8], o: usize) -> u32 {
73 u32::from(b[o]) << 8 | u32::from(b[o + 1])
74}
75fn be32(b: &[u8], o: usize) -> u32 {
76 be16(b, o) << 16 | be16(b, o + 2)
77}
78
79fn parse_header(buf: &[u8], first_field: bool, prev_field: usize) -> Result<Header> {
80 if buf.len() < 0x280 {
81 return Err(Error::corrupt(format!("DNxHD frame too small ({} < 640)", buf.len())));
82 }
83 let prefix = u64::from(be32(buf, 0)) << 16 | u64::from(buf[4]) << 8;
84 let hr = {
85 let off = prefix >> 16;
86 (prefix & 0xFFFF_0000_FFFF) == 0x0300 && (0x0280..=0x2170).contains(&off) && off & 3 == 0
87 };
88 if !(prefix == 0x0000_0280_0100 || prefix == 0x0000_0280_0200 || hr) {
89 return Err(Error::corrupt("DNxHD: unknown header prefix"));
90 }
91 let interlaced = buf[5] & 2 != 0;
92 let cur_field = if interlaced {
93 if first_field { usize::from(buf[5] & 1) } else { 1 - prev_field }
94 } else {
95 0
96 };
97 let top_first = interlaced && ((usize::from(first_field)) ^ cur_field) != 0;
98 let mbaff = (buf[6] >> 5) & 1 != 0;
99 if buf[7] & 1 != 0 {
100 return Err(Error::unsupported(
101 "DNxHD alpha channel",
102 "streams with an alpha plane are refused",
103 ));
104 }
105 let mut height = be16(buf, 0x18);
106 let mut width = be16(buf, 0x1a);
107 let bit_depth = match buf[0x21] >> 5 {
108 1 => 8,
109 2 => 10,
110 3 => 12,
111 d => return Err(Error::corrupt(format!("DNxHD: unknown bit depth indicator {d}"))),
112 };
113 let cid = be32(buf, 0x28);
114 let entry = cid_entry(cid)
115 .ok_or_else(|| Error::unsupported(format!("DNxHD compression id {cid}"), "unknown cid"))?;
116 if entry.bit_depth != bit_depth && entry.bit_depth != 0 {
117 return Err(Error::corrupt(format!(
118 "DNxHD: bit depth {bit_depth} does not match cid {cid}"
119 )));
120 }
121 let matrix = match (buf[0x2c] >> 1) & 3 {
122 0 => 1,
123 1 => 9,
124 2 => 10,
125 _ => 2,
126 };
127 let act = buf[0x2c] & 1 != 0;
128 let is_444 = (buf[0x2c] >> 6) & 1 != 0;
129 if is_444 {
130 if bit_depth == 8 {
131 return Err(Error::unsupported("DNxHD 4:4:4 8-bit", "no such profile"));
132 }
133 if !act {
134 return Err(Error::unsupported(
135 "DNxHR 4:4:4 RGB (GBR planes)",
136 "only YCbCr 4:4:4 (ACT flag set, as ffmpeg writes it) is decoded",
137 ));
138 }
139 } else if act {
140 return Err(Error::unsupported(
141 "DNxHD adaptive colour transform",
142 "the ACT variants are refused",
143 ));
144 }
145 let hqx = cid == 1271;
146 let mut sar = None;
147 if entry.width != 0 && width != entry.width {
148 let g = gcd(width, entry.width);
149 sar = Some((width / g, entry.width / g));
150 width = entry.width;
151 }
152 if buf.len() < entry.coding_unit_size as usize {
153 return Err(Error::corrupt("DNxHD: incorrect frame size"));
154 }
155 let mb_width = width.div_ceil(16) as usize;
156 let mb_height = be16(buf, 0x16c) as usize;
157 if height.div_ceil(16) as usize == mb_height && interlaced {
158 height <<= 1;
159 }
160 let data_offset = if mb_height > 68 && hr {
161 0x170 + (mb_height << 2)
162 } else {
163 if mb_height > 68 {
164 return Err(Error::corrupt("DNxHD: mb height too big"));
165 }
166 0x280
167 };
168 if (mb_height << usize::from(interlaced)) > height.div_ceil(16) as usize {
169 return Err(Error::corrupt("DNxHD: mb height too big"));
170 }
171 if width == 0 || height == 0 || mb_height == 0 {
172 return Err(Error::corrupt("DNxHD: empty picture"));
173 }
174 // Allocation bound for hostile headers (8K UHD is the largest picture the
175 // format is used for).
176 if u64::from(width) * u64::from(height) > MAX_PIXELS {
177 return Err(Error::unsupported(
178 format!("DNxHD picture {width}x{height}"),
179 "larger than 8192x4608",
180 ));
181 }
182 if buf.len() < data_offset {
183 return Err(Error::corrupt("DNxHD: buffer too small for the scan index"));
184 }
185 let mut scan = Vec::with_capacity(mb_height);
186 for i in 0..mb_height {
187 let v = be32(buf, 0x170 + 4 * i);
188 if ((buf.len() - data_offset) as u64) < u64::from(v) {
189 return Err(Error::corrupt("DNxHD: invalid mb scan index"));
190 }
191 scan.push(v);
192 }
193 Ok(Header {
194 info: FrameInfo {
195 cid,
196 bit_depth,
197 chroma: if is_444 { Chroma::C444 } else { Chroma::C422 },
198 width,
199 height,
200 interlaced,
201 top_field_first: top_first,
202 mbaff,
203 sample_aspect_ratio: sar,
204 matrix,
205 },
206 cur_field,
207 mb_width,
208 mb_height,
209 data_offset,
210 coding_unit_size: entry.coding_unit_size as usize,
211 scan,
212 code_set_key: (cid, bit_depth),
213 hqx,
214 })
215}
216
217fn gcd(a: u32, b: u32) -> u32 {
218 if b == 0 { a } else { gcd(b, a % b) }
219}
220
221/// Per-bit-depth dequantisation parameters of the coefficient decoder.
222#[derive(Clone, Copy)]
223struct Quant {
224 index_bits: u32,
225 level_bias: i32,
226 level_shift: u32,
227 dc_shift: u32,
228}
229
230fn quant_for(info: &FrameInfo, hqx: bool) -> Quant {
231 let q = |index_bits, level_bias, level_shift, dc_shift| Quant {
232 index_bits,
233 level_bias,
234 level_shift,
235 dc_shift,
236 };
237 match (info.chroma, info.bit_depth) {
238 (Chroma::C444, 10) => q(6, 32, 6, 0),
239 (Chroma::C444, _) => q(6, 32, 4, 2),
240 (Chroma::C422, 12) => q(6, 8, 4, 2),
241 (Chroma::C422, 10) if hqx => q(6, 32, 6, 0),
242 (Chroma::C422, 10) => q(6, 8, 4, 0),
243 _ => q(4, 32, 6, 0),
244 }
245}
246
247/// Everything a row decoder reads and shares between rows.
248struct RowShared<'a> {
249 codes: &'a CodeSet,
250 quant: Quant,
251 is_444: bool,
252 mbaff: bool,
253 interlaced: bool,
254 cur_field: usize,
255 mb_width: usize,
256 bit_depth: u32,
257 idct: IdctPut,
258 /// Bytes per sample (1 or 2).
259 bps: usize,
260 /// Row pitch of each plane, in samples.
261 strides: [usize; 3],
262}
263
264struct RowState {
265 last_dc: [i32; 3],
266 last_qscale: i32,
267 luma_scale: [i32; 64],
268 chroma_scale: [i32; 64],
269}
270
271fn corrupt(what: &str) -> Error {
272 Error::corrupt(format!("DNxHD: {what}"))
273}
274
275fn decode_block(
276 sh: &RowShared,
277 st: &mut RowState,
278 r: &mut BitReader,
279 n: usize,
280 block: &mut Block,
281) -> Result<usize> {
282 *block = [[0; 8]; 8];
283 let cid = sh.codes.cid;
284 let component = if sh.is_444 { (n >> 1) % 3 } else if n & 2 != 0 { 1 + (n & 1) } else { 0 };
285 let (scale, weights) = if component != 0 {
286 (&st.chroma_scale, cid.chroma_weight)
287 } else {
288 (&st.luma_scale, cid.luma_weight)
289 };
290 let q = sh.quant;
291 r.refill();
292 let len = sh.codes.dc.get(r).ok_or_else(|| corrupt("bad dc code"))?;
293 if len != 0 {
294 let v = r.get(len) as i32;
295 let level = if v >> (len - 1) != 0 { v } else { v - ((1 << len) - 1) };
296 st.last_dc[component] = st.last_dc[component].wrapping_add(level.wrapping_shl(q.dc_shift));
297 }
298 block[0][0] = st.last_dc[component] as i16;
299 let eob = cid.eob_index;
300 let ac_info = cid.ac_info;
301 let mut i = 0usize;
302 loop {
303 r.refill();
304 let index1 = sh.codes.ac.get(r).ok_or_else(|| corrupt("bad ac code"))?;
305 if index1 == eob {
306 break;
307 }
308 let mut level = i32::from(ac_info[2 * index1 as usize]);
309 let flags = ac_info[2 * index1 as usize + 1];
310 let sign = -(r.get(1) as i32);
311 if flags & 1 != 0 {
312 level += (r.get(q.index_bits) as i32) << 7;
313 }
314 if flags & 2 != 0 {
315 let run = sh.codes.run.get(r).ok_or_else(|| corrupt("bad run code"))?;
316 i += run as usize;
317 }
318 i += 1;
319 if i > 63 {
320 return Err(corrupt("ac coefficient overrun"));
321 }
322 let j = ZIGZAG[i] as usize & 63;
323 level = level.wrapping_mul(scale[i]);
324 level = level.wrapping_add(scale[i] >> 1);
325 if q.level_bias < 32 || i32::from(weights[i]) != q.level_bias {
326 level = level.wrapping_add(q.level_bias);
327 }
328 level >>= q.level_shift;
329 block[j >> 3][j & 7] = ((level ^ sign) - sign) as i16;
330 }
331 Ok(i)
332}
333
334/// Decode macroblock row `data` (starting at the row's bit offset) into the
335/// plane windows `win` (one MB-row high: 16 lines, 32 for interlaced).
336fn decode_row(sh: &RowShared, data: &[u8], win: &mut [&mut [u8]; 3]) -> Result<()> {
337 let mut r = BitReader::new(data);
338 let mut st = RowState {
339 last_dc: [1 << (sh.bit_depth + 2); 3],
340 last_qscale: 0,
341 luma_scale: [0; 64],
342 chroma_scale: [0; 64],
343 };
344 let cid = sh.codes.cid;
345 let nblocks = if sh.is_444 { 12 } else { 8 };
346 let mut blocks = [[[0i16; 8]; 8]; 12];
347 let mut last = [0usize; 12];
348 for x in 0..sh.mb_width {
349 r.refill();
350 let (interlaced_mb, qscale) = if sh.mbaff {
351 (r.get(1) != 0, r.get(10) as i32)
352 } else {
353 (false, r.get(11) as i32)
354 };
355 let _act = r.get(1);
356 if qscale != st.last_qscale {
357 for i in 0..64 {
358 st.luma_scale[i] = qscale * i32::from(cid.luma_weight[i]);
359 st.chroma_scale[i] = qscale * i32::from(cid.chroma_weight[i]);
360 }
361 st.last_qscale = qscale;
362 }
363 for n in 0..nblocks {
364 last[n] = decode_block(sh, &mut st, &mut r, n, &mut blocks[n])?;
365 }
366 if r.overrun() {
367 return Err(corrupt("macroblock data past the end"));
368 }
369 // Destination geometry, mirroring the reference layout.
370 let mut dls = sh.strides;
371 let mut base = [0usize; 3];
372 if sh.interlaced {
373 for p in 0..3 {
374 dls[p] <<= 1;
375 if sh.cur_field != 0 {
376 base[p] = sh.strides[p];
377 }
378 }
379 }
380 let yoff = |p: usize, il: bool, dls: &[usize; 3]| if il { sh.strides[p] } else { dls[p] << 3 };
381 if interlaced_mb {
382 for d in &mut dls {
383 *d <<= 1;
384 }
385 }
386 let xl = x * 16;
387 let xc = if sh.is_444 { x * 16 } else { x * 8 };
388 let bps = sh.bps;
389 let mut put = |win: &mut [&mut [u8]; 3], p: usize, n: usize, off: usize| {
390 (sh.idct)(&mut blocks[n], &mut win[p][off * bps..], dls[p] * bps, last[n]);
391 };
392 let yo = yoff(0, interlaced_mb, &dls);
393 let co = yoff(1, interlaced_mb, &dls);
394 let b0 = base[0] + xl;
395 let b1 = base[1] + xc;
396 let b2 = base[2] + xc;
397 if !sh.is_444 {
398 put(win, 0, 0, b0);
399 put(win, 0, 1, b0 + 8);
400 put(win, 0, 4, b0 + yo);
401 put(win, 0, 5, b0 + yo + 8);
402 put(win, 1, 2, b1);
403 put(win, 2, 3, b2);
404 put(win, 1, 6, b1 + co);
405 put(win, 2, 7, b2 + co);
406 } else {
407 put(win, 0, 0, b0);
408 put(win, 0, 1, b0 + 8);
409 put(win, 0, 6, b0 + yo);
410 put(win, 0, 7, b0 + yo + 8);
411 put(win, 1, 2, b1);
412 put(win, 1, 3, b1 + 8);
413 put(win, 1, 8, b1 + co);
414 put(win, 1, 9, b1 + co + 8);
415 put(win, 2, 4, b2);
416 put(win, 2, 5, b2 + 8);
417 put(win, 2, 10, b2 + co);
418 put(win, 2, 11, b2 + co + 8);
419 }
420 }
421 Ok(())
422}
423
424/// A decoded frame as the decoder holds it: whole-macroblock planes of 8-bit
425/// samples or little-endian 16-bit samples (`bps` bytes each).
426pub(crate) struct Canvas {
427 pub info: FrameInfo,
428 pub planes: [Vec<u8>; 3],
429 /// Row pitch in bytes.
430 pub strides: [usize; 3],
431 pub bps: usize,
432}
433
434/// Decoder state kept between frames: the code tables of the last CID.
435pub(crate) struct Core {
436 codes: Option<CodeSet>,
437 pub threads: usize,
438}
439
440impl Core {
441 pub fn new(threads: usize) -> Core {
442 Core { codes: None, threads: threads.clamp(1, 6) }
443 }
444
445 pub fn decode(&mut self, data: &[u8]) -> Result<Canvas> {
446 let mut hdr = parse_header(data, true, 0)?;
447 let info = hdr.info.clone();
448 let is_444 = info.chroma == Chroma::C444;
449 let bps = if info.bit_depth > 8 { 2 } else { 1 };
450 // Canvas rows: whole macroblock rows of the whole frame (the header
451 // only guarantees the coded rows do not exceed these).
452 let rows = (info.height as usize).div_ceil(16) * 16;
453 let cstride = hdr.mb_width * if is_444 { 16 } else { 8 };
454 let ystride = hdr.mb_width * 16;
455 let strides = [ystride, cstride, cstride];
456 let mut planes: [Vec<u8>; 3] = [
457 vec![0; ystride * bps * rows],
458 vec![0; cstride * bps * rows],
459 vec![0; cstride * bps * rows],
460 ];
461 let units = if info.interlaced { 2 } else { 1 };
462 let mut off = 0usize;
463 for u in 0..units {
464 if u == 1 {
465 off += hdr.coding_unit_size;
466 if off >= data.len() {
467 return Err(corrupt("second field missing"));
468 }
469 let h2 = parse_header(&data[off..], false, hdr.cur_field)?;
470 if h2.info.cid != info.cid
471 || h2.info.width != info.width
472 || h2.info.bit_depth != info.bit_depth
473 || h2.info.chroma != info.chroma
474 || h2.mb_height != hdr.mb_height
475 {
476 return Err(corrupt("second field header differs from the first"));
477 }
478 hdr = h2;
479 }
480 self.decode_unit(&hdr, &data[off..], &info, strides, bps, &mut planes)?;
481 }
482 Ok(Canvas { info, planes, strides: strides.map(|s| s * bps), bps })
483 }
484
485 fn decode_unit(
486 &mut self,
487 hdr: &Header,
488 unit: &[u8],
489 info: &FrameInfo,
490 strides: [usize; 3],
491 bps: usize,
492 canvas: &mut [Vec<u8>; 3],
493 ) -> Result<()> {
494 if self.codes.as_ref().map(|c| (c.cid.cid, c.bit_depth)) != Some(hdr.code_set_key) {
495 let e = cid_entry(hdr.code_set_key.0).expect("cid validated by the header");
496 self.codes = Some(CodeSet::new(e, hdr.code_set_key.1));
497 }
498 let codes = self.codes.as_ref().unwrap();
499 if info.mbaff && codes.cid.flags & FLAG_MBAFF == 0 {
500 // The reference decoder only warns; so do we, by decoding as stated.
501 }
502 let sh = RowShared {
503 codes,
504 quant: quant_for(info, hdr.hqx),
505 is_444: info.chroma == Chroma::C444,
506 mbaff: info.mbaff,
507 interlaced: info.interlaced,
508 cur_field: hdr.cur_field,
509 mb_width: hdr.mb_width,
510 bit_depth: info.bit_depth,
511 idct: idct_for(info.bit_depth),
512 bps,
513 strides,
514 };
515 let body = &unit[hdr.data_offset..];
516 let lines = if info.interlaced { 32 } else { 16 };
517 let [cy, cu, cv] = canvas;
518 let mut work: Vec<(usize, [&mut [u8]; 3])> = cy
519 .chunks_mut(lines * strides[0] * bps)
520 .zip(cu.chunks_mut(lines * strides[1] * bps))
521 .zip(cv.chunks_mut(lines * strides[2] * bps))
522 .take(hdr.mb_height)
523 .enumerate()
524 .map(|(y, ((a, b), c))| (y, [a, b, c]))
525 .collect();
526 let nthreads = self.threads.min(work.len()).max(1);
527 let run = |items: &mut [(usize, [&mut [u8]; 3])]| -> Result<()> {
528 for (y, win) in items.iter_mut() {
529 let start = hdr.scan[*y] as usize;
530 decode_row(&sh, &body[start..], win)?;
531 }
532 Ok(())
533 };
534 if nthreads == 1 {
535 return run(&mut work);
536 }
537 // Rows are handed out one at a time, so a thread that gets descheduled
538 // or draws dense rows does not hold the others back.
539 let queue = std::sync::Mutex::new(work.into_iter());
540 let mut result = Ok(());
541 std::thread::scope(|s| {
542 let handles: Vec<_> = (0..nthreads)
543 .map(|_| {
544 let (queue, sh) = (&queue, &sh);
545 s.spawn(move || -> Result<()> {
546 loop {
547 let item = queue.lock().ok().and_then(|mut q| q.next());
548 let Some((y, mut win)) = item else { return Ok(()) };
549 let start = hdr.scan[y] as usize;
550 decode_row(sh, &body[start..], &mut win)?;
551 }
552 })
553 })
554 .collect();
555 for h in handles {
556 if let Err(e) = h.join().unwrap_or_else(|_| Err(corrupt("worker panicked"))) {
557 result = Err(e);
558 }
559 }
560 });
561 result
562 }
563}
564
565/// Visible-area planes at native depth as `u16`.
566pub(crate) fn to_picture(c: Canvas) -> Picture {
567 let info = c.info;
568 let (w, h) = (info.width as usize, info.height as usize);
569 let cw = if info.chroma == Chroma::C444 { w } else { w.div_ceil(2) };
570 let widths = [w, cw, cw];
571 let planes = std::array::from_fn(|p| {
572 let mut out = Vec::with_capacity(widths[p] * h);
573 for y in 0..h {
574 let row = &c.planes[p][y * c.strides[p]..y * c.strides[p] + widths[p] * c.bps];
575 if c.bps == 1 {
576 out.extend(row.iter().map(|&v| u16::from(v)));
577 } else {
578 out.extend(row.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])));
579 }
580 }
581 out
582 });
583 Picture { info, planes, strides: widths }
584}
585
586/// An [`ec_core::frame::VideoFrame`] from a decoded canvas: 8- and 10-bit
587/// samples are used as they are, 12-bit ones narrowed to 10 (`(v + 2) >> 2`).
588pub(crate) fn to_video_frame(mut c: Canvas) -> Result<VideoFrame> {
589 let info = c.info.clone();
590 let is_444 = info.chroma == Chroma::C444;
591 let format = match (is_444, info.bit_depth) {
592 (false, 8) => PixelFormat::I422,
593 (false, _) => PixelFormat::I210,
594 (true, 8) => PixelFormat::I444,
595 (true, _) => PixelFormat::I410,
596 };
597 if info.bit_depth == 12 {
598 for p in &mut c.planes {
599 for b in p.chunks_exact_mut(2) {
600 let v = (u32::from(u16::from_le_bytes([b[0], b[1]])) + 2) >> 2;
601 b.copy_from_slice(&(v.min(1023) as u16).to_le_bytes());
602 }
603 }
604 }
605 let planes = c
606 .planes
607 .into_iter()
608 .zip(c.strides)
609 .map(|(data, stride)| Plane::new(data, stride))
610 .collect();
611 let mut f = VideoFrame::try_new(format, info.width, info.height, planes)?;
612 f.color = ColorInfo { primaries: 2, transfer: 2, matrix: info.matrix, full_range: false };
613 f.interlace = if !info.interlaced {
614 Interlace::Progressive
615 } else if info.top_field_first {
616 Interlace::TopFieldFirst
617 } else {
618 Interlace::BottomFieldFirst
619 };
620 Ok(f)
621}