1 use nihav_core::codecs::*;
2 use nihav_core::io::bitreader::*;
3 use nihav_codec_support::codecs::{MV, ZIGZAG};
4 use nihav_codec_support::codecs::blockdsp::edge_emu;
5 use super::vpcommon::*;
29 impl VP56Parser for VP6BR {
30 fn parse_header(&mut self, bc: &mut BoolCoder) -> DecoderResult<VP56Header> {
31 let mut hdr = VP56Header::default();
32 // horrible hack to match VP6 header parsing
34 let mut br = BitReader::new(src, BitReaderMode::BE);
36 hdr.is_intra = !br.read_bool()?;
37 hdr.is_golden = hdr.is_intra;
38 hdr.quant = br.read(6)? as u8;
39 hdr.multistream = br.read_bool()?;
41 hdr.version = br.read(5)? as u8;
42 validate!((hdr.version >= VERSION_VP60) && (hdr.version <= VERSION_VP62));
43 hdr.profile = br.read(2)? as u8;
44 validate!((hdr.profile == VP6_SIMPLE_PROFILE) || (hdr.profile == VP6_ADVANCED_PROFILE));
45 hdr.interlaced = br.read_bool()?;
47 hdr.version = self.vpversion;
48 hdr.profile = self.profile;
49 hdr.interlaced = self.interlaced;
51 if hdr.multistream || (hdr.profile == VP6_SIMPLE_PROFILE) {
52 hdr.offset = br.read(16)? as u16;
53 validate!(hdr.offset > if hdr.is_intra { 6 } else { 2 });
54 hdr.multistream = true;
56 let bytes = br.tell() >> 3;
61 hdr.mb_h = bc.read_bits(8) as u8;
62 hdr.mb_w = bc.read_bits(8) as u8;
63 hdr.disp_h = bc.read_bits(8) as u8;
64 hdr.disp_w = bc.read_bits(8) as u8;
65 validate!((hdr.mb_h > 0) && (hdr.mb_w > 0) && (hdr.disp_w > 0) && (hdr.disp_h > 0));
66 validate!((hdr.disp_w <= hdr.mb_w) && (hdr.disp_h <= hdr.mb_h));
67 hdr.scale = bc.read_bits(2) as u8;
69 hdr.is_golden = bc.read_bool();
70 if hdr.profile == VP6_ADVANCED_PROFILE {
71 self.loop_mode = bc.read_bool() as u8;
72 if self.loop_mode != 0 {
73 self.loop_mode += bc.read_bool() as u8;
74 validate!(self.loop_mode <= 1);
76 if hdr.version == VERSION_VP62 {
77 self.do_pm = bc.read_bool();
82 if (hdr.profile == VP6_ADVANCED_PROFILE) && (hdr.is_intra || self.do_pm) {
83 self.autosel_pm = bc.read_bool();
85 self.var_thresh = bc.read_bits(5) as u16;
86 if hdr.version != VERSION_VP62 {
87 self.var_thresh <<= 5;
89 self.mv_thresh = bc.read_bits(3) as u8;
91 self.bicubic = bc.read_bool();
93 if hdr.version == VERSION_VP62 {
94 self.filter_alpha = bc.read_bits(4) as usize;
96 self.filter_alpha = 16;
100 hdr.use_huffman = bc.read_bool();
102 self.vpversion = hdr.version;
103 self.profile = hdr.profile;
104 self.interlaced = hdr.interlaced;
107 fn decode_mv(&self, bc: &mut BoolCoder, model: &VP56MVModel) -> i16 {
108 let val = if !bc.read_prob(model.nz_prob) { // short vector
109 vp_tree!(bc, model.tree_probs[0],
110 vp_tree!(bc, model.tree_probs[1],
111 vp_tree!(bc, model.tree_probs[2], 0, 1),
112 vp_tree!(bc, model.tree_probs[3], 2, 3)),
113 vp_tree!(bc, model.tree_probs[4],
114 vp_tree!(bc, model.tree_probs[5], 4, 5),
115 vp_tree!(bc, model.tree_probs[6], 6, 7)))
118 for ord in LONG_VECTOR_ORDER.iter() {
119 raw |= (bc.read_prob(model.raw_probs[*ord]) as i16) << *ord;
121 if (raw & 0xF0) != 0 {
122 raw |= (bc.read_prob(model.raw_probs[3]) as i16) << 3;
128 if (val != 0) && bc.read_prob(model.sign_prob) {
134 fn reset_models(&self, models: &mut VP56Models) {
135 for (i, mdl) in models.mv_models.iter_mut().enumerate() {
136 mdl.nz_prob = NZ_PROBS[i];
138 mdl.raw_probs.copy_from_slice(&RAW_PROBS[i]);
139 mdl.tree_probs.copy_from_slice(&TREE_PROBS[i]);
141 models.vp6models.zero_run_probs.copy_from_slice(&ZERO_RUN_PROBS);
142 reset_scan(&mut models.vp6models, self.interlaced);
144 fn decode_mv_models(&self, bc: &mut BoolCoder, models: &mut [VP56MVModel; 2]) -> DecoderResult<()> {
146 if bc.read_prob(HAS_NZ_PROB[comp]) {
147 models[comp].nz_prob = bc.read_probability();
149 if bc.read_prob(HAS_SIGN_PROB[comp]) {
150 models[comp].sign_prob = bc.read_probability();
154 for (i, prob) in HAS_TREE_PROB[comp].iter().enumerate() {
155 if bc.read_prob(*prob) {
156 models[comp].tree_probs[i] = bc.read_probability();
161 for (i, prob) in HAS_RAW_PROB[comp].iter().enumerate() {
162 if bc.read_prob(*prob) {
163 models[comp].raw_probs[i] = bc.read_probability();
169 fn decode_coeff_models(&self, bc: &mut BoolCoder, models: &mut VP56Models, is_intra: bool) -> DecoderResult<()> {
170 let mut def_prob = [128u8; 11];
173 if bc.read_prob(HAS_COEF_PROBS[plane][i]) {
174 def_prob[i] = bc.read_probability();
175 models.coeff_models[plane].dc_value_probs[i] = def_prob[i];
177 models.coeff_models[plane].dc_value_probs[i] = def_prob[i];
184 if bc.read_prob(HAS_SCAN_UPD_PROBS[i]) {
185 models.vp6models.scan_order[i] = bc.read_bits(4) as usize;
188 update_scan(&mut models.vp6models);
190 reset_scan(&mut models.vp6models, self.interlaced);
195 if bc.read_prob(HAS_ZERO_RUN_PROBS[comp][i]) {
196 models.vp6models.zero_run_probs[comp][i] = bc.read_probability();
205 if bc.read_prob(VP6_AC_PROBS[ctype][plane][group][i]) {
206 def_prob[i] = bc.read_probability();
207 models.coeff_models[plane].ac_val_probs[ctype][group][i] = def_prob[i];
209 models.coeff_models[plane].ac_val_probs[ctype][group][i] = def_prob[i];
216 let mdl = &mut models.coeff_models[plane];
219 mdl.dc_token_probs[0][i][k] = rescale_prob(mdl.dc_value_probs[k], &VP6_DC_WEIGHTS[k][i], 255);
225 fn decode_block(&self, bc: &mut BoolCoder, coeffs: &mut [i16; 64], model: &VP56CoeffModel, vp6model: &VP6Models, fstate: &mut FrameState) -> DecoderResult<()> {
226 let left_ctx = fstate.coeff_cat[fstate.ctx_idx][0] as usize;
227 let top_ctx = fstate.top_ctx as usize;
228 let dc_mode = top_ctx + left_ctx;
229 let token = decode_token_bc(bc, &model.dc_token_probs[0][dc_mode], model.dc_value_probs[5], true, true);
230 let val = expand_token_bc(bc, &model.dc_value_probs, token, 6);
232 fstate.last_idx[fstate.ctx_idx] = 0;
235 let mut last_val = val;
237 let ac_band = VP6_IDX_TO_AC_BAND[idx];
238 let ac_mode = last_val.abs().min(2) as usize;
239 let has_nnz = (idx == 1) || (last_val != 0);
240 let token = decode_token_bc(bc, &model.ac_val_probs[ac_mode][ac_band], model.ac_val_probs[ac_mode][ac_band][5], false, has_nnz);
241 if token == 42 { break; }
242 let val = expand_token_bc(bc, &model.ac_val_probs[ac_mode][ac_band], token, 6);
243 coeffs[vp6model.zigzag[idx]] = val.wrapping_mul(fstate.ac_quant);
247 idx += decode_zero_run_bc(bc, &vp6model.zero_run_probs[if idx >= 7 { 1 } else { 0 }]);
248 validate!(idx <= 64);
251 fstate.coeff_cat[fstate.ctx_idx][0] = if coeffs[0] != 0 { 1 } else { 0 };
252 fstate.top_ctx = fstate.coeff_cat[fstate.ctx_idx][0];
253 fstate.last_idx[fstate.ctx_idx] = idx;
256 fn decode_block_huff(&self, br: &mut BitReader, coeffs: &mut [i16; 64], vp6model: &VP6Models, model: &VP6HuffModels, fstate: &mut FrameState) -> DecoderResult<()> {
257 let plane = if (fstate.plane == 0) || (fstate.plane == 3) { 0 } else { 1 };
260 if fstate.dc_zero_run[plane] == 0 {
261 let (val, eob) = decode_token_huff(br, &model.dc_token_tree[plane])?;
268 fstate.dc_zero_run[plane] = decode_eob_run_huff(br)?;
272 fstate.dc_zero_run[plane] -= 1;
275 if fstate.ac_zero_run[plane] > 0 {
276 fstate.ac_zero_run[plane] -= 1;
277 fstate.last_idx[fstate.ctx_idx] = 0;
283 let ac_band = VP6_IDX_TO_AC_BAND[idx].min(3);
284 let ac_mode = last_val.abs().min(2) as usize;
285 let (val, eob) = decode_token_huff(br, &model.ac_token_tree[plane][ac_mode][ac_band])?;
288 fstate.ac_zero_run[plane] = decode_eob_run_huff(br)?;
292 coeffs[vp6model.zigzag[idx]] = val.wrapping_mul(fstate.ac_quant);
296 idx += decode_zero_run_huff(br, &model.zero_run_tree[if idx >= 7 { 1 } else { 0 }])?;
297 validate!(idx <= 64);
301 fstate.last_idx[fstate.ctx_idx] = idx;
305 fn mc_block(&self, dst: &mut NASimpleVideoFrame<u8>, mut mc_buf: NAVideoBufferRef<u8>, src: NAVideoBufferRef<u8>, plane: usize, x: usize, y: usize, mv: MV, loop_str: i16) {
306 let is_luma = (plane != 1) && (plane != 2);
307 let (sx, sy, mx, my, msx, msy) = if is_luma {
308 (mv.x >> 2, mv.y >> 2, (mv.x & 3) << 1, (mv.y & 3) << 1, mv.x / 4, mv.y / 4)
310 (mv.x >> 3, mv.y >> 3, mv.x & 7, mv.y & 7, mv.x / 8, mv.y / 8)
312 let tmp_blk = mc_buf.get_data_mut().unwrap();
313 get_block(tmp_blk, 16, src, plane, x, y, sx, sy);
315 let foff = (8 - (sx & 7)) as usize;
317 vp31_loop_filter(tmp_blk, off, 1, 16, 12, loop_str);
320 let foff = (8 - (sy & 7)) as usize;
321 let off = (2 + foff) * 16;
322 vp31_loop_filter(tmp_blk, off, 16, 1, 12, loop_str);
324 let copy_mode = (mx == 0) && (my == 0);
325 let mut bicubic = !copy_mode && is_luma && self.bicubic;
326 if is_luma && !copy_mode && (self.profile == VP6_ADVANCED_PROFILE) {
327 if !self.autosel_pm {
330 let mv_limit = 1 << (self.mv_thresh + 1);
331 if (mv.x.abs() <= mv_limit) && (mv.y.abs() <= mv_limit) {
332 let mut var_off = 16 * 2 + 2;
333 if mv.x < 0 { var_off += 1; }
334 if mv.y < 0 { var_off += 16; }
335 let var = calc_variance(&tmp_blk[var_off..], 16);
336 if var >= self.var_thresh {
342 let dstride = dst.stride[plane];
343 let dbuf = &mut dst.data[dst.offset[plane] + x + y * dstride..];
345 let src = &tmp_blk[2 * 16 + 2..];
346 for (dline, sline) in dbuf.chunks_mut(dst.stride[plane]).zip(src.chunks(16)).take(8) {
347 dline[..8].copy_from_slice(&sline[..8]);
350 let coeff_h = &VP6_BICUBIC_COEFFS[self.filter_alpha][mx as usize];
351 let coeff_v = &VP6_BICUBIC_COEFFS[self.filter_alpha][my as usize];
352 mc_bicubic(dbuf, dstride, tmp_blk, 16 * 2 + 2, 16, coeff_h, coeff_v);
354 mc_bilinear(dbuf, dstride, tmp_blk, 16 * 2 + 2, 16, mx as u16, my as u16);
359 fn update_scan(model: &mut VP6Models) {
363 if model.scan_order[i] == band {
370 model.zigzag[i] = ZIGZAG[model.scan[i]];
374 fn reset_scan(model: &mut VP6Models, interlaced: bool) {
376 model.scan_order.copy_from_slice(&VP6_DEFAULT_SCAN_ORDER);
378 model.scan_order.copy_from_slice(&VP6_INTERLACED_SCAN_ORDER);
380 for i in 0..64 { model.scan[i] = i; }
381 model.zigzag.copy_from_slice(&ZIGZAG);
384 fn decode_token_bc(bc: &mut BoolCoder, probs: &[u8], prob34: u8, is_dc: bool, has_nnz: bool) -> u8 {
385 if has_nnz && !bc.read_prob(probs[0]) {
386 if is_dc || bc.read_prob(probs[1]) {
392 vp_tree!(bc, probs[2],
394 vp_tree!(bc, probs[3],
395 vp_tree!(bc, probs[4],
397 vp_tree!(bc, prob34, 3, 4)),
402 fn decode_zero_run_bc(bc: &mut BoolCoder, probs: &[u8; 14]) -> usize {
403 let val = vp_tree!(bc, probs[0],
404 vp_tree!(bc, probs[1],
405 vp_tree!(bc, probs[2], 0, 1),
406 vp_tree!(bc, probs[3], 2, 3)),
407 vp_tree!(bc, probs[4],
408 vp_tree!(bc, probs[5],
409 vp_tree!(bc, probs[6], 4, 5),
410 vp_tree!(bc, probs[7], 6, 7)),
417 nval += (bc.read_prob(probs[i + 8]) as usize) << i;
423 fn decode_token_huff(br: &mut BitReader, huff: &VP6Huff) -> DecoderResult<(i16, bool)> {
424 let tok = br.read_huff(huff)?;
428 if !br.read_bool()? {
429 Ok((i16::from(tok), false))
431 Ok((-i16::from(tok), false))
434 5 | 6 | 7 | 8 | 9 | 10 => {
435 let base = (tok - 5) as usize;
436 let add_bits = br.read(VP6_COEF_ADD_BITS[base])? as i16;
437 let val = VP56_COEF_BASE[base] + add_bits;
438 if !br.read_bool()? {
448 fn decode_eob_run_huff(br: &mut BitReader) -> DecoderResult<usize> {
449 let val = br.read(2)?;
454 let val = br.read(2)?;
455 Ok((val as usize) + 2)
459 Ok((br.read(6)? as usize) + 10)
461 Ok((br.read(2)? as usize) + 6)
467 fn decode_zero_run_huff(br: &mut BitReader, huff: &VP6Huff) -> DecoderResult<usize> {
468 let val = br.read_huff(huff)?;
472 Ok((br.read(6)? as usize) + 8)
476 #[allow(clippy::too_many_arguments)]
477 fn get_block(dst: &mut [u8], dstride: usize, src: NAVideoBufferRef<u8>, comp: usize,
478 dx: usize, dy: usize, mv_x: i16, mv_y: i16)
480 let (w, h) = src.get_dimensions(comp);
481 let sx = (dx as isize) + (mv_x as isize);
482 let sy = (dy as isize) + (mv_y as isize);
484 if (sx - 2 < 0) || (sx + 8 + 2 > (w as isize)) ||
485 (sy - 2 < 0) || (sy + 8 + 2 > (h as isize)) {
486 edge_emu(&src, sx - 2, sy - 2, 8 + 2 + 2, 8 + 2 + 2,
487 dst, dstride, comp, 0);
489 let sstride = src.get_stride(comp);
490 let soff = src.get_offset(comp);
491 let sdta = src.get_data();
492 let sbuf: &[u8] = sdta.as_slice();
493 let saddr = soff + ((sx - 2) as usize) + ((sy - 2) as usize) * sstride;
494 let src = &sbuf[saddr..];
495 for (dline, sline) in dst.chunks_mut(dstride).zip(src.chunks(sstride)).take(12) {
496 dline[..12].copy_from_slice(&sline[..12]);
501 fn calc_variance(src: &[u8], stride: usize) -> u16 {
504 for line in src.chunks(stride * 2).take(4) {
505 for el in line.iter().take(8).step_by(2) {
506 let pix = u32::from(*el);
511 ((ssum * 16 - sum * sum) >> 8) as u16
514 macro_rules! mc_filter {
515 (bilinear; $a: expr, $b: expr, $c: expr) => {
516 ((u16::from($a) * (8 - $c) + u16::from($b) * $c + 4) >> 3) as u8
518 (bicubic; $src: expr, $off: expr, $step: expr, $coeffs: expr) => {
519 ((i32::from($src[$off - $step] ) * i32::from($coeffs[0]) +
520 i32::from($src[$off] ) * i32::from($coeffs[1]) +
521 i32::from($src[$off + $step] ) * i32::from($coeffs[2]) +
522 i32::from($src[$off + $step * 2]) * i32::from($coeffs[3]) + 64) >> 7).min(255).max(0) as u8
526 //#[allow(snake_case)]
527 fn mc_bilinear(dst: &mut [u8], dstride: usize, src: &[u8], mut soff: usize, sstride: usize, mx: u16, my: u16) {
529 for dline in dst.chunks_mut(dstride).take(8) {
531 dline[i] = mc_filter!(bilinear; src[soff + i], src[soff + i + 1], mx);
536 for dline in dst.chunks_mut(dstride).take(8) {
538 dline[i] = mc_filter!(bilinear; src[soff + i], src[soff + i + sstride], my);
543 let mut tmp = [0u8; 8];
545 tmp[i] = mc_filter!(bilinear; src[soff + i], src[soff + i + 1], mx);
548 for dline in dst.chunks_mut(dstride).take(8) {
550 let cur = mc_filter!(bilinear; src[soff + i], src[soff + i + 1], mx);
551 dline[i] = mc_filter!(bilinear; tmp[i], cur, my);
559 #[allow(clippy::trivially_copy_pass_by_ref)]
560 fn mc_bicubic(dst: &mut [u8], dstride: usize, src: &[u8], mut soff: usize, sstride: usize, coeffs_w: &[i16; 4], coeffs_h: &[i16; 4]) {
561 if coeffs_h[1] == 128 {
562 for dline in dst.chunks_mut(dstride).take(8) {
564 dline[i] = mc_filter!(bicubic; src, soff + i, 1, coeffs_w);
568 } else if coeffs_w[1] == 128 { // horizontal-only interpolation
569 for dline in dst.chunks_mut(dstride).take(8) {
571 dline[i] = mc_filter!(bicubic; src, soff + i, sstride, coeffs_h);
576 let mut buf = [0u8; 16 * 11];
578 for dline in buf.chunks_mut(16) {
580 dline[i] = mc_filter!(bicubic; src, soff + i, 1, coeffs_w);
585 for dline in dst.chunks_mut(dstride).take(8) {
587 dline[i] = mc_filter!(bicubic; buf, soff + i, 16, coeffs_h);
596 info: NACodecInfoRef,
602 fn new(has_alpha: bool) -> Self {
604 dec: VP56Decoder::new(6, has_alpha, true),
605 info: NACodecInfoRef::default(),
612 impl NADecoder for VP6Decoder {
613 fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()> {
614 if let NACodecTypeInfo::Video(vinfo) = info.get_properties() {
615 let fmt = if !self.has_alpha {
620 let myvinfo = NAVideoInfo::new(vinfo.get_width(), vinfo.get_height(), false, fmt);
621 let myinfo = NACodecTypeInfo::Video(myvinfo);
622 self.info = NACodecInfo::new_ref(info.get_name(), myinfo, info.get_extradata()).into_ref();
623 self.dec.init(supp, myvinfo)?;
626 Err(DecoderError::InvalidData)
629 fn decode(&mut self, supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
630 let src = pkt.get_buffer();
632 let (bufinfo, ftype) = self.dec.decode_frame(supp, src.as_slice(), &mut self.br)?;
634 let mut frm = NAFrame::new_from_pkt(pkt, self.info.clone(), bufinfo);
635 frm.set_keyframe(ftype == FrameType::I);
636 frm.set_frame_type(ftype);
639 fn flush(&mut self) {
644 impl NAOptionHandler for VP6Decoder {
645 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
646 fn set_options(&mut self, _options: &[NAOption]) { }
647 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
650 pub fn get_decoder_vp6() -> Box<dyn NADecoder + Send> {
651 Box::new(VP6Decoder::new(false))
654 pub fn get_decoder_vp6_alpha() -> Box<dyn NADecoder + Send> {
655 Box::new(VP6Decoder::new(true))
660 use nihav_core::codecs::RegisteredDecoders;
661 use nihav_core::demuxers::RegisteredDemuxers;
662 use nihav_codec_support::test::dec_video::*;
663 use crate::duck_register_all_decoders;
664 use nihav_commonfmt::generic_register_all_demuxers;
668 let mut dmx_reg = RegisteredDemuxers::new();
669 generic_register_all_demuxers(&mut dmx_reg);
670 let mut dec_reg = RegisteredDecoders::new();
671 duck_register_all_decoders(&mut dec_reg);
673 test_decoding("avi", "vp6", "assets/Duck/selection_720x576_300kBit_vp60i.avi", Some(16),
675 ExpectedTestResult::MD5([0x042c3e96, 0x8a9b26a2, 0x4dcbaf66, 0x1b788d03]));
679 let mut dmx_reg = RegisteredDemuxers::new();
680 generic_register_all_demuxers(&mut dmx_reg);
681 let mut dec_reg = RegisteredDecoders::new();
682 duck_register_all_decoders(&mut dec_reg);
684 test_decoding("avi", "vp6", "assets/Duck/vp6_crash.avi", Some(4),
685 &dmx_reg, &dec_reg, ExpectedTestResult::MD5Frames(vec![
686 [0xdcd70fa0, 0x0d075ce2, 0xc9e65077, 0xb003a92e],
687 [0x334abf96, 0x3a004c7a, 0x5781cd5c, 0x25c3ae5c],
688 [0x6164b851, 0x528cd8de, 0xecab7328, 0x4b49708a],
689 [0x11b048ac, 0xedb3e471, 0xd04e9399, 0x64e623e3],
690 [0x182871b1, 0x2146893a, 0x2912210e, 0x6dd592e8]]));
692 // todo find good sample for vp6a test