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

Generated by: LCOV version 1.13