LCOV - code coverage report
Current view: top level - libavcodec - vp3.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 935 1227 76.2 %
Date: 2017-12-18 13:19:42 Functions: 26 31 83.9 %

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

Generated by: LCOV version 1.13