FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
vp3.c
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2003-2004 the ffmpeg project
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 /**
22  * @file
23  * On2 VP3 Video Decoder
24  *
25  * VP3 Video Decoder by Mike Melanson (mike at multimedia.cx)
26  * For more information about the VP3 coding process, visit:
27  * http://wiki.multimedia.cx/index.php?title=On2_VP3
28  *
29  * Theora decoder by Alex Beregszaszi
30  */
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 
36 #include "libavutil/imgutils.h"
37 #include "avcodec.h"
38 #include "internal.h"
39 #include "dsputil.h"
40 #include "get_bits.h"
41 #include "hpeldsp.h"
42 #include "videodsp.h"
43 #include "vp3data.h"
44 #include "vp3dsp.h"
45 #include "xiph.h"
46 #include "thread.h"
47 
48 #define FRAGMENT_PIXELS 8
49 
50 //FIXME split things out into their own arrays
51 typedef struct Vp3Fragment {
52  int16_t dc;
55 } Vp3Fragment;
56 
57 #define SB_NOT_CODED 0
58 #define SB_PARTIALLY_CODED 1
59 #define SB_FULLY_CODED 2
60 
61 // This is the maximum length of a single long bit run that can be encoded
62 // for superblock coding or block qps. Theora special-cases this to read a
63 // bit instead of flipping the current bit to allow for runs longer than 4129.
64 #define MAXIMUM_LONG_BIT_RUN 4129
65 
66 #define MODE_INTER_NO_MV 0
67 #define MODE_INTRA 1
68 #define MODE_INTER_PLUS_MV 2
69 #define MODE_INTER_LAST_MV 3
70 #define MODE_INTER_PRIOR_LAST 4
71 #define MODE_USING_GOLDEN 5
72 #define MODE_GOLDEN_MV 6
73 #define MODE_INTER_FOURMV 7
74 #define CODING_MODE_COUNT 8
75 
76 /* special internal mode */
77 #define MODE_COPY 8
78 
79 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
80 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
81 
82 
83 /* There are 6 preset schemes, plus a free-form scheme */
84 static const int ModeAlphabet[6][CODING_MODE_COUNT] =
85 {
86  /* scheme 1: Last motion vector dominates */
91 
92  /* scheme 2 */
97 
98  /* scheme 3 */
103 
104  /* scheme 4 */
109 
110  /* scheme 5: No motion vector dominates */
115 
116  /* scheme 6 */
121 
122 };
123 
124 static const uint8_t hilbert_offset[16][2] = {
125  {0,0}, {1,0}, {1,1}, {0,1},
126  {0,2}, {0,3}, {1,3}, {1,2},
127  {2,2}, {2,3}, {3,3}, {3,2},
128  {3,1}, {2,1}, {2,0}, {3,0}
129 };
130 
131 #define MIN_DEQUANT_VAL 2
132 
133 typedef struct Vp3DecodeContext {
136  int version;
137  int width, height;
142  int keyframe;
148  DECLARE_ALIGNED(16, int16_t, block)[64];
152 
153  int qps[3];
154  int nqps;
155  int last_qps[3];
156 
166  unsigned char *superblock_coding;
167 
171 
175 
178  int data_offset[3];
179 
180  int8_t (*motion_val[2])[2];
181 
182  /* tables */
183  uint16_t coded_dc_scale_factor[64];
184  uint32_t coded_ac_scale_factor[64];
187  uint8_t qr_size [2][3][64];
188  uint16_t qr_base[2][3][64];
189 
190  /**
191  * This is a list of all tokens in bitstream order. Reordering takes place
192  * by pulling from each level during IDCT. As a consequence, IDCT must be
193  * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
194  * otherwise. The 32 different tokens with up to 12 bits of extradata are
195  * collapsed into 3 types, packed as follows:
196  * (from the low to high bits)
197  *
198  * 2 bits: type (0,1,2)
199  * 0: EOB run, 14 bits for run length (12 needed)
200  * 1: zero run, 7 bits for run length
201  * 7 bits for the next coefficient (3 needed)
202  * 2: coefficient, 14 bits (11 needed)
203  *
204  * Coefficients are signed, so are packed in the highest bits for automatic
205  * sign extension.
206  */
207  int16_t *dct_tokens[3][64];
208  int16_t *dct_tokens_base;
209 #define TOKEN_EOB(eob_run) ((eob_run) << 2)
210 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) << 9) + ((zero_run) << 2) + 1)
211 #define TOKEN_COEFF(coeff) (((coeff) << 2) + 2)
212 
213  /**
214  * number of blocks that contain DCT coefficients at the given level or higher
215  */
216  int num_coded_frags[3][64];
218 
219  /* this is a list of indexes into the all_fragments array indicating
220  * which of the fragments are coded */
222 
223  VLC dc_vlc[16];
228 
233 
234  /* these arrays need to be on 16-byte boundaries since SSE2 operations
235  * index into them */
236  DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
237 
238  /* This table contains superblock_count * 16 entries. Each set of 16
239  * numbers corresponds to the fragment indexes 0..15 of the superblock.
240  * An entry will be -1 to indicate that no entry corresponds to that
241  * index. */
243 
244  /* This is an array that indicates how a particular macroblock
245  * is coded. */
246  unsigned char *macroblock_coding;
247 
249 
250  /* Huffman decode */
251  int hti;
252  unsigned int hbits;
253  int entries;
255  uint32_t huffman_table[80][32][2];
256 
260 
261 /************************************************************************
262  * VP3 specific functions
263  ************************************************************************/
264 
265 static void vp3_decode_flush(AVCodecContext *avctx)
266 {
267  Vp3DecodeContext *s = avctx->priv_data;
268 
269  if (s->golden_frame.f)
271  if (s->last_frame.f)
273  if (s->current_frame.f)
275 }
276 
278 {
279  Vp3DecodeContext *s = avctx->priv_data;
280  int i;
281 
283  av_freep(&s->all_fragments);
288  av_freep(&s->motion_val[0]);
289  av_freep(&s->motion_val[1]);
291 
292  s->theora_tables = 0;
293 
294  /* release all frames */
295  vp3_decode_flush(avctx);
299 
300  if (avctx->internal->is_copy)
301  return 0;
302 
303  for (i = 0; i < 16; i++) {
304  ff_free_vlc(&s->dc_vlc[i]);
305  ff_free_vlc(&s->ac_vlc_1[i]);
306  ff_free_vlc(&s->ac_vlc_2[i]);
307  ff_free_vlc(&s->ac_vlc_3[i]);
308  ff_free_vlc(&s->ac_vlc_4[i]);
309  }
310 
315 
316 
317  return 0;
318 }
319 
320 /**
321  * This function sets up all of the various blocks mappings:
322  * superblocks <-> fragments, macroblocks <-> fragments,
323  * superblocks <-> macroblocks
324  *
325  * @return 0 is successful; returns 1 if *anything* went wrong.
326  */
328 {
329  int sb_x, sb_y, plane;
330  int x, y, i, j = 0;
331 
332  for (plane = 0; plane < 3; plane++) {
333  int sb_width = plane ? s->c_superblock_width : s->y_superblock_width;
334  int sb_height = plane ? s->c_superblock_height : s->y_superblock_height;
335  int frag_width = s->fragment_width[!!plane];
336  int frag_height = s->fragment_height[!!plane];
337 
338  for (sb_y = 0; sb_y < sb_height; sb_y++)
339  for (sb_x = 0; sb_x < sb_width; sb_x++)
340  for (i = 0; i < 16; i++) {
341  x = 4*sb_x + hilbert_offset[i][0];
342  y = 4*sb_y + hilbert_offset[i][1];
343 
344  if (x < frag_width && y < frag_height)
345  s->superblock_fragments[j++] = s->fragment_start[plane] + y*frag_width + x;
346  else
347  s->superblock_fragments[j++] = -1;
348  }
349  }
350 
351  return 0; /* successful path out */
352 }
353 
354 /*
355  * This function sets up the dequantization tables used for a particular
356  * frame.
357  */
358 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
359 {
360  int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
361  int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
362  int i, plane, inter, qri, bmi, bmj, qistart;
363 
364  for(inter=0; inter<2; inter++){
365  for(plane=0; plane<3; plane++){
366  int sum=0;
367  for(qri=0; qri<s->qr_count[inter][plane]; qri++){
368  sum+= s->qr_size[inter][plane][qri];
369  if(s->qps[qpi] <= sum)
370  break;
371  }
372  qistart= sum - s->qr_size[inter][plane][qri];
373  bmi= s->qr_base[inter][plane][qri ];
374  bmj= s->qr_base[inter][plane][qri+1];
375  for(i=0; i<64; i++){
376  int coeff= ( 2*(sum -s->qps[qpi])*s->base_matrix[bmi][i]
377  - 2*(qistart-s->qps[qpi])*s->base_matrix[bmj][i]
378  + s->qr_size[inter][plane][qri])
379  / (2*s->qr_size[inter][plane][qri]);
380 
381  int qmin= 8<<(inter + !i);
382  int qscale= i ? ac_scale_factor : dc_scale_factor;
383 
384  s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
385  av_clip((qscale * coeff) / 100 * 4, qmin, 4096);
386  }
387  // all DC coefficients use the same quant so as not to interfere with DC prediction
388  s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
389  }
390  }
391 }
392 
393 /*
394  * This function initializes the loop filter boundary limits if the frame's
395  * quality index is different from the previous frame's.
396  *
397  * The filter_limit_values may not be larger than 127.
398  */
400 {
401  int *bounding_values= s->bounding_values_array+127;
402  int filter_limit;
403  int x;
404  int value;
405 
406  filter_limit = s->filter_limit_values[s->qps[0]];
407  av_assert0(filter_limit < 128U);
408 
409  /* set up the bounding values */
410  memset(s->bounding_values_array, 0, 256 * sizeof(int));
411  for (x = 0; x < filter_limit; x++) {
412  bounding_values[-x] = -x;
413  bounding_values[x] = x;
414  }
415  for (x = value = filter_limit; x < 128 && value; x++, value--) {
416  bounding_values[ x] = value;
417  bounding_values[-x] = -value;
418  }
419  if (value)
420  bounding_values[128] = value;
421  bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
422 }
423 
424 /*
425  * This function unpacks all of the superblock/macroblock/fragment coding
426  * information from the bitstream.
427  */
429 {
430  int superblock_starts[3] = { 0, s->u_superblock_start, s->v_superblock_start };
431  int bit = 0;
432  int current_superblock = 0;
433  int current_run = 0;
434  int num_partial_superblocks = 0;
435 
436  int i, j;
437  int current_fragment;
438  int plane;
439 
440  if (s->keyframe) {
442 
443  } else {
444 
445  /* unpack the list of partially-coded superblocks */
446  bit = get_bits1(gb) ^ 1;
447  current_run = 0;
448 
449  while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
450  if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
451  bit = get_bits1(gb);
452  else
453  bit ^= 1;
454 
455  current_run = get_vlc2(gb,
456  s->superblock_run_length_vlc.table, 6, 2) + 1;
457  if (current_run == 34)
458  current_run += get_bits(gb, 12);
459 
460  if (current_superblock + current_run > s->superblock_count) {
461  av_log(s->avctx, AV_LOG_ERROR, "Invalid partially coded superblock run length\n");
462  return -1;
463  }
464 
465  memset(s->superblock_coding + current_superblock, bit, current_run);
466 
467  current_superblock += current_run;
468  if (bit)
469  num_partial_superblocks += current_run;
470  }
471 
472  /* unpack the list of fully coded superblocks if any of the blocks were
473  * not marked as partially coded in the previous step */
474  if (num_partial_superblocks < s->superblock_count) {
475  int superblocks_decoded = 0;
476 
477  current_superblock = 0;
478  bit = get_bits1(gb) ^ 1;
479  current_run = 0;
480 
481  while (superblocks_decoded < s->superblock_count - num_partial_superblocks
482  && get_bits_left(gb) > 0) {
483 
484  if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
485  bit = get_bits1(gb);
486  else
487  bit ^= 1;
488 
489  current_run = get_vlc2(gb,
490  s->superblock_run_length_vlc.table, 6, 2) + 1;
491  if (current_run == 34)
492  current_run += get_bits(gb, 12);
493 
494  for (j = 0; j < current_run; current_superblock++) {
495  if (current_superblock >= s->superblock_count) {
496  av_log(s->avctx, AV_LOG_ERROR, "Invalid fully coded superblock run length\n");
497  return -1;
498  }
499 
500  /* skip any superblocks already marked as partially coded */
501  if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
502  s->superblock_coding[current_superblock] = 2*bit;
503  j++;
504  }
505  }
506  superblocks_decoded += current_run;
507  }
508  }
509 
510  /* if there were partial blocks, initialize bitstream for
511  * unpacking fragment codings */
512  if (num_partial_superblocks) {
513 
514  current_run = 0;
515  bit = get_bits1(gb);
516  /* toggle the bit because as soon as the first run length is
517  * fetched the bit will be toggled again */
518  bit ^= 1;
519  }
520  }
521 
522  /* figure out which fragments are coded; iterate through each
523  * superblock (all planes) */
524  s->total_num_coded_frags = 0;
526 
527  for (plane = 0; plane < 3; plane++) {
528  int sb_start = superblock_starts[plane];
529  int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);
530  int num_coded_frags = 0;
531 
532  for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
533 
534  /* iterate through all 16 fragments in a superblock */
535  for (j = 0; j < 16; j++) {
536 
537  /* if the fragment is in bounds, check its coding status */
538  current_fragment = s->superblock_fragments[i * 16 + j];
539  if (current_fragment != -1) {
540  int coded = s->superblock_coding[i];
541 
542  if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
543 
544  /* fragment may or may not be coded; this is the case
545  * that cares about the fragment coding runs */
546  if (current_run-- == 0) {
547  bit ^= 1;
548  current_run = get_vlc2(gb,
549  s->fragment_run_length_vlc.table, 5, 2);
550  }
551  coded = bit;
552  }
553 
554  if (coded) {
555  /* default mode; actual mode will be decoded in
556  * the next phase */
557  s->all_fragments[current_fragment].coding_method =
559  s->coded_fragment_list[plane][num_coded_frags++] =
560  current_fragment;
561  } else {
562  /* not coded; copy this fragment from the prior frame */
563  s->all_fragments[current_fragment].coding_method =
564  MODE_COPY;
565  }
566  }
567  }
568  }
569  s->total_num_coded_frags += num_coded_frags;
570  for (i = 0; i < 64; i++)
571  s->num_coded_frags[plane][i] = num_coded_frags;
572  if (plane < 2)
573  s->coded_fragment_list[plane+1] = s->coded_fragment_list[plane] + num_coded_frags;
574  }
575  return 0;
576 }
577 
578 /*
579  * This function unpacks all the coding mode data for individual macroblocks
580  * from the bitstream.
581  */
583 {
584  int i, j, k, sb_x, sb_y;
585  int scheme;
586  int current_macroblock;
587  int current_fragment;
588  int coding_mode;
589  int custom_mode_alphabet[CODING_MODE_COUNT];
590  const int *alphabet;
591  Vp3Fragment *frag;
592 
593  if (s->keyframe) {
594  for (i = 0; i < s->fragment_count; i++)
596 
597  } else {
598 
599  /* fetch the mode coding scheme for this frame */
600  scheme = get_bits(gb, 3);
601 
602  /* is it a custom coding scheme? */
603  if (scheme == 0) {
604  for (i = 0; i < 8; i++)
605  custom_mode_alphabet[i] = MODE_INTER_NO_MV;
606  for (i = 0; i < 8; i++)
607  custom_mode_alphabet[get_bits(gb, 3)] = i;
608  alphabet = custom_mode_alphabet;
609  } else
610  alphabet = ModeAlphabet[scheme-1];
611 
612  /* iterate through all of the macroblocks that contain 1 or more
613  * coded fragments */
614  for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
615  for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
616  if (get_bits_left(gb) <= 0)
617  return -1;
618 
619  for (j = 0; j < 4; j++) {
620  int mb_x = 2*sb_x + (j>>1);
621  int mb_y = 2*sb_y + (((j>>1)+j)&1);
622  current_macroblock = mb_y * s->macroblock_width + mb_x;
623 
624  if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height)
625  continue;
626 
627 #define BLOCK_X (2*mb_x + (k&1))
628 #define BLOCK_Y (2*mb_y + (k>>1))
629  /* coding modes are only stored if the macroblock has at least one
630  * luma block coded, otherwise it must be INTER_NO_MV */
631  for (k = 0; k < 4; k++) {
632  current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
633  if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
634  break;
635  }
636  if (k == 4) {
637  s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
638  continue;
639  }
640 
641  /* mode 7 means get 3 bits for each coding mode */
642  if (scheme == 7)
643  coding_mode = get_bits(gb, 3);
644  else
645  coding_mode = alphabet
646  [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
647 
648  s->macroblock_coding[current_macroblock] = coding_mode;
649  for (k = 0; k < 4; k++) {
650  frag = s->all_fragments + BLOCK_Y*s->fragment_width[0] + BLOCK_X;
651  if (frag->coding_method != MODE_COPY)
652  frag->coding_method = coding_mode;
653  }
654 
655 #define SET_CHROMA_MODES \
656  if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
657  frag[s->fragment_start[1]].coding_method = coding_mode;\
658  if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
659  frag[s->fragment_start[2]].coding_method = coding_mode;
660 
661  if (s->chroma_y_shift) {
662  frag = s->all_fragments + mb_y*s->fragment_width[1] + mb_x;
664  } else if (s->chroma_x_shift) {
665  frag = s->all_fragments + 2*mb_y*s->fragment_width[1] + mb_x;
666  for (k = 0; k < 2; k++) {
668  frag += s->fragment_width[1];
669  }
670  } else {
671  for (k = 0; k < 4; k++) {
672  frag = s->all_fragments + BLOCK_Y*s->fragment_width[1] + BLOCK_X;
674  }
675  }
676  }
677  }
678  }
679  }
680 
681  return 0;
682 }
683 
684 /*
685  * This function unpacks all the motion vectors for the individual
686  * macroblocks from the bitstream.
687  */
689 {
690  int j, k, sb_x, sb_y;
691  int coding_mode;
692  int motion_x[4];
693  int motion_y[4];
694  int last_motion_x = 0;
695  int last_motion_y = 0;
696  int prior_last_motion_x = 0;
697  int prior_last_motion_y = 0;
698  int current_macroblock;
699  int current_fragment;
700  int frag;
701 
702  if (s->keyframe)
703  return 0;
704 
705  /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
706  coding_mode = get_bits1(gb);
707 
708  /* iterate through all of the macroblocks that contain 1 or more
709  * coded fragments */
710  for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
711  for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
712  if (get_bits_left(gb) <= 0)
713  return -1;
714 
715  for (j = 0; j < 4; j++) {
716  int mb_x = 2*sb_x + (j>>1);
717  int mb_y = 2*sb_y + (((j>>1)+j)&1);
718  current_macroblock = mb_y * s->macroblock_width + mb_x;
719 
720  if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||
721  (s->macroblock_coding[current_macroblock] == MODE_COPY))
722  continue;
723 
724  switch (s->macroblock_coding[current_macroblock]) {
725 
726  case MODE_INTER_PLUS_MV:
727  case MODE_GOLDEN_MV:
728  /* all 6 fragments use the same motion vector */
729  if (coding_mode == 0) {
730  motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
731  motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
732  } else {
733  motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
734  motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
735  }
736 
737  /* vector maintenance, only on MODE_INTER_PLUS_MV */
738  if (s->macroblock_coding[current_macroblock] ==
740  prior_last_motion_x = last_motion_x;
741  prior_last_motion_y = last_motion_y;
742  last_motion_x = motion_x[0];
743  last_motion_y = motion_y[0];
744  }
745  break;
746 
747  case MODE_INTER_FOURMV:
748  /* vector maintenance */
749  prior_last_motion_x = last_motion_x;
750  prior_last_motion_y = last_motion_y;
751 
752  /* fetch 4 vectors from the bitstream, one for each
753  * Y fragment, then average for the C fragment vectors */
754  for (k = 0; k < 4; k++) {
755  current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
756  if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
757  if (coding_mode == 0) {
758  motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
759  motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
760  } else {
761  motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
762  motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
763  }
764  last_motion_x = motion_x[k];
765  last_motion_y = motion_y[k];
766  } else {
767  motion_x[k] = 0;
768  motion_y[k] = 0;
769  }
770  }
771  break;
772 
773  case MODE_INTER_LAST_MV:
774  /* all 6 fragments use the last motion vector */
775  motion_x[0] = last_motion_x;
776  motion_y[0] = last_motion_y;
777 
778  /* no vector maintenance (last vector remains the
779  * last vector) */
780  break;
781 
783  /* all 6 fragments use the motion vector prior to the
784  * last motion vector */
785  motion_x[0] = prior_last_motion_x;
786  motion_y[0] = prior_last_motion_y;
787 
788  /* vector maintenance */
789  prior_last_motion_x = last_motion_x;
790  prior_last_motion_y = last_motion_y;
791  last_motion_x = motion_x[0];
792  last_motion_y = motion_y[0];
793  break;
794 
795  default:
796  /* covers intra, inter without MV, golden without MV */
797  motion_x[0] = 0;
798  motion_y[0] = 0;
799 
800  /* no vector maintenance */
801  break;
802  }
803 
804  /* assign the motion vectors to the correct fragments */
805  for (k = 0; k < 4; k++) {
806  current_fragment =
808  if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
809  s->motion_val[0][current_fragment][0] = motion_x[k];
810  s->motion_val[0][current_fragment][1] = motion_y[k];
811  } else {
812  s->motion_val[0][current_fragment][0] = motion_x[0];
813  s->motion_val[0][current_fragment][1] = motion_y[0];
814  }
815  }
816 
817  if (s->chroma_y_shift) {
818  if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
819  motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] + motion_x[2] + motion_x[3], 2);
820  motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] + motion_y[2] + motion_y[3], 2);
821  }
822  motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
823  motion_y[0] = (motion_y[0]>>1) | (motion_y[0]&1);
824  frag = mb_y*s->fragment_width[1] + mb_x;
825  s->motion_val[1][frag][0] = motion_x[0];
826  s->motion_val[1][frag][1] = motion_y[0];
827  } else if (s->chroma_x_shift) {
828  if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
829  motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
830  motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
831  motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
832  motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
833  } else {
834  motion_x[1] = motion_x[0];
835  motion_y[1] = motion_y[0];
836  }
837  motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
838  motion_x[1] = (motion_x[1]>>1) | (motion_x[1]&1);
839 
840  frag = 2*mb_y*s->fragment_width[1] + mb_x;
841  for (k = 0; k < 2; k++) {
842  s->motion_val[1][frag][0] = motion_x[k];
843  s->motion_val[1][frag][1] = motion_y[k];
844  frag += s->fragment_width[1];
845  }
846  } else {
847  for (k = 0; k < 4; k++) {
848  frag = BLOCK_Y*s->fragment_width[1] + BLOCK_X;
849  if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
850  s->motion_val[1][frag][0] = motion_x[k];
851  s->motion_val[1][frag][1] = motion_y[k];
852  } else {
853  s->motion_val[1][frag][0] = motion_x[0];
854  s->motion_val[1][frag][1] = motion_y[0];
855  }
856  }
857  }
858  }
859  }
860  }
861 
862  return 0;
863 }
864 
866 {
867  int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
868  int num_blocks = s->total_num_coded_frags;
869 
870  for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
871  i = blocks_decoded = num_blocks_at_qpi = 0;
872 
873  bit = get_bits1(gb) ^ 1;
874  run_length = 0;
875 
876  do {
877  if (run_length == MAXIMUM_LONG_BIT_RUN)
878  bit = get_bits1(gb);
879  else
880  bit ^= 1;
881 
882  run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
883  if (run_length == 34)
884  run_length += get_bits(gb, 12);
885  blocks_decoded += run_length;
886 
887  if (!bit)
888  num_blocks_at_qpi += run_length;
889 
890  for (j = 0; j < run_length; i++) {
891  if (i >= s->total_num_coded_frags)
892  return -1;
893 
894  if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
895  s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
896  j++;
897  }
898  }
899  } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
900 
901  num_blocks -= num_blocks_at_qpi;
902  }
903 
904  return 0;
905 }
906 
907 /*
908  * This function is called by unpack_dct_coeffs() to extract the VLCs from
909  * the bitstream. The VLCs encode tokens which are used to unpack DCT
910  * data. This function unpacks all the VLCs for either the Y plane or both
911  * C planes, and is called for DC coefficients or different AC coefficient
912  * levels (since different coefficient types require different VLC tables.
913  *
914  * This function returns a residual eob run. E.g, if a particular token gave
915  * instructions to EOB the next 5 fragments and there were only 2 fragments
916  * left in the current fragment range, 3 would be returned so that it could
917  * be passed into the next call to this same function.
918  */
920  VLC *table, int coeff_index,
921  int plane,
922  int eob_run)
923 {
924  int i, j = 0;
925  int token;
926  int zero_run = 0;
927  int16_t coeff = 0;
928  int bits_to_get;
929  int blocks_ended;
930  int coeff_i = 0;
931  int num_coeffs = s->num_coded_frags[plane][coeff_index];
932  int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
933 
934  /* local references to structure members to avoid repeated deferences */
935  int *coded_fragment_list = s->coded_fragment_list[plane];
936  Vp3Fragment *all_fragments = s->all_fragments;
937  VLC_TYPE (*vlc_table)[2] = table->table;
938 
939  if (num_coeffs < 0)
940  av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);
941 
942  if (eob_run > num_coeffs) {
943  coeff_i = blocks_ended = num_coeffs;
944  eob_run -= num_coeffs;
945  } else {
946  coeff_i = blocks_ended = eob_run;
947  eob_run = 0;
948  }
949 
950  // insert fake EOB token to cover the split between planes or zzi
951  if (blocks_ended)
952  dct_tokens[j++] = blocks_ended << 2;
953 
954  while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
955  /* decode a VLC into a token */
956  token = get_vlc2(gb, vlc_table, 11, 3);
957  /* use the token to get a zero run, a coefficient, and an eob run */
958  if ((unsigned) token <= 6U) {
959  eob_run = eob_run_base[token];
960  if (eob_run_get_bits[token])
961  eob_run += get_bits(gb, eob_run_get_bits[token]);
962 
963  // record only the number of blocks ended in this plane,
964  // any spill will be recorded in the next plane.
965  if (eob_run > num_coeffs - coeff_i) {
966  dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
967  blocks_ended += num_coeffs - coeff_i;
968  eob_run -= num_coeffs - coeff_i;
969  coeff_i = num_coeffs;
970  } else {
971  dct_tokens[j++] = TOKEN_EOB(eob_run);
972  blocks_ended += eob_run;
973  coeff_i += eob_run;
974  eob_run = 0;
975  }
976  } else if (token >= 0) {
977  bits_to_get = coeff_get_bits[token];
978  if (bits_to_get)
979  bits_to_get = get_bits(gb, bits_to_get);
980  coeff = coeff_tables[token][bits_to_get];
981 
982  zero_run = zero_run_base[token];
983  if (zero_run_get_bits[token])
984  zero_run += get_bits(gb, zero_run_get_bits[token]);
985 
986  if (zero_run) {
987  dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
988  } else {
989  // Save DC into the fragment structure. DC prediction is
990  // done in raster order, so the actual DC can't be in with
991  // other tokens. We still need the token in dct_tokens[]
992  // however, or else the structure collapses on itself.
993  if (!coeff_index)
994  all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
995 
996  dct_tokens[j++] = TOKEN_COEFF(coeff);
997  }
998 
999  if (coeff_index + zero_run > 64) {
1000  av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
1001  " %d coeffs left\n", zero_run, 64-coeff_index);
1002  zero_run = 64 - coeff_index;
1003  }
1004 
1005  // zero runs code multiple coefficients,
1006  // so don't try to decode coeffs for those higher levels
1007  for (i = coeff_index+1; i <= coeff_index+zero_run; i++)
1008  s->num_coded_frags[plane][i]--;
1009  coeff_i++;
1010  } else {
1012  "Invalid token %d\n", token);
1013  return -1;
1014  }
1015  }
1016 
1017  if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1018  av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1019 
1020  // decrement the number of blocks that have higher coeffecients for each
1021  // EOB run at this level
1022  if (blocks_ended)
1023  for (i = coeff_index+1; i < 64; i++)
1024  s->num_coded_frags[plane][i] -= blocks_ended;
1025 
1026  // setup the next buffer
1027  if (plane < 2)
1028  s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;
1029  else if (coeff_index < 63)
1030  s->dct_tokens[0][coeff_index+1] = dct_tokens + j;
1031 
1032  return eob_run;
1033 }
1034 
1036  int first_fragment,
1037  int fragment_width,
1038  int fragment_height);
1039 /*
1040  * This function unpacks all of the DCT coefficient data from the
1041  * bitstream.
1042  */
1044 {
1045  int i;
1046  int dc_y_table;
1047  int dc_c_table;
1048  int ac_y_table;
1049  int ac_c_table;
1050  int residual_eob_run = 0;
1051  VLC *y_tables[64];
1052  VLC *c_tables[64];
1053 
1054  s->dct_tokens[0][0] = s->dct_tokens_base;
1055 
1056  /* fetch the DC table indexes */
1057  dc_y_table = get_bits(gb, 4);
1058  dc_c_table = get_bits(gb, 4);
1059 
1060  /* unpack the Y plane DC coefficients */
1061  residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
1062  0, residual_eob_run);
1063  if (residual_eob_run < 0)
1064  return residual_eob_run;
1065 
1066  /* reverse prediction of the Y-plane DC coefficients */
1068 
1069  /* unpack the C plane DC coefficients */
1070  residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1071  1, residual_eob_run);
1072  if (residual_eob_run < 0)
1073  return residual_eob_run;
1074  residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1075  2, residual_eob_run);
1076  if (residual_eob_run < 0)
1077  return residual_eob_run;
1078 
1079  /* reverse prediction of the C-plane DC coefficients */
1080  if (!(s->avctx->flags & CODEC_FLAG_GRAY))
1081  {
1083  s->fragment_width[1], s->fragment_height[1]);
1085  s->fragment_width[1], s->fragment_height[1]);
1086  }
1087 
1088  /* fetch the AC table indexes */
1089  ac_y_table = get_bits(gb, 4);
1090  ac_c_table = get_bits(gb, 4);
1091 
1092  /* build tables of AC VLC tables */
1093  for (i = 1; i <= 5; i++) {
1094  y_tables[i] = &s->ac_vlc_1[ac_y_table];
1095  c_tables[i] = &s->ac_vlc_1[ac_c_table];
1096  }
1097  for (i = 6; i <= 14; i++) {
1098  y_tables[i] = &s->ac_vlc_2[ac_y_table];
1099  c_tables[i] = &s->ac_vlc_2[ac_c_table];
1100  }
1101  for (i = 15; i <= 27; i++) {
1102  y_tables[i] = &s->ac_vlc_3[ac_y_table];
1103  c_tables[i] = &s->ac_vlc_3[ac_c_table];
1104  }
1105  for (i = 28; i <= 63; i++) {
1106  y_tables[i] = &s->ac_vlc_4[ac_y_table];
1107  c_tables[i] = &s->ac_vlc_4[ac_c_table];
1108  }
1109 
1110  /* decode all AC coefficents */
1111  for (i = 1; i <= 63; i++) {
1112  residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1113  0, residual_eob_run);
1114  if (residual_eob_run < 0)
1115  return residual_eob_run;
1116 
1117  residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1118  1, residual_eob_run);
1119  if (residual_eob_run < 0)
1120  return residual_eob_run;
1121  residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1122  2, residual_eob_run);
1123  if (residual_eob_run < 0)
1124  return residual_eob_run;
1125  }
1126 
1127  return 0;
1128 }
1129 
1130 /*
1131  * This function reverses the DC prediction for each coded fragment in
1132  * the frame. Much of this function is adapted directly from the original
1133  * VP3 source code.
1134  */
1135 #define COMPATIBLE_FRAME(x) \
1136  (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1137 #define DC_COEFF(u) s->all_fragments[u].dc
1138 
1140  int first_fragment,
1141  int fragment_width,
1142  int fragment_height)
1143 {
1144 
1145 #define PUL 8
1146 #define PU 4
1147 #define PUR 2
1148 #define PL 1
1149 
1150  int x, y;
1151  int i = first_fragment;
1152 
1153  int predicted_dc;
1154 
1155  /* DC values for the left, up-left, up, and up-right fragments */
1156  int vl, vul, vu, vur;
1157 
1158  /* indexes for the left, up-left, up, and up-right fragments */
1159  int l, ul, u, ur;
1160 
1161  /*
1162  * The 6 fields mean:
1163  * 0: up-left multiplier
1164  * 1: up multiplier
1165  * 2: up-right multiplier
1166  * 3: left multiplier
1167  */
1168  static const int predictor_transform[16][4] = {
1169  { 0, 0, 0, 0},
1170  { 0, 0, 0,128}, // PL
1171  { 0, 0,128, 0}, // PUR
1172  { 0, 0, 53, 75}, // PUR|PL
1173  { 0,128, 0, 0}, // PU
1174  { 0, 64, 0, 64}, // PU|PL
1175  { 0,128, 0, 0}, // PU|PUR
1176  { 0, 0, 53, 75}, // PU|PUR|PL
1177  {128, 0, 0, 0}, // PUL
1178  { 0, 0, 0,128}, // PUL|PL
1179  { 64, 0, 64, 0}, // PUL|PUR
1180  { 0, 0, 53, 75}, // PUL|PUR|PL
1181  { 0,128, 0, 0}, // PUL|PU
1182  {-104,116, 0,116}, // PUL|PU|PL
1183  { 24, 80, 24, 0}, // PUL|PU|PUR
1184  {-104,116, 0,116} // PUL|PU|PUR|PL
1185  };
1186 
1187  /* This table shows which types of blocks can use other blocks for
1188  * prediction. For example, INTRA is the only mode in this table to
1189  * have a frame number of 0. That means INTRA blocks can only predict
1190  * from other INTRA blocks. There are 2 golden frame coding types;
1191  * blocks encoding in these modes can only predict from other blocks
1192  * that were encoded with these 1 of these 2 modes. */
1193  static const unsigned char compatible_frame[9] = {
1194  1, /* MODE_INTER_NO_MV */
1195  0, /* MODE_INTRA */
1196  1, /* MODE_INTER_PLUS_MV */
1197  1, /* MODE_INTER_LAST_MV */
1198  1, /* MODE_INTER_PRIOR_MV */
1199  2, /* MODE_USING_GOLDEN */
1200  2, /* MODE_GOLDEN_MV */
1201  1, /* MODE_INTER_FOUR_MV */
1202  3 /* MODE_COPY */
1203  };
1204  int current_frame_type;
1205 
1206  /* there is a last DC predictor for each of the 3 frame types */
1207  short last_dc[3];
1208 
1209  int transform = 0;
1210 
1211  vul = vu = vur = vl = 0;
1212  last_dc[0] = last_dc[1] = last_dc[2] = 0;
1213 
1214  /* for each fragment row... */
1215  for (y = 0; y < fragment_height; y++) {
1216 
1217  /* for each fragment in a row... */
1218  for (x = 0; x < fragment_width; x++, i++) {
1219 
1220  /* reverse prediction if this block was coded */
1221  if (s->all_fragments[i].coding_method != MODE_COPY) {
1222 
1223  current_frame_type =
1224  compatible_frame[s->all_fragments[i].coding_method];
1225 
1226  transform= 0;
1227  if(x){
1228  l= i-1;
1229  vl = DC_COEFF(l);
1230  if(COMPATIBLE_FRAME(l))
1231  transform |= PL;
1232  }
1233  if(y){
1234  u= i-fragment_width;
1235  vu = DC_COEFF(u);
1236  if(COMPATIBLE_FRAME(u))
1237  transform |= PU;
1238  if(x){
1239  ul= i-fragment_width-1;
1240  vul = DC_COEFF(ul);
1241  if(COMPATIBLE_FRAME(ul))
1242  transform |= PUL;
1243  }
1244  if(x + 1 < fragment_width){
1245  ur= i-fragment_width+1;
1246  vur = DC_COEFF(ur);
1247  if(COMPATIBLE_FRAME(ur))
1248  transform |= PUR;
1249  }
1250  }
1251 
1252  if (transform == 0) {
1253 
1254  /* if there were no fragments to predict from, use last
1255  * DC saved */
1256  predicted_dc = last_dc[current_frame_type];
1257  } else {
1258 
1259  /* apply the appropriate predictor transform */
1260  predicted_dc =
1261  (predictor_transform[transform][0] * vul) +
1262  (predictor_transform[transform][1] * vu) +
1263  (predictor_transform[transform][2] * vur) +
1264  (predictor_transform[transform][3] * vl);
1265 
1266  predicted_dc /= 128;
1267 
1268  /* check for outranging on the [ul u l] and
1269  * [ul u ur l] predictors */
1270  if ((transform == 15) || (transform == 13)) {
1271  if (FFABS(predicted_dc - vu) > 128)
1272  predicted_dc = vu;
1273  else if (FFABS(predicted_dc - vl) > 128)
1274  predicted_dc = vl;
1275  else if (FFABS(predicted_dc - vul) > 128)
1276  predicted_dc = vul;
1277  }
1278  }
1279 
1280  /* at long last, apply the predictor */
1281  DC_COEFF(i) += predicted_dc;
1282  /* save the DC */
1283  last_dc[current_frame_type] = DC_COEFF(i);
1284  }
1285  }
1286  }
1287 }
1288 
1289 static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
1290 {
1291  int x, y;
1292  int *bounding_values= s->bounding_values_array+127;
1293 
1294  int width = s->fragment_width[!!plane];
1295  int height = s->fragment_height[!!plane];
1296  int fragment = s->fragment_start [plane] + ystart * width;
1297  ptrdiff_t stride = s->current_frame.f->linesize[plane];
1298  uint8_t *plane_data = s->current_frame.f->data [plane];
1299  if (!s->flipped_image) stride = -stride;
1300  plane_data += s->data_offset[plane] + 8*ystart*stride;
1301 
1302  for (y = ystart; y < yend; y++) {
1303 
1304  for (x = 0; x < width; x++) {
1305  /* This code basically just deblocks on the edges of coded blocks.
1306  * However, it has to be much more complicated because of the
1307  * braindamaged deblock ordering used in VP3/Theora. Order matters
1308  * because some pixels get filtered twice. */
1309  if( s->all_fragments[fragment].coding_method != MODE_COPY )
1310  {
1311  /* do not perform left edge filter for left columns frags */
1312  if (x > 0) {
1313  s->vp3dsp.h_loop_filter(
1314  plane_data + 8*x,
1315  stride, bounding_values);
1316  }
1317 
1318  /* do not perform top edge filter for top row fragments */
1319  if (y > 0) {
1320  s->vp3dsp.v_loop_filter(
1321  plane_data + 8*x,
1322  stride, bounding_values);
1323  }
1324 
1325  /* do not perform right edge filter for right column
1326  * fragments or if right fragment neighbor is also coded
1327  * in this frame (it will be filtered in next iteration) */
1328  if ((x < width - 1) &&
1329  (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1330  s->vp3dsp.h_loop_filter(
1331  plane_data + 8*x + 8,
1332  stride, bounding_values);
1333  }
1334 
1335  /* do not perform bottom edge filter for bottom row
1336  * fragments or if bottom fragment neighbor is also coded
1337  * in this frame (it will be filtered in the next row) */
1338  if ((y < height - 1) &&
1339  (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1340  s->vp3dsp.v_loop_filter(
1341  plane_data + 8*x + 8*stride,
1342  stride, bounding_values);
1343  }
1344  }
1345 
1346  fragment++;
1347  }
1348  plane_data += 8*stride;
1349  }
1350 }
1351 
1352 /**
1353  * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1354  * for the next block in coding order
1355  */
1356 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1357  int plane, int inter, int16_t block[64])
1358 {
1359  int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1360  uint8_t *perm = s->idct_scantable;
1361  int i = 0;
1362 
1363  do {
1364  int token = *s->dct_tokens[plane][i];
1365  switch (token & 3) {
1366  case 0: // EOB
1367  if (--token < 4) // 0-3 are token types, so the EOB run must now be 0
1368  s->dct_tokens[plane][i]++;
1369  else
1370  *s->dct_tokens[plane][i] = token & ~3;
1371  goto end;
1372  case 1: // zero run
1373  s->dct_tokens[plane][i]++;
1374  i += (token >> 2) & 0x7f;
1375  if (i > 63) {
1376  av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1377  return i;
1378  }
1379  block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1380  i++;
1381  break;
1382  case 2: // coeff
1383  block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1384  s->dct_tokens[plane][i++]++;
1385  break;
1386  default: // shouldn't happen
1387  return i;
1388  }
1389  } while (i < 64);
1390  // return value is expected to be a valid level
1391  i--;
1392 end:
1393  // the actual DC+prediction is in the fragment structure
1394  block[0] = frag->dc * s->qmat[0][inter][plane][0];
1395  return i;
1396 }
1397 
1398 /**
1399  * called when all pixels up to row y are complete
1400  */
1402 {
1403  int h, cy, i;
1405 
1406  if (HAVE_THREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {
1407  int y_flipped = s->flipped_image ? s->avctx->height-y : y;
1408 
1409  // At the end of the frame, report INT_MAX instead of the height of the frame.
1410  // This makes the other threads' ff_thread_await_progress() calls cheaper, because
1411  // they don't have to clip their values.
1412  ff_thread_report_progress(&s->current_frame, y_flipped==s->avctx->height ? INT_MAX : y_flipped-1, 0);
1413  }
1414 
1415  if(s->avctx->draw_horiz_band==NULL)
1416  return;
1417 
1418  h= y - s->last_slice_end;
1419  s->last_slice_end= y;
1420  y -= h;
1421 
1422  if (!s->flipped_image) {
1423  y = s->avctx->height - y - h;
1424  }
1425 
1426  cy = y >> s->chroma_y_shift;
1427  offset[0] = s->current_frame.f->linesize[0]*y;
1428  offset[1] = s->current_frame.f->linesize[1]*cy;
1429  offset[2] = s->current_frame.f->linesize[2]*cy;
1430  for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1431  offset[i] = 0;
1432 
1433  emms_c();
1434  s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1435 }
1436 
1437 /**
1438  * Wait for the reference frame of the current fragment.
1439  * The progress value is in luma pixel rows.
1440  */
1441 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment, int motion_y, int y)
1442 {
1444  int ref_row;
1445  int border = motion_y&1;
1446 
1447  if (fragment->coding_method == MODE_USING_GOLDEN ||
1448  fragment->coding_method == MODE_GOLDEN_MV)
1449  ref_frame = &s->golden_frame;
1450  else
1451  ref_frame = &s->last_frame;
1452 
1453  ref_row = y + (motion_y>>1);
1454  ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1455 
1456  ff_thread_await_progress(ref_frame, ref_row, 0);
1457 }
1458 
1459 /*
1460  * Perform the final rendering for a particular slice of data.
1461  * The slice number ranges from 0..(c_superblock_height - 1).
1462  */
1463 static void render_slice(Vp3DecodeContext *s, int slice)
1464 {
1465  int x, y, i, j, fragment;
1466  int16_t *block = s->block;
1467  int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1468  int motion_halfpel_index;
1469  uint8_t *motion_source;
1470  int plane, first_pixel;
1471 
1472  if (slice >= s->c_superblock_height)
1473  return;
1474 
1475  for (plane = 0; plane < 3; plane++) {
1476  uint8_t *output_plane = s->current_frame.f->data [plane] + s->data_offset[plane];
1477  uint8_t * last_plane = s-> last_frame.f->data [plane] + s->data_offset[plane];
1478  uint8_t *golden_plane = s-> golden_frame.f->data [plane] + s->data_offset[plane];
1479  ptrdiff_t stride = s->current_frame.f->linesize[plane];
1480  int plane_width = s->width >> (plane && s->chroma_x_shift);
1481  int plane_height = s->height >> (plane && s->chroma_y_shift);
1482  int8_t (*motion_val)[2] = s->motion_val[!!plane];
1483 
1484  int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
1485  int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
1486  int slice_width = plane ? s->c_superblock_width : s->y_superblock_width;
1487 
1488  int fragment_width = s->fragment_width[!!plane];
1489  int fragment_height = s->fragment_height[!!plane];
1490  int fragment_start = s->fragment_start[plane];
1491  int do_await = !plane && HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_FRAME);
1492 
1493  if (!s->flipped_image) stride = -stride;
1494  if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
1495  continue;
1496 
1497  /* for each superblock row in the slice (both of them)... */
1498  for (; sb_y < slice_height; sb_y++) {
1499 
1500  /* for each superblock in a row... */
1501  for (sb_x = 0; sb_x < slice_width; sb_x++) {
1502 
1503  /* for each block in a superblock... */
1504  for (j = 0; j < 16; j++) {
1505  x = 4*sb_x + hilbert_offset[j][0];
1506  y = 4*sb_y + hilbert_offset[j][1];
1507  fragment = y*fragment_width + x;
1508 
1509  i = fragment_start + fragment;
1510 
1511  // bounds check
1512  if (x >= fragment_width || y >= fragment_height)
1513  continue;
1514 
1515  first_pixel = 8*y*stride + 8*x;
1516 
1517  if (do_await && s->all_fragments[i].coding_method != MODE_INTRA)
1518  await_reference_row(s, &s->all_fragments[i], motion_val[fragment][1], (16*y) >> s->chroma_y_shift);
1519 
1520  /* transform if this block was coded */
1521  if (s->all_fragments[i].coding_method != MODE_COPY) {
1524  motion_source= golden_plane;
1525  else
1526  motion_source= last_plane;
1527 
1528  motion_source += first_pixel;
1529  motion_halfpel_index = 0;
1530 
1531  /* sort out the motion vector if this fragment is coded
1532  * using a motion vector method */
1533  if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1535  int src_x, src_y;
1536  motion_x = motion_val[fragment][0];
1537  motion_y = motion_val[fragment][1];
1538 
1539  src_x= (motion_x>>1) + 8*x;
1540  src_y= (motion_y>>1) + 8*y;
1541 
1542  motion_halfpel_index = motion_x & 0x01;
1543  motion_source += (motion_x >> 1);
1544 
1545  motion_halfpel_index |= (motion_y & 0x01) << 1;
1546  motion_source += ((motion_y >> 1) * stride);
1547 
1548  if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
1550  if(stride<0) temp -= 8*stride;
1551 
1552  s->vdsp.emulated_edge_mc(temp, motion_source,
1553  stride, stride,
1554  9, 9, src_x, src_y,
1555  plane_width,
1556  plane_height);
1557  motion_source= temp;
1558  }
1559  }
1560 
1561 
1562  /* first, take care of copying a block from either the
1563  * previous or the golden frame */
1564  if (s->all_fragments[i].coding_method != MODE_INTRA) {
1565  /* Note, it is possible to implement all MC cases with
1566  put_no_rnd_pixels_l2 which would look more like the
1567  VP3 source but this would be slower as
1568  put_no_rnd_pixels_tab is better optimzed */
1569  if(motion_halfpel_index != 3){
1570  s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1571  output_plane + first_pixel,
1572  motion_source, stride, 8);
1573  }else{
1574  int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
1576  output_plane + first_pixel,
1577  motion_source - d,
1578  motion_source + stride + 1 + d,
1579  stride, 8);
1580  }
1581  }
1582 
1583  /* invert DCT and place (or add) in final output */
1584 
1585  if (s->all_fragments[i].coding_method == MODE_INTRA) {
1586  vp3_dequant(s, s->all_fragments + i, plane, 0, block);
1587  s->vp3dsp.idct_put(
1588  output_plane + first_pixel,
1589  stride,
1590  block);
1591  } else {
1592  if (vp3_dequant(s, s->all_fragments + i, plane, 1, block)) {
1593  s->vp3dsp.idct_add(
1594  output_plane + first_pixel,
1595  stride,
1596  block);
1597  } else {
1598  s->vp3dsp.idct_dc_add(output_plane + first_pixel, stride, block);
1599  }
1600  }
1601  } else {
1602 
1603  /* copy directly from the previous frame */
1604  s->hdsp.put_pixels_tab[1][0](
1605  output_plane + first_pixel,
1606  last_plane + first_pixel,
1607  stride, 8);
1608 
1609  }
1610  }
1611  }
1612 
1613  // Filter up to the last row in the superblock row
1614  if (!s->skip_loop_filter)
1615  apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
1616  }
1617  }
1618 
1619  /* this looks like a good place for slice dispatch... */
1620  /* algorithm:
1621  * if (slice == s->macroblock_height - 1)
1622  * dispatch (both last slice & 2nd-to-last slice);
1623  * else if (slice > 0)
1624  * dispatch (slice - 1);
1625  */
1626 
1627  vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) -16, s->height-16));
1628 }
1629 
1630 /// Allocate tables for per-frame data in Vp3DecodeContext
1632 {
1633  Vp3DecodeContext *s = avctx->priv_data;
1634  int y_fragment_count, c_fragment_count;
1635 
1636  y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1637  c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1638 
1641  s->coded_fragment_list[0] = av_mallocz(s->fragment_count * sizeof(int));
1642  s->dct_tokens_base = av_mallocz(64*s->fragment_count * sizeof(*s->dct_tokens_base));
1643  s->motion_val[0] = av_mallocz(y_fragment_count * sizeof(*s->motion_val[0]));
1644  s->motion_val[1] = av_mallocz(c_fragment_count * sizeof(*s->motion_val[1]));
1645 
1646  /* work out the block mapping tables */
1647  s->superblock_fragments = av_mallocz(s->superblock_count * 16 * sizeof(int));
1649 
1650  if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
1652  !s->motion_val[0] || !s->motion_val[1]) {
1653  vp3_decode_end(avctx);
1654  return -1;
1655  }
1656 
1657  init_block_mapping(s);
1658 
1659  return 0;
1660 }
1661 
1663 {
1665  s->last_frame.f = av_frame_alloc();
1666  s->golden_frame.f = av_frame_alloc();
1667 
1668  if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
1670  av_frame_free(&s->last_frame.f);
1672  return AVERROR(ENOMEM);
1673  }
1674 
1675  return 0;
1676 }
1677 
1679 {
1680  Vp3DecodeContext *s = avctx->priv_data;
1681  int i, inter, plane, ret;
1682  int c_width;
1683  int c_height;
1684  int y_fragment_count, c_fragment_count;
1685 
1686  ret = init_frames(s);
1687  if (ret < 0)
1688  return ret;
1689 
1690  avctx->internal->allocate_progress = 1;
1691 
1692  if (avctx->codec_tag == MKTAG('V','P','3','0'))
1693  s->version = 0;
1694  else
1695  s->version = 1;
1696 
1697  s->avctx = avctx;
1698  s->width = FFALIGN(avctx->width, 16);
1699  s->height = FFALIGN(avctx->height, 16);
1700  if (avctx->codec_id != AV_CODEC_ID_THEORA)
1701  avctx->pix_fmt = AV_PIX_FMT_YUV420P;
1704  ff_videodsp_init(&s->vdsp, 8);
1705  ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
1706 
1707  for (i = 0; i < 64; i++) {
1708 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
1709  s->idct_permutation[i] = TRANSPOSE(i);
1711 #undef TRANSPOSE
1712  }
1713 
1714  /* initialize to an impossible value which will force a recalculation
1715  * in the first frame decode */
1716  for (i = 0; i < 3; i++)
1717  s->qps[i] = -1;
1718 
1720 
1721  s->y_superblock_width = (s->width + 31) / 32;
1722  s->y_superblock_height = (s->height + 31) / 32;
1724 
1725  /* work out the dimensions for the C planes */
1726  c_width = s->width >> s->chroma_x_shift;
1727  c_height = s->height >> s->chroma_y_shift;
1728  s->c_superblock_width = (c_width + 31) / 32;
1729  s->c_superblock_height = (c_height + 31) / 32;
1731 
1735 
1736  s->macroblock_width = (s->width + 15) / 16;
1737  s->macroblock_height = (s->height + 15) / 16;
1739 
1740  s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1741  s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1742  s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
1743  s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
1744 
1745  /* fragment count covers all 8x8 blocks for all 3 planes */
1746  y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1747  c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1748  s->fragment_count = y_fragment_count + 2*c_fragment_count;
1749  s->fragment_start[1] = y_fragment_count;
1750  s->fragment_start[2] = y_fragment_count + c_fragment_count;
1751 
1752  if (!s->theora_tables)
1753  {
1754  for (i = 0; i < 64; i++) {
1757  s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1758  s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1759  s->base_matrix[2][i] = vp31_inter_dequant[i];
1761  }
1762 
1763  for(inter=0; inter<2; inter++){
1764  for(plane=0; plane<3; plane++){
1765  s->qr_count[inter][plane]= 1;
1766  s->qr_size [inter][plane][0]= 63;
1767  s->qr_base [inter][plane][0]=
1768  s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
1769  }
1770  }
1771 
1772  /* init VLC tables */
1773  for (i = 0; i < 16; i++) {
1774 
1775  /* DC histograms */
1776  init_vlc(&s->dc_vlc[i], 11, 32,
1777  &dc_bias[i][0][1], 4, 2,
1778  &dc_bias[i][0][0], 4, 2, 0);
1779 
1780  /* group 1 AC histograms */
1781  init_vlc(&s->ac_vlc_1[i], 11, 32,
1782  &ac_bias_0[i][0][1], 4, 2,
1783  &ac_bias_0[i][0][0], 4, 2, 0);
1784 
1785  /* group 2 AC histograms */
1786  init_vlc(&s->ac_vlc_2[i], 11, 32,
1787  &ac_bias_1[i][0][1], 4, 2,
1788  &ac_bias_1[i][0][0], 4, 2, 0);
1789 
1790  /* group 3 AC histograms */
1791  init_vlc(&s->ac_vlc_3[i], 11, 32,
1792  &ac_bias_2[i][0][1], 4, 2,
1793  &ac_bias_2[i][0][0], 4, 2, 0);
1794 
1795  /* group 4 AC histograms */
1796  init_vlc(&s->ac_vlc_4[i], 11, 32,
1797  &ac_bias_3[i][0][1], 4, 2,
1798  &ac_bias_3[i][0][0], 4, 2, 0);
1799  }
1800  } else {
1801 
1802  for (i = 0; i < 16; i++) {
1803  /* DC histograms */
1804  if (init_vlc(&s->dc_vlc[i], 11, 32,
1805  &s->huffman_table[i][0][1], 8, 4,
1806  &s->huffman_table[i][0][0], 8, 4, 0) < 0)
1807  goto vlc_fail;
1808 
1809  /* group 1 AC histograms */
1810  if (init_vlc(&s->ac_vlc_1[i], 11, 32,
1811  &s->huffman_table[i+16][0][1], 8, 4,
1812  &s->huffman_table[i+16][0][0], 8, 4, 0) < 0)
1813  goto vlc_fail;
1814 
1815  /* group 2 AC histograms */
1816  if (init_vlc(&s->ac_vlc_2[i], 11, 32,
1817  &s->huffman_table[i+16*2][0][1], 8, 4,
1818  &s->huffman_table[i+16*2][0][0], 8, 4, 0) < 0)
1819  goto vlc_fail;
1820 
1821  /* group 3 AC histograms */
1822  if (init_vlc(&s->ac_vlc_3[i], 11, 32,
1823  &s->huffman_table[i+16*3][0][1], 8, 4,
1824  &s->huffman_table[i+16*3][0][0], 8, 4, 0) < 0)
1825  goto vlc_fail;
1826 
1827  /* group 4 AC histograms */
1828  if (init_vlc(&s->ac_vlc_4[i], 11, 32,
1829  &s->huffman_table[i+16*4][0][1], 8, 4,
1830  &s->huffman_table[i+16*4][0][0], 8, 4, 0) < 0)
1831  goto vlc_fail;
1832  }
1833  }
1834 
1836  &superblock_run_length_vlc_table[0][1], 4, 2,
1837  &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1838 
1839  init_vlc(&s->fragment_run_length_vlc, 5, 30,
1840  &fragment_run_length_vlc_table[0][1], 4, 2,
1841  &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1842 
1843  init_vlc(&s->mode_code_vlc, 3, 8,
1844  &mode_code_vlc_table[0][1], 2, 1,
1845  &mode_code_vlc_table[0][0], 2, 1, 0);
1846 
1847  init_vlc(&s->motion_vector_vlc, 6, 63,
1848  &motion_vector_vlc_table[0][1], 2, 1,
1849  &motion_vector_vlc_table[0][0], 2, 1, 0);
1850 
1851  return allocate_tables(avctx);
1852 
1853 vlc_fail:
1854  av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1855  return -1;
1856 }
1857 
1858 /// Release and shuffle frames after decode finishes
1859 static int update_frames(AVCodecContext *avctx)
1860 {
1861  Vp3DecodeContext *s = avctx->priv_data;
1862  int ret = 0;
1863 
1864 
1865  /* shuffle frames (last = current) */
1868  if (ret < 0)
1869  goto fail;
1870 
1871  if (s->keyframe) {
1874  }
1875 
1876 fail:
1878  return ret;
1879 }
1880 
1882 {
1884  if (src->f->data[0])
1885  return ff_thread_ref_frame(dst, src);
1886  return 0;
1887 }
1888 
1890 {
1891  int ret;
1892  if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
1893  (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
1894  (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
1895  return ret;
1896  return 0;
1897 }
1898 
1900 {
1901  Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
1902  int qps_changed = 0, i, err;
1903 
1904 #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
1905 
1906  if (!s1->current_frame.f->data[0]
1907  ||s->width != s1->width
1908  ||s->height!= s1->height) {
1909  if (s != s1)
1910  ref_frames(s, s1);
1911  return -1;
1912  }
1913 
1914  if (s != s1) {
1915  // init tables if the first frame hasn't been decoded
1916  if (!s->current_frame.f->data[0]) {
1917  int y_fragment_count, c_fragment_count;
1918  s->avctx = dst;
1919  err = allocate_tables(dst);
1920  if (err)
1921  return err;
1922  y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
1923  c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
1924  memcpy(s->motion_val[0], s1->motion_val[0], y_fragment_count * sizeof(*s->motion_val[0]));
1925  memcpy(s->motion_val[1], s1->motion_val[1], c_fragment_count * sizeof(*s->motion_val[1]));
1926  }
1927 
1928  // copy previous frame data
1929  if ((err = ref_frames(s, s1)) < 0)
1930  return err;
1931 
1932  s->keyframe = s1->keyframe;
1933 
1934  // copy qscale data if necessary
1935  for (i = 0; i < 3; i++) {
1936  if (s->qps[i] != s1->qps[1]) {
1937  qps_changed = 1;
1938  memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
1939  }
1940  }
1941 
1942  if (s->qps[0] != s1->qps[0])
1943  memcpy(&s->bounding_values_array, &s1->bounding_values_array, sizeof(s->bounding_values_array));
1944 
1945  if (qps_changed)
1946  copy_fields(s, s1, qps, superblock_count);
1947 #undef copy_fields
1948  }
1949 
1950  return update_frames(dst);
1951 }
1952 
1954  void *data, int *got_frame,
1955  AVPacket *avpkt)
1956 {
1957  const uint8_t *buf = avpkt->data;
1958  int buf_size = avpkt->size;
1959  Vp3DecodeContext *s = avctx->priv_data;
1960  GetBitContext gb;
1961  int i, ret;
1962 
1963  init_get_bits(&gb, buf, buf_size * 8);
1964 
1965 #if CONFIG_THEORA_DECODER
1966  if (s->theora && get_bits1(&gb))
1967  {
1968  int type = get_bits(&gb, 7);
1969  skip_bits_long(&gb, 6*8); /* "theora" */
1970 
1972  av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
1973  return AVERROR_PATCHWELCOME;
1974  }
1975  if (type == 0) {
1976  vp3_decode_end(avctx);
1977  ret = theora_decode_header(avctx, &gb);
1978 
1979  if (ret < 0) {
1980  vp3_decode_end(avctx);
1981  } else
1982  ret = vp3_decode_init(avctx);
1983  return ret;
1984  } else if (type == 2) {
1985  ret = theora_decode_tables(avctx, &gb);
1986  if (ret < 0) {
1987  vp3_decode_end(avctx);
1988  } else
1989  ret = vp3_decode_init(avctx);
1990  return ret;
1991  }
1992 
1993  av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1994  return -1;
1995  }
1996 #endif
1997 
1998  s->keyframe = !get_bits1(&gb);
1999  if (!s->all_fragments) {
2000  av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2001  return -1;
2002  }
2003  if (!s->theora)
2004  skip_bits(&gb, 1);
2005  for (i = 0; i < 3; i++)
2006  s->last_qps[i] = s->qps[i];
2007 
2008  s->nqps=0;
2009  do{
2010  s->qps[s->nqps++]= get_bits(&gb, 6);
2011  } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
2012  for (i = s->nqps; i < 3; i++)
2013  s->qps[i] = -1;
2014 
2015  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2016  av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2017  s->keyframe?"key":"", avctx->frame_number+1, s->qps[0]);
2018 
2019  s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2020  avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY);
2021 
2022  if (s->qps[0] != s->last_qps[0])
2024 
2025  for (i = 0; i < s->nqps; i++)
2026  // reinit all dequantizers if the first one changed, because
2027  // the DC of the first quantizer must be used for all matrices
2028  if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2029  init_dequantizer(s, i);
2030 
2031  if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2032  return buf_size;
2033 
2034  s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
2035  s->current_frame.f->key_frame = s->keyframe;
2036  if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2037  goto error;
2038 
2039  if (!s->edge_emu_buffer)
2040  s->edge_emu_buffer = av_malloc(9*FFABS(s->current_frame.f->linesize[0]));
2041 
2042  if (s->keyframe) {
2043  if (!s->theora)
2044  {
2045  skip_bits(&gb, 4); /* width code */
2046  skip_bits(&gb, 4); /* height code */
2047  if (s->version)
2048  {
2049  s->version = get_bits(&gb, 5);
2050  if (avctx->frame_number == 0)
2051  av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
2052  }
2053  }
2054  if (s->version || s->theora)
2055  {
2056  if (get_bits1(&gb))
2057  av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
2058  skip_bits(&gb, 2); /* reserved? */
2059  }
2060  } else {
2061  if (!s->golden_frame.f->data[0]) {
2062  av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
2063 
2064  s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2065  if (ff_thread_get_buffer(avctx, &s->golden_frame, AV_GET_BUFFER_FLAG_REF) < 0)
2066  goto error;
2067  ff_thread_release_buffer(avctx, &s->last_frame);
2068  if ((ret = ff_thread_ref_frame(&s->last_frame, &s->golden_frame)) < 0)
2069  goto error;
2070  ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2071  }
2072  }
2073 
2074  memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2075  ff_thread_finish_setup(avctx);
2076 
2077  if (unpack_superblocks(s, &gb)){
2078  av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2079  goto error;
2080  }
2081  if (unpack_modes(s, &gb)){
2082  av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2083  goto error;
2084  }
2085  if (unpack_vectors(s, &gb)){
2086  av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2087  goto error;
2088  }
2089  if (unpack_block_qpis(s, &gb)){
2090  av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2091  goto error;
2092  }
2093  if (unpack_dct_coeffs(s, &gb)){
2094  av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2095  goto error;
2096  }
2097 
2098  for (i = 0; i < 3; i++) {
2099  int height = s->height >> (i && s->chroma_y_shift);
2100  if (s->flipped_image)
2101  s->data_offset[i] = 0;
2102  else
2103  s->data_offset[i] = (height-1) * s->current_frame.f->linesize[i];
2104  }
2105 
2106  s->last_slice_end = 0;
2107  for (i = 0; i < s->c_superblock_height; i++)
2108  render_slice(s, i);
2109 
2110  // filter the last row
2111  for (i = 0; i < 3; i++) {
2112  int row = (s->height >> (3+(i && s->chroma_y_shift))) - 1;
2113  apply_loop_filter(s, i, row, row+1);
2114  }
2115  vp3_draw_horiz_band(s, s->avctx->height);
2116 
2117  if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2118  return ret;
2119  *got_frame = 1;
2120 
2121  if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME)) {
2122  ret = update_frames(avctx);
2123  if (ret < 0)
2124  return ret;
2125  }
2126 
2127  return buf_size;
2128 
2129 error:
2130  ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2131 
2132  if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
2133  av_frame_unref(s->current_frame.f);
2134 
2135  return -1;
2136 }
2137 
2139 {
2140  Vp3DecodeContext *s = avctx->priv_data;
2141 
2142  if (get_bits1(gb)) {
2143  int token;
2144  if (s->entries >= 32) { /* overflow */
2145  av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2146  return -1;
2147  }
2148  token = get_bits(gb, 5);
2149  av_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2150  s->hti, s->hbits, token, s->entries, s->huff_code_size);
2151  s->huffman_table[s->hti][token][0] = s->hbits;
2152  s->huffman_table[s->hti][token][1] = s->huff_code_size;
2153  s->entries++;
2154  }
2155  else {
2156  if (s->huff_code_size >= 32) {/* overflow */
2157  av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2158  return -1;
2159  }
2160  s->huff_code_size++;
2161  s->hbits <<= 1;
2162  if (read_huffman_tree(avctx, gb))
2163  return -1;
2164  s->hbits |= 1;
2165  if (read_huffman_tree(avctx, gb))
2166  return -1;
2167  s->hbits >>= 1;
2168  s->huff_code_size--;
2169  }
2170  return 0;
2171 }
2172 
2174 {
2175  Vp3DecodeContext *s = avctx->priv_data;
2176 
2177  s->superblock_coding = NULL;
2178  s->all_fragments = NULL;
2179  s->coded_fragment_list[0] = NULL;
2180  s->dct_tokens_base = NULL;
2181  s->superblock_fragments = NULL;
2182  s->macroblock_coding = NULL;
2183  s->motion_val[0] = NULL;
2184  s->motion_val[1] = NULL;
2185  s->edge_emu_buffer = NULL;
2186 
2187  return init_frames(s);
2188 }
2189 
2190 #if CONFIG_THEORA_DECODER
2191 static const enum AVPixelFormat theora_pix_fmts[4] = {
2193 };
2194 
2195 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2196 {
2197  Vp3DecodeContext *s = avctx->priv_data;
2198  int visible_width, visible_height, colorspace;
2199  int offset_x = 0, offset_y = 0;
2200  int ret;
2201  AVRational fps, aspect;
2202 
2203  s->theora = get_bits_long(gb, 24);
2204  av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2205 
2206  /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
2207  /* but previous versions have the image flipped relative to vp3 */
2208  if (s->theora < 0x030200)
2209  {
2210  s->flipped_image = 1;
2211  av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
2212  }
2213 
2214  visible_width = s->width = get_bits(gb, 16) << 4;
2215  visible_height = s->height = get_bits(gb, 16) << 4;
2216 
2217  if (s->theora >= 0x030200) {
2218  visible_width = get_bits_long(gb, 24);
2219  visible_height = get_bits_long(gb, 24);
2220 
2221  offset_x = get_bits(gb, 8); /* offset x */
2222  offset_y = get_bits(gb, 8); /* offset y, from bottom */
2223  }
2224 
2225  fps.num = get_bits_long(gb, 32);
2226  fps.den = get_bits_long(gb, 32);
2227  if (fps.num && fps.den) {
2228  if (fps.num < 0 || fps.den < 0) {
2229  av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2230  return AVERROR_INVALIDDATA;
2231  }
2232  av_reduce(&avctx->time_base.num, &avctx->time_base.den,
2233  fps.den, fps.num, 1<<30);
2234  }
2235 
2236  aspect.num = get_bits_long(gb, 24);
2237  aspect.den = get_bits_long(gb, 24);
2238  if (aspect.num && aspect.den) {
2240  &avctx->sample_aspect_ratio.den,
2241  aspect.num, aspect.den, 1<<30);
2242  }
2243 
2244  if (s->theora < 0x030200)
2245  skip_bits(gb, 5); /* keyframe frequency force */
2246  colorspace = get_bits(gb, 8);
2247  skip_bits(gb, 24); /* bitrate */
2248 
2249  skip_bits(gb, 6); /* quality hint */
2250 
2251  if (s->theora >= 0x030200)
2252  {
2253  skip_bits(gb, 5); /* keyframe frequency force */
2254  avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2255  if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2256  av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2257  return AVERROR_INVALIDDATA;
2258  }
2259  skip_bits(gb, 3); /* reserved */
2260  }
2261 
2262 // align_get_bits(gb);
2263 
2264  if ( visible_width <= s->width && visible_width > s->width-16
2265  && visible_height <= s->height && visible_height > s->height-16
2266  && !offset_x && (offset_y == s->height - visible_height))
2267  ret = ff_set_dimensions(avctx, visible_width, visible_height);
2268  else
2269  ret = ff_set_dimensions(avctx, s->width, s->height);
2270  if (ret < 0)
2271  return ret;
2272 
2273  if (colorspace == 1) {
2275  } else if (colorspace == 2) {
2277  }
2278  if (colorspace == 1 || colorspace == 2) {
2279  avctx->colorspace = AVCOL_SPC_BT470BG;
2280  avctx->color_trc = AVCOL_TRC_BT709;
2281  }
2282 
2283  return 0;
2284 }
2285 
2286 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2287 {
2288  Vp3DecodeContext *s = avctx->priv_data;
2289  int i, n, matrices, inter, plane;
2290 
2291  if (s->theora >= 0x030200) {
2292  n = get_bits(gb, 3);
2293  /* loop filter limit values table */
2294  if (n)
2295  for (i = 0; i < 64; i++)
2296  s->filter_limit_values[i] = get_bits(gb, n);
2297  }
2298 
2299  if (s->theora >= 0x030200)
2300  n = get_bits(gb, 4) + 1;
2301  else
2302  n = 16;
2303  /* quality threshold table */
2304  for (i = 0; i < 64; i++)
2305  s->coded_ac_scale_factor[i] = get_bits(gb, n);
2306 
2307  if (s->theora >= 0x030200)
2308  n = get_bits(gb, 4) + 1;
2309  else
2310  n = 16;
2311  /* dc scale factor table */
2312  for (i = 0; i < 64; i++)
2313  s->coded_dc_scale_factor[i] = get_bits(gb, n);
2314 
2315  if (s->theora >= 0x030200)
2316  matrices = get_bits(gb, 9) + 1;
2317  else
2318  matrices = 3;
2319 
2320  if(matrices > 384){
2321  av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2322  return -1;
2323  }
2324 
2325  for(n=0; n<matrices; n++){
2326  for (i = 0; i < 64; i++)
2327  s->base_matrix[n][i]= get_bits(gb, 8);
2328  }
2329 
2330  for (inter = 0; inter <= 1; inter++) {
2331  for (plane = 0; plane <= 2; plane++) {
2332  int newqr= 1;
2333  if (inter || plane > 0)
2334  newqr = get_bits1(gb);
2335  if (!newqr) {
2336  int qtj, plj;
2337  if(inter && get_bits1(gb)){
2338  qtj = 0;
2339  plj = plane;
2340  }else{
2341  qtj= (3*inter + plane - 1) / 3;
2342  plj= (plane + 2) % 3;
2343  }
2344  s->qr_count[inter][plane]= s->qr_count[qtj][plj];
2345  memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
2346  memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
2347  } else {
2348  int qri= 0;
2349  int qi = 0;
2350 
2351  for(;;){
2352  i= get_bits(gb, av_log2(matrices-1)+1);
2353  if(i>= matrices){
2354  av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
2355  return -1;
2356  }
2357  s->qr_base[inter][plane][qri]= i;
2358  if(qi >= 63)
2359  break;
2360  i = get_bits(gb, av_log2(63-qi)+1) + 1;
2361  s->qr_size[inter][plane][qri++]= i;
2362  qi += i;
2363  }
2364 
2365  if (qi > 63) {
2366  av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2367  return -1;
2368  }
2369  s->qr_count[inter][plane]= qri;
2370  }
2371  }
2372  }
2373 
2374  /* Huffman tables */
2375  for (s->hti = 0; s->hti < 80; s->hti++) {
2376  s->entries = 0;
2377  s->huff_code_size = 1;
2378  if (!get_bits1(gb)) {
2379  s->hbits = 0;
2380  if(read_huffman_tree(avctx, gb))
2381  return -1;
2382  s->hbits = 1;
2383  if(read_huffman_tree(avctx, gb))
2384  return -1;
2385  }
2386  }
2387 
2388  s->theora_tables = 1;
2389 
2390  return 0;
2391 }
2392 
2393 static av_cold int theora_decode_init(AVCodecContext *avctx)
2394 {
2395  Vp3DecodeContext *s = avctx->priv_data;
2396  GetBitContext gb;
2397  int ptype;
2398  uint8_t *header_start[3];
2399  int header_len[3];
2400  int i;
2401 
2402  avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2403 
2404  s->theora = 1;
2405 
2406  if (!avctx->extradata_size)
2407  {
2408  av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2409  return -1;
2410  }
2411 
2413  42, header_start, header_len) < 0) {
2414  av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2415  return -1;
2416  }
2417 
2418  for(i=0;i<3;i++) {
2419  if (header_len[i] <= 0)
2420  continue;
2421  init_get_bits(&gb, header_start[i], header_len[i] * 8);
2422 
2423  ptype = get_bits(&gb, 8);
2424 
2425  if (!(ptype & 0x80))
2426  {
2427  av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2428 // return -1;
2429  }
2430 
2431  // FIXME: Check for this as well.
2432  skip_bits_long(&gb, 6*8); /* "theora" */
2433 
2434  switch(ptype)
2435  {
2436  case 0x80:
2437  if (theora_decode_header(avctx, &gb) < 0)
2438  return -1;
2439  break;
2440  case 0x81:
2441 // FIXME: is this needed? it breaks sometimes
2442 // theora_decode_comments(avctx, gb);
2443  break;
2444  case 0x82:
2445  if (theora_decode_tables(avctx, &gb))
2446  return -1;
2447  break;
2448  default:
2449  av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2450  break;
2451  }
2452  if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
2453  av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
2454  if (s->theora < 0x030200)
2455  break;
2456  }
2457 
2458  return vp3_decode_init(avctx);
2459 }
2460 
2461 AVCodec ff_theora_decoder = {
2462  .name = "theora",
2463  .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2464  .type = AVMEDIA_TYPE_VIDEO,
2465  .id = AV_CODEC_ID_THEORA,
2466  .priv_data_size = sizeof(Vp3DecodeContext),
2467  .init = theora_decode_init,
2468  .close = vp3_decode_end,
2470  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
2474  .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
2475 };
2476 #endif
2477 
2479  .name = "vp3",
2480  .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2481  .type = AVMEDIA_TYPE_VIDEO,
2482  .id = AV_CODEC_ID_VP3,
2483  .priv_data_size = sizeof(Vp3DecodeContext),
2484  .init = vp3_decode_init,
2485  .close = vp3_decode_end,
2487  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
2491  .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
2492 };