forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust382.4 MiBe18142dTahinli11 hours ago4543 commits

core.rs574 lines, 16.7 KiBHistoryRawDownload
1//! Decoder state: pictures, per-frame tables and the picture-level flow.
2
3use std::collections::VecDeque;
4use std::sync::Arc;
5
6use ec_core::error::Result;
7use ec_core::frame::{ColorInfo, Interlace, PixelFormat, Plane, VideoFrame};
8use ec_core::timebase::Timestamp;
9
10use crate::bits::Br;
11use crate::header::*;
12use crate::tables::*;
13
14pub const K_INTRA: u8 = 1;
15pub const K_8X8: u8 = 2;
16pub const K_FIELD: u8 = 4;
17pub const K_GMC: u8 = 8;
18
19#[derive(Clone)]
20pub struct Pic {
21 pub y: Vec<u8>,
22 pub u: Vec<u8>,
23 pub v: Vec<u8>,
24 pub mv: Vec<[i16; 2]>,
25 pub mb_kind: Vec<u8>,
26 pub mbskip: Vec<u8>,
27 pub field_mv: Vec<[[i16; 2]; 2]>,
28 pub field_sel: Vec<[u8; 2]>,
29 pub pts: Option<Timestamp>,
30 pub interlaced: bool,
31 pub tff: bool,
32 pub keyframe: bool,
33 pub pict: Option<Pt>,
34}
35
36impl Pic {
37 pub fn new(mb_w: usize, mb_h: usize) -> Pic {
38 let (aw, ah) = (mb_w * 16, mb_h * 16);
39 Pic {
40 y: vec![0; aw * ah],
41 u: vec![0; aw * ah / 4],
42 v: vec![0; aw * ah / 4],
43 mv: vec![[0; 2]; (2 * mb_w + 1) * (2 * mb_h + 1) + 8],
44 mb_kind: vec![0; mb_w * mb_h],
45 mbskip: vec![0; mb_w * mb_h],
46 field_mv: vec![[[0; 2]; 2]; mb_w * mb_h],
47 field_sel: vec![[0; 2]; mb_w * mb_h],
48 pts: None,
49 interlaced: false,
50 tff: false,
51 keyframe: false,
52 pict: None,
53 }
54 }
55
56 pub fn gray(mb_w: usize, mb_h: usize) -> Pic {
57 let mut p = Pic::new(mb_w, mb_h);
58 p.y.fill(0x80);
59 p.u.fill(0x80);
60 p.v.fill(0x80);
61 p
62 }
63}
64
65/// A decoded picture ready for the caller, with the bits `VideoFrame` can't carry.
66pub struct Output {
67 pub frame: VideoFrame,
68 pub info: PictureInfo,
69}
70
71/// Facts about a decoded picture that [`VideoFrame`] cannot carry.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct PictureInfo {
74 /// `I`, `P`, `B` or `S` (GMC) coding type.
75 pub pict_type: char,
76 /// The picture was partly or wholly concealed after a bitstream error.
77 pub damaged: bool,
78}
79
80#[derive(Clone, Copy, PartialEq, Eq)]
81pub enum Mvt {
82 M16,
83 M8,
84 Field,
85}
86
87pub struct MbWork {
88 pub intra: bool,
89 pub mv_dir: u8,
90 pub mvt: Mvt,
91 pub mv: [[[i32; 2]; 4]; 2],
92 pub field_select: [[u8; 2]; 2],
93 pub mcsel: bool,
94 pub interlaced_dct: bool,
95 pub skipped: bool,
96 pub ac_pred: bool,
97 pub blocks: [[i16; 64]; 6],
98 pub last_index: [i32; 6],
99}
100
101impl MbWork {
102 pub fn new() -> MbWork {
103 MbWork {
104 intra: false,
105 mv_dir: 1,
106 mvt: Mvt::M16,
107 mv: [[[0; 2]; 4]; 2],
108 field_select: [[0; 2]; 2],
109 mcsel: false,
110 interlaced_dct: false,
111 skipped: false,
112 ac_pred: false,
113 blocks: [[0; 64]; 6],
114 last_index: [-1; 6],
115 }
116 }
117}
118
119pub struct Core {
120 pub ident: Ident,
121 pub vol: Vol,
122 pub have_vol: bool,
123 pub is_h263: bool,
124 pub h263_long_vectors: bool,
125 pub gob_index: usize,
126 pub ts: TimeState,
127 pub picture_number: u64,
128 pub sprite: SpriteState,
129 // geometry
130 pub w: usize,
131 pub h: usize,
132 pub mb_w: usize,
133 pub mb_h: usize,
134 pub mb_num: usize,
135 pub b8s: usize,
136 pub mvoff: usize,
137 // references and output
138 pub last: Option<Arc<Pic>>,
139 pub next: Option<Arc<Pic>>,
140 pub cur: Pic,
141 pub out: VecDeque<Output>,
142 /// Remainder of a packed packet (DivX packed B-frames), decoded with the next packet.
143 pub stash: Option<Vec<u8>>,
144 /// The last VOP seen was a not-coded VOP (N-VOP).
145 pub skipped_last_frame: bool,
146 pub last_pts: Option<Timestamp>,
147 pub dummy_last: bool,
148 pub done: Vec<bool>,
149 pub last_resync_pos: usize,
150 pub raster_end_zz: [u8; 64],
151 pub raster_end_alt: [u8; 64],
152 pub tag: [u8; 4],
153 // picture state
154 pub pt: Pt,
155 pub qscale: i32,
156 pub f_code: i32,
157 pub b_code: i32,
158 pub no_rounding: bool,
159 pub alternate_scan: bool,
160 pub intra_dc_threshold: i32,
161 pub top_field_first: bool,
162 pub y_dc_scale: i32,
163 pub c_dc_scale: i32,
164 // macroblock position / slice
165 pub mb_x: usize,
166 pub mb_y: usize,
167 pub resync_mb_x: usize,
168 pub resync_mb_y: usize,
169 pub first_slice_line: bool,
170 pub damaged: bool,
171 // prediction tables
172 pub w8: usize,
173 pub wc: usize,
174 pub dc: [Vec<i16>; 3],
175 pub ac: [Vec<[i16; 16]>; 3],
176 pub qscale_table: Vec<i8>,
177 pub cbp_table: Vec<u8>,
178 pub pred_dir_table: Vec<u8>,
179 pub mb_type_tab: Vec<u8>,
180 pub mb_acpred: Vec<u8>,
181 pub last_mv: [[[i32; 2]; 2]; 2],
182 pub direct_scale_mv: [[i16; 64]; 2],
183 // bug workarounds
184 pub bug_qpel_chroma: bool,
185 pub bug_qpel_chroma2: bool,
186 pub bug_hpel_chroma: bool,
187 pub bug_dc_clip: bool,
188 pub bug_direct_blocksize: bool,
189 pub bug_edge: bool,
190 pub bug_ump4: bool,
191 pub bug_xvid_ilace: bool,
192 pub xvid_idct: bool,
193 pub force_xvid_idct: Option<bool>,
194 /// MS-MPEG4 version (2 or 3), 0 for MPEG-4 / H.263.
195 pub ms_version: u8,
196 pub ms: crate::msmpeg4::MsState,
197}
198
199impl Core {
200 pub fn new() -> Core {
201 Core {
202 ident: Ident::default(),
203 vol: Vol::default(),
204 have_vol: false,
205 is_h263: false,
206 h263_long_vectors: false,
207 gob_index: 1,
208 ts: TimeState::default(),
209 picture_number: 0,
210 sprite: SpriteState::default(),
211 w: 0,
212 h: 0,
213 mb_w: 0,
214 mb_h: 0,
215 mb_num: 0,
216 b8s: 0,
217 mvoff: 0,
218 last: None,
219 next: None,
220 cur: Pic::new(0, 0),
221 out: VecDeque::new(),
222 stash: None,
223 skipped_last_frame: false,
224 last_pts: None,
225 dummy_last: false,
226 done: Vec::new(),
227 last_resync_pos: 0,
228 raster_end_zz: raster_end(&ZIGZAG_DIRECT),
229 raster_end_alt: raster_end(&ALTERNATE_VERTICAL_SCAN),
230 tag: [0; 4],
231 pt: Pt::I,
232 qscale: 1,
233 f_code: 1,
234 b_code: 1,
235 no_rounding: false,
236 alternate_scan: false,
237 intra_dc_threshold: 0,
238 top_field_first: false,
239 y_dc_scale: 8,
240 c_dc_scale: 8,
241 mb_x: 0,
242 mb_y: 0,
243 resync_mb_x: 0,
244 resync_mb_y: 0,
245 first_slice_line: true,
246 damaged: false,
247 w8: 0,
248 wc: 0,
249 dc: [Vec::new(), Vec::new(), Vec::new()],
250 ac: [Vec::new(), Vec::new(), Vec::new()],
251 qscale_table: Vec::new(),
252 cbp_table: Vec::new(),
253 pred_dir_table: Vec::new(),
254 mb_type_tab: Vec::new(),
255 mb_acpred: Vec::new(),
256 last_mv: [[[0; 2]; 2]; 2],
257 direct_scale_mv: [[0; 64]; 2],
258 bug_qpel_chroma: false,
259 bug_qpel_chroma2: false,
260 bug_hpel_chroma: false,
261 bug_dc_clip: false,
262 bug_direct_blocksize: false,
263 bug_edge: false,
264 bug_ump4: false,
265 bug_xvid_ilace: false,
266 xvid_idct: false,
267 force_xvid_idct: None,
268 ms_version: 0,
269 ms: Default::default(),
270 }
271 }
272
273 pub fn reset(&mut self) {
274 self.last = None;
275 self.next = None;
276 self.out.clear();
277 self.stash = None;
278 self.skipped_last_frame = false;
279 self.ts = TimeState::default();
280 }
281
282 /// Set up geometry-dependent buffers for a new picture size.
283 pub fn set_size(&mut self, w: usize, h: usize) {
284 self.w = w;
285 self.h = h;
286 self.mb_w = w.div_ceil(16);
287 self.mb_h = h.div_ceil(16);
288 self.mb_num = self.mb_w * self.mb_h;
289 self.b8s = 2 * self.mb_w + 1;
290 self.mvoff = self.b8s + 1;
291 self.done = vec![false; self.mb_num];
292 self.w8 = 2 * self.mb_w + 1;
293 self.wc = self.mb_w + 1;
294 self.last = None;
295 self.next = None;
296 let ny = self.w8 * (2 * self.mb_h + 1) + 2;
297 let nc = self.wc * (self.mb_h + 1) + 2;
298 self.dc = [vec![1024; ny], vec![1024; nc], vec![1024; nc]];
299 self.ac = [vec![[0; 16]; ny], vec![[0; 16]; nc], vec![[0; 16]; nc]];
300 self.qscale_table = vec![0; self.mb_num];
301 self.cbp_table = vec![0; self.mb_num];
302 self.pred_dir_table = vec![0; self.mb_num];
303 self.mb_type_tab = vec![0; self.mb_num];
304 self.mb_acpred = vec![0; self.mb_num];
305 self.ms.coded = vec![0; ny];
306 }
307
308 pub fn h263_pred(&self) -> bool {
309 !self.is_h263
310 }
311
312 pub fn set_qscale(&mut self, q: i32) {
313 let q = q.clamp(1, 31);
314 self.qscale = q;
315 if self.ms_version != 0 {
316 if self.ms_version == 3 {
317 self.y_dc_scale = crate::msdata::OLD_FF_Y_DC_SCALE[q as usize] as i32;
318 self.c_dc_scale = crate::msdata::WMV1_C_DC_SCALE[q as usize] as i32;
319 } else {
320 self.y_dc_scale = 8;
321 self.c_dc_scale = 8;
322 }
323 } else if self.is_h263 {
324 // The H.263 decoder keeps the MPEG-1 DC scale (8) for intra DC.
325 self.y_dc_scale = 8;
326 self.c_dc_scale = 8;
327 } else {
328 self.y_dc_scale = MPEG4_Y_DC_SCALE_TABLE[q as usize] as i32;
329 self.c_dc_scale = MPEG4_C_DC_SCALE_TABLE[q as usize] as i32;
330 }
331 }
332
333 /// Index of luma block cell (bx, by) in `dc[0]`/`ac[0]`.
334 #[inline]
335 pub fn yidx(&self, bx: usize, by: usize) -> usize {
336 (by + 1) * self.w8 + bx + 1
337 }
338
339 #[inline]
340 pub fn cidx(&self, x: usize, y: usize) -> usize {
341 (y + 1) * self.wc + x + 1
342 }
343
344 /// Reset DC/AC predictor tables to their "unavailable" state.
345 pub fn reset_pred_tables(&mut self) {
346 for d in &mut self.dc {
347 d.fill(1024);
348 }
349 for a in &mut self.ac {
350 a.fill([0; 16]);
351 }
352 }
353
354 /// `ff_mpeg4_clean_buffers`
355 pub fn clean_buffers(&mut self) {
356 let (mx, my) = (self.mb_x as isize, self.mb_y as isize);
357 let w8 = self.w8 as isize;
358 // luma: cells (2mx-1, 2my-1) .. + (2*w8+1)
359 let start = (2 * my - 1 + 1) * w8 + (2 * mx - 1 + 1);
360 for k in 0..(2 * w8 + 1) {
361 let i = (start + k) as usize;
362 if i < self.ac[0].len() {
363 self.ac[0][i] = [0; 16];
364 }
365 }
366 let wc = self.wc as isize;
367 for ac in self.ac[1..3].iter_mut() {
368 let start = (my - 1 + 1) * wc + (mx - 1 + 1);
369 for k in 0..(wc + 1) {
370 let i = (start + k) as usize;
371 if i < ac.len() {
372 ac[i] = [0; 16];
373 }
374 }
375 }
376 // Only the frame MVs are cleared, not the second (field) entries: ffmpeg's quirk.
377 self.last_mv[0][0] = [0; 2];
378 self.last_mv[1][0] = [0; 2];
379 }
380
381 pub fn init_direct_mv(&mut self) {
382 let pb = self.ts.pb_time as i32;
383 let pp = self.ts.pp_time as i32;
384 for i in 0..64 {
385 let v = i as i32 - 32;
386 self.direct_scale_mv[0][i] = (v * pb / pp) as i16;
387 self.direct_scale_mv[1][i] = (v * (pb - pp) / pp) as i16;
388 }
389 }
390
391 // ------------------------------------------------------------------
392 // Output
393
394 pub fn make_frame(&self, p: &Pic) -> VideoFrame {
395 let (w, h) = (self.w, self.h);
396 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
397 let aw = self.mb_w * 16;
398 let crop = |src: &[u8], stride: usize, w: usize, h: usize| -> Plane {
399 let mut d = Vec::with_capacity(w * h);
400 for r in 0..h {
401 d.extend_from_slice(&src[r * stride..r * stride + w]);
402 }
403 Plane::new(d, w)
404 };
405 let planes = vec![
406 crop(&p.y, aw, w, h),
407 crop(&p.u, aw / 2, cw, ch),
408 crop(&p.v, aw / 2, cw, ch),
409 ];
410 let interlace = if p.interlaced {
411 if p.tff {
412 Interlace::TopFieldFirst
413 } else {
414 Interlace::BottomFieldFirst
415 }
416 } else {
417 Interlace::Progressive
418 };
419 VideoFrame {
420 format: PixelFormat::I420,
421 width: w as u32,
422 height: h as u32,
423 planes,
424 color: ColorInfo::default(),
425 pts: p.pts,
426 interlace,
427 }
428 }
429
430 pub fn push_out(&mut self, p: &Pic) {
431 let frame = self.make_frame(p);
432 let pict_type = match p.pict {
433 Some(Pt::I) => 'I',
434 Some(Pt::P) => 'P',
435 Some(Pt::B) => 'B',
436 Some(Pt::S) => 'S',
437 None => '?',
438 };
439 self.out.push_back(Output {
440 frame,
441 info: PictureInfo {
442 pict_type,
443 damaged: self.damaged,
444 },
445 });
446 }
447
448 /// Drain the delayed reference at end of stream.
449 pub fn flush(&mut self) {
450 if let Some(n) = self.next.take()
451 && (!self.vol.low_delay || self.skipped_last_frame)
452 {
453 if self.skipped_last_frame {
454 // libavcodec: a stream ending with an N-VOP outputs the held
455 // picture with the timestamp of the last input packet.
456 let mut c = (*n).clone();
457 c.pts = self.last_pts;
458 self.push_out(&c);
459 } else {
460 self.push_out(&n);
461 }
462 }
463 self.last = None;
464 self.stash = None;
465 self.skipped_last_frame = false;
466 }
467
468 /// `ff_mpeg4_workaround_bugs`: derive the emulated-bug flags from the
469 /// stream identification (user data and optional container FourCC).
470 pub fn finish_workaround_flags(&mut self) {
471 let tag = &self.tag;
472 let is = |t: &[u8; 4]| tag == t;
473 let id = &mut self.ident;
474 if id.xvid_build == -1
475 && id.divx_version == -1
476 && id.lavc_build == -1
477 && (is(b"XVID") || is(b"XVIX") || is(b"RMP4") || is(b"ZMP4") || is(b"SIPP"))
478 {
479 id.xvid_build = 0;
480 }
481 if id.xvid_build == -1
482 && id.divx_version == -1
483 && id.lavc_build == -1
484 && is(b"DIVX")
485 && self.vol.vo_type == 0
486 && !self.vol.vol_control_parameters
487 {
488 id.divx_version = 400;
489 }
490 if id.xvid_build >= 0 && id.divx_version >= 0 {
491 id.divx_version = -1;
492 id.divx_build = -1;
493 }
494 let id = self.ident;
495 self.bug_xvid_ilace = self.tag == *b"XVIX";
496 self.bug_ump4 = self.tag == *b"UMP4";
497 self.bug_qpel_chroma = false;
498 self.bug_qpel_chroma2 = false;
499 self.bug_hpel_chroma = false;
500 self.bug_dc_clip = false;
501 self.bug_direct_blocksize = false;
502 self.bug_edge = false;
503 if id.divx_version >= 500 && id.divx_build < 1814 {
504 self.bug_qpel_chroma = true;
505 }
506 if id.divx_version > 502 && id.divx_build < 1814 {
507 self.bug_qpel_chroma2 = true;
508 }
509 let xb = id.xvid_build as u32;
510 if xb <= 1 {
511 self.bug_qpel_chroma = true;
512 }
513 if xb <= 12 {
514 self.bug_edge = true;
515 }
516 if xb <= 32 {
517 self.bug_dc_clip = true;
518 }
519 let lb = id.lavc_build as u32;
520 if lb < 4655 {
521 self.bug_direct_blocksize = true;
522 }
523 if lb < 4670 {
524 self.bug_edge = true;
525 }
526 if lb <= 4712 {
527 self.bug_dc_clip = true;
528 }
529 if id.divx_version >= 0 {
530 self.bug_direct_blocksize = true;
531 self.bug_hpel_chroma = true;
532 }
533 if (id.divx_version as u32) < 500 {
534 self.bug_edge = true;
535 }
536 if id.xvid_build >= 0 {
537 self.xvid_idct = true;
538 }
539 if let Some(f) = self.force_xvid_idct {
540 self.xvid_idct = f;
541 }
542 }
543
544 // ------------------------------------------------------------------
545 // Packet-level flow
546
547 /// Decode all pictures found in `data`.
548 pub fn decode_packet(&mut self, data: &[u8], pts: Option<Timestamp>) -> Result<()> {
549 if data.is_empty() {
550 return Ok(());
551 }
552 if data.len() >= 3 && data[0] == 0 && data[1] == 0 && data[2] & 0xFC == 0x80 {
553 return self.decode_h263_packet(data, pts);
554 }
555 self.is_h263 = false;
556 self.decode_mpeg4_packet(data, pts)
557 }
558
559 /// Parse headers in `data` (decoder configuration): VOL and friends only.
560 pub fn parse_config(&mut self, data: &[u8]) -> Result<()> {
561 let mut br = Br::new(data);
562 self.scan_headers(&mut br, true).map(|_| ())
563 }
564}
565
566fn raster_end(scan: &[u8; 64]) -> [u8; 64] {
567 let mut out = [0u8; 64];
568 let mut m = 0;
569 for i in 0..64 {
570 m = m.max(scan[i]);
571 out[i] = m;
572 }
573 out
574}