forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

core.rs576 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 partitioned: bool,
163 pub y_dc_scale: i32,
164 pub c_dc_scale: i32,
165 // macroblock position / slice
166 pub mb_x: usize,
167 pub mb_y: usize,
168 pub resync_mb_x: usize,
169 pub resync_mb_y: usize,
170 pub first_slice_line: bool,
171 pub damaged: bool,
172 // prediction tables
173 pub w8: usize,
174 pub wc: usize,
175 pub dc: [Vec<i16>; 3],
176 pub ac: [Vec<[i16; 16]>; 3],
177 pub qscale_table: Vec<i8>,
178 pub cbp_table: Vec<u8>,
179 pub pred_dir_table: Vec<u8>,
180 pub mb_type_tab: Vec<u8>,
181 pub mb_acpred: Vec<u8>,
182 pub last_mv: [[[i32; 2]; 2]; 2],
183 pub direct_scale_mv: [[i16; 64]; 2],
184 // bug workarounds
185 pub bug_qpel_chroma: bool,
186 pub bug_qpel_chroma2: bool,
187 pub bug_hpel_chroma: bool,
188 pub bug_dc_clip: bool,
189 pub bug_direct_blocksize: bool,
190 pub bug_edge: bool,
191 pub bug_ump4: bool,
192 pub bug_xvid_ilace: bool,
193 pub xvid_idct: bool,
194 pub force_xvid_idct: Option<bool>,
195 /// MS-MPEG4 version (2 or 3), 0 for MPEG-4 / H.263.
196 pub ms_version: u8,
197 pub ms: crate::msmpeg4::MsState,
198}
199
200impl Core {
201 pub fn new() -> Core {
202 Core {
203 ident: Ident::default(),
204 vol: Vol::default(),
205 have_vol: false,
206 is_h263: false,
207 h263_long_vectors: false,
208 gob_index: 1,
209 ts: TimeState::default(),
210 picture_number: 0,
211 sprite: SpriteState::default(),
212 w: 0,
213 h: 0,
214 mb_w: 0,
215 mb_h: 0,
216 mb_num: 0,
217 b8s: 0,
218 mvoff: 0,
219 last: None,
220 next: None,
221 cur: Pic::new(0, 0),
222 out: VecDeque::new(),
223 stash: None,
224 skipped_last_frame: false,
225 last_pts: None,
226 dummy_last: false,
227 done: Vec::new(),
228 last_resync_pos: 0,
229 raster_end_zz: raster_end(&ZIGZAG_DIRECT),
230 raster_end_alt: raster_end(&ALTERNATE_VERTICAL_SCAN),
231 tag: [0; 4],
232 pt: Pt::I,
233 qscale: 1,
234 f_code: 1,
235 b_code: 1,
236 no_rounding: false,
237 alternate_scan: false,
238 intra_dc_threshold: 0,
239 top_field_first: false,
240 partitioned: false,
241 y_dc_scale: 8,
242 c_dc_scale: 8,
243 mb_x: 0,
244 mb_y: 0,
245 resync_mb_x: 0,
246 resync_mb_y: 0,
247 first_slice_line: true,
248 damaged: false,
249 w8: 0,
250 wc: 0,
251 dc: [Vec::new(), Vec::new(), Vec::new()],
252 ac: [Vec::new(), Vec::new(), Vec::new()],
253 qscale_table: Vec::new(),
254 cbp_table: Vec::new(),
255 pred_dir_table: Vec::new(),
256 mb_type_tab: Vec::new(),
257 mb_acpred: Vec::new(),
258 last_mv: [[[0; 2]; 2]; 2],
259 direct_scale_mv: [[0; 64]; 2],
260 bug_qpel_chroma: false,
261 bug_qpel_chroma2: false,
262 bug_hpel_chroma: false,
263 bug_dc_clip: false,
264 bug_direct_blocksize: false,
265 bug_edge: false,
266 bug_ump4: false,
267 bug_xvid_ilace: false,
268 xvid_idct: false,
269 force_xvid_idct: None,
270 ms_version: 0,
271 ms: Default::default(),
272 }
273 }
274
275 pub fn reset(&mut self) {
276 self.last = None;
277 self.next = None;
278 self.out.clear();
279 self.stash = None;
280 self.skipped_last_frame = false;
281 self.ts = TimeState::default();
282 }
283
284 /// Set up geometry-dependent buffers for a new picture size.
285 pub fn set_size(&mut self, w: usize, h: usize) {
286 self.w = w;
287 self.h = h;
288 self.mb_w = w.div_ceil(16);
289 self.mb_h = h.div_ceil(16);
290 self.mb_num = self.mb_w * self.mb_h;
291 self.b8s = 2 * self.mb_w + 1;
292 self.mvoff = self.b8s + 1;
293 self.done = vec![false; self.mb_num];
294 self.w8 = 2 * self.mb_w + 1;
295 self.wc = self.mb_w + 1;
296 self.last = None;
297 self.next = None;
298 let ny = self.w8 * (2 * self.mb_h + 1) + 2;
299 let nc = self.wc * (self.mb_h + 1) + 2;
300 self.dc = [vec![1024; ny], vec![1024; nc], vec![1024; nc]];
301 self.ac = [vec![[0; 16]; ny], vec![[0; 16]; nc], vec![[0; 16]; nc]];
302 self.qscale_table = vec![0; self.mb_num];
303 self.cbp_table = vec![0; self.mb_num];
304 self.pred_dir_table = vec![0; self.mb_num];
305 self.mb_type_tab = vec![0; self.mb_num];
306 self.mb_acpred = vec![0; self.mb_num];
307 self.ms.coded = vec![0; ny];
308 }
309
310 pub fn h263_pred(&self) -> bool {
311 !self.is_h263
312 }
313
314 pub fn set_qscale(&mut self, q: i32) {
315 let q = q.clamp(1, 31);
316 self.qscale = q;
317 if self.ms_version != 0 {
318 if self.ms_version == 3 {
319 self.y_dc_scale = crate::msdata::OLD_FF_Y_DC_SCALE[q as usize] as i32;
320 self.c_dc_scale = crate::msdata::WMV1_C_DC_SCALE[q as usize] as i32;
321 } else {
322 self.y_dc_scale = 8;
323 self.c_dc_scale = 8;
324 }
325 } else if self.is_h263 {
326 // The H.263 decoder keeps the MPEG-1 DC scale (8) for intra DC.
327 self.y_dc_scale = 8;
328 self.c_dc_scale = 8;
329 } else {
330 self.y_dc_scale = MPEG4_Y_DC_SCALE_TABLE[q as usize] as i32;
331 self.c_dc_scale = MPEG4_C_DC_SCALE_TABLE[q as usize] as i32;
332 }
333 }
334
335 /// Index of luma block cell (bx, by) in `dc[0]`/`ac[0]`.
336 #[inline]
337 pub fn yidx(&self, bx: usize, by: usize) -> usize {
338 (by + 1) * self.w8 + bx + 1
339 }
340
341 #[inline]
342 pub fn cidx(&self, x: usize, y: usize) -> usize {
343 (y + 1) * self.wc + x + 1
344 }
345
346 /// Reset DC/AC predictor tables to their "unavailable" state.
347 pub fn reset_pred_tables(&mut self) {
348 for d in &mut self.dc {
349 d.fill(1024);
350 }
351 for a in &mut self.ac {
352 a.fill([0; 16]);
353 }
354 }
355
356 /// `ff_mpeg4_clean_buffers`
357 pub fn clean_buffers(&mut self) {
358 let (mx, my) = (self.mb_x as isize, self.mb_y as isize);
359 let w8 = self.w8 as isize;
360 // luma: cells (2mx-1, 2my-1) .. + (2*w8+1)
361 let start = (2 * my - 1 + 1) * w8 + (2 * mx - 1 + 1);
362 for k in 0..(2 * w8 + 1) {
363 let i = (start + k) as usize;
364 if i < self.ac[0].len() {
365 self.ac[0][i] = [0; 16];
366 }
367 }
368 let wc = self.wc as isize;
369 for p in 1..3 {
370 let start = (my - 1 + 1) * wc + (mx - 1 + 1);
371 for k in 0..(wc + 1) {
372 let i = (start + k) as usize;
373 if i < self.ac[p].len() {
374 self.ac[p][i] = [0; 16];
375 }
376 }
377 }
378 // Only the frame MVs are cleared, not the second (field) entries: ffmpeg's quirk.
379 self.last_mv[0][0] = [0; 2];
380 self.last_mv[1][0] = [0; 2];
381 }
382
383 pub fn init_direct_mv(&mut self) {
384 let pb = self.ts.pb_time as i32;
385 let pp = self.ts.pp_time as i32;
386 for i in 0..64 {
387 let v = i as i32 - 32;
388 self.direct_scale_mv[0][i] = (v * pb / pp) as i16;
389 self.direct_scale_mv[1][i] = (v * (pb - pp) / pp) as i16;
390 }
391 }
392
393 // ------------------------------------------------------------------
394 // Output
395
396 pub fn make_frame(&self, p: &Pic) -> VideoFrame {
397 let (w, h) = (self.w, self.h);
398 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
399 let aw = self.mb_w * 16;
400 let crop = |src: &[u8], stride: usize, w: usize, h: usize| -> Plane {
401 let mut d = Vec::with_capacity(w * h);
402 for r in 0..h {
403 d.extend_from_slice(&src[r * stride..r * stride + w]);
404 }
405 Plane::new(d, w)
406 };
407 let planes = vec![
408 crop(&p.y, aw, w, h),
409 crop(&p.u, aw / 2, cw, ch),
410 crop(&p.v, aw / 2, cw, ch),
411 ];
412 let interlace = if p.interlaced {
413 if p.tff {
414 Interlace::TopFieldFirst
415 } else {
416 Interlace::BottomFieldFirst
417 }
418 } else {
419 Interlace::Progressive
420 };
421 VideoFrame {
422 format: PixelFormat::I420,
423 width: w as u32,
424 height: h as u32,
425 planes,
426 color: ColorInfo::default(),
427 pts: p.pts,
428 interlace,
429 }
430 }
431
432 pub fn push_out(&mut self, p: &Pic) {
433 let frame = self.make_frame(p);
434 let pict_type = match p.pict {
435 Some(Pt::I) => 'I',
436 Some(Pt::P) => 'P',
437 Some(Pt::B) => 'B',
438 Some(Pt::S) => 'S',
439 None => '?',
440 };
441 self.out.push_back(Output {
442 frame,
443 info: PictureInfo {
444 pict_type,
445 damaged: self.damaged,
446 },
447 });
448 }
449
450 /// Drain the delayed reference at end of stream.
451 pub fn flush(&mut self) {
452 if let Some(n) = self.next.take()
453 && (!self.vol.low_delay || self.skipped_last_frame)
454 {
455 if self.skipped_last_frame {
456 // libavcodec: a stream ending with an N-VOP outputs the held
457 // picture with the timestamp of the last input packet.
458 let mut c = (*n).clone();
459 c.pts = self.last_pts;
460 self.push_out(&c);
461 } else {
462 self.push_out(&n);
463 }
464 }
465 self.last = None;
466 self.stash = None;
467 self.skipped_last_frame = false;
468 }
469
470 /// `ff_mpeg4_workaround_bugs`: derive the emulated-bug flags from the
471 /// stream identification (user data and optional container FourCC).
472 pub fn finish_workaround_flags(&mut self) {
473 let tag = &self.tag;
474 let is = |t: &[u8; 4]| tag == t;
475 let id = &mut self.ident;
476 if id.xvid_build == -1
477 && id.divx_version == -1
478 && id.lavc_build == -1
479 && (is(b"XVID") || is(b"XVIX") || is(b"RMP4") || is(b"ZMP4") || is(b"SIPP"))
480 {
481 id.xvid_build = 0;
482 }
483 if id.xvid_build == -1
484 && id.divx_version == -1
485 && id.lavc_build == -1
486 && is(b"DIVX")
487 && self.vol.vo_type == 0
488 && !self.vol.vol_control_parameters
489 {
490 id.divx_version = 400;
491 }
492 if id.xvid_build >= 0 && id.divx_version >= 0 {
493 id.divx_version = -1;
494 id.divx_build = -1;
495 }
496 let id = self.ident;
497 self.bug_xvid_ilace = self.tag == *b"XVIX";
498 self.bug_ump4 = self.tag == *b"UMP4";
499 self.bug_qpel_chroma = false;
500 self.bug_qpel_chroma2 = false;
501 self.bug_hpel_chroma = false;
502 self.bug_dc_clip = false;
503 self.bug_direct_blocksize = false;
504 self.bug_edge = false;
505 if id.divx_version >= 500 && id.divx_build < 1814 {
506 self.bug_qpel_chroma = true;
507 }
508 if id.divx_version > 502 && id.divx_build < 1814 {
509 self.bug_qpel_chroma2 = true;
510 }
511 let xb = id.xvid_build as u32;
512 if xb <= 1 {
513 self.bug_qpel_chroma = true;
514 }
515 if xb <= 12 {
516 self.bug_edge = true;
517 }
518 if xb <= 32 {
519 self.bug_dc_clip = true;
520 }
521 let lb = id.lavc_build as u32;
522 if lb < 4655 {
523 self.bug_direct_blocksize = true;
524 }
525 if lb < 4670 {
526 self.bug_edge = true;
527 }
528 if lb <= 4712 {
529 self.bug_dc_clip = true;
530 }
531 if id.divx_version >= 0 {
532 self.bug_direct_blocksize = true;
533 self.bug_hpel_chroma = true;
534 }
535 if (id.divx_version as u32) < 500 {
536 self.bug_edge = true;
537 }
538 if id.xvid_build >= 0 {
539 self.xvid_idct = true;
540 }
541 if let Some(f) = self.force_xvid_idct {
542 self.xvid_idct = f;
543 }
544 }
545
546 // ------------------------------------------------------------------
547 // Packet-level flow
548
549 /// Decode all pictures found in `data`.
550 pub fn decode_packet(&mut self, data: &[u8], pts: Option<Timestamp>) -> Result<()> {
551 if data.is_empty() {
552 return Ok(());
553 }
554 if data.len() >= 3 && data[0] == 0 && data[1] == 0 && data[2] & 0xFC == 0x80 {
555 return self.decode_h263_packet(data, pts);
556 }
557 self.is_h263 = false;
558 self.decode_mpeg4_packet(data, pts)
559 }
560
561 /// Parse headers in `data` (decoder configuration): VOL and friends only.
562 pub fn parse_config(&mut self, data: &[u8]) -> Result<()> {
563 let mut br = Br::new(data);
564 self.scan_headers(&mut br, true).map(|_| ())
565 }
566}
567
568fn raster_end(scan: &[u8; 64]) -> [u8; 64] {
569 let mut out = [0u8; 64];
570 let mut m = 0;
571 for i in 0..64 {
572 m = m.max(scan[i]);
573 out[i] = m;
574 }
575 out
576}