forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

video.rs730 lines, 26.7 KiBHistoryRawDownload
1//! The DV video frame decoder: a line-for-line port of FFmpeg's `dvdec.c` arithmetic.
2
3use std::sync::OnceLock;
4
5use ec_core::error::{Error, Result};
6use ec_core::frame::Interlace;
7
8use crate::idct::{idct248_tile, idct_tile};
9use crate::profile::{Chroma, PROFILE_BYTES, Profile, WorkChunk, frame_profile, work_chunks};
10use crate::tables::*;
11
12const DV_VIDEO_CONTROL: u8 = 0x61;
13const IWEIGHT_BITS: u32 = 14;
14
15/// The standard 8x8 zig-zag scan (ITU-T T.81 Figure A.6; ISO/IEC 13818-2 Figure 7-2 scan 0).
16/// Regenerated algorithmically and compared in `zigzag_is_standard`.
17const ZIGZAG: [u8; 64] = [
18 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
19 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58,
20 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
21];
22
23#[derive(Clone, Copy, Default)]
24struct VlcEntry {
25 len: u8,
26 run: u8,
27 level: i16,
28}
29
30/// Direct 16-bit lookup: next 16 bits -> (code length incl. sign, run + 1, signed level).
31fn vlc_table() -> &'static [VlcEntry] {
32 static T: OnceLock<Box<[VlcEntry]>> = OnceLock::new();
33 T.get_or_init(|| {
34 let mut t = vec![VlcEntry::default(); 1 << 16];
35 let mut code: u32 = 0;
36 for i in 0..NB_VLC {
37 let len = u32::from(VLC_LEN[i]);
38 let cur = code >> (32 - len);
39 code = code.wrapping_add(1u32 << (32 - len));
40 let run = VLC_RUN[i].wrapping_add(1);
41 let level = i16::from(VLC_LEVEL[i]);
42 let mut fill = |c: u32, l: u32, lv: i16| {
43 let start = (c << (16 - l)) as usize;
44 for e in &mut t[start..start + (1usize << (16 - l))] {
45 *e = VlcEntry { len: l as u8, run, level: lv };
46 }
47 };
48 if level != 0 {
49 fill(cur << 1, len + 1, level);
50 fill((cur << 1) | 1, len + 1, -level);
51 } else {
52 fill(cur, len, 0);
53 }
54 }
55 // FFmpeg decodes through a 10-bit first level plus sub-tables and consumes the sub-table's
56 // full depth for every code under a prefix, not the code's own length. Only the 15-bit
57 // `run 0, level 0` code is affected (it shares its prefix with 16-bit signed codes and is
58 // consumed as 16 bits); reproduce that.
59 for block in t.chunks_mut(1 << 6) {
60 let max = block.iter().map(|e| e.len).max().unwrap_or(0);
61 if max > 10 {
62 for e in block.iter_mut() {
63 e.len = max;
64 }
65 }
66 }
67 t.into_boxed_slice()
68 })
69}
70
71#[inline(always)]
72fn peek32(data: &[u8], p: usize) -> u32 {
73 let byte = p >> 3;
74 let v = if let Some(w) = data.get(byte..byte + 8) {
75 u64::from_be_bytes(w.try_into().unwrap_or([0; 8]))
76 } else {
77 let mut v = 0u64;
78 for i in 0..8 {
79 v = (v << 8) | u64::from(data.get(byte + i).copied().unwrap_or(0));
80 }
81 v
82 };
83 ((v << (p & 7)) >> 32) as u32
84}
85
86struct Gb<'a> {
87 data: &'a [u8],
88 size: usize,
89 pos: usize,
90}
91
92impl<'a> Gb<'a> {
93 fn left(&self) -> usize {
94 self.size.saturating_sub(self.pos)
95 }
96}
97
98/// Append-only bit sink (MSB first).
99struct Bw {
100 buf: Vec<u8>,
101 acc: u64,
102 nacc: u32,
103}
104
105impl Bw {
106 fn new() -> Bw {
107 Bw { buf: Vec::with_capacity(512), acc: 0, nacc: 0 }
108 }
109 fn clear(&mut self) {
110 self.buf.clear();
111 self.acc = 0;
112 self.nacc = 0;
113 }
114 fn count(&self) -> usize {
115 self.buf.len() * 8 + self.nacc as usize
116 }
117 fn put(&mut self, n: u32, v: u32) {
118 self.acc = (self.acc << n) | u64::from(v & ((1u32 << n) - 1));
119 self.nacc += n;
120 while self.nacc >= 8 {
121 self.buf.push((self.acc >> (self.nacc - 8)) as u8);
122 self.nacc -= 8;
123 }
124 self.acc &= (1u64 << self.nacc) - 1;
125 }
126 /// Copy every bit still unread in `gb`.
127 fn bit_copy(&mut self, gb: &mut Gb) {
128 while gb.left() > 0 {
129 let n = gb.left().min(16);
130 let v = peek32(gb.data, gb.pos) >> (32 - n);
131 self.put(n as u32, v);
132 gb.pos += n;
133 }
134 }
135 /// Zero padding so readers may look past the end.
136 fn pad(&mut self) {
137 if self.nacc > 0 {
138 self.put(8 - self.nacc, 0);
139 }
140 self.buf.extend_from_slice(&[0; 8]);
141 }
142}
143
144#[derive(Clone, Copy, Default)]
145struct BlockInfo {
146 factor: usize,
147 scan: u8,
148 use248: bool,
149 pos: u16,
150 pbc: u8,
151 pbuf: u32,
152}
153
154fn decode_ac(gb: &mut Gb, mb: &mut BlockInfo, block: &mut [i16; 64], factors: &[u32], vlc: &[VlcEntry], scan: &[u8; 64]) {
155 let size = gb.size as i32;
156 let mut idx = gb.pos as i32;
157 let mut cache = peek32(gb.data, gb.pos);
158 if mb.pbc > 0 {
159 cache = (cache >> mb.pbc) | mb.pbuf;
160 idx -= i32::from(mb.pbc);
161 mb.pbc = 0;
162 }
163 let mut pos = usize::from(mb.pos);
164 let factor = &factors[mb.factor..mb.factor + 64];
165 loop {
166 let e = vlc[(cache >> 16) as usize];
167 let len = i32::from(e.len.max(1));
168 if idx + len > size {
169 let n = (size - idx).max(0) as u32;
170 mb.pbc = n as u8;
171 mb.pbuf = cache & !(u32::MAX >> n);
172 idx = size;
173 break;
174 }
175 idx += len;
176 pos += usize::from(e.run);
177 if pos >= 64 {
178 break;
179 }
180 let level = (i32::from(e.level).wrapping_mul(factor[pos] as i32).wrapping_add(1 << (IWEIGHT_BITS - 1))) >> IWEIGHT_BITS;
181 block[usize::from(scan[pos])] = level as i16;
182 cache = peek32(gb.data, idx as usize);
183 }
184 gb.pos = idx.max(0) as usize;
185 mb.pos = pos as u16;
186}
187
188/// Planar output of one decoded DV frame in the stream's native layout.
189#[derive(Debug, Clone)]
190pub struct DvPicture {
191 /// The profile the frame was decoded under.
192 pub profile: &'static Profile,
193 /// Width in pixels.
194 pub width: u32,
195 /// Height in pixels.
196 pub height: u32,
197 /// Native chroma layout (`Yuv411`, `Yuv420` or `Yuv422`).
198 pub chroma: Chroma,
199 /// Y, Cb, Cr planes, tightly packed (stride = plane width).
200 pub planes: [Vec<u8>; 3],
201 /// Row pitch of each plane in bytes.
202 pub strides: [usize; 3],
203 /// Field structure per the VAUX video-control pack.
204 pub interlace: Interlace,
205 /// True when the VAUX pack signals a 16:9 picture.
206 pub is_16_9: bool,
207}
208
209impl DvPicture {
210 /// Chroma plane width in samples.
211 pub fn chroma_width(&self) -> usize {
212 chroma_dims(self.chroma, self.width as usize, self.height as usize).0
213 }
214 /// Chroma plane height in rows.
215 pub fn chroma_height(&self) -> usize {
216 chroma_dims(self.chroma, self.width as usize, self.height as usize).1
217 }
218}
219
220pub(crate) fn chroma_dims(c: Chroma, w: usize, h: usize) -> (usize, usize) {
221 match c {
222 Chroma::Yuv411 => (w / 4, h),
223 Chroma::Yuv420 => (w / 2, h / 2),
224 Chroma::Yuv422 => (w / 2, h),
225 }
226}
227
228/// Stateful DV frame decoder (keeps the previous profile for damaged-header recovery and caches
229/// the dequantisation tables per profile).
230pub struct DvVideoDecoder {
231 sys: Option<&'static Profile>,
232 chunks: Vec<WorkChunk>,
233 factors: Vec<u32>,
234 zigzag: [[u8; 64]; 2],
235}
236
237impl Default for DvVideoDecoder {
238 fn default() -> Self {
239 DvVideoDecoder::new()
240 }
241}
242
243impl DvVideoDecoder {
244 /// A decoder with no stream state.
245 pub fn new() -> DvVideoDecoder {
246 DvVideoDecoder { sys: None, chunks: Vec::new(), factors: Vec::new(), zigzag: [ZIGZAG, ZIGZAG248] }
247 }
248
249 /// Forget the remembered profile.
250 pub fn reset(&mut self) {
251 self.sys = None;
252 }
253
254 fn init_weights(&mut self, d: &Profile) {
255 self.factors.clear();
256 if d.is_hd() {
257 const QSTEP: [u32; 16] = [1, 1, 2, 3, 4, 5, 6, 7, 8, 16, 18, 20, 22, 24, 28, 52];
258 let (w1, w2): (&[u16; 64], &[u16; 64]) = if d.height == 720 {
259 (&IWEIGHT_720_Y, &IWEIGHT_720_C)
260 } else {
261 (&IWEIGHT_1080_Y, &IWEIGHT_1080_C)
262 };
263 let mut f1 = Vec::with_capacity(4096);
264 let mut f2 = Vec::with_capacity(4096);
265 for c in 0..4 {
266 for s in 0..16 {
267 for i in 0..64 {
268 f1.push((QSTEP[s] << (c + 9)).wrapping_mul(u32::from(w1[i])));
269 f2.push((QSTEP[s] << (c + 9)).wrapping_mul(u32::from(w2[i])));
270 }
271 }
272 }
273 self.factors = f1;
274 self.factors.extend(f2);
275 } else {
276 const AREAS: [usize; 4] = [6, 21, 43, 64];
277 let mut f1 = Vec::with_capacity(2816);
278 let mut f2 = Vec::with_capacity(2816);
279 for iw in [&IWEIGHT_88, &IWEIGHT_248] {
280 for s in 0..22 {
281 let mut i = 0;
282 for c in 0..4 {
283 while i < AREAS[c] {
284 let v = u32::from(iw[i]) << (QUANT_SHIFTS[s][c] + 1);
285 f1.push(v);
286 f2.push(v << 1);
287 i += 1;
288 }
289 }
290 }
291 }
292 self.factors = f1;
293 self.factors.extend(f2);
294 }
295 }
296
297 /// Profile of the frame last decoded.
298 pub fn profile(&self) -> Option<&'static Profile> {
299 self.sys
300 }
301
302 /// Decode one DV frame (at least `frame_size` bytes; extra bytes are ignored).
303 pub fn decode(&mut self, buf: &[u8]) -> Result<DvPicture> {
304 let sys = match frame_profile(self.sys, buf) {
305 Some(s) if buf.len() >= s.frame_size => s,
306 _ => return Err(Error::corrupt("DV: could not find a frame profile (short or unrecognised frame)")),
307 };
308 if self.sys.map(|p| p as *const Profile) != Some(sys as *const Profile) {
309 self.chunks = work_chunks(sys);
310 self.init_weights(sys);
311 self.sys = Some(sys);
312 }
313 let (w, h) = (sys.width as usize, sys.height as usize);
314 let (cw, ch) = chroma_dims(sys.chroma, w, h);
315 let mut planes = [vec![0u8; w * h], vec![0u8; cw * ch], vec![0u8; cw * ch]];
316 let strides = [w, cw, cw];
317
318 let vsc = &buf[80 * 5 + 48 + 5..];
319 let mut interlace = Interlace::Progressive;
320 let mut is_16_9 = false;
321 if vsc[0] == DV_VIDEO_CONTROL {
322 let apt = buf[4] & 7;
323 is_16_9 = (vsc[2] & 7) == 2 || (apt == 0 && (vsc[2] & 7) == 7);
324 if sys.height == 720 {
325 interlace = Interlace::Progressive;
326 } else if sys.height == 1080 {
327 interlace = if vsc[3] & 0x40 == 0x40 { Interlace::TopFieldFirst } else { Interlace::BottomFieldFirst };
328 } else if vsc[3] & 0x10 == 0x10 {
329 interlace = if vsc[3] & 0x40 == 0 { Interlace::TopFieldFirst } else { Interlace::BottomFieldFirst };
330 }
331 }
332
333 let vlc = vlc_table();
334 let chunks = std::mem::take(&mut self.chunks);
335 {
336 let lens = [planes[0].len(), planes[1].len(), planes[2].len()];
337 let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 8).min(chunks.len().max(1));
338 let per = chunks.len().div_ceil(threads).max(1);
339 let this = &*self;
340 let outs: Vec<Out> = std::thread::scope(|sc| {
341 let handles: Vec<_> = chunks
342 .chunks(per)
343 .map(|part| {
344 sc.spawn(move || {
345 let mut out = Out { ops: Vec::new(), lens, strides };
346 for chunk in part {
347 this.decode_segment(buf, sys, chunk, &mut out, vlc);
348 }
349 out
350 })
351 })
352 .collect();
353 handles.into_iter().map(|h| h.join().expect("DV segment worker panicked")).collect()
354 });
355 for o in &outs {
356 o.apply(&mut planes);
357 }
358 }
359 self.chunks = chunks;
360 Ok(DvPicture {
361 profile: sys,
362 width: sys.width,
363 height: sys.height,
364 chroma: sys.chroma,
365 planes,
366 strides,
367 interlace,
368 is_16_9,
369 })
370 }
371
372 fn decode_segment(&self, buf: &[u8], sys: &Profile, chunk: &WorkChunk, out: &mut Out, vlc: &[VlcEntry]) {
373 let bpm = sys.bpm;
374 let hd = sys.is_hd();
375 let mut sblock = [[0i16; 64]; 40];
376 let mut mbd = [BlockInfo::default(); 40];
377 let mut is_field = [false; 5];
378 let mut vs_damaged = false;
379 let mut mb_damaged = [false; 5];
380 let mut retried = false;
381 let mut seg_sta = 0u8;
382 let mut pb = Bw::new();
383 let mut vs_pb = Bw::new();
384
385 loop {
386 let mut base = usize::from(chunk.buf_offset) * 80;
387 vs_pb.clear();
388 for mb_index in 0..5 {
389 let m0 = mb_index * bpm;
390 let quant = usize::from(buf[base + 3] & 0x0f);
391 // Error concealment as the ffmpeg CLI runs it (`-ec` defaults to 3): a DIF block
392 // with status 0xE, or a status that differs inside the segment, marks the
393 // segment's shuffled bit stream as damaged.
394 let sta = buf[base + 3] >> 4;
395 if sta == 0x0e {
396 vs_damaged = true;
397 }
398 if mb_index == 0 {
399 seg_sta = sta;
400 } else if seg_sta != sta {
401 vs_damaged = true;
402 }
403 base += 4;
404 pb.clear();
405 is_field[mb_index] = false;
406 for j in 0..bpm {
407 let last_index = usize::from(sys.block_sizes[j]);
408 let data = &buf[base..base + (last_index >> 3)];
409 let mut gb = Gb { data, size: last_index, pos: 12 };
410 let v = (u32::from(data[0]) << 8) | u32::from(data[1]);
411 let dc = (((v >> 7) as i32) << 23) >> 23;
412 let dct_mode = (v >> 6) & 1 != 0;
413 let class1 = ((v >> 4) & 3) as usize;
414 let mb = &mut mbd[m0 + j];
415 if hd {
416 mb.use248 = false;
417 mb.scan = 0;
418 mb.factor = usize::from(j >= 4) * 4 * 16 * 64 + class1 * 16 * 64 + quant * 64;
419 is_field[mb_index] |= j == 0 && dct_mode;
420 } else {
421 mb.use248 = dct_mode;
422 mb.scan = u8::from(dct_mode);
423 mb.factor = usize::from(class1 == 3) * 2 * 22 * 64
424 + usize::from(dct_mode) * 22 * 64
425 + (quant + usize::from(QUANT_OFFSET[class1])) * 64;
426 }
427 sblock[m0 + j][0] = (dc * 4 + 1024) as i16;
428 base += last_index >> 3;
429 mb.pos = 0;
430 mb.pbc = 0;
431 let scan = &self.zigzag[usize::from(mb.scan)];
432 decode_ac(&mut gb, mb, &mut sblock[m0 + j], &self.factors, vlc, scan);
433 if mb.pos >= 64 {
434 pb.bit_copy(&mut gb);
435 }
436 if mb.pos >= 64 && mb.pos < 127 {
437 vs_damaged = true;
438 mb_damaged[mb_index] = true;
439 }
440 }
441 if mb_damaged[mb_index] {
442 continue;
443 }
444 // pass 2: the leftover bits of this macroblock's finished blocks
445 let n = pb.count();
446 pb.pad();
447 let mut gb = Gb { data: &pb.buf, size: n, pos: 0 };
448 let mut j = 0;
449 while j < bpm {
450 let mb = &mut mbd[m0 + j];
451 if mb.pos < 64 && gb.left() > 0 {
452 let scan = &self.zigzag[usize::from(mb.scan)];
453 decode_ac(&mut gb, mb, &mut sblock[m0 + j], &self.factors, vlc, scan);
454 if mb.pos < 64 {
455 break;
456 }
457 if mb.pos < 127 {
458 vs_damaged = true;
459 mb_damaged[mb_index] = true;
460 }
461 }
462 j += 1;
463 }
464 if j >= bpm {
465 vs_pb.bit_copy(&mut gb);
466 }
467 }
468
469 // pass 3: leftovers of the whole video segment
470 let n = vs_pb.count();
471 vs_pb.pad();
472 let mut gb = Gb { data: &vs_pb.buf, size: n, pos: 0 };
473 for i in 0..5 * bpm {
474 let mb = &mut mbd[i];
475 if mb.pos < 64 && gb.left() > 0 && !vs_damaged {
476 let scan = &self.zigzag[usize::from(mb.scan)];
477 decode_ac(&mut gb, mb, &mut sblock[i], &self.factors, vlc, scan);
478 }
479 if mb.pos >= 64 && mb.pos < 127 {
480 vs_damaged = true;
481 }
482 }
483 if vs_damaged && !retried {
484 retried = true;
485 sblock = [[0; 64]; 40];
486 continue;
487 }
488 break;
489 }
490
491 self.place(buf, sys, chunk, &mut sblock, &mbd, &is_field, out);
492 }
493
494 #[allow(clippy::too_many_arguments)]
495 fn place(&self, buf: &[u8], sys: &Profile, chunk: &WorkChunk, sblock: &mut [[i16; 64]; 40], mbd: &[BlockInfo; 40], is_field: &[bool; 5], out: &mut Out) {
496 let bpm = sys.bpm;
497 let [ls0, ls1, ls2] = out.strides;
498 let lsz = [ls0, ls1, ls2];
499 let chroma = sys.chroma;
500 for mb_index in 0..5 {
501 let mb_x = usize::from(chunk.mb[mb_index] & 0xff);
502 let mut mb_y = usize::from(chunk.mb[mb_index] >> 8);
503 if sys.height == 720 && buf[1] & 0x0c == 0 {
504 mb_y = if mb_y > 17 { mb_y - 18 } else { mb_y + 72 };
505 }
506 let m0 = mb_index * bpm;
507 let field = is_field[mb_index];
508 let mut bi = 0usize; // block index within the macroblock
509
510 // luminance
511 let y_stride = if chroma == Chroma::Yuv420
512 || (chroma == Chroma::Yuv411 && mb_x >= 704 / 8)
513 || (sys.height >= 720 && mb_y != 134)
514 {
515 ls0 << (usize::from(!field) * 3)
516 } else {
517 2 << 3
518 };
519 let y_off = (mb_y * ls0 + mb_x) << 3;
520 if mb_y == 134 && field {
521 last_row_field_luma(out, 0, y_off, ls0, &mut sblock[m0..m0 + 4]);
522 } else {
523 let linesize = ls0 << usize::from(field);
524 let put = |out: &mut Out, k: usize, off: usize, sblock: &mut [[i16; 64]; 40]| {
525 out.put_block(0, off, linesize, &mut sblock[m0 + k], mbd[m0 + k].use248);
526 };
527 if sys.video_stype == 4 {
528 put(out, 0, y_off, sblock);
529 put(out, 2, y_off + 8, sblock);
530 } else {
531 put(out, 0, y_off, sblock);
532 put(out, 1, y_off + 8, sblock);
533 put(out, 2, y_off + y_stride, sblock);
534 put(out, 3, y_off + 8 + y_stride, sblock);
535 }
536 }
537 bi += 4;
538
539 // chrominance
540 let cshift_y = usize::from(chroma == Chroma::Yuv420);
541 let cshift_x = if chroma == Chroma::Yuv411 { 2 } else { 1 };
542 for j in [2usize, 1] {
543 let cs = lsz[j];
544 let c_off = ((mb_y >> cshift_y) * cs + (mb_x >> cshift_x)) << 3;
545 if chroma == Chroma::Yuv411 && mb_x >= 704 / 8 {
546 let k = m0 + bi;
547 let pixels = out.put_pixels(0, 8, &mut sblock[k], mbd[k].use248);
548 for y in 0..8 {
549 let c0 = c_off + y * cs;
550 let c1 = c0 + (cs << 3);
551 for x in 0..4 {
552 out.set(j, c0 + x, pixels[y * 8 + x]);
553 out.set(j, c1 + x, pixels[y * 8 + 4 + x]);
554 }
555 }
556 bi += 1;
557 } else {
558 let y_stride = if mb_y == 134 { 8 } else { cs << (usize::from(!field) * 3) };
559 if mb_y == 134 && field {
560 last_row_field_chroma(out, j, c_off, cs, &mut sblock[m0 + bi..m0 + bi + 2]);
561 bi += 2;
562 } else {
563 let linesize = cs << usize::from(field);
564 let k = m0 + bi;
565 out.put_block(j, c_off, linesize, &mut sblock[k], mbd[k].use248);
566 bi += 1;
567 if bpm == 8 {
568 let k = m0 + bi;
569 out.put_block(j, c_off + y_stride, linesize, &mut sblock[k], mbd[k].use248);
570 bi += 1;
571 }
572 }
573 }
574 }
575 }
576 }
577}
578
579/// Pixel writes recorded by a segment decode, applied to the planes afterwards in segment order
580/// (so segments can be decoded on several threads with a result identical to a serial decode).
581enum Op {
582 Tile { plane: u8, off: usize, stride: usize, px: [u8; 64] },
583 Px { plane: u8, idx: usize, v: u8 },
584}
585
586struct Out {
587 ops: Vec<Op>,
588 lens: [usize; 3],
589 strides: [usize; 3],
590}
591
592impl Out {
593 fn apply(&self, planes: &mut [Vec<u8>; 3]) {
594 for op in &self.ops {
595 match op {
596 Op::Tile { plane, off, stride, px } => {
597 let d = &mut planes[usize::from(*plane)];
598 for (r, row) in px.as_chunks::<8>().0.iter().enumerate() {
599 let o = off + r * stride;
600 d[o..o + 8].copy_from_slice(row);
601 }
602 }
603 Op::Px { plane, idx, v } => planes[usize::from(*plane)][*idx] = *v,
604 }
605 }
606 }
607
608 #[inline]
609 fn set(&mut self, plane: usize, i: usize, v: u8) {
610 if i < self.lens[plane] {
611 self.ops.push(Op::Px { plane: plane as u8, idx: i, v });
612 }
613 }
614
615 /// IDCT-and-store one block, skipping it when it would fall outside the plane.
616 fn put_block(&mut self, plane: usize, off: usize, stride: usize, block: &mut [i16; 64], use248: bool) {
617 // Both transforms touch rows 0..8 at `stride` pitch, so the last byte is at 7 * stride + 7.
618 if off.saturating_add(7usize.saturating_mul(stride)).saturating_add(7) >= self.lens[plane] {
619 return;
620 }
621 let px = if use248 { idct248_tile(block) } else { idct_tile(block) };
622 self.ops.push(Op::Tile { plane: plane as u8, off, stride, px });
623 }
624
625 fn put_pixels(&mut self, off: usize, stride: usize, block: &mut [i16; 64], use248: bool) -> [u8; 64] {
626 let _ = (off, stride);
627 if use248 { idct248_tile(block) } else { idct_tile(block) }
628 }
629}
630
631/// In-place (no clamp) IDCT as `s->idsp.idct`: results are stored as `int16`.
632fn idct_inplace(block: &mut [i16; 64]) {
633 crate::idct::idct_i16(block);
634}
635
636fn put_block_8x4(src: &[i16], out: &mut Out, plane: usize, off: usize, stride: usize) {
637 for i in 0..4 {
638 for j in 0..8 {
639 out.set(plane, off + i * stride + j, src[i * 8 + j].clamp(0, 255) as u8);
640 }
641 }
642}
643
644fn last_row_field_chroma(out: &mut Out, plane: usize, off: usize, stride: usize, blocks: &mut [[i16; 64]]) {
645 idct_inplace(&mut blocks[0]);
646 idct_inplace(&mut blocks[1]);
647 let s2 = stride << 1;
648 put_block_8x4(&blocks[0][..32], out, plane, off, s2);
649 put_block_8x4(&blocks[0][32..], out, plane, off + 8, s2);
650 put_block_8x4(&blocks[1][..32], out, plane, off + stride, s2);
651 put_block_8x4(&blocks[1][32..], out, plane, off + 8 + stride, s2);
652}
653
654fn last_row_field_luma(out: &mut Out, plane: usize, off: usize, stride: usize, blocks: &mut [[i16; 64]]) {
655 for b in blocks.iter_mut() {
656 idct_inplace(b);
657 }
658 let s2 = stride << 1;
659 put_block_8x4(&blocks[0][..32], out, plane, off, s2);
660 put_block_8x4(&blocks[0][32..], out, plane, off + 16, s2);
661 put_block_8x4(&blocks[1][..32], out, plane, off + 8, s2);
662 put_block_8x4(&blocks[1][32..], out, plane, off + 24, s2);
663 put_block_8x4(&blocks[2][..32], out, plane, off + stride, s2);
664 put_block_8x4(&blocks[2][32..], out, plane, off + 16 + stride, s2);
665 put_block_8x4(&blocks[3][..32], out, plane, off + 8 + stride, s2);
666 put_block_8x4(&blocks[3][32..], out, plane, off + 24 + stride, s2);
667}
668
669/// `true` when `buf` starts a plausible DV frame header (DIF header block of a DV file).
670pub fn is_dv_header(buf: &[u8]) -> bool {
671 buf.len() >= PROFILE_BYTES && (buf[0] == 0x1f) && buf[1] & 0x07 == 0x07 && buf[2] == 0 && (buf[3] & 0x7f) == 0x3f
672}
673
674#[cfg(test)]
675mod tests {
676 use super::ZIGZAG;
677 #[test]
678 fn zigzag_is_standard() {
679 let mut z = Vec::new();
680 for d in 0..15usize {
681 let (lo, hi) = (d.saturating_sub(7), d.min(7));
682 let rows: Vec<usize> = if d % 2 == 0 { (lo..=hi).rev().collect() } else { (lo..=hi).collect() };
683 for r in rows {
684 z.push((r * 8 + (d - r)) as u8);
685 }
686 }
687 assert_eq!(z, ZIGZAG.to_vec());
688 }
689
690 use super::*;
691 use crate::profile::PROFILES;
692
693 #[test]
694 fn vlc_table_is_a_complete_prefix_code() {
695 let t = vlc_table();
696 assert_eq!(t.len(), 1 << 16);
697 assert!(t.iter().all(|e| e.len >= 2), "unused code space");
698 // EOB is the 4-bit code 0110: run 127 + 1, no level.
699 let e = t[0b0110 << 12];
700 assert_eq!((e.len, e.run, e.level), (4, 128, 0));
701 // the one length quirk: the 15-bit `run 0, level 0` code is consumed as 16 bits.
702 let quirky = t.iter().filter(|e| e.len == 16 && e.level == 0).count();
703 assert_eq!(quirky, 2);
704 }
705
706 #[test]
707 fn work_chunks_stay_inside_the_frame_and_the_picture() {
708 for (i, p) in PROFILES.iter().enumerate() {
709 let chunks = work_chunks(p);
710 assert_eq!(chunks.len(), p.work_size(), "profile {i}");
711 let mut seen = std::collections::HashSet::new();
712 for c in &chunks {
713 assert!(usize::from(c.buf_offset) * 80 + 5 * 80 <= p.frame_size, "profile {i}: segment outside frame");
714 assert!(seen.insert(c.buf_offset), "profile {i}: duplicate segment");
715 }
716 }
717 }
718
719 #[test]
720 fn short_and_unknown_frames_are_refused() {
721 let mut d = DvVideoDecoder::new();
722 assert!(d.decode(&[]).is_err());
723 assert!(d.decode(&[0u8; 100]).is_err());
724 assert!(d.decode(&vec![0xffu8; 120000]).is_err() || d.profile().is_some());
725 let mut f = vec![0u8; 120000];
726 f[80 * 5 + 48 + 3] = 0; // dsf 0, stype 0 => NTSC DV25
727 assert!(d.decode(&f[..119999]).is_err(), "truncated frame");
728 assert!(d.decode(&f).is_ok());
729 }
730}