Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  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;
  53.     uint8_t coding_method;
  54.     uint8_t qpi;
  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 */
  87.     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
  88.          MODE_INTER_PLUS_MV,    MODE_INTER_NO_MV,
  89.          MODE_INTRA,            MODE_USING_GOLDEN,
  90.          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
  91.  
  92.     /* scheme 2 */
  93.     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
  94.          MODE_INTER_NO_MV,      MODE_INTER_PLUS_MV,
  95.          MODE_INTRA,            MODE_USING_GOLDEN,
  96.          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
  97.  
  98.     /* scheme 3 */
  99.     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
  100.          MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
  101.          MODE_INTRA,            MODE_USING_GOLDEN,
  102.          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
  103.  
  104.     /* scheme 4 */
  105.     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
  106.          MODE_INTER_NO_MV,      MODE_INTER_PRIOR_LAST,
  107.          MODE_INTRA,            MODE_USING_GOLDEN,
  108.          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
  109.  
  110.     /* scheme 5: No motion vector dominates */
  111.     {    MODE_INTER_NO_MV,      MODE_INTER_LAST_MV,
  112.          MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
  113.          MODE_INTRA,            MODE_USING_GOLDEN,
  114.          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
  115.  
  116.     /* scheme 6 */
  117.     {    MODE_INTER_NO_MV,      MODE_USING_GOLDEN,
  118.          MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
  119.          MODE_INTER_PLUS_MV,    MODE_INTRA,
  120.          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
  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 {
  134.     AVCodecContext *avctx;
  135.     int theora, theora_tables;
  136.     int version;
  137.     int width, height;
  138.     int chroma_x_shift, chroma_y_shift;
  139.     ThreadFrame golden_frame;
  140.     ThreadFrame last_frame;
  141.     ThreadFrame current_frame;
  142.     int keyframe;
  143.     uint8_t idct_permutation[64];
  144.     uint8_t idct_scantable[64];
  145.     HpelDSPContext hdsp;
  146.     VideoDSPContext vdsp;
  147.     VP3DSPContext vp3dsp;
  148.     DECLARE_ALIGNED(16, int16_t, block)[64];
  149.     int flipped_image;
  150.     int last_slice_end;
  151.     int skip_loop_filter;
  152.  
  153.     int qps[3];
  154.     int nqps;
  155.     int last_qps[3];
  156.  
  157.     int superblock_count;
  158.     int y_superblock_width;
  159.     int y_superblock_height;
  160.     int y_superblock_count;
  161.     int c_superblock_width;
  162.     int c_superblock_height;
  163.     int c_superblock_count;
  164.     int u_superblock_start;
  165.     int v_superblock_start;
  166.     unsigned char *superblock_coding;
  167.  
  168.     int macroblock_count;
  169.     int macroblock_width;
  170.     int macroblock_height;
  171.  
  172.     int fragment_count;
  173.     int fragment_width[2];
  174.     int fragment_height[2];
  175.  
  176.     Vp3Fragment *all_fragments;
  177.     int fragment_start[3];
  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];
  185.     uint8_t base_matrix[384][64];
  186.     uint8_t qr_count[2][3];
  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];
  217.     int total_num_coded_frags;
  218.  
  219.     /* this is a list of indexes into the all_fragments array indicating
  220.      * which of the fragments are coded */
  221.     int *coded_fragment_list[3];
  222.  
  223.     VLC dc_vlc[16];
  224.     VLC ac_vlc_1[16];
  225.     VLC ac_vlc_2[16];
  226.     VLC ac_vlc_3[16];
  227.     VLC ac_vlc_4[16];
  228.  
  229.     VLC superblock_run_length_vlc;
  230.     VLC fragment_run_length_vlc;
  231.     VLC mode_code_vlc;
  232.     VLC motion_vector_vlc;
  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. */
  242.     int *superblock_fragments;
  243.  
  244.     /* This is an array that indicates how a particular macroblock
  245.      * is coded. */
  246.     unsigned char *macroblock_coding;
  247.  
  248.     uint8_t *edge_emu_buffer;
  249.  
  250.     /* Huffman decode */
  251.     int hti;
  252.     unsigned int hbits;
  253.     int entries;
  254.     int huff_code_size;
  255.     uint32_t huffman_table[80][32][2];
  256.  
  257.     uint8_t filter_limit_values[64];
  258.     DECLARE_ALIGNED(8, int, bounding_values_array)[256+2];
  259. } Vp3DecodeContext;
  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)
  270.         ff_thread_release_buffer(avctx, &s->golden_frame);
  271.     if (s->last_frame.f)
  272.         ff_thread_release_buffer(avctx, &s->last_frame);
  273.     if (s->current_frame.f)
  274.         ff_thread_release_buffer(avctx, &s->current_frame);
  275. }
  276.  
  277. static av_cold int vp3_decode_end(AVCodecContext *avctx)
  278. {
  279.     Vp3DecodeContext *s = avctx->priv_data;
  280.     int i;
  281.  
  282.     av_freep(&s->superblock_coding);
  283.     av_freep(&s->all_fragments);
  284.     av_freep(&s->coded_fragment_list[0]);
  285.     av_freep(&s->dct_tokens_base);
  286.     av_freep(&s->superblock_fragments);
  287.     av_freep(&s->macroblock_coding);
  288.     av_freep(&s->motion_val[0]);
  289.     av_freep(&s->motion_val[1]);
  290.     av_freep(&s->edge_emu_buffer);
  291.  
  292.     s->theora_tables = 0;
  293.  
  294.     /* release all frames */
  295.     vp3_decode_flush(avctx);
  296.     av_frame_free(&s->current_frame.f);
  297.     av_frame_free(&s->last_frame.f);
  298.     av_frame_free(&s->golden_frame.f);
  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.  
  311.     ff_free_vlc(&s->superblock_run_length_vlc);
  312.     ff_free_vlc(&s->fragment_run_length_vlc);
  313.     ff_free_vlc(&s->mode_code_vlc);
  314.     ff_free_vlc(&s->motion_vector_vlc);
  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.  */
  327. static int init_block_mapping(Vp3DecodeContext *s)
  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.  */
  399. static void init_loop_filter(Vp3DecodeContext *s)
  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.  */
  428. static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
  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) {
  441.         memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
  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;
  525.     memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
  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 =
  558.                             MODE_INTER_NO_MV;
  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.  */
  582. static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
  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++)
  595.             s->all_fragments[i].coding_method = MODE_INTRA;
  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;
  663.                     SET_CHROMA_MODES
  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++) {
  667.                         SET_CHROMA_MODES
  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;
  673.                         SET_CHROMA_MODES
  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.  */
  688. static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
  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] ==
  739.                     MODE_INTER_PLUS_MV) {
  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.  
  782.             case MODE_INTER_PRIOR_LAST:
  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 =
  807.                     BLOCK_Y*s->fragment_width[0] + BLOCK_X;
  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.  
  865. static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
  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.  */
  919. static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
  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 {
  1011.                 av_log(s->avctx, AV_LOG_ERROR,
  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.  
  1035. static void reverse_dc_prediction(Vp3DecodeContext *s,
  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.  */
  1043. static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
  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 */
  1067.     reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
  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.     {
  1082.         reverse_dc_prediction(s, s->fragment_start[1],
  1083.             s->fragment_width[1], s->fragment_height[1]);
  1084.         reverse_dc_prediction(s, s->fragment_start[2],
  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.  
  1139. static void reverse_dc_prediction(Vp3DecodeContext *s,
  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.  */
  1401. static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
  1402. {
  1403.     int h, cy, i;
  1404.     int offset[AV_NUM_DATA_POINTERS];
  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. {
  1443.     ThreadFrame *ref_frame;
  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) {
  1522.                     if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
  1523.                         (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
  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) &&
  1534.                         (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
  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){
  1549.                             uint8_t *temp= s->edge_emu_buffer;
  1550.                             if(stride<0) temp -= 8*stride;
  1551.  
  1552.                             s->vdsp.emulated_edge_mc(temp, stride,
  1553.                                                      motion_source, stride,
  1554.                                                      9, 9, src_x, src_y,
  1555.                                                      plane_width, plane_height);
  1556.                             motion_source= temp;
  1557.                         }
  1558.                     }
  1559.  
  1560.  
  1561.                     /* first, take care of copying a block from either the
  1562.                      * previous or the golden frame */
  1563.                     if (s->all_fragments[i].coding_method != MODE_INTRA) {
  1564.                         /* Note, it is possible to implement all MC cases with
  1565.                            put_no_rnd_pixels_l2 which would look more like the
  1566.                            VP3 source but this would be slower as
  1567.                            put_no_rnd_pixels_tab is better optimzed */
  1568.                         if(motion_halfpel_index != 3){
  1569.                             s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
  1570.                                 output_plane + first_pixel,
  1571.                                 motion_source, stride, 8);
  1572.                         }else{
  1573.                             int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
  1574.                             s->vp3dsp.put_no_rnd_pixels_l2(
  1575.                                 output_plane + first_pixel,
  1576.                                 motion_source - d,
  1577.                                 motion_source + stride + 1 + d,
  1578.                                 stride, 8);
  1579.                         }
  1580.                     }
  1581.  
  1582.                     /* invert DCT and place (or add) in final output */
  1583.  
  1584.                     if (s->all_fragments[i].coding_method == MODE_INTRA) {
  1585.                         vp3_dequant(s, s->all_fragments + i, plane, 0, block);
  1586.                         s->vp3dsp.idct_put(
  1587.                             output_plane + first_pixel,
  1588.                             stride,
  1589.                             block);
  1590.                     } else {
  1591.                         if (vp3_dequant(s, s->all_fragments + i, plane, 1, block)) {
  1592.                         s->vp3dsp.idct_add(
  1593.                             output_plane + first_pixel,
  1594.                             stride,
  1595.                             block);
  1596.                         } else {
  1597.                             s->vp3dsp.idct_dc_add(output_plane + first_pixel, stride, block);
  1598.                         }
  1599.                     }
  1600.                 } else {
  1601.  
  1602.                     /* copy directly from the previous frame */
  1603.                     s->hdsp.put_pixels_tab[1][0](
  1604.                         output_plane + first_pixel,
  1605.                         last_plane + first_pixel,
  1606.                         stride, 8);
  1607.  
  1608.                 }
  1609.                 }
  1610.             }
  1611.  
  1612.             // Filter up to the last row in the superblock row
  1613.             if (!s->skip_loop_filter)
  1614.                 apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
  1615.         }
  1616.     }
  1617.  
  1618.      /* this looks like a good place for slice dispatch... */
  1619.      /* algorithm:
  1620.       *   if (slice == s->macroblock_height - 1)
  1621.       *     dispatch (both last slice & 2nd-to-last slice);
  1622.       *   else if (slice > 0)
  1623.       *     dispatch (slice - 1);
  1624.       */
  1625.  
  1626.     vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) -16, s->height-16));
  1627. }
  1628.  
  1629. /// Allocate tables for per-frame data in Vp3DecodeContext
  1630. static av_cold int allocate_tables(AVCodecContext *avctx)
  1631. {
  1632.     Vp3DecodeContext *s = avctx->priv_data;
  1633.     int y_fragment_count, c_fragment_count;
  1634.  
  1635.     y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
  1636.     c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
  1637.  
  1638.     s->superblock_coding = av_mallocz(s->superblock_count);
  1639.     s->all_fragments = av_mallocz(s->fragment_count * sizeof(Vp3Fragment));
  1640.     s->coded_fragment_list[0] = av_mallocz(s->fragment_count * sizeof(int));
  1641.     s->dct_tokens_base = av_mallocz(64*s->fragment_count * sizeof(*s->dct_tokens_base));
  1642.     s->motion_val[0] = av_mallocz(y_fragment_count * sizeof(*s->motion_val[0]));
  1643.     s->motion_val[1] = av_mallocz(c_fragment_count * sizeof(*s->motion_val[1]));
  1644.  
  1645.     /* work out the block mapping tables */
  1646.     s->superblock_fragments = av_mallocz(s->superblock_count * 16 * sizeof(int));
  1647.     s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
  1648.  
  1649.     if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
  1650.         !s->coded_fragment_list[0] || !s->superblock_fragments || !s->macroblock_coding ||
  1651.         !s->motion_val[0] || !s->motion_val[1]) {
  1652.         vp3_decode_end(avctx);
  1653.         return -1;
  1654.     }
  1655.  
  1656.     init_block_mapping(s);
  1657.  
  1658.     return 0;
  1659. }
  1660.  
  1661. static av_cold int init_frames(Vp3DecodeContext *s)
  1662. {
  1663.     s->current_frame.f = av_frame_alloc();
  1664.     s->last_frame.f    = av_frame_alloc();
  1665.     s->golden_frame.f  = av_frame_alloc();
  1666.  
  1667.     if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
  1668.         av_frame_free(&s->current_frame.f);
  1669.         av_frame_free(&s->last_frame.f);
  1670.         av_frame_free(&s->golden_frame.f);
  1671.         return AVERROR(ENOMEM);
  1672.     }
  1673.  
  1674.     return 0;
  1675. }
  1676.  
  1677. static av_cold int vp3_decode_init(AVCodecContext *avctx)
  1678. {
  1679.     Vp3DecodeContext *s = avctx->priv_data;
  1680.     int i, inter, plane, ret;
  1681.     int c_width;
  1682.     int c_height;
  1683.     int y_fragment_count, c_fragment_count;
  1684.  
  1685.     ret = init_frames(s);
  1686.     if (ret < 0)
  1687.         return ret;
  1688.  
  1689.     avctx->internal->allocate_progress = 1;
  1690.  
  1691.     if (avctx->codec_tag == MKTAG('V','P','3','0'))
  1692.         s->version = 0;
  1693.     else
  1694.         s->version = 1;
  1695.  
  1696.     s->avctx = avctx;
  1697.     s->width = FFALIGN(avctx->width, 16);
  1698.     s->height = FFALIGN(avctx->height, 16);
  1699.     if (avctx->codec_id != AV_CODEC_ID_THEORA)
  1700.         avctx->pix_fmt = AV_PIX_FMT_YUV420P;
  1701.     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
  1702.     ff_hpeldsp_init(&s->hdsp, avctx->flags | CODEC_FLAG_BITEXACT);
  1703.     ff_videodsp_init(&s->vdsp, 8);
  1704.     ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
  1705.  
  1706.     for (i = 0; i < 64; i++) {
  1707. #define T(x) (x >> 3) | ((x & 7) << 3)
  1708.         s->idct_permutation[i] = T(i);
  1709.         s->idct_scantable[i] = T(ff_zigzag_direct[i]);
  1710. #undef T
  1711.     }
  1712.  
  1713.     /* initialize to an impossible value which will force a recalculation
  1714.      * in the first frame decode */
  1715.     for (i = 0; i < 3; i++)
  1716.         s->qps[i] = -1;
  1717.  
  1718.     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
  1719.  
  1720.     s->y_superblock_width = (s->width + 31) / 32;
  1721.     s->y_superblock_height = (s->height + 31) / 32;
  1722.     s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
  1723.  
  1724.     /* work out the dimensions for the C planes */
  1725.     c_width = s->width >> s->chroma_x_shift;
  1726.     c_height = s->height >> s->chroma_y_shift;
  1727.     s->c_superblock_width = (c_width + 31) / 32;
  1728.     s->c_superblock_height = (c_height + 31) / 32;
  1729.     s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
  1730.  
  1731.     s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
  1732.     s->u_superblock_start = s->y_superblock_count;
  1733.     s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
  1734.  
  1735.     s->macroblock_width = (s->width + 15) / 16;
  1736.     s->macroblock_height = (s->height + 15) / 16;
  1737.     s->macroblock_count = s->macroblock_width * s->macroblock_height;
  1738.  
  1739.     s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
  1740.     s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
  1741.     s->fragment_width[1]  = s->fragment_width[0]  >> s->chroma_x_shift;
  1742.     s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
  1743.  
  1744.     /* fragment count covers all 8x8 blocks for all 3 planes */
  1745.     y_fragment_count     = s->fragment_width[0] * s->fragment_height[0];
  1746.     c_fragment_count     = s->fragment_width[1] * s->fragment_height[1];
  1747.     s->fragment_count    = y_fragment_count + 2*c_fragment_count;
  1748.     s->fragment_start[1] = y_fragment_count;
  1749.     s->fragment_start[2] = y_fragment_count + c_fragment_count;
  1750.  
  1751.     if (!s->theora_tables)
  1752.     {
  1753.         for (i = 0; i < 64; i++) {
  1754.             s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
  1755.             s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
  1756.             s->base_matrix[0][i] = vp31_intra_y_dequant[i];
  1757.             s->base_matrix[1][i] = vp31_intra_c_dequant[i];
  1758.             s->base_matrix[2][i] = vp31_inter_dequant[i];
  1759.             s->filter_limit_values[i] = vp31_filter_limit_values[i];
  1760.         }
  1761.  
  1762.         for(inter=0; inter<2; inter++){
  1763.             for(plane=0; plane<3; plane++){
  1764.                 s->qr_count[inter][plane]= 1;
  1765.                 s->qr_size [inter][plane][0]= 63;
  1766.                 s->qr_base [inter][plane][0]=
  1767.                 s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
  1768.             }
  1769.         }
  1770.  
  1771.         /* init VLC tables */
  1772.         for (i = 0; i < 16; i++) {
  1773.  
  1774.             /* DC histograms */
  1775.             init_vlc(&s->dc_vlc[i], 11, 32,
  1776.                 &dc_bias[i][0][1], 4, 2,
  1777.                 &dc_bias[i][0][0], 4, 2, 0);
  1778.  
  1779.             /* group 1 AC histograms */
  1780.             init_vlc(&s->ac_vlc_1[i], 11, 32,
  1781.                 &ac_bias_0[i][0][1], 4, 2,
  1782.                 &ac_bias_0[i][0][0], 4, 2, 0);
  1783.  
  1784.             /* group 2 AC histograms */
  1785.             init_vlc(&s->ac_vlc_2[i], 11, 32,
  1786.                 &ac_bias_1[i][0][1], 4, 2,
  1787.                 &ac_bias_1[i][0][0], 4, 2, 0);
  1788.  
  1789.             /* group 3 AC histograms */
  1790.             init_vlc(&s->ac_vlc_3[i], 11, 32,
  1791.                 &ac_bias_2[i][0][1], 4, 2,
  1792.                 &ac_bias_2[i][0][0], 4, 2, 0);
  1793.  
  1794.             /* group 4 AC histograms */
  1795.             init_vlc(&s->ac_vlc_4[i], 11, 32,
  1796.                 &ac_bias_3[i][0][1], 4, 2,
  1797.                 &ac_bias_3[i][0][0], 4, 2, 0);
  1798.         }
  1799.     } else {
  1800.  
  1801.         for (i = 0; i < 16; i++) {
  1802.             /* DC histograms */
  1803.             if (init_vlc(&s->dc_vlc[i], 11, 32,
  1804.                 &s->huffman_table[i][0][1], 8, 4,
  1805.                 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
  1806.                 goto vlc_fail;
  1807.  
  1808.             /* group 1 AC histograms */
  1809.             if (init_vlc(&s->ac_vlc_1[i], 11, 32,
  1810.                 &s->huffman_table[i+16][0][1], 8, 4,
  1811.                 &s->huffman_table[i+16][0][0], 8, 4, 0) < 0)
  1812.                 goto vlc_fail;
  1813.  
  1814.             /* group 2 AC histograms */
  1815.             if (init_vlc(&s->ac_vlc_2[i], 11, 32,
  1816.                 &s->huffman_table[i+16*2][0][1], 8, 4,
  1817.                 &s->huffman_table[i+16*2][0][0], 8, 4, 0) < 0)
  1818.                 goto vlc_fail;
  1819.  
  1820.             /* group 3 AC histograms */
  1821.             if (init_vlc(&s->ac_vlc_3[i], 11, 32,
  1822.                 &s->huffman_table[i+16*3][0][1], 8, 4,
  1823.                 &s->huffman_table[i+16*3][0][0], 8, 4, 0) < 0)
  1824.                 goto vlc_fail;
  1825.  
  1826.             /* group 4 AC histograms */
  1827.             if (init_vlc(&s->ac_vlc_4[i], 11, 32,
  1828.                 &s->huffman_table[i+16*4][0][1], 8, 4,
  1829.                 &s->huffman_table[i+16*4][0][0], 8, 4, 0) < 0)
  1830.                 goto vlc_fail;
  1831.         }
  1832.     }
  1833.  
  1834.     init_vlc(&s->superblock_run_length_vlc, 6, 34,
  1835.         &superblock_run_length_vlc_table[0][1], 4, 2,
  1836.         &superblock_run_length_vlc_table[0][0], 4, 2, 0);
  1837.  
  1838.     init_vlc(&s->fragment_run_length_vlc, 5, 30,
  1839.         &fragment_run_length_vlc_table[0][1], 4, 2,
  1840.         &fragment_run_length_vlc_table[0][0], 4, 2, 0);
  1841.  
  1842.     init_vlc(&s->mode_code_vlc, 3, 8,
  1843.         &mode_code_vlc_table[0][1], 2, 1,
  1844.         &mode_code_vlc_table[0][0], 2, 1, 0);
  1845.  
  1846.     init_vlc(&s->motion_vector_vlc, 6, 63,
  1847.         &motion_vector_vlc_table[0][1], 2, 1,
  1848.         &motion_vector_vlc_table[0][0], 2, 1, 0);
  1849.  
  1850.     return allocate_tables(avctx);
  1851.  
  1852. vlc_fail:
  1853.     av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
  1854.     return -1;
  1855. }
  1856.  
  1857. /// Release and shuffle frames after decode finishes
  1858. static int update_frames(AVCodecContext *avctx)
  1859. {
  1860.     Vp3DecodeContext *s = avctx->priv_data;
  1861.     int ret = 0;
  1862.  
  1863.  
  1864.     /* shuffle frames (last = current) */
  1865.     ff_thread_release_buffer(avctx, &s->last_frame);
  1866.     ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
  1867.     if (ret < 0)
  1868.         goto fail;
  1869.  
  1870.     if (s->keyframe) {
  1871.         ff_thread_release_buffer(avctx, &s->golden_frame);
  1872.         ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
  1873.     }
  1874.  
  1875. fail:
  1876.     ff_thread_release_buffer(avctx, &s->current_frame);
  1877.     return ret;
  1878. }
  1879.  
  1880. static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
  1881. {
  1882.     ff_thread_release_buffer(s->avctx, dst);
  1883.     if (src->f->data[0])
  1884.         return ff_thread_ref_frame(dst, src);
  1885.     return 0;
  1886. }
  1887.  
  1888. static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
  1889. {
  1890.     int ret;
  1891.     if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
  1892.         (ret = ref_frame(dst, &dst->golden_frame,  &src->golden_frame)) < 0  ||
  1893.         (ret = ref_frame(dst, &dst->last_frame,    &src->last_frame)) < 0)
  1894.         return ret;
  1895.     return 0;
  1896. }
  1897.  
  1898. static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  1899. {
  1900.     Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
  1901.     int qps_changed = 0, i, err;
  1902.  
  1903. #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
  1904.  
  1905.     if (!s1->current_frame.f->data[0]
  1906.         ||s->width != s1->width
  1907.         ||s->height!= s1->height) {
  1908.         if (s != s1)
  1909.             ref_frames(s, s1);
  1910.         return -1;
  1911.     }
  1912.  
  1913.     if (s != s1) {
  1914.         // init tables if the first frame hasn't been decoded
  1915.         if (!s->current_frame.f->data[0]) {
  1916.             int y_fragment_count, c_fragment_count;
  1917.             s->avctx = dst;
  1918.             err = allocate_tables(dst);
  1919.             if (err)
  1920.                 return err;
  1921.             y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
  1922.             c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
  1923.             memcpy(s->motion_val[0], s1->motion_val[0], y_fragment_count * sizeof(*s->motion_val[0]));
  1924.             memcpy(s->motion_val[1], s1->motion_val[1], c_fragment_count * sizeof(*s->motion_val[1]));
  1925.         }
  1926.  
  1927.         // copy previous frame data
  1928.         if ((err = ref_frames(s, s1)) < 0)
  1929.             return err;
  1930.  
  1931.         s->keyframe = s1->keyframe;
  1932.  
  1933.         // copy qscale data if necessary
  1934.         for (i = 0; i < 3; i++) {
  1935.             if (s->qps[i] != s1->qps[1]) {
  1936.                 qps_changed = 1;
  1937.                 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
  1938.             }
  1939.         }
  1940.  
  1941.         if (s->qps[0] != s1->qps[0])
  1942.             memcpy(&s->bounding_values_array, &s1->bounding_values_array, sizeof(s->bounding_values_array));
  1943.  
  1944.         if (qps_changed)
  1945.             copy_fields(s, s1, qps, superblock_count);
  1946. #undef copy_fields
  1947.     }
  1948.  
  1949.     return update_frames(dst);
  1950. }
  1951.  
  1952. static int vp3_decode_frame(AVCodecContext *avctx,
  1953.                             void *data, int *got_frame,
  1954.                             AVPacket *avpkt)
  1955. {
  1956.     const uint8_t *buf = avpkt->data;
  1957.     int buf_size = avpkt->size;
  1958.     Vp3DecodeContext *s = avctx->priv_data;
  1959.     GetBitContext gb;
  1960.     int i, ret;
  1961.  
  1962.     init_get_bits(&gb, buf, buf_size * 8);
  1963.  
  1964. #if CONFIG_THEORA_DECODER
  1965.     if (s->theora && get_bits1(&gb))
  1966.     {
  1967.         int type = get_bits(&gb, 7);
  1968.         skip_bits_long(&gb, 6*8); /* "theora" */
  1969.  
  1970.         if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
  1971.             av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
  1972.             return AVERROR_PATCHWELCOME;
  1973.         }
  1974.         if (type == 0) {
  1975.             vp3_decode_end(avctx);
  1976.             ret = theora_decode_header(avctx, &gb);
  1977.  
  1978.             if (ret < 0) {
  1979.                 vp3_decode_end(avctx);
  1980.             } else
  1981.                 ret = vp3_decode_init(avctx);
  1982.             return ret;
  1983.         } else if (type == 2) {
  1984.             ret = theora_decode_tables(avctx, &gb);
  1985.             if (ret < 0) {
  1986.                 vp3_decode_end(avctx);
  1987.             } else
  1988.                 ret = vp3_decode_init(avctx);
  1989.             return ret;
  1990.         }
  1991.  
  1992.         av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
  1993.         return -1;
  1994.     }
  1995. #endif
  1996.  
  1997.     s->keyframe = !get_bits1(&gb);
  1998.     if (!s->all_fragments) {
  1999.         av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
  2000.         return -1;
  2001.     }
  2002.     if (!s->theora)
  2003.         skip_bits(&gb, 1);
  2004.     for (i = 0; i < 3; i++)
  2005.         s->last_qps[i] = s->qps[i];
  2006.  
  2007.     s->nqps=0;
  2008.     do{
  2009.         s->qps[s->nqps++]= get_bits(&gb, 6);
  2010.     } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
  2011.     for (i = s->nqps; i < 3; i++)
  2012.         s->qps[i] = -1;
  2013.  
  2014.     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  2015.         av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
  2016.             s->keyframe?"key":"", avctx->frame_number+1, s->qps[0]);
  2017.  
  2018.     s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
  2019.         avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY);
  2020.  
  2021.     if (s->qps[0] != s->last_qps[0])
  2022.         init_loop_filter(s);
  2023.  
  2024.     for (i = 0; i < s->nqps; i++)
  2025.         // reinit all dequantizers if the first one changed, because
  2026.         // the DC of the first quantizer must be used for all matrices
  2027.         if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
  2028.             init_dequantizer(s, i);
  2029.  
  2030.     if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
  2031.         return buf_size;
  2032.  
  2033.     s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
  2034.     s->current_frame.f->key_frame = s->keyframe;
  2035.     if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
  2036.         goto error;
  2037.  
  2038.     if (!s->edge_emu_buffer)
  2039.         s->edge_emu_buffer = av_malloc(9*FFABS(s->current_frame.f->linesize[0]));
  2040.  
  2041.     if (s->keyframe) {
  2042.         if (!s->theora)
  2043.         {
  2044.             skip_bits(&gb, 4); /* width code */
  2045.             skip_bits(&gb, 4); /* height code */
  2046.             if (s->version)
  2047.             {
  2048.                 s->version = get_bits(&gb, 5);
  2049.                 if (avctx->frame_number == 0)
  2050.                     av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
  2051.             }
  2052.         }
  2053.         if (s->version || s->theora)
  2054.         {
  2055.                 if (get_bits1(&gb))
  2056.                     av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
  2057.             skip_bits(&gb, 2); /* reserved? */
  2058.         }
  2059.     } else {
  2060.         if (!s->golden_frame.f->data[0]) {
  2061.             av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
  2062.  
  2063.             s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
  2064.             if (ff_thread_get_buffer(avctx, &s->golden_frame, AV_GET_BUFFER_FLAG_REF) < 0)
  2065.                 goto error;
  2066.             ff_thread_release_buffer(avctx, &s->last_frame);
  2067.             if ((ret = ff_thread_ref_frame(&s->last_frame, &s->golden_frame)) < 0)
  2068.                 goto error;
  2069.             ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
  2070.         }
  2071.     }
  2072.  
  2073.     memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
  2074.     ff_thread_finish_setup(avctx);
  2075.  
  2076.     if (unpack_superblocks(s, &gb)){
  2077.         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
  2078.         goto error;
  2079.     }
  2080.     if (unpack_modes(s, &gb)){
  2081.         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
  2082.         goto error;
  2083.     }
  2084.     if (unpack_vectors(s, &gb)){
  2085.         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
  2086.         goto error;
  2087.     }
  2088.     if (unpack_block_qpis(s, &gb)){
  2089.         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
  2090.         goto error;
  2091.     }
  2092.     if (unpack_dct_coeffs(s, &gb)){
  2093.         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
  2094.         goto error;
  2095.     }
  2096.  
  2097.     for (i = 0; i < 3; i++) {
  2098.         int height = s->height >> (i && s->chroma_y_shift);
  2099.         if (s->flipped_image)
  2100.             s->data_offset[i] = 0;
  2101.         else
  2102.             s->data_offset[i] = (height-1) * s->current_frame.f->linesize[i];
  2103.     }
  2104.  
  2105.     s->last_slice_end = 0;
  2106.     for (i = 0; i < s->c_superblock_height; i++)
  2107.         render_slice(s, i);
  2108.  
  2109.     // filter the last row
  2110.     for (i = 0; i < 3; i++) {
  2111.         int row = (s->height >> (3+(i && s->chroma_y_shift))) - 1;
  2112.         apply_loop_filter(s, i, row, row+1);
  2113.     }
  2114.     vp3_draw_horiz_band(s, s->avctx->height);
  2115.  
  2116.     if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
  2117.         return ret;
  2118.     *got_frame = 1;
  2119.  
  2120.     if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME)) {
  2121.         ret = update_frames(avctx);
  2122.         if (ret < 0)
  2123.             return ret;
  2124.     }
  2125.  
  2126.     return buf_size;
  2127.  
  2128. error:
  2129.     ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
  2130.  
  2131.     if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
  2132.         av_frame_unref(s->current_frame.f);
  2133.  
  2134.     return -1;
  2135. }
  2136.  
  2137. static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
  2138. {
  2139.     Vp3DecodeContext *s = avctx->priv_data;
  2140.  
  2141.     if (get_bits1(gb)) {
  2142.         int token;
  2143.         if (s->entries >= 32) { /* overflow */
  2144.             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
  2145.             return -1;
  2146.         }
  2147.         token = get_bits(gb, 5);
  2148.         av_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
  2149.                 s->hti, s->hbits, token, s->entries, s->huff_code_size);
  2150.         s->huffman_table[s->hti][token][0] = s->hbits;
  2151.         s->huffman_table[s->hti][token][1] = s->huff_code_size;
  2152.         s->entries++;
  2153.     }
  2154.     else {
  2155.         if (s->huff_code_size >= 32) {/* overflow */
  2156.             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
  2157.             return -1;
  2158.         }
  2159.         s->huff_code_size++;
  2160.         s->hbits <<= 1;
  2161.         if (read_huffman_tree(avctx, gb))
  2162.             return -1;
  2163.         s->hbits |= 1;
  2164.         if (read_huffman_tree(avctx, gb))
  2165.             return -1;
  2166.         s->hbits >>= 1;
  2167.         s->huff_code_size--;
  2168.     }
  2169.     return 0;
  2170. }
  2171.  
  2172. static int vp3_init_thread_copy(AVCodecContext *avctx)
  2173. {
  2174.     Vp3DecodeContext *s = avctx->priv_data;
  2175.  
  2176.     s->superblock_coding      = NULL;
  2177.     s->all_fragments          = NULL;
  2178.     s->coded_fragment_list[0] = NULL;
  2179.     s->dct_tokens_base        = NULL;
  2180.     s->superblock_fragments   = NULL;
  2181.     s->macroblock_coding      = NULL;
  2182.     s->motion_val[0]          = NULL;
  2183.     s->motion_val[1]          = NULL;
  2184.     s->edge_emu_buffer        = NULL;
  2185.  
  2186.     return init_frames(s);
  2187. }
  2188.  
  2189. #if CONFIG_THEORA_DECODER
  2190. static const enum AVPixelFormat theora_pix_fmts[4] = {
  2191.     AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
  2192. };
  2193.  
  2194. static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
  2195. {
  2196.     Vp3DecodeContext *s = avctx->priv_data;
  2197.     int visible_width, visible_height, colorspace;
  2198.     int offset_x = 0, offset_y = 0;
  2199.     AVRational fps, aspect;
  2200.  
  2201.     s->theora = get_bits_long(gb, 24);
  2202.     av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
  2203.  
  2204.     /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
  2205.     /* but previous versions have the image flipped relative to vp3 */
  2206.     if (s->theora < 0x030200)
  2207.     {
  2208.         s->flipped_image = 1;
  2209.         av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
  2210.     }
  2211.  
  2212.     visible_width  = s->width  = get_bits(gb, 16) << 4;
  2213.     visible_height = s->height = get_bits(gb, 16) << 4;
  2214.  
  2215.     if(av_image_check_size(s->width, s->height, 0, avctx)){
  2216.         av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
  2217.         s->width= s->height= 0;
  2218.         return -1;
  2219.     }
  2220.  
  2221.     if (s->theora >= 0x030200) {
  2222.         visible_width  = get_bits_long(gb, 24);
  2223.         visible_height = get_bits_long(gb, 24);
  2224.  
  2225.         offset_x = get_bits(gb, 8); /* offset x */
  2226.         offset_y = get_bits(gb, 8); /* offset y, from bottom */
  2227.     }
  2228.  
  2229.     fps.num = get_bits_long(gb, 32);
  2230.     fps.den = get_bits_long(gb, 32);
  2231.     if (fps.num && fps.den) {
  2232.         if (fps.num < 0 || fps.den < 0) {
  2233.             av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
  2234.             return AVERROR_INVALIDDATA;
  2235.         }
  2236.         av_reduce(&avctx->time_base.num, &avctx->time_base.den,
  2237.                   fps.den, fps.num, 1<<30);
  2238.     }
  2239.  
  2240.     aspect.num = get_bits_long(gb, 24);
  2241.     aspect.den = get_bits_long(gb, 24);
  2242.     if (aspect.num && aspect.den) {
  2243.         av_reduce(&avctx->sample_aspect_ratio.num,
  2244.                   &avctx->sample_aspect_ratio.den,
  2245.                   aspect.num, aspect.den, 1<<30);
  2246.     }
  2247.  
  2248.     if (s->theora < 0x030200)
  2249.         skip_bits(gb, 5); /* keyframe frequency force */
  2250.     colorspace = get_bits(gb, 8);
  2251.     skip_bits(gb, 24); /* bitrate */
  2252.  
  2253.     skip_bits(gb, 6); /* quality hint */
  2254.  
  2255.     if (s->theora >= 0x030200)
  2256.     {
  2257.         skip_bits(gb, 5); /* keyframe frequency force */
  2258.         avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
  2259.         if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
  2260.             av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
  2261.             return AVERROR_INVALIDDATA;
  2262.         }
  2263.         skip_bits(gb, 3); /* reserved */
  2264.     }
  2265.  
  2266. //    align_get_bits(gb);
  2267.  
  2268.     if (   visible_width  <= s->width  && visible_width  > s->width-16
  2269.         && visible_height <= s->height && visible_height > s->height-16
  2270.         && !offset_x && (offset_y == s->height - visible_height))
  2271.         avcodec_set_dimensions(avctx, visible_width, visible_height);
  2272.     else
  2273.         avcodec_set_dimensions(avctx, s->width, s->height);
  2274.  
  2275.     if (colorspace == 1) {
  2276.         avctx->color_primaries = AVCOL_PRI_BT470M;
  2277.     } else if (colorspace == 2) {
  2278.         avctx->color_primaries = AVCOL_PRI_BT470BG;
  2279.     }
  2280.     if (colorspace == 1 || colorspace == 2) {
  2281.         avctx->colorspace = AVCOL_SPC_BT470BG;
  2282.         avctx->color_trc  = AVCOL_TRC_BT709;
  2283.     }
  2284.  
  2285.     return 0;
  2286. }
  2287.  
  2288. static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
  2289. {
  2290.     Vp3DecodeContext *s = avctx->priv_data;
  2291.     int i, n, matrices, inter, plane;
  2292.  
  2293.     if (s->theora >= 0x030200) {
  2294.         n = get_bits(gb, 3);
  2295.         /* loop filter limit values table */
  2296.         if (n)
  2297.             for (i = 0; i < 64; i++)
  2298.                 s->filter_limit_values[i] = get_bits(gb, n);
  2299.     }
  2300.  
  2301.     if (s->theora >= 0x030200)
  2302.         n = get_bits(gb, 4) + 1;
  2303.     else
  2304.         n = 16;
  2305.     /* quality threshold table */
  2306.     for (i = 0; i < 64; i++)
  2307.         s->coded_ac_scale_factor[i] = get_bits(gb, n);
  2308.  
  2309.     if (s->theora >= 0x030200)
  2310.         n = get_bits(gb, 4) + 1;
  2311.     else
  2312.         n = 16;
  2313.     /* dc scale factor table */
  2314.     for (i = 0; i < 64; i++)
  2315.         s->coded_dc_scale_factor[i] = get_bits(gb, n);
  2316.  
  2317.     if (s->theora >= 0x030200)
  2318.         matrices = get_bits(gb, 9) + 1;
  2319.     else
  2320.         matrices = 3;
  2321.  
  2322.     if(matrices > 384){
  2323.         av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
  2324.         return -1;
  2325.     }
  2326.  
  2327.     for(n=0; n<matrices; n++){
  2328.         for (i = 0; i < 64; i++)
  2329.             s->base_matrix[n][i]= get_bits(gb, 8);
  2330.     }
  2331.  
  2332.     for (inter = 0; inter <= 1; inter++) {
  2333.         for (plane = 0; plane <= 2; plane++) {
  2334.             int newqr= 1;
  2335.             if (inter || plane > 0)
  2336.                 newqr = get_bits1(gb);
  2337.             if (!newqr) {
  2338.                 int qtj, plj;
  2339.                 if(inter && get_bits1(gb)){
  2340.                     qtj = 0;
  2341.                     plj = plane;
  2342.                 }else{
  2343.                     qtj= (3*inter + plane - 1) / 3;
  2344.                     plj= (plane + 2) % 3;
  2345.                 }
  2346.                 s->qr_count[inter][plane]= s->qr_count[qtj][plj];
  2347.                 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
  2348.                 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
  2349.             } else {
  2350.                 int qri= 0;
  2351.                 int qi = 0;
  2352.  
  2353.                 for(;;){
  2354.                     i= get_bits(gb, av_log2(matrices-1)+1);
  2355.                     if(i>= matrices){
  2356.                         av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
  2357.                         return -1;
  2358.                     }
  2359.                     s->qr_base[inter][plane][qri]= i;
  2360.                     if(qi >= 63)
  2361.                         break;
  2362.                     i = get_bits(gb, av_log2(63-qi)+1) + 1;
  2363.                     s->qr_size[inter][plane][qri++]= i;
  2364.                     qi += i;
  2365.                 }
  2366.  
  2367.                 if (qi > 63) {
  2368.                     av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
  2369.                     return -1;
  2370.                 }
  2371.                 s->qr_count[inter][plane]= qri;
  2372.             }
  2373.         }
  2374.     }
  2375.  
  2376.     /* Huffman tables */
  2377.     for (s->hti = 0; s->hti < 80; s->hti++) {
  2378.         s->entries = 0;
  2379.         s->huff_code_size = 1;
  2380.         if (!get_bits1(gb)) {
  2381.             s->hbits = 0;
  2382.             if(read_huffman_tree(avctx, gb))
  2383.                 return -1;
  2384.             s->hbits = 1;
  2385.             if(read_huffman_tree(avctx, gb))
  2386.                 return -1;
  2387.         }
  2388.     }
  2389.  
  2390.     s->theora_tables = 1;
  2391.  
  2392.     return 0;
  2393. }
  2394.  
  2395. static av_cold int theora_decode_init(AVCodecContext *avctx)
  2396. {
  2397.     Vp3DecodeContext *s = avctx->priv_data;
  2398.     GetBitContext gb;
  2399.     int ptype;
  2400.     uint8_t *header_start[3];
  2401.     int header_len[3];
  2402.     int i;
  2403.  
  2404.     avctx->pix_fmt = AV_PIX_FMT_YUV420P;
  2405.  
  2406.     s->theora = 1;
  2407.  
  2408.     if (!avctx->extradata_size)
  2409.     {
  2410.         av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
  2411.         return -1;
  2412.     }
  2413.  
  2414.     if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
  2415.                               42, header_start, header_len) < 0) {
  2416.         av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
  2417.         return -1;
  2418.     }
  2419.  
  2420.   for(i=0;i<3;i++) {
  2421.     if (header_len[i] <= 0)
  2422.         continue;
  2423.     init_get_bits(&gb, header_start[i], header_len[i] * 8);
  2424.  
  2425.     ptype = get_bits(&gb, 8);
  2426.  
  2427.      if (!(ptype & 0x80))
  2428.      {
  2429.         av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
  2430. //        return -1;
  2431.      }
  2432.  
  2433.     // FIXME: Check for this as well.
  2434.     skip_bits_long(&gb, 6*8); /* "theora" */
  2435.  
  2436.     switch(ptype)
  2437.     {
  2438.         case 0x80:
  2439.             if (theora_decode_header(avctx, &gb) < 0)
  2440.                 return -1;
  2441.                 break;
  2442.         case 0x81:
  2443. // FIXME: is this needed? it breaks sometimes
  2444. //            theora_decode_comments(avctx, gb);
  2445.             break;
  2446.         case 0x82:
  2447.             if (theora_decode_tables(avctx, &gb))
  2448.                 return -1;
  2449.             break;
  2450.         default:
  2451.             av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
  2452.             break;
  2453.     }
  2454.     if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
  2455.         av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
  2456.     if (s->theora < 0x030200)
  2457.         break;
  2458.   }
  2459.  
  2460.     return vp3_decode_init(avctx);
  2461. }
  2462.  
  2463. AVCodec ff_theora_decoder = {
  2464.     .name                  = "theora",
  2465.     .long_name             = NULL_IF_CONFIG_SMALL("Theora"),
  2466.     .type                  = AVMEDIA_TYPE_VIDEO,
  2467.     .id                    = AV_CODEC_ID_THEORA,
  2468.     .priv_data_size        = sizeof(Vp3DecodeContext),
  2469.     .init                  = theora_decode_init,
  2470.     .close                 = vp3_decode_end,
  2471.     .decode                = vp3_decode_frame,
  2472.     .capabilities          = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
  2473.                              CODEC_CAP_FRAME_THREADS,
  2474.     .flush                 = vp3_decode_flush,
  2475.     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
  2476.     .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
  2477. };
  2478. #endif
  2479.  
  2480. AVCodec ff_vp3_decoder = {
  2481.     .name                  = "vp3",
  2482.     .long_name             = NULL_IF_CONFIG_SMALL("On2 VP3"),
  2483.     .type                  = AVMEDIA_TYPE_VIDEO,
  2484.     .id                    = AV_CODEC_ID_VP3,
  2485.     .priv_data_size        = sizeof(Vp3DecodeContext),
  2486.     .init                  = vp3_decode_init,
  2487.     .close                 = vp3_decode_end,
  2488.     .decode                = vp3_decode_frame,
  2489.     .capabilities          = CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND |
  2490.                              CODEC_CAP_FRAME_THREADS,
  2491.     .flush                 = vp3_decode_flush,
  2492.     .init_thread_copy      = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
  2493.     .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
  2494. };
  2495.