forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

slice.rs567 lines, 19.3 KiBHistoryRawDownload
1//! Slice decoding: entropy-coded DC/AC coefficients, dequantisation, IDCT, alpha.
2
3use ec_core::error::{Error, Result};
4
5use crate::idct::idct_put;
6use crate::tables::*;
7
8/// MSB-first bit reader over a zero-padded copy of one component (at least 8 bytes of padding),
9/// so a 64-bit window can always be loaded. Reads past the end return zeros and are
10/// reported by [`Br::overrun`].
11pub struct Br<'a> {
12 buf: &'a [u8],
13 /// Real data length in bits.
14 total: usize,
15 pos: usize,
16 err: bool,
17}
18
19/// Sentinel length for an oversized codeword.
20const BAD: u32 = 255;
21
22impl<'a> Br<'a> {
23 /// `buf` is the component data followed by at least 8 zero bytes; `len` the data length.
24 pub fn new(buf: &'a [u8], len: usize) -> Self {
25 debug_assert!(buf.len() >= len + 8);
26 Br { buf, total: len * 8, pos: 0, err: false }
27 }
28
29 /// 64 bits at the current position (the top 57 are always valid).
30 #[inline(always)]
31 fn peek(&self) -> u64 {
32 let byte = (self.pos >> 3).min(self.buf.len() - 8);
33 let w = u64::from_be_bytes(self.buf[byte..byte + 8].try_into().unwrap());
34 w << (self.pos & 7)
35 }
36
37 #[inline(always)]
38 fn advance(&mut self, n: u32) {
39 self.pos += n as usize;
40 }
41
42 #[inline(always)]
43 fn bits(&mut self, n: u32) -> u32 {
44 let v = ((self.peek() >> 1) >> (63 - n)) as u32;
45 self.advance(n);
46 v
47 }
48
49 #[inline(always)]
50 pub fn overrun(&self) -> bool {
51 self.err || self.pos > self.total
52 }
53
54 #[inline(always)]
55 fn left(&self) -> usize {
56 self.total.saturating_sub(self.pos)
57 }
58
59 /// Decode one Rice / exp-Golomb hybrid codeword from the window `w` (RDD 36 section
60 /// 7.1.1): `(value, length)`, length [`BAD`] when oversized.
61 #[inline(always)]
62 fn decode_w(cb: u8, w: u64) -> (u32, u32) {
63 let switch_bits = u32::from(cb & 3) + 1;
64 let rice = u32::from(cb >> 5);
65 let exp = u32::from((cb >> 2) & 7);
66 let q = w.leading_zeros();
67 if q < switch_bits {
68 let r = (((w << (q + 1)) >> 1) >> (63 - rice)) as u32;
69 ((q << rice) + r, q + 1 + rice)
70 } else {
71 if q > 24 {
72 return (0, BAD);
73 }
74 let nb = q - switch_bits + exp; // bits after the leading 1, at most 30
75 let rest = (((w << (q + 1)) >> 1) >> (63 - nb)) as u32;
76 (((1u32 << nb) + rest - (1 << exp)) + (switch_bits << rice), q + 1 + nb)
77 }
78 }
79
80 #[inline(always)]
81 fn codeword(&mut self, cb: u8) -> u32 {
82 let (v, l) = Self::decode_w(cb, self.peek());
83 if l == BAD {
84 self.err = true;
85 return 0;
86 }
87 self.advance(l);
88 v
89 }
90}
91
92/// 8-bit-window lookup tables for the codebooks the AC coefficients use, indexed by
93/// `context * 256 + window byte`. Entry bits: 0..6 code length (0 when the code is longer than
94/// 8 bits; level entries include the sign bit), 8..20 decoded value, 20.. the table offset (`context * 256`) of the next code of the
95/// same kind, so the dependent chain through the tables needs no clamping.
96struct Luts {
97 run: [u32; 16 * 256],
98 level: [u32; 10 * 256],
99 /// DC codebooks, entry `value << 4 | length`, 0 for codes over 8 bits.
100 dc: [[u16; 256]; 7],
101}
102
103fn luts() -> &'static Luts {
104 static L: std::sync::OnceLock<Box<Luts>> = std::sync::OnceLock::new();
105 L.get_or_init(|| {
106 let mut l = Box::new(Luts { run: [0; 16 * 256], level: [0; 10 * 256], dc: [[0; 256]; 7] });
107 for ctx in 0..7 {
108 for i in 0..256usize {
109 let (v, n) = Br::decode_w(DC_CB[ctx], (i as u64) << 56);
110 if n <= 8 && v < 4096 {
111 l.dc[ctx][i] = (v as u16) << 4 | n as u16;
112 }
113 }
114 }
115 for ctx in 0..16 {
116 for i in 0..256usize {
117 let (v, n) = Br::decode_w(RUN_CB[ctx], (i as u64) << 56);
118 if n <= 8 && v < 4000 {
119 l.run[ctx * 256 + i] = n | (v + 1) << 8 | (v.min(15) << 8) << 20;
120 }
121 }
122 }
123 for ctx in 0..10 {
124 for i in 0..256usize {
125 let (v, n) = Br::decode_w(LEVEL_CB[ctx], (i as u64) << 56);
126 if n <= 8 && v < 4096 {
127 l.level[ctx * 256 + i] = (n + 1) | v << 8 | ((v + 1).min(9) << 8) << 20;
128 }
129 }
130 }
131 l
132 })
133}
134
135fn decode_dc(br: &mut Br, out: &mut [i16], nblocks: usize, q: &[i16; 64]) -> Result<()> {
136 let mut code = br.codeword(FIRST_DC_CB);
137 let mut prev = (((code >> 1) as i32) ^ -((code & 1) as i32)) as i16;
138 let q0 = i32::from(q[0]);
139 out[0] = (i32::from(prev).wrapping_mul(q0)) as i16;
140 let lt = luts();
141 let mut delta: i16 = 3;
142 // The first delta's codebook is fixed (index 5), whatever the first DC code was.
143 code = 5;
144 for b in 1..nblocks {
145 let ctx = (code as usize).min(6);
146 let e = lt.dc[ctx][(br.peek() >> 56) as usize];
147 if e & 15 != 0 {
148 br.advance(u32::from(e & 15));
149 code = u32::from(e >> 4);
150 } else {
151 code = br.codeword(DC_CB[ctx]);
152 }
153 let sign: i32 = -((((delta >> 15) & 1) as i32) ^ (code & 1) as i32);
154 delta = ((((code.wrapping_add(1)) >> 1) as i32 ^ sign) - sign) as i16;
155 prev = prev.wrapping_add(delta);
156 out[b * 64] = (i32::from(prev).wrapping_mul(q0)) as i16;
157 }
158 if br.overrun() {
159 return Err(Error::corrupt("ProRes slice: DC data past the component size or oversized codeword"));
160 }
161 Ok(())
162}
163
164/// Register-buffered AC decoder for one component of one slice. Several of these advance
165/// in lock step so the CPU overlaps their (latency-bound) bit-stream dependency chains.
166struct AcState<'a> {
167 buf: &'a [u8],
168 total: usize,
169 ptr: usize,
170 acc: u64,
171 cnt: u32,
172 roff: usize,
173 loff: usize,
174 pos: usize,
175 log2: u32,
176 mask: usize,
177 max_coeffs: usize,
178 out: &'a mut [i16],
179 scan: &'a [u8; 64],
180 q: &'a [i16; 64],
181}
182
183impl<'a> AcState<'a> {
184 /// `buf`: component data plus at least 40 zero bytes; `bitpos` where the AC data starts.
185 fn new(buf: &'a [u8], len: usize, bitpos: usize, out: &'a mut [i16], nblocks: usize, scan: &'a [u8; 64], q: &'a [i16; 64]) -> Self {
186 let (ptr, acc, cnt) = sync(buf, bitpos);
187 let log2 = nblocks.trailing_zeros();
188 AcState {
189 buf,
190 total: len * 8,
191 ptr,
192 acc,
193 cnt,
194 roff: 4 << 8,
195 loff: 2 << 8,
196 pos: nblocks - 1,
197 log2,
198 mask: nblocks - 1,
199 max_coeffs: 64usize << log2,
200 out,
201 scan,
202 q,
203 }
204 }
205
206 /// Stores one decoded coefficient (`level` is the raw level, one less than its magnitude).
207 #[inline(always)]
208 fn put(&mut self, run: u32, level: u32, sign: u64) -> Result<()> {
209 self.pos += run as usize;
210 if self.pos >= self.max_coeffs {
211 return Err(Error::corrupt("ProRes slice: AC run past the block"));
212 }
213 let sign = sign as i32;
214 let v = (((level as i32 + 1) ^ -sign) + sign) as i16;
215 let at = self.scan[(self.pos >> self.log2) & 63] as usize & 63;
216 let idx = ((self.pos & self.mask) << 6) + at;
217 self.out[idx] = i32::from(v).wrapping_mul(i32::from(self.q[at])) as i16;
218 Ok(())
219 }
220
221 /// One coefficient; `Ok(false)` when it took the slow path (state resynchronised).
222 #[inline(always)]
223 fn step(&mut self, lt: &Luts) -> Result<bool> {
224 let w = self.acc;
225 let e1 = lt.run[self.roff + (w >> 56) as usize];
226 let l1 = e1 & 63;
227 let w1 = w << l1;
228 let e2 = lt.level[self.loff + (w1 >> 56) as usize];
229 let l2 = e2 & 63;
230 if (l1 != 0) & (l2 != 0) {
231 self.acc = w1 << l2;
232 self.cnt -= l1 + l2;
233 self.roff = (e1 >> 20) as usize;
234 self.loff = (e2 >> 20) as usize;
235 self.put((e1 >> 8) & 0xfff, (e2 >> 8) & 0xfff, (w1 >> (64 - l2)) & 1)?;
236 Ok(true)
237 } else {
238 self.slow()?;
239 Ok(false)
240 }
241 }
242
243 #[cold]
244 #[inline(never)]
245 fn slow(&mut self) -> Result<()> {
246 let buf = self.buf;
247 let at = self.ptr * 8 - self.cnt as usize;
248 let (run, a) = Br::decode_w(RUN_CB[self.roff >> 8], be_at(buf, at));
249 if a == BAD {
250 return Err(Error::corrupt("ProRes slice: oversized AC run codeword"));
251 }
252 let (level, b) = Br::decode_w(LEVEL_CB[self.loff >> 8], be_at(buf, at + a as usize));
253 if b == BAD {
254 return Err(Error::corrupt("ProRes slice: oversized AC level codeword"));
255 }
256 let sign = be_at(buf, at + (a + b) as usize) >> 63;
257 (self.ptr, self.acc, self.cnt) = sync(buf, at + (a + b) as usize + 1);
258 self.roff = (run.min(15) as usize) << 8;
259 self.loff = ((level + 1).min(9) as usize) << 8;
260 self.put(run + 1, level, sign)
261 }
262
263 /// Decodes a few coefficients; `Ok(true)` when the component is finished.
264 #[inline(always)]
265 fn advance(&mut self, lt: &Luts) -> Result<bool> {
266 // Branch-free refill to at least 57 valid bits.
267 self.acc |= be64(self.buf, self.ptr) >> self.cnt;
268 let take = (64 - self.cnt) >> 3;
269 self.ptr += take as usize;
270 self.cnt += take * 8;
271 let left = self.total.saturating_sub(self.ptr * 8 - self.cnt as usize);
272 if left < 192 {
273 // Near the end: all-zero padding terminates the data.
274 if left < 32 && (left == 0 || (self.acc >> (64 - left as u32)) == 0) {
275 return self.finish();
276 }
277 self.step(lt)?;
278 } else if self.step(lt)? && self.step(lt)? {
279 // 57+ bits cover three fast coefficients (17 bits at most each).
280 self.step(lt)?;
281 }
282 Ok(false)
283 }
284
285 fn finish(&self) -> Result<bool> {
286 if self.ptr * 8 - self.cnt as usize > self.total {
287 return Err(Error::corrupt("ProRes slice: AC data past the component size"));
288 }
289 Ok(true)
290 }
291}
292
293/// Runs one or two AC decoders to completion, interleaved.
294fn run_ac(a: &mut AcState, b: Option<&mut AcState>) -> Result<()> {
295 let lt = luts();
296 match b {
297 Some(b) => {
298 let (mut da, mut db) = (false, false);
299 while !(da || db) {
300 da = a.advance(lt)?;
301 db = b.advance(lt)?;
302 }
303 while !da {
304 da = a.advance(lt)?;
305 }
306 while !db {
307 db = b.advance(lt)?;
308 }
309 }
310 None => while !a.advance(lt)? {},
311 }
312 Ok(())
313}
314
315#[inline(always)]
316fn be64(buf: &[u8], at: usize) -> u64 {
317 u64::from_be_bytes(buf[at..at + 8].try_into().unwrap())
318}
319
320/// Register bit buffer state `(ptr, acc, cnt)` for stream bit position `pos`: `acc` holds `cnt`
321/// valid bits MSB-first (the bits below are zero or the true following bits), the next
322/// unloaded byte is `ptr`, and the consumed position is `ptr * 8 - cnt`.
323#[inline(always)]
324fn sync(buf: &[u8], pos: usize) -> (usize, u64, u32) {
325 let p = pos >> 3;
326 (p + 7, be64(buf, p) << (pos & 7), 56 - (pos & 7) as u32)
327}
328
329/// 64 bits at bit position `pos`, the top 57 valid.
330#[inline(always)]
331fn be_at(buf: &[u8], pos: usize) -> u64 {
332 be64(buf, pos >> 3) << (pos & 7)
333}
334
335/// Everything slice decoding needs to know about the picture.
336pub struct SliceCtx<'a> {
337 pub is_444: bool,
338 pub alpha_bits: u8,
339 pub scan: &'a [u8; 64],
340 pub qmat_luma: &'a [u8; 64],
341 pub qmat_chroma: &'a [u8; 64],
342 /// 12-bit output (4:4:4) rather than 10-bit.
343 pub b12: bool,
344}
345
346/// Destination rows of one group of macroblock rows. Planes are little-endian `u16` samples, rows
347/// `16 * mb_rows` tall, `ys`/`cs` samples wide.
348pub struct RowBuf {
349 pub y: Vec<u8>,
350 pub u: Vec<u8>,
351 pub v: Vec<u8>,
352 pub a: Vec<u16>,
353 pub ys: usize,
354 pub cs: usize,
355}
356
357pub struct Scratch {
358 coef: [Vec<i16>; 2],
359 pad: [Vec<u8>; 2],
360 alpha: Vec<u16>,
361}
362
363impl Scratch {
364 pub fn new() -> Self {
365 Scratch { coef: [vec![0; 64 * 32], vec![0; 64 * 32]], pad: [Vec::new(), Vec::new()], alpha: Vec::new() }
366 }
367}
368
369/// Quantiser (raster order in the header) times the slice quantiser, as the 16-bit values
370/// ffmpeg multiplies by, in transposed layout (`[col * 8 + row]`) to match the blocks.
371fn scaled(q: &[u8; 64], qscale: i32) -> [i16; 64] {
372 let mut o = [0i16; 64];
373 for i in 0..64 {
374 o[(i & 7) * 8 + (i >> 3)] = (i32::from(q[i]) * qscale) as i16;
375 }
376 o
377}
378
379/// One slice to decode: its bytes and where it lands (macroblock column, group-relative row).
380pub struct SliceIn<'a> {
381 pub data: &'a [u8],
382 pub mb_count: usize,
383 pub mb_x: usize,
384 pub row: usize,
385}
386
387struct Parsed<'a> {
388 comp: [&'a [u8]; 3],
389 alpha: &'a [u8],
390 q: [[i16; 64]; 2],
391 mb_count: usize,
392 mb_x: usize,
393 row: usize,
394}
395
396fn parse<'a>(cx: &SliceCtx, s: &SliceIn<'a>) -> Result<Parsed<'a>> {
397 let data = s.data;
398 let hdr = usize::from(data.first().copied().unwrap_or(0) >> 3);
399 if hdr < 6 || hdr > data.len() {
400 return Err(Error::corrupt(format!("ProRes slice header: size {hdr}")));
401 }
402 let idx = i32::from(data[1]);
403 let qscale = if idx > 128 { (idx - 96) << 2 } else { idx };
404 let ysz = usize::from(u16::from_be_bytes([data[2], data[3]]));
405 let usz = usize::from(u16::from_be_bytes([data[4], data[5]]));
406 let total = data.len();
407 let rest = total - hdr;
408 let vsz = if hdr > 7 {
409 usize::from(u16::from_be_bytes([data[6], data[7]]))
410 } else {
411 rest.checked_sub(ysz + usz).ok_or_else(|| Error::corrupt("ProRes slice: component sizes past the slice"))?
412 };
413 // With alpha, the remainder after Y/U/V is the alpha data.
414 let yuv = ysz + usz + vsz;
415 if yuv > rest {
416 return Err(Error::corrupt("ProRes slice: component sizes past the slice"));
417 }
418 let asz = if cx.alpha_bits != 0 { rest - yuv } else { 0 };
419 let body = &data[hdr..];
420 Ok(Parsed {
421 comp: [&body[..ysz], &body[ysz..ysz + usz], &body[ysz + usz..yuv]],
422 alpha: &body[yuv..yuv + asz],
423 q: [scaled(cx.qmat_luma, qscale), scaled(cx.qmat_chroma, qscale)],
424 mb_count: s.mb_count,
425 mb_x: s.mb_x,
426 row: s.row,
427 })
428}
429
430/// Zeroes the coefficient buffer, copies the component behind zero padding and decodes its DC
431/// coefficients; returns the bit position where the AC data starts.
432fn prep(pad: &mut Vec<u8>, coef: &mut [i16], data: &[u8], nblocks: usize, q: &[i16; 64]) -> Result<usize> {
433 coef.fill(0);
434 pad.clear();
435 pad.extend_from_slice(data);
436 pad.extend_from_slice(&[0; 40]);
437 let mut br = Br::new(pad, data.len());
438 decode_dc(&mut br, coef, nblocks, q)?;
439 Ok(br.pos)
440}
441
442/// Inverse transform every block of one component of one slice into `dst`.
443fn put_blocks(cx: &SliceCtx, comp: usize, p: &Parsed, coef: &mut [i16], dst: &mut [u8], stride: usize) {
444 let (per_mb, mbw) = match (comp, cx.is_444) {
445 (0, _) | (_, true) => (4, 16),
446 _ => (2, 8),
447 };
448 let base = p.row * 16 * stride + p.mb_x * mbw;
449 for m in 0..p.mb_count {
450 for k in 0..per_mb {
451 let off = match (comp, cx.is_444) {
452 (0, _) => base + m * 16 + (k & 1) * 8 + (k >> 1) * 8 * stride,
453 (_, true) => base + m * 16 + (k >> 1) * 8 + (k & 1) * 8 * stride,
454 _ => base + m * 8 + k * 8 * stride,
455 };
456 let i = m * per_mb + k;
457 let blk: &mut [i16; 64] = (&mut coef[i * 64..i * 64 + 64]).try_into().unwrap();
458 if cx.b12 {
459 idct_put::<true>(&mut dst[off * 2..], stride, blk);
460 } else {
461 idct_put::<false>(&mut dst[off * 2..], stride, blk);
462 }
463 }
464 }
465}
466
467fn blocks(cx: &SliceCtx, comp: usize, mb_count: usize) -> usize {
468 if comp == 0 || cx.is_444 { mb_count * 4 } else { mb_count * 2 }
469}
470
471/// Decode one or two slices into `rb`. Two slices have their entropy decoding interleaved,
472/// which hides the latency of the serial bit-stream parsing.
473pub fn decode_slices(cx: &SliceCtx, items: &[SliceIn], rb: &mut RowBuf, sc: &mut Scratch) -> Result<()> {
474 let pa = parse(cx, &items[0])?;
475 let pb = items.get(1).map(|s| parse(cx, s)).transpose()?;
476 let Scratch { coef, pad, alpha } = sc;
477 let [coef_a, coef_b] = coef;
478 let [pad_a, pad_b] = pad;
479 for comp in 0..3 {
480 let qi = usize::from(comp != 0);
481 let na = blocks(cx, comp, pa.mb_count);
482 let (ca, cb) = (&mut coef_a[..na * 64], &mut coef_b[..]);
483 let posa = prep(pad_a, ca, pa.comp[comp], na, &pa.q[qi])?;
484 let nb = pb.as_ref().map_or(0, |p| blocks(cx, comp, p.mb_count));
485 let posb = match &pb {
486 Some(p) => prep(pad_b, &mut cb[..nb * 64], p.comp[comp], nb, &p.q[qi])?,
487 None => 0,
488 };
489 let mut sa = AcState::new(pad_a, pa.comp[comp].len(), posa, ca, na, cx.scan, &pa.q[qi]);
490 let mut sb = pb.as_ref().map(|p| AcState::new(pad_b, p.comp[comp].len(), posb, &mut cb[..nb * 64], nb, cx.scan, &p.q[qi]));
491 run_ac(&mut sa, sb.as_mut())?;
492
493 let (ys, cs) = (rb.ys, rb.cs);
494 let (dst, stride) = match comp {
495 0 => (&mut rb.y, ys),
496 1 => (&mut rb.u, cs),
497 _ => (&mut rb.v, cs),
498 };
499 put_blocks(cx, comp, &pa, &mut coef_a[..na * 64], dst, stride);
500 if let Some(p) = &pb {
501 put_blocks(cx, comp, p, &mut coef_b[..nb * 64], dst, stride);
502 }
503 }
504 if cx.alpha_bits != 0 {
505 for p in std::iter::once(&pa).chain(pb.as_ref()) {
506 let n = p.mb_count * 256;
507 alpha.clear();
508 alpha.resize(n, 0);
509 unpack_alpha(p.alpha, alpha, cx.alpha_bits)?;
510 let w = p.mb_count * 16;
511 for r in 0..16 {
512 let o = (p.row * 16 + r) * rb.ys + p.mb_x * 16;
513 rb.a[o..o + w].copy_from_slice(&alpha[r * w..r * w + w]);
514 }
515 }
516 }
517 Ok(())
518}
519
520/// Run-length coded alpha (RDD 36 section 7.3). Output is 16-bit; 8-bit alpha is replicated
521/// into both bytes so full scale is 0xFFFF either way.
522fn unpack_alpha(d: &[u8], dst: &mut [u16], bits: u8) -> Result<()> {
523 let mut padded = d.to_vec();
524 padded.extend_from_slice(&[0; 8]);
525 let mut br = Br::new(&padded, d.len());
526 let n = dst.len();
527 let mask: i32 = (1 << bits) - 1;
528 let expand = |v: i32| -> u16 { if bits == 16 { v as u16 } else { ((v << 8) | v) as u16 } };
529 let mut idx = 0usize;
530 let mut alpha = mask;
531 while idx < n {
532 loop {
533 let val = if br.bits(1) != 0 {
534 br.bits(u32::from(bits)) as i32
535 } else {
536 let v = br.bits(if bits == 16 { 7 } else { 4 }) as i32;
537 let neg = v & 1 != 0;
538 let m = (v + 2) >> 1;
539 if neg { -m } else { m }
540 };
541 alpha = (alpha + val) & mask;
542 dst[idx] = expand(alpha);
543 idx += 1;
544 if br.overrun() {
545 return Err(Error::corrupt("ProRes slice: alpha data past the slice"));
546 }
547 if idx >= n {
548 return Ok(());
549 }
550 if br.left() == 0 || br.bits(1) == 0 {
551 break;
552 }
553 }
554 let mut run = br.bits(4) as usize;
555 if run == 0 {
556 run = br.bits(11) as usize;
557 }
558 if br.overrun() {
559 return Err(Error::corrupt("ProRes slice: alpha data past the slice"));
560 }
561 let run = run.min(n - idx);
562 let v = expand(alpha);
563 dst[idx..idx + run].fill(v);
564 idx += run;
565 }
566 Ok(())
567}