Libav 0.7.1
libavcodec/vp3.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2003-2004 the ffmpeg project
00003  *
00004  * This file is part of Libav.
00005  *
00006  * Libav is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2.1 of the License, or (at your option) any later version.
00010  *
00011  * Libav is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with Libav; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00019  */
00020 
00032 #include <stdio.h>
00033 #include <stdlib.h>
00034 #include <string.h>
00035 
00036 #include "libavutil/imgutils.h"
00037 #include "avcodec.h"
00038 #include "dsputil.h"
00039 #include "get_bits.h"
00040 
00041 #include "vp3data.h"
00042 #include "xiph.h"
00043 #include "thread.h"
00044 
00045 #define FRAGMENT_PIXELS 8
00046 
00047 static av_cold int vp3_decode_end(AVCodecContext *avctx);
00048 
00049 //FIXME split things out into their own arrays
00050 typedef struct Vp3Fragment {
00051     int16_t dc;
00052     uint8_t coding_method;
00053     uint8_t qpi;
00054 } Vp3Fragment;
00055 
00056 #define SB_NOT_CODED        0
00057 #define SB_PARTIALLY_CODED  1
00058 #define SB_FULLY_CODED      2
00059 
00060 // This is the maximum length of a single long bit run that can be encoded
00061 // for superblock coding or block qps. Theora special-cases this to read a
00062 // bit instead of flipping the current bit to allow for runs longer than 4129.
00063 #define MAXIMUM_LONG_BIT_RUN 4129
00064 
00065 #define MODE_INTER_NO_MV      0
00066 #define MODE_INTRA            1
00067 #define MODE_INTER_PLUS_MV    2
00068 #define MODE_INTER_LAST_MV    3
00069 #define MODE_INTER_PRIOR_LAST 4
00070 #define MODE_USING_GOLDEN     5
00071 #define MODE_GOLDEN_MV        6
00072 #define MODE_INTER_FOURMV     7
00073 #define CODING_MODE_COUNT     8
00074 
00075 /* special internal mode */
00076 #define MODE_COPY             8
00077 
00078 /* There are 6 preset schemes, plus a free-form scheme */
00079 static const int ModeAlphabet[6][CODING_MODE_COUNT] =
00080 {
00081     /* scheme 1: Last motion vector dominates */
00082     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
00083          MODE_INTER_PLUS_MV,    MODE_INTER_NO_MV,
00084          MODE_INTRA,            MODE_USING_GOLDEN,
00085          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
00086 
00087     /* scheme 2 */
00088     {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
00089          MODE_INTER_NO_MV,      MODE_INTER_PLUS_MV,
00090          MODE_INTRA,            MODE_USING_GOLDEN,
00091          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
00092 
00093     /* scheme 3 */
00094     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
00095          MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
00096          MODE_INTRA,            MODE_USING_GOLDEN,
00097          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
00098 
00099     /* scheme 4 */
00100     {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
00101          MODE_INTER_NO_MV,      MODE_INTER_PRIOR_LAST,
00102          MODE_INTRA,            MODE_USING_GOLDEN,
00103          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
00104 
00105     /* scheme 5: No motion vector dominates */
00106     {    MODE_INTER_NO_MV,      MODE_INTER_LAST_MV,
00107          MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
00108          MODE_INTRA,            MODE_USING_GOLDEN,
00109          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
00110 
00111     /* scheme 6 */
00112     {    MODE_INTER_NO_MV,      MODE_USING_GOLDEN,
00113          MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
00114          MODE_INTER_PLUS_MV,    MODE_INTRA,
00115          MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
00116 
00117 };
00118 
00119 static const uint8_t hilbert_offset[16][2] = {
00120     {0,0}, {1,0}, {1,1}, {0,1},
00121     {0,2}, {0,3}, {1,3}, {1,2},
00122     {2,2}, {2,3}, {3,3}, {3,2},
00123     {3,1}, {2,1}, {2,0}, {3,0}
00124 };
00125 
00126 #define MIN_DEQUANT_VAL 2
00127 
00128 typedef struct Vp3DecodeContext {
00129     AVCodecContext *avctx;
00130     int theora, theora_tables;
00131     int version;
00132     int width, height;
00133     int chroma_x_shift, chroma_y_shift;
00134     AVFrame golden_frame;
00135     AVFrame last_frame;
00136     AVFrame current_frame;
00137     int keyframe;
00138     DSPContext dsp;
00139     int flipped_image;
00140     int last_slice_end;
00141     int skip_loop_filter;
00142 
00143     int qps[3];
00144     int nqps;
00145     int last_qps[3];
00146 
00147     int superblock_count;
00148     int y_superblock_width;
00149     int y_superblock_height;
00150     int y_superblock_count;
00151     int c_superblock_width;
00152     int c_superblock_height;
00153     int c_superblock_count;
00154     int u_superblock_start;
00155     int v_superblock_start;
00156     unsigned char *superblock_coding;
00157 
00158     int macroblock_count;
00159     int macroblock_width;
00160     int macroblock_height;
00161 
00162     int fragment_count;
00163     int fragment_width[2];
00164     int fragment_height[2];
00165 
00166     Vp3Fragment *all_fragments;
00167     int fragment_start[3];
00168     int data_offset[3];
00169 
00170     int8_t (*motion_val[2])[2];
00171 
00172     ScanTable scantable;
00173 
00174     /* tables */
00175     uint16_t coded_dc_scale_factor[64];
00176     uint32_t coded_ac_scale_factor[64];
00177     uint8_t base_matrix[384][64];
00178     uint8_t qr_count[2][3];
00179     uint8_t qr_size [2][3][64];
00180     uint16_t qr_base[2][3][64];
00181 
00199     int16_t *dct_tokens[3][64];
00200     int16_t *dct_tokens_base;
00201 #define TOKEN_EOB(eob_run)              ((eob_run) << 2)
00202 #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) << 9) + ((zero_run) << 2) + 1)
00203 #define TOKEN_COEFF(coeff)              (((coeff) << 2) + 2)
00204 
00208     int num_coded_frags[3][64];
00209     int total_num_coded_frags;
00210 
00211     /* this is a list of indexes into the all_fragments array indicating
00212      * which of the fragments are coded */
00213     int *coded_fragment_list[3];
00214 
00215     VLC dc_vlc[16];
00216     VLC ac_vlc_1[16];
00217     VLC ac_vlc_2[16];
00218     VLC ac_vlc_3[16];
00219     VLC ac_vlc_4[16];
00220 
00221     VLC superblock_run_length_vlc;
00222     VLC fragment_run_length_vlc;
00223     VLC mode_code_vlc;
00224     VLC motion_vector_vlc;
00225 
00226     /* these arrays need to be on 16-byte boundaries since SSE2 operations
00227      * index into them */
00228     DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64];     //<qmat[qpi][is_inter][plane]
00229 
00230     /* This table contains superblock_count * 16 entries. Each set of 16
00231      * numbers corresponds to the fragment indexes 0..15 of the superblock.
00232      * An entry will be -1 to indicate that no entry corresponds to that
00233      * index. */
00234     int *superblock_fragments;
00235 
00236     /* This is an array that indicates how a particular macroblock
00237      * is coded. */
00238     unsigned char *macroblock_coding;
00239 
00240     uint8_t *edge_emu_buffer;
00241 
00242     /* Huffman decode */
00243     int hti;
00244     unsigned int hbits;
00245     int entries;
00246     int huff_code_size;
00247     uint32_t huffman_table[80][32][2];
00248 
00249     uint8_t filter_limit_values[64];
00250     DECLARE_ALIGNED(8, int, bounding_values_array)[256+2];
00251 } Vp3DecodeContext;
00252 
00253 /************************************************************************
00254  * VP3 specific functions
00255  ************************************************************************/
00256 
00257 /*
00258  * This function sets up all of the various blocks mappings:
00259  * superblocks <-> fragments, macroblocks <-> fragments,
00260  * superblocks <-> macroblocks
00261  *
00262  * @return 0 is successful; returns 1 if *anything* went wrong.
00263  */
00264 static int init_block_mapping(Vp3DecodeContext *s)
00265 {
00266     int sb_x, sb_y, plane;
00267     int x, y, i, j = 0;
00268 
00269     for (plane = 0; plane < 3; plane++) {
00270         int sb_width    = plane ? s->c_superblock_width  : s->y_superblock_width;
00271         int sb_height   = plane ? s->c_superblock_height : s->y_superblock_height;
00272         int frag_width  = s->fragment_width[!!plane];
00273         int frag_height = s->fragment_height[!!plane];
00274 
00275         for (sb_y = 0; sb_y < sb_height; sb_y++)
00276             for (sb_x = 0; sb_x < sb_width; sb_x++)
00277                 for (i = 0; i < 16; i++) {
00278                     x = 4*sb_x + hilbert_offset[i][0];
00279                     y = 4*sb_y + hilbert_offset[i][1];
00280 
00281                     if (x < frag_width && y < frag_height)
00282                         s->superblock_fragments[j++] = s->fragment_start[plane] + y*frag_width + x;
00283                     else
00284                         s->superblock_fragments[j++] = -1;
00285                 }
00286     }
00287 
00288     return 0;  /* successful path out */
00289 }
00290 
00291 /*
00292  * This function sets up the dequantization tables used for a particular
00293  * frame.
00294  */
00295 static void init_dequantizer(Vp3DecodeContext *s, int qpi)
00296 {
00297     int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
00298     int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
00299     int i, plane, inter, qri, bmi, bmj, qistart;
00300 
00301     for(inter=0; inter<2; inter++){
00302         for(plane=0; plane<3; plane++){
00303             int sum=0;
00304             for(qri=0; qri<s->qr_count[inter][plane]; qri++){
00305                 sum+= s->qr_size[inter][plane][qri];
00306                 if(s->qps[qpi] <= sum)
00307                     break;
00308             }
00309             qistart= sum - s->qr_size[inter][plane][qri];
00310             bmi= s->qr_base[inter][plane][qri  ];
00311             bmj= s->qr_base[inter][plane][qri+1];
00312             for(i=0; i<64; i++){
00313                 int coeff= (  2*(sum    -s->qps[qpi])*s->base_matrix[bmi][i]
00314                             - 2*(qistart-s->qps[qpi])*s->base_matrix[bmj][i]
00315                             + s->qr_size[inter][plane][qri])
00316                            / (2*s->qr_size[inter][plane][qri]);
00317 
00318                 int qmin= 8<<(inter + !i);
00319                 int qscale= i ? ac_scale_factor : dc_scale_factor;
00320 
00321                 s->qmat[qpi][inter][plane][s->dsp.idct_permutation[i]]= av_clip((qscale * coeff)/100 * 4, qmin, 4096);
00322             }
00323             // all DC coefficients use the same quant so as not to interfere with DC prediction
00324             s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
00325         }
00326     }
00327 }
00328 
00329 /*
00330  * This function initializes the loop filter boundary limits if the frame's
00331  * quality index is different from the previous frame's.
00332  *
00333  * The filter_limit_values may not be larger than 127.
00334  */
00335 static void init_loop_filter(Vp3DecodeContext *s)
00336 {
00337     int *bounding_values= s->bounding_values_array+127;
00338     int filter_limit;
00339     int x;
00340     int value;
00341 
00342     filter_limit = s->filter_limit_values[s->qps[0]];
00343 
00344     /* set up the bounding values */
00345     memset(s->bounding_values_array, 0, 256 * sizeof(int));
00346     for (x = 0; x < filter_limit; x++) {
00347         bounding_values[-x] = -x;
00348         bounding_values[x] = x;
00349     }
00350     for (x = value = filter_limit; x < 128 && value; x++, value--) {
00351         bounding_values[ x] =  value;
00352         bounding_values[-x] = -value;
00353     }
00354     if (value)
00355         bounding_values[128] = value;
00356     bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
00357 }
00358 
00359 /*
00360  * This function unpacks all of the superblock/macroblock/fragment coding
00361  * information from the bitstream.
00362  */
00363 static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
00364 {
00365     int superblock_starts[3] = { 0, s->u_superblock_start, s->v_superblock_start };
00366     int bit = 0;
00367     int current_superblock = 0;
00368     int current_run = 0;
00369     int num_partial_superblocks = 0;
00370 
00371     int i, j;
00372     int current_fragment;
00373     int plane;
00374 
00375     if (s->keyframe) {
00376         memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
00377 
00378     } else {
00379 
00380         /* unpack the list of partially-coded superblocks */
00381         bit = get_bits1(gb) ^ 1;
00382         current_run = 0;
00383 
00384         while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
00385             if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
00386                 bit = get_bits1(gb);
00387             else
00388                 bit ^= 1;
00389 
00390                 current_run = get_vlc2(gb,
00391                     s->superblock_run_length_vlc.table, 6, 2) + 1;
00392                 if (current_run == 34)
00393                     current_run += get_bits(gb, 12);
00394 
00395             if (current_superblock + current_run > s->superblock_count) {
00396                 av_log(s->avctx, AV_LOG_ERROR, "Invalid partially coded superblock run length\n");
00397                 return -1;
00398             }
00399 
00400             memset(s->superblock_coding + current_superblock, bit, current_run);
00401 
00402             current_superblock += current_run;
00403             if (bit)
00404                 num_partial_superblocks += current_run;
00405         }
00406 
00407         /* unpack the list of fully coded superblocks if any of the blocks were
00408          * not marked as partially coded in the previous step */
00409         if (num_partial_superblocks < s->superblock_count) {
00410             int superblocks_decoded = 0;
00411 
00412             current_superblock = 0;
00413             bit = get_bits1(gb) ^ 1;
00414             current_run = 0;
00415 
00416             while (superblocks_decoded < s->superblock_count - num_partial_superblocks
00417                    && get_bits_left(gb) > 0) {
00418 
00419                 if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
00420                     bit = get_bits1(gb);
00421                 else
00422                     bit ^= 1;
00423 
00424                         current_run = get_vlc2(gb,
00425                             s->superblock_run_length_vlc.table, 6, 2) + 1;
00426                         if (current_run == 34)
00427                             current_run += get_bits(gb, 12);
00428 
00429                 for (j = 0; j < current_run; current_superblock++) {
00430                     if (current_superblock >= s->superblock_count) {
00431                         av_log(s->avctx, AV_LOG_ERROR, "Invalid fully coded superblock run length\n");
00432                         return -1;
00433                     }
00434 
00435                 /* skip any superblocks already marked as partially coded */
00436                 if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
00437                     s->superblock_coding[current_superblock] = 2*bit;
00438                     j++;
00439                 }
00440                 }
00441                 superblocks_decoded += current_run;
00442             }
00443         }
00444 
00445         /* if there were partial blocks, initialize bitstream for
00446          * unpacking fragment codings */
00447         if (num_partial_superblocks) {
00448 
00449             current_run = 0;
00450             bit = get_bits1(gb);
00451             /* toggle the bit because as soon as the first run length is
00452              * fetched the bit will be toggled again */
00453             bit ^= 1;
00454         }
00455     }
00456 
00457     /* figure out which fragments are coded; iterate through each
00458      * superblock (all planes) */
00459     s->total_num_coded_frags = 0;
00460     memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
00461 
00462     for (plane = 0; plane < 3; plane++) {
00463         int sb_start = superblock_starts[plane];
00464         int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);
00465         int num_coded_frags = 0;
00466 
00467     for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
00468 
00469         /* iterate through all 16 fragments in a superblock */
00470         for (j = 0; j < 16; j++) {
00471 
00472             /* if the fragment is in bounds, check its coding status */
00473             current_fragment = s->superblock_fragments[i * 16 + j];
00474             if (current_fragment != -1) {
00475                 int coded = s->superblock_coding[i];
00476 
00477                 if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
00478 
00479                     /* fragment may or may not be coded; this is the case
00480                      * that cares about the fragment coding runs */
00481                     if (current_run-- == 0) {
00482                         bit ^= 1;
00483                         current_run = get_vlc2(gb,
00484                             s->fragment_run_length_vlc.table, 5, 2);
00485                     }
00486                     coded = bit;
00487                 }
00488 
00489                     if (coded) {
00490                         /* default mode; actual mode will be decoded in
00491                          * the next phase */
00492                         s->all_fragments[current_fragment].coding_method =
00493                             MODE_INTER_NO_MV;
00494                         s->coded_fragment_list[plane][num_coded_frags++] =
00495                             current_fragment;
00496                     } else {
00497                         /* not coded; copy this fragment from the prior frame */
00498                         s->all_fragments[current_fragment].coding_method =
00499                             MODE_COPY;
00500                     }
00501             }
00502         }
00503     }
00504         s->total_num_coded_frags += num_coded_frags;
00505         for (i = 0; i < 64; i++)
00506             s->num_coded_frags[plane][i] = num_coded_frags;
00507         if (plane < 2)
00508             s->coded_fragment_list[plane+1] = s->coded_fragment_list[plane] + num_coded_frags;
00509     }
00510     return 0;
00511 }
00512 
00513 /*
00514  * This function unpacks all the coding mode data for individual macroblocks
00515  * from the bitstream.
00516  */
00517 static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
00518 {
00519     int i, j, k, sb_x, sb_y;
00520     int scheme;
00521     int current_macroblock;
00522     int current_fragment;
00523     int coding_mode;
00524     int custom_mode_alphabet[CODING_MODE_COUNT];
00525     const int *alphabet;
00526     Vp3Fragment *frag;
00527 
00528     if (s->keyframe) {
00529         for (i = 0; i < s->fragment_count; i++)
00530             s->all_fragments[i].coding_method = MODE_INTRA;
00531 
00532     } else {
00533 
00534         /* fetch the mode coding scheme for this frame */
00535         scheme = get_bits(gb, 3);
00536 
00537         /* is it a custom coding scheme? */
00538         if (scheme == 0) {
00539             for (i = 0; i < 8; i++)
00540                 custom_mode_alphabet[i] = MODE_INTER_NO_MV;
00541             for (i = 0; i < 8; i++)
00542                 custom_mode_alphabet[get_bits(gb, 3)] = i;
00543             alphabet = custom_mode_alphabet;
00544         } else
00545             alphabet = ModeAlphabet[scheme-1];
00546 
00547         /* iterate through all of the macroblocks that contain 1 or more
00548          * coded fragments */
00549         for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
00550             for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
00551                 if (get_bits_left(gb) <= 0)
00552                     return -1;
00553 
00554             for (j = 0; j < 4; j++) {
00555                 int mb_x = 2*sb_x +   (j>>1);
00556                 int mb_y = 2*sb_y + (((j>>1)+j)&1);
00557                 current_macroblock = mb_y * s->macroblock_width + mb_x;
00558 
00559                 if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height)
00560                     continue;
00561 
00562 #define BLOCK_X (2*mb_x + (k&1))
00563 #define BLOCK_Y (2*mb_y + (k>>1))
00564                 /* coding modes are only stored if the macroblock has at least one
00565                  * luma block coded, otherwise it must be INTER_NO_MV */
00566                 for (k = 0; k < 4; k++) {
00567                     current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
00568                     if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
00569                         break;
00570                 }
00571                 if (k == 4) {
00572                     s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
00573                     continue;
00574                 }
00575 
00576                 /* mode 7 means get 3 bits for each coding mode */
00577                 if (scheme == 7)
00578                     coding_mode = get_bits(gb, 3);
00579                 else
00580                     coding_mode = alphabet
00581                         [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
00582 
00583                 s->macroblock_coding[current_macroblock] = coding_mode;
00584                 for (k = 0; k < 4; k++) {
00585                     frag = s->all_fragments + BLOCK_Y*s->fragment_width[0] + BLOCK_X;
00586                     if (frag->coding_method != MODE_COPY)
00587                         frag->coding_method = coding_mode;
00588                 }
00589 
00590 #define SET_CHROMA_MODES \
00591     if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
00592         frag[s->fragment_start[1]].coding_method = coding_mode;\
00593     if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
00594         frag[s->fragment_start[2]].coding_method = coding_mode;
00595 
00596                 if (s->chroma_y_shift) {
00597                     frag = s->all_fragments + mb_y*s->fragment_width[1] + mb_x;
00598                     SET_CHROMA_MODES
00599                 } else if (s->chroma_x_shift) {
00600                     frag = s->all_fragments + 2*mb_y*s->fragment_width[1] + mb_x;
00601                     for (k = 0; k < 2; k++) {
00602                         SET_CHROMA_MODES
00603                         frag += s->fragment_width[1];
00604                     }
00605                 } else {
00606                     for (k = 0; k < 4; k++) {
00607                         frag = s->all_fragments + BLOCK_Y*s->fragment_width[1] + BLOCK_X;
00608                         SET_CHROMA_MODES
00609                     }
00610                 }
00611             }
00612             }
00613         }
00614     }
00615 
00616     return 0;
00617 }
00618 
00619 /*
00620  * This function unpacks all the motion vectors for the individual
00621  * macroblocks from the bitstream.
00622  */
00623 static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
00624 {
00625     int j, k, sb_x, sb_y;
00626     int coding_mode;
00627     int motion_x[4];
00628     int motion_y[4];
00629     int last_motion_x = 0;
00630     int last_motion_y = 0;
00631     int prior_last_motion_x = 0;
00632     int prior_last_motion_y = 0;
00633     int current_macroblock;
00634     int current_fragment;
00635     int frag;
00636 
00637     if (s->keyframe)
00638         return 0;
00639 
00640     /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
00641     coding_mode = get_bits1(gb);
00642 
00643     /* iterate through all of the macroblocks that contain 1 or more
00644      * coded fragments */
00645     for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
00646         for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
00647             if (get_bits_left(gb) <= 0)
00648                 return -1;
00649 
00650         for (j = 0; j < 4; j++) {
00651             int mb_x = 2*sb_x +   (j>>1);
00652             int mb_y = 2*sb_y + (((j>>1)+j)&1);
00653             current_macroblock = mb_y * s->macroblock_width + mb_x;
00654 
00655             if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||
00656                 (s->macroblock_coding[current_macroblock] == MODE_COPY))
00657                 continue;
00658 
00659             switch (s->macroblock_coding[current_macroblock]) {
00660 
00661             case MODE_INTER_PLUS_MV:
00662             case MODE_GOLDEN_MV:
00663                 /* all 6 fragments use the same motion vector */
00664                 if (coding_mode == 0) {
00665                     motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
00666                     motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
00667                 } else {
00668                     motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
00669                     motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
00670                 }
00671 
00672                 /* vector maintenance, only on MODE_INTER_PLUS_MV */
00673                 if (s->macroblock_coding[current_macroblock] ==
00674                     MODE_INTER_PLUS_MV) {
00675                     prior_last_motion_x = last_motion_x;
00676                     prior_last_motion_y = last_motion_y;
00677                     last_motion_x = motion_x[0];
00678                     last_motion_y = motion_y[0];
00679                 }
00680                 break;
00681 
00682             case MODE_INTER_FOURMV:
00683                 /* vector maintenance */
00684                 prior_last_motion_x = last_motion_x;
00685                 prior_last_motion_y = last_motion_y;
00686 
00687                 /* fetch 4 vectors from the bitstream, one for each
00688                  * Y fragment, then average for the C fragment vectors */
00689                 for (k = 0; k < 4; k++) {
00690                     current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
00691                     if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
00692                         if (coding_mode == 0) {
00693                             motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
00694                             motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
00695                         } else {
00696                             motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
00697                             motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
00698                         }
00699                         last_motion_x = motion_x[k];
00700                         last_motion_y = motion_y[k];
00701                     } else {
00702                         motion_x[k] = 0;
00703                         motion_y[k] = 0;
00704                     }
00705                 }
00706                 break;
00707 
00708             case MODE_INTER_LAST_MV:
00709                 /* all 6 fragments use the last motion vector */
00710                 motion_x[0] = last_motion_x;
00711                 motion_y[0] = last_motion_y;
00712 
00713                 /* no vector maintenance (last vector remains the
00714                  * last vector) */
00715                 break;
00716 
00717             case MODE_INTER_PRIOR_LAST:
00718                 /* all 6 fragments use the motion vector prior to the
00719                  * last motion vector */
00720                 motion_x[0] = prior_last_motion_x;
00721                 motion_y[0] = prior_last_motion_y;
00722 
00723                 /* vector maintenance */
00724                 prior_last_motion_x = last_motion_x;
00725                 prior_last_motion_y = last_motion_y;
00726                 last_motion_x = motion_x[0];
00727                 last_motion_y = motion_y[0];
00728                 break;
00729 
00730             default:
00731                 /* covers intra, inter without MV, golden without MV */
00732                 motion_x[0] = 0;
00733                 motion_y[0] = 0;
00734 
00735                 /* no vector maintenance */
00736                 break;
00737             }
00738 
00739             /* assign the motion vectors to the correct fragments */
00740             for (k = 0; k < 4; k++) {
00741                 current_fragment =
00742                     BLOCK_Y*s->fragment_width[0] + BLOCK_X;
00743                 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
00744                     s->motion_val[0][current_fragment][0] = motion_x[k];
00745                     s->motion_val[0][current_fragment][1] = motion_y[k];
00746                 } else {
00747                     s->motion_val[0][current_fragment][0] = motion_x[0];
00748                     s->motion_val[0][current_fragment][1] = motion_y[0];
00749                 }
00750             }
00751 
00752             if (s->chroma_y_shift) {
00753                 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
00754                     motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] + motion_x[2] + motion_x[3], 2);
00755                     motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] + motion_y[2] + motion_y[3], 2);
00756                 }
00757                 motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
00758                 motion_y[0] = (motion_y[0]>>1) | (motion_y[0]&1);
00759                 frag = mb_y*s->fragment_width[1] + mb_x;
00760                 s->motion_val[1][frag][0] = motion_x[0];
00761                 s->motion_val[1][frag][1] = motion_y[0];
00762             } else if (s->chroma_x_shift) {
00763                 if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
00764                     motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
00765                     motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
00766                     motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
00767                     motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
00768                 } else {
00769                     motion_x[1] = motion_x[0];
00770                     motion_y[1] = motion_y[0];
00771                 }
00772                 motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
00773                 motion_x[1] = (motion_x[1]>>1) | (motion_x[1]&1);
00774 
00775                 frag = 2*mb_y*s->fragment_width[1] + mb_x;
00776                 for (k = 0; k < 2; k++) {
00777                     s->motion_val[1][frag][0] = motion_x[k];
00778                     s->motion_val[1][frag][1] = motion_y[k];
00779                     frag += s->fragment_width[1];
00780                 }
00781             } else {
00782                 for (k = 0; k < 4; k++) {
00783                     frag = BLOCK_Y*s->fragment_width[1] + BLOCK_X;
00784                     if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
00785                         s->motion_val[1][frag][0] = motion_x[k];
00786                         s->motion_val[1][frag][1] = motion_y[k];
00787                     } else {
00788                         s->motion_val[1][frag][0] = motion_x[0];
00789                         s->motion_val[1][frag][1] = motion_y[0];
00790                     }
00791                 }
00792             }
00793         }
00794         }
00795     }
00796 
00797     return 0;
00798 }
00799 
00800 static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
00801 {
00802     int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
00803     int num_blocks = s->total_num_coded_frags;
00804 
00805     for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
00806         i = blocks_decoded = num_blocks_at_qpi = 0;
00807 
00808         bit = get_bits1(gb) ^ 1;
00809         run_length = 0;
00810 
00811         do {
00812             if (run_length == MAXIMUM_LONG_BIT_RUN)
00813                 bit = get_bits1(gb);
00814             else
00815                 bit ^= 1;
00816 
00817             run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
00818             if (run_length == 34)
00819                 run_length += get_bits(gb, 12);
00820             blocks_decoded += run_length;
00821 
00822             if (!bit)
00823                 num_blocks_at_qpi += run_length;
00824 
00825             for (j = 0; j < run_length; i++) {
00826                 if (i >= s->total_num_coded_frags)
00827                     return -1;
00828 
00829                 if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
00830                     s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
00831                     j++;
00832                 }
00833             }
00834         } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
00835 
00836         num_blocks -= num_blocks_at_qpi;
00837     }
00838 
00839     return 0;
00840 }
00841 
00842 /*
00843  * This function is called by unpack_dct_coeffs() to extract the VLCs from
00844  * the bitstream. The VLCs encode tokens which are used to unpack DCT
00845  * data. This function unpacks all the VLCs for either the Y plane or both
00846  * C planes, and is called for DC coefficients or different AC coefficient
00847  * levels (since different coefficient types require different VLC tables.
00848  *
00849  * This function returns a residual eob run. E.g, if a particular token gave
00850  * instructions to EOB the next 5 fragments and there were only 2 fragments
00851  * left in the current fragment range, 3 would be returned so that it could
00852  * be passed into the next call to this same function.
00853  */
00854 static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
00855                         VLC *table, int coeff_index,
00856                         int plane,
00857                         int eob_run)
00858 {
00859     int i, j = 0;
00860     int token;
00861     int zero_run = 0;
00862     DCTELEM coeff = 0;
00863     int bits_to_get;
00864     int blocks_ended;
00865     int coeff_i = 0;
00866     int num_coeffs = s->num_coded_frags[plane][coeff_index];
00867     int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
00868 
00869     /* local references to structure members to avoid repeated deferences */
00870     int *coded_fragment_list = s->coded_fragment_list[plane];
00871     Vp3Fragment *all_fragments = s->all_fragments;
00872     VLC_TYPE (*vlc_table)[2] = table->table;
00873 
00874     if (num_coeffs < 0)
00875         av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);
00876 
00877     if (eob_run > num_coeffs) {
00878         coeff_i = blocks_ended = num_coeffs;
00879         eob_run -= num_coeffs;
00880     } else {
00881         coeff_i = blocks_ended = eob_run;
00882         eob_run = 0;
00883     }
00884 
00885     // insert fake EOB token to cover the split between planes or zzi
00886     if (blocks_ended)
00887         dct_tokens[j++] = blocks_ended << 2;
00888 
00889     while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
00890             /* decode a VLC into a token */
00891             token = get_vlc2(gb, vlc_table, 11, 3);
00892             /* use the token to get a zero run, a coefficient, and an eob run */
00893             if (token <= 6) {
00894                 eob_run = eob_run_base[token];
00895                 if (eob_run_get_bits[token])
00896                     eob_run += get_bits(gb, eob_run_get_bits[token]);
00897 
00898                 // record only the number of blocks ended in this plane,
00899                 // any spill will be recorded in the next plane.
00900                 if (eob_run > num_coeffs - coeff_i) {
00901                     dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
00902                     blocks_ended   += num_coeffs - coeff_i;
00903                     eob_run        -= num_coeffs - coeff_i;
00904                     coeff_i         = num_coeffs;
00905                 } else {
00906                     dct_tokens[j++] = TOKEN_EOB(eob_run);
00907                     blocks_ended   += eob_run;
00908                     coeff_i        += eob_run;
00909                     eob_run = 0;
00910                 }
00911             } else {
00912                 bits_to_get = coeff_get_bits[token];
00913                 if (bits_to_get)
00914                     bits_to_get = get_bits(gb, bits_to_get);
00915                 coeff = coeff_tables[token][bits_to_get];
00916 
00917                 zero_run = zero_run_base[token];
00918                 if (zero_run_get_bits[token])
00919                     zero_run += get_bits(gb, zero_run_get_bits[token]);
00920 
00921                 if (zero_run) {
00922                     dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
00923                 } else {
00924                     // Save DC into the fragment structure. DC prediction is
00925                     // done in raster order, so the actual DC can't be in with
00926                     // other tokens. We still need the token in dct_tokens[]
00927                     // however, or else the structure collapses on itself.
00928                     if (!coeff_index)
00929                         all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
00930 
00931                     dct_tokens[j++] = TOKEN_COEFF(coeff);
00932                 }
00933 
00934                 if (coeff_index + zero_run > 64) {
00935                     av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
00936                            " %d coeffs left\n", zero_run, 64-coeff_index);
00937                     zero_run = 64 - coeff_index;
00938                 }
00939 
00940                 // zero runs code multiple coefficients,
00941                 // so don't try to decode coeffs for those higher levels
00942                 for (i = coeff_index+1; i <= coeff_index+zero_run; i++)
00943                     s->num_coded_frags[plane][i]--;
00944                 coeff_i++;
00945             }
00946     }
00947 
00948     if (blocks_ended > s->num_coded_frags[plane][coeff_index])
00949         av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
00950 
00951     // decrement the number of blocks that have higher coeffecients for each
00952     // EOB run at this level
00953     if (blocks_ended)
00954         for (i = coeff_index+1; i < 64; i++)
00955             s->num_coded_frags[plane][i] -= blocks_ended;
00956 
00957     // setup the next buffer
00958     if (plane < 2)
00959         s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;
00960     else if (coeff_index < 63)
00961         s->dct_tokens[0][coeff_index+1] = dct_tokens + j;
00962 
00963     return eob_run;
00964 }
00965 
00966 static void reverse_dc_prediction(Vp3DecodeContext *s,
00967                                   int first_fragment,
00968                                   int fragment_width,
00969                                   int fragment_height);
00970 /*
00971  * This function unpacks all of the DCT coefficient data from the
00972  * bitstream.
00973  */
00974 static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
00975 {
00976     int i;
00977     int dc_y_table;
00978     int dc_c_table;
00979     int ac_y_table;
00980     int ac_c_table;
00981     int residual_eob_run = 0;
00982     VLC *y_tables[64];
00983     VLC *c_tables[64];
00984 
00985     s->dct_tokens[0][0] = s->dct_tokens_base;
00986 
00987     /* fetch the DC table indexes */
00988     dc_y_table = get_bits(gb, 4);
00989     dc_c_table = get_bits(gb, 4);
00990 
00991     /* unpack the Y plane DC coefficients */
00992     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
00993         0, residual_eob_run);
00994 
00995     /* reverse prediction of the Y-plane DC coefficients */
00996     reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
00997 
00998     /* unpack the C plane DC coefficients */
00999     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
01000         1, residual_eob_run);
01001     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
01002         2, residual_eob_run);
01003 
01004     /* reverse prediction of the C-plane DC coefficients */
01005     if (!(s->avctx->flags & CODEC_FLAG_GRAY))
01006     {
01007         reverse_dc_prediction(s, s->fragment_start[1],
01008             s->fragment_width[1], s->fragment_height[1]);
01009         reverse_dc_prediction(s, s->fragment_start[2],
01010             s->fragment_width[1], s->fragment_height[1]);
01011     }
01012 
01013     /* fetch the AC table indexes */
01014     ac_y_table = get_bits(gb, 4);
01015     ac_c_table = get_bits(gb, 4);
01016 
01017     /* build tables of AC VLC tables */
01018     for (i = 1; i <= 5; i++) {
01019         y_tables[i] = &s->ac_vlc_1[ac_y_table];
01020         c_tables[i] = &s->ac_vlc_1[ac_c_table];
01021     }
01022     for (i = 6; i <= 14; i++) {
01023         y_tables[i] = &s->ac_vlc_2[ac_y_table];
01024         c_tables[i] = &s->ac_vlc_2[ac_c_table];
01025     }
01026     for (i = 15; i <= 27; i++) {
01027         y_tables[i] = &s->ac_vlc_3[ac_y_table];
01028         c_tables[i] = &s->ac_vlc_3[ac_c_table];
01029     }
01030     for (i = 28; i <= 63; i++) {
01031         y_tables[i] = &s->ac_vlc_4[ac_y_table];
01032         c_tables[i] = &s->ac_vlc_4[ac_c_table];
01033     }
01034 
01035     /* decode all AC coefficents */
01036     for (i = 1; i <= 63; i++) {
01037             residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
01038                 0, residual_eob_run);
01039 
01040             residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
01041                 1, residual_eob_run);
01042             residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
01043                 2, residual_eob_run);
01044     }
01045 
01046     return 0;
01047 }
01048 
01049 /*
01050  * This function reverses the DC prediction for each coded fragment in
01051  * the frame. Much of this function is adapted directly from the original
01052  * VP3 source code.
01053  */
01054 #define COMPATIBLE_FRAME(x) \
01055   (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
01056 #define DC_COEFF(u) s->all_fragments[u].dc
01057 
01058 static void reverse_dc_prediction(Vp3DecodeContext *s,
01059                                   int first_fragment,
01060                                   int fragment_width,
01061                                   int fragment_height)
01062 {
01063 
01064 #define PUL 8
01065 #define PU 4
01066 #define PUR 2
01067 #define PL 1
01068 
01069     int x, y;
01070     int i = first_fragment;
01071 
01072     int predicted_dc;
01073 
01074     /* DC values for the left, up-left, up, and up-right fragments */
01075     int vl, vul, vu, vur;
01076 
01077     /* indexes for the left, up-left, up, and up-right fragments */
01078     int l, ul, u, ur;
01079 
01080     /*
01081      * The 6 fields mean:
01082      *   0: up-left multiplier
01083      *   1: up multiplier
01084      *   2: up-right multiplier
01085      *   3: left multiplier
01086      */
01087     static const int predictor_transform[16][4] = {
01088         {  0,  0,  0,  0},
01089         {  0,  0,  0,128},        // PL
01090         {  0,  0,128,  0},        // PUR
01091         {  0,  0, 53, 75},        // PUR|PL
01092         {  0,128,  0,  0},        // PU
01093         {  0, 64,  0, 64},        // PU|PL
01094         {  0,128,  0,  0},        // PU|PUR
01095         {  0,  0, 53, 75},        // PU|PUR|PL
01096         {128,  0,  0,  0},        // PUL
01097         {  0,  0,  0,128},        // PUL|PL
01098         { 64,  0, 64,  0},        // PUL|PUR
01099         {  0,  0, 53, 75},        // PUL|PUR|PL
01100         {  0,128,  0,  0},        // PUL|PU
01101        {-104,116,  0,116},        // PUL|PU|PL
01102         { 24, 80, 24,  0},        // PUL|PU|PUR
01103        {-104,116,  0,116}         // PUL|PU|PUR|PL
01104     };
01105 
01106     /* This table shows which types of blocks can use other blocks for
01107      * prediction. For example, INTRA is the only mode in this table to
01108      * have a frame number of 0. That means INTRA blocks can only predict
01109      * from other INTRA blocks. There are 2 golden frame coding types;
01110      * blocks encoding in these modes can only predict from other blocks
01111      * that were encoded with these 1 of these 2 modes. */
01112     static const unsigned char compatible_frame[9] = {
01113         1,    /* MODE_INTER_NO_MV */
01114         0,    /* MODE_INTRA */
01115         1,    /* MODE_INTER_PLUS_MV */
01116         1,    /* MODE_INTER_LAST_MV */
01117         1,    /* MODE_INTER_PRIOR_MV */
01118         2,    /* MODE_USING_GOLDEN */
01119         2,    /* MODE_GOLDEN_MV */
01120         1,    /* MODE_INTER_FOUR_MV */
01121         3     /* MODE_COPY */
01122     };
01123     int current_frame_type;
01124 
01125     /* there is a last DC predictor for each of the 3 frame types */
01126     short last_dc[3];
01127 
01128     int transform = 0;
01129 
01130     vul = vu = vur = vl = 0;
01131     last_dc[0] = last_dc[1] = last_dc[2] = 0;
01132 
01133     /* for each fragment row... */
01134     for (y = 0; y < fragment_height; y++) {
01135 
01136         /* for each fragment in a row... */
01137         for (x = 0; x < fragment_width; x++, i++) {
01138 
01139             /* reverse prediction if this block was coded */
01140             if (s->all_fragments[i].coding_method != MODE_COPY) {
01141 
01142                 current_frame_type =
01143                     compatible_frame[s->all_fragments[i].coding_method];
01144 
01145                 transform= 0;
01146                 if(x){
01147                     l= i-1;
01148                     vl = DC_COEFF(l);
01149                     if(COMPATIBLE_FRAME(l))
01150                         transform |= PL;
01151                 }
01152                 if(y){
01153                     u= i-fragment_width;
01154                     vu = DC_COEFF(u);
01155                     if(COMPATIBLE_FRAME(u))
01156                         transform |= PU;
01157                     if(x){
01158                         ul= i-fragment_width-1;
01159                         vul = DC_COEFF(ul);
01160                         if(COMPATIBLE_FRAME(ul))
01161                             transform |= PUL;
01162                     }
01163                     if(x + 1 < fragment_width){
01164                         ur= i-fragment_width+1;
01165                         vur = DC_COEFF(ur);
01166                         if(COMPATIBLE_FRAME(ur))
01167                             transform |= PUR;
01168                     }
01169                 }
01170 
01171                 if (transform == 0) {
01172 
01173                     /* if there were no fragments to predict from, use last
01174                      * DC saved */
01175                     predicted_dc = last_dc[current_frame_type];
01176                 } else {
01177 
01178                     /* apply the appropriate predictor transform */
01179                     predicted_dc =
01180                         (predictor_transform[transform][0] * vul) +
01181                         (predictor_transform[transform][1] * vu) +
01182                         (predictor_transform[transform][2] * vur) +
01183                         (predictor_transform[transform][3] * vl);
01184 
01185                     predicted_dc /= 128;
01186 
01187                     /* check for outranging on the [ul u l] and
01188                      * [ul u ur l] predictors */
01189                     if ((transform == 15) || (transform == 13)) {
01190                         if (FFABS(predicted_dc - vu) > 128)
01191                             predicted_dc = vu;
01192                         else if (FFABS(predicted_dc - vl) > 128)
01193                             predicted_dc = vl;
01194                         else if (FFABS(predicted_dc - vul) > 128)
01195                             predicted_dc = vul;
01196                     }
01197                 }
01198 
01199                 /* at long last, apply the predictor */
01200                 DC_COEFF(i) += predicted_dc;
01201                 /* save the DC */
01202                 last_dc[current_frame_type] = DC_COEFF(i);
01203             }
01204         }
01205     }
01206 }
01207 
01208 static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
01209 {
01210     int x, y;
01211     int *bounding_values= s->bounding_values_array+127;
01212 
01213     int width           = s->fragment_width[!!plane];
01214     int height          = s->fragment_height[!!plane];
01215     int fragment        = s->fragment_start        [plane] + ystart * width;
01216     int stride          = s->current_frame.linesize[plane];
01217     uint8_t *plane_data = s->current_frame.data    [plane];
01218     if (!s->flipped_image) stride = -stride;
01219     plane_data += s->data_offset[plane] + 8*ystart*stride;
01220 
01221     for (y = ystart; y < yend; y++) {
01222 
01223         for (x = 0; x < width; x++) {
01224             /* This code basically just deblocks on the edges of coded blocks.
01225              * However, it has to be much more complicated because of the
01226              * braindamaged deblock ordering used in VP3/Theora. Order matters
01227              * because some pixels get filtered twice. */
01228             if( s->all_fragments[fragment].coding_method != MODE_COPY )
01229             {
01230                 /* do not perform left edge filter for left columns frags */
01231                 if (x > 0) {
01232                     s->dsp.vp3_h_loop_filter(
01233                         plane_data + 8*x,
01234                         stride, bounding_values);
01235                 }
01236 
01237                 /* do not perform top edge filter for top row fragments */
01238                 if (y > 0) {
01239                     s->dsp.vp3_v_loop_filter(
01240                         plane_data + 8*x,
01241                         stride, bounding_values);
01242                 }
01243 
01244                 /* do not perform right edge filter for right column
01245                  * fragments or if right fragment neighbor is also coded
01246                  * in this frame (it will be filtered in next iteration) */
01247                 if ((x < width - 1) &&
01248                     (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
01249                     s->dsp.vp3_h_loop_filter(
01250                         plane_data + 8*x + 8,
01251                         stride, bounding_values);
01252                 }
01253 
01254                 /* do not perform bottom edge filter for bottom row
01255                  * fragments or if bottom fragment neighbor is also coded
01256                  * in this frame (it will be filtered in the next row) */
01257                 if ((y < height - 1) &&
01258                     (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
01259                     s->dsp.vp3_v_loop_filter(
01260                         plane_data + 8*x + 8*stride,
01261                         stride, bounding_values);
01262                 }
01263             }
01264 
01265             fragment++;
01266         }
01267         plane_data += 8*stride;
01268     }
01269 }
01270 
01275 static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
01276                               int plane, int inter, DCTELEM block[64])
01277 {
01278     int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
01279     uint8_t *perm = s->scantable.permutated;
01280     int i = 0;
01281 
01282     do {
01283         int token = *s->dct_tokens[plane][i];
01284         switch (token & 3) {
01285         case 0: // EOB
01286             if (--token < 4) // 0-3 are token types, so the EOB run must now be 0
01287                 s->dct_tokens[plane][i]++;
01288             else
01289                 *s->dct_tokens[plane][i] = token & ~3;
01290             goto end;
01291         case 1: // zero run
01292             s->dct_tokens[plane][i]++;
01293             i += (token >> 2) & 0x7f;
01294             block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
01295             i++;
01296             break;
01297         case 2: // coeff
01298             block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
01299             s->dct_tokens[plane][i++]++;
01300             break;
01301         default: // shouldn't happen
01302             return i;
01303         }
01304     } while (i < 64);
01305 end:
01306     // the actual DC+prediction is in the fragment structure
01307     block[0] = frag->dc * s->qmat[0][inter][plane][0];
01308     return i;
01309 }
01310 
01314 static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
01315 {
01316     int h, cy;
01317     int offset[4];
01318 
01319     if (HAVE_PTHREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {
01320         int y_flipped = s->flipped_image ? s->avctx->height-y : y;
01321 
01322         // At the end of the frame, report INT_MAX instead of the height of the frame.
01323         // This makes the other threads' ff_thread_await_progress() calls cheaper, because
01324         // they don't have to clip their values.
01325         ff_thread_report_progress(&s->current_frame, y_flipped==s->avctx->height ? INT_MAX : y_flipped-1, 0);
01326     }
01327 
01328     if(s->avctx->draw_horiz_band==NULL)
01329         return;
01330 
01331     h= y - s->last_slice_end;
01332     s->last_slice_end= y;
01333     y -= h;
01334 
01335     if (!s->flipped_image) {
01336         y = s->avctx->height - y - h;
01337     }
01338 
01339     cy = y >> s->chroma_y_shift;
01340     offset[0] = s->current_frame.linesize[0]*y;
01341     offset[1] = s->current_frame.linesize[1]*cy;
01342     offset[2] = s->current_frame.linesize[2]*cy;
01343     offset[3] = 0;
01344 
01345     emms_c();
01346     s->avctx->draw_horiz_band(s->avctx, &s->current_frame, offset, y, 3, h);
01347 }
01348 
01353 static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment, int motion_y, int y)
01354 {
01355     AVFrame *ref_frame;
01356     int ref_row;
01357     int border = motion_y&1;
01358 
01359     if (fragment->coding_method == MODE_USING_GOLDEN ||
01360         fragment->coding_method == MODE_GOLDEN_MV)
01361         ref_frame = &s->golden_frame;
01362     else
01363         ref_frame = &s->last_frame;
01364 
01365     ref_row = y + (motion_y>>1);
01366     ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
01367 
01368     ff_thread_await_progress(ref_frame, ref_row, 0);
01369 }
01370 
01371 /*
01372  * Perform the final rendering for a particular slice of data.
01373  * The slice number ranges from 0..(c_superblock_height - 1).
01374  */
01375 static void render_slice(Vp3DecodeContext *s, int slice)
01376 {
01377     int x, y, i, j, fragment;
01378     LOCAL_ALIGNED_16(DCTELEM, block, [64]);
01379     int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
01380     int motion_halfpel_index;
01381     uint8_t *motion_source;
01382     int plane, first_pixel;
01383 
01384     if (slice >= s->c_superblock_height)
01385         return;
01386 
01387     for (plane = 0; plane < 3; plane++) {
01388         uint8_t *output_plane = s->current_frame.data    [plane] + s->data_offset[plane];
01389         uint8_t *  last_plane = s->   last_frame.data    [plane] + s->data_offset[plane];
01390         uint8_t *golden_plane = s-> golden_frame.data    [plane] + s->data_offset[plane];
01391         int stride            = s->current_frame.linesize[plane];
01392         int plane_width       = s->width  >> (plane && s->chroma_x_shift);
01393         int plane_height      = s->height >> (plane && s->chroma_y_shift);
01394         int8_t (*motion_val)[2] = s->motion_val[!!plane];
01395 
01396         int sb_x, sb_y        = slice << (!plane && s->chroma_y_shift);
01397         int slice_height      = sb_y + 1 + (!plane && s->chroma_y_shift);
01398         int slice_width       = plane ? s->c_superblock_width : s->y_superblock_width;
01399 
01400         int fragment_width    = s->fragment_width[!!plane];
01401         int fragment_height   = s->fragment_height[!!plane];
01402         int fragment_start    = s->fragment_start[plane];
01403         int do_await          = !plane && HAVE_PTHREADS && (s->avctx->active_thread_type&FF_THREAD_FRAME);
01404 
01405         if (!s->flipped_image) stride = -stride;
01406         if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
01407             continue;
01408 
01409         /* for each superblock row in the slice (both of them)... */
01410         for (; sb_y < slice_height; sb_y++) {
01411 
01412             /* for each superblock in a row... */
01413             for (sb_x = 0; sb_x < slice_width; sb_x++) {
01414 
01415                 /* for each block in a superblock... */
01416                 for (j = 0; j < 16; j++) {
01417                     x = 4*sb_x + hilbert_offset[j][0];
01418                     y = 4*sb_y + hilbert_offset[j][1];
01419                     fragment = y*fragment_width + x;
01420 
01421                     i = fragment_start + fragment;
01422 
01423                     // bounds check
01424                     if (x >= fragment_width || y >= fragment_height)
01425                         continue;
01426 
01427                 first_pixel = 8*y*stride + 8*x;
01428 
01429                 if (do_await && s->all_fragments[i].coding_method != MODE_INTRA)
01430                     await_reference_row(s, &s->all_fragments[i], motion_val[fragment][1], (16*y) >> s->chroma_y_shift);
01431 
01432                 /* transform if this block was coded */
01433                 if (s->all_fragments[i].coding_method != MODE_COPY) {
01434                     if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
01435                         (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
01436                         motion_source= golden_plane;
01437                     else
01438                         motion_source= last_plane;
01439 
01440                     motion_source += first_pixel;
01441                     motion_halfpel_index = 0;
01442 
01443                     /* sort out the motion vector if this fragment is coded
01444                      * using a motion vector method */
01445                     if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
01446                         (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
01447                         int src_x, src_y;
01448                         motion_x = motion_val[fragment][0];
01449                         motion_y = motion_val[fragment][1];
01450 
01451                         src_x= (motion_x>>1) + 8*x;
01452                         src_y= (motion_y>>1) + 8*y;
01453 
01454                         motion_halfpel_index = motion_x & 0x01;
01455                         motion_source += (motion_x >> 1);
01456 
01457                         motion_halfpel_index |= (motion_y & 0x01) << 1;
01458                         motion_source += ((motion_y >> 1) * stride);
01459 
01460                         if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
01461                             uint8_t *temp= s->edge_emu_buffer;
01462                             if(stride<0) temp -= 8*stride;
01463 
01464                             s->dsp.emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
01465                             motion_source= temp;
01466                         }
01467                     }
01468 
01469 
01470                     /* first, take care of copying a block from either the
01471                      * previous or the golden frame */
01472                     if (s->all_fragments[i].coding_method != MODE_INTRA) {
01473                         /* Note, it is possible to implement all MC cases with
01474                            put_no_rnd_pixels_l2 which would look more like the
01475                            VP3 source but this would be slower as
01476                            put_no_rnd_pixels_tab is better optimzed */
01477                         if(motion_halfpel_index != 3){
01478                             s->dsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
01479                                 output_plane + first_pixel,
01480                                 motion_source, stride, 8);
01481                         }else{
01482                             int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
01483                             s->dsp.put_no_rnd_pixels_l2[1](
01484                                 output_plane + first_pixel,
01485                                 motion_source - d,
01486                                 motion_source + stride + 1 + d,
01487                                 stride, 8);
01488                         }
01489                     }
01490 
01491                         s->dsp.clear_block(block);
01492 
01493                     /* invert DCT and place (or add) in final output */
01494 
01495                     if (s->all_fragments[i].coding_method == MODE_INTRA) {
01496                         vp3_dequant(s, s->all_fragments + i, plane, 0, block);
01497                         if(s->avctx->idct_algo!=FF_IDCT_VP3)
01498                             block[0] += 128<<3;
01499                         s->dsp.idct_put(
01500                             output_plane + first_pixel,
01501                             stride,
01502                             block);
01503                     } else {
01504                         if (vp3_dequant(s, s->all_fragments + i, plane, 1, block)) {
01505                         s->dsp.idct_add(
01506                             output_plane + first_pixel,
01507                             stride,
01508                             block);
01509                         } else {
01510                             s->dsp.vp3_idct_dc_add(output_plane + first_pixel, stride, block);
01511                         }
01512                     }
01513                 } else {
01514 
01515                     /* copy directly from the previous frame */
01516                     s->dsp.put_pixels_tab[1][0](
01517                         output_plane + first_pixel,
01518                         last_plane + first_pixel,
01519                         stride, 8);
01520 
01521                 }
01522                 }
01523             }
01524 
01525             // Filter up to the last row in the superblock row
01526             if (!s->skip_loop_filter)
01527                 apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
01528         }
01529     }
01530 
01531      /* this looks like a good place for slice dispatch... */
01532      /* algorithm:
01533       *   if (slice == s->macroblock_height - 1)
01534       *     dispatch (both last slice & 2nd-to-last slice);
01535       *   else if (slice > 0)
01536       *     dispatch (slice - 1);
01537       */
01538 
01539     vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) -16, s->height-16));
01540 }
01541 
01543 static av_cold int allocate_tables(AVCodecContext *avctx)
01544 {
01545     Vp3DecodeContext *s = avctx->priv_data;
01546     int y_fragment_count, c_fragment_count;
01547 
01548     y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
01549     c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
01550 
01551     s->superblock_coding = av_malloc(s->superblock_count);
01552     s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
01553     s->coded_fragment_list[0] = av_malloc(s->fragment_count * sizeof(int));
01554     s->dct_tokens_base = av_malloc(64*s->fragment_count * sizeof(*s->dct_tokens_base));
01555     s->motion_val[0] = av_malloc(y_fragment_count * sizeof(*s->motion_val[0]));
01556     s->motion_val[1] = av_malloc(c_fragment_count * sizeof(*s->motion_val[1]));
01557 
01558     /* work out the block mapping tables */
01559     s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
01560     s->macroblock_coding = av_malloc(s->macroblock_count + 1);
01561 
01562     if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
01563         !s->coded_fragment_list[0] || !s->superblock_fragments || !s->macroblock_coding ||
01564         !s->motion_val[0] || !s->motion_val[1]) {
01565         vp3_decode_end(avctx);
01566         return -1;
01567     }
01568 
01569     init_block_mapping(s);
01570 
01571     return 0;
01572 }
01573 
01574 /*
01575  * This is the ffmpeg/libavcodec API init function.
01576  */
01577 static av_cold int vp3_decode_init(AVCodecContext *avctx)
01578 {
01579     Vp3DecodeContext *s = avctx->priv_data;
01580     int i, inter, plane;
01581     int c_width;
01582     int c_height;
01583     int y_fragment_count, c_fragment_count;
01584 
01585     if (avctx->codec_tag == MKTAG('V','P','3','0'))
01586         s->version = 0;
01587     else
01588         s->version = 1;
01589 
01590     s->avctx = avctx;
01591     s->width = FFALIGN(avctx->width, 16);
01592     s->height = FFALIGN(avctx->height, 16);
01593     if (avctx->pix_fmt == PIX_FMT_NONE)
01594         avctx->pix_fmt = PIX_FMT_YUV420P;
01595     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
01596     if(avctx->idct_algo==FF_IDCT_AUTO)
01597         avctx->idct_algo=FF_IDCT_VP3;
01598     dsputil_init(&s->dsp, avctx);
01599 
01600     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
01601 
01602     /* initialize to an impossible value which will force a recalculation
01603      * in the first frame decode */
01604     for (i = 0; i < 3; i++)
01605         s->qps[i] = -1;
01606 
01607     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
01608 
01609     s->y_superblock_width = (s->width + 31) / 32;
01610     s->y_superblock_height = (s->height + 31) / 32;
01611     s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
01612 
01613     /* work out the dimensions for the C planes */
01614     c_width = s->width >> s->chroma_x_shift;
01615     c_height = s->height >> s->chroma_y_shift;
01616     s->c_superblock_width = (c_width + 31) / 32;
01617     s->c_superblock_height = (c_height + 31) / 32;
01618     s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
01619 
01620     s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
01621     s->u_superblock_start = s->y_superblock_count;
01622     s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
01623 
01624     s->macroblock_width = (s->width + 15) / 16;
01625     s->macroblock_height = (s->height + 15) / 16;
01626     s->macroblock_count = s->macroblock_width * s->macroblock_height;
01627 
01628     s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
01629     s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
01630     s->fragment_width[1]  = s->fragment_width[0]  >> s->chroma_x_shift;
01631     s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
01632 
01633     /* fragment count covers all 8x8 blocks for all 3 planes */
01634     y_fragment_count     = s->fragment_width[0] * s->fragment_height[0];
01635     c_fragment_count     = s->fragment_width[1] * s->fragment_height[1];
01636     s->fragment_count    = y_fragment_count + 2*c_fragment_count;
01637     s->fragment_start[1] = y_fragment_count;
01638     s->fragment_start[2] = y_fragment_count + c_fragment_count;
01639 
01640     if (!s->theora_tables)
01641     {
01642         for (i = 0; i < 64; i++) {
01643             s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
01644             s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
01645             s->base_matrix[0][i] = vp31_intra_y_dequant[i];
01646             s->base_matrix[1][i] = vp31_intra_c_dequant[i];
01647             s->base_matrix[2][i] = vp31_inter_dequant[i];
01648             s->filter_limit_values[i] = vp31_filter_limit_values[i];
01649         }
01650 
01651         for(inter=0; inter<2; inter++){
01652             for(plane=0; plane<3; plane++){
01653                 s->qr_count[inter][plane]= 1;
01654                 s->qr_size [inter][plane][0]= 63;
01655                 s->qr_base [inter][plane][0]=
01656                 s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
01657             }
01658         }
01659 
01660         /* init VLC tables */
01661         for (i = 0; i < 16; i++) {
01662 
01663             /* DC histograms */
01664             init_vlc(&s->dc_vlc[i], 11, 32,
01665                 &dc_bias[i][0][1], 4, 2,
01666                 &dc_bias[i][0][0], 4, 2, 0);
01667 
01668             /* group 1 AC histograms */
01669             init_vlc(&s->ac_vlc_1[i], 11, 32,
01670                 &ac_bias_0[i][0][1], 4, 2,
01671                 &ac_bias_0[i][0][0], 4, 2, 0);
01672 
01673             /* group 2 AC histograms */
01674             init_vlc(&s->ac_vlc_2[i], 11, 32,
01675                 &ac_bias_1[i][0][1], 4, 2,
01676                 &ac_bias_1[i][0][0], 4, 2, 0);
01677 
01678             /* group 3 AC histograms */
01679             init_vlc(&s->ac_vlc_3[i], 11, 32,
01680                 &ac_bias_2[i][0][1], 4, 2,
01681                 &ac_bias_2[i][0][0], 4, 2, 0);
01682 
01683             /* group 4 AC histograms */
01684             init_vlc(&s->ac_vlc_4[i], 11, 32,
01685                 &ac_bias_3[i][0][1], 4, 2,
01686                 &ac_bias_3[i][0][0], 4, 2, 0);
01687         }
01688     } else {
01689 
01690         for (i = 0; i < 16; i++) {
01691             /* DC histograms */
01692             if (init_vlc(&s->dc_vlc[i], 11, 32,
01693                 &s->huffman_table[i][0][1], 8, 4,
01694                 &s->huffman_table[i][0][0], 8, 4, 0) < 0)
01695                 goto vlc_fail;
01696 
01697             /* group 1 AC histograms */
01698             if (init_vlc(&s->ac_vlc_1[i], 11, 32,
01699                 &s->huffman_table[i+16][0][1], 8, 4,
01700                 &s->huffman_table[i+16][0][0], 8, 4, 0) < 0)
01701                 goto vlc_fail;
01702 
01703             /* group 2 AC histograms */
01704             if (init_vlc(&s->ac_vlc_2[i], 11, 32,
01705                 &s->huffman_table[i+16*2][0][1], 8, 4,
01706                 &s->huffman_table[i+16*2][0][0], 8, 4, 0) < 0)
01707                 goto vlc_fail;
01708 
01709             /* group 3 AC histograms */
01710             if (init_vlc(&s->ac_vlc_3[i], 11, 32,
01711                 &s->huffman_table[i+16*3][0][1], 8, 4,
01712                 &s->huffman_table[i+16*3][0][0], 8, 4, 0) < 0)
01713                 goto vlc_fail;
01714 
01715             /* group 4 AC histograms */
01716             if (init_vlc(&s->ac_vlc_4[i], 11, 32,
01717                 &s->huffman_table[i+16*4][0][1], 8, 4,
01718                 &s->huffman_table[i+16*4][0][0], 8, 4, 0) < 0)
01719                 goto vlc_fail;
01720         }
01721     }
01722 
01723     init_vlc(&s->superblock_run_length_vlc, 6, 34,
01724         &superblock_run_length_vlc_table[0][1], 4, 2,
01725         &superblock_run_length_vlc_table[0][0], 4, 2, 0);
01726 
01727     init_vlc(&s->fragment_run_length_vlc, 5, 30,
01728         &fragment_run_length_vlc_table[0][1], 4, 2,
01729         &fragment_run_length_vlc_table[0][0], 4, 2, 0);
01730 
01731     init_vlc(&s->mode_code_vlc, 3, 8,
01732         &mode_code_vlc_table[0][1], 2, 1,
01733         &mode_code_vlc_table[0][0], 2, 1, 0);
01734 
01735     init_vlc(&s->motion_vector_vlc, 6, 63,
01736         &motion_vector_vlc_table[0][1], 2, 1,
01737         &motion_vector_vlc_table[0][0], 2, 1, 0);
01738 
01739     for (i = 0; i < 3; i++) {
01740         s->current_frame.data[i] = NULL;
01741         s->last_frame.data[i] = NULL;
01742         s->golden_frame.data[i] = NULL;
01743     }
01744 
01745     return allocate_tables(avctx);
01746 
01747 vlc_fail:
01748     av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
01749     return -1;
01750 }
01751 
01753 static void update_frames(AVCodecContext *avctx)
01754 {
01755     Vp3DecodeContext *s = avctx->priv_data;
01756 
01757     /* release the last frame, if it is allocated and if it is not the
01758      * golden frame */
01759     if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
01760         ff_thread_release_buffer(avctx, &s->last_frame);
01761 
01762     /* shuffle frames (last = current) */
01763     s->last_frame= s->current_frame;
01764 
01765     if (s->keyframe) {
01766         if (s->golden_frame.data[0])
01767             ff_thread_release_buffer(avctx, &s->golden_frame);
01768         s->golden_frame = s->current_frame;
01769         s->last_frame.type = FF_BUFFER_TYPE_COPY;
01770     }
01771 
01772     s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
01773 }
01774 
01775 static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
01776 {
01777     Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
01778     int qps_changed = 0, i, err;
01779 
01780     if (!s1->current_frame.data[0]
01781         ||s->width != s1->width
01782         ||s->height!= s1->height)
01783         return -1;
01784 
01785     if (s != s1) {
01786         // init tables if the first frame hasn't been decoded
01787         if (!s->current_frame.data[0]) {
01788             int y_fragment_count, c_fragment_count;
01789             s->avctx = dst;
01790             err = allocate_tables(dst);
01791             if (err)
01792                 return err;
01793             y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
01794             c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
01795             memcpy(s->motion_val[0], s1->motion_val[0], y_fragment_count * sizeof(*s->motion_val[0]));
01796             memcpy(s->motion_val[1], s1->motion_val[1], c_fragment_count * sizeof(*s->motion_val[1]));
01797         }
01798 
01799 #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
01800 
01801         // copy previous frame data
01802         copy_fields(s, s1, golden_frame, dsp);
01803 
01804         // copy qscale data if necessary
01805         for (i = 0; i < 3; i++) {
01806             if (s->qps[i] != s1->qps[1]) {
01807                 qps_changed = 1;
01808                 memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
01809             }
01810         }
01811 
01812         if (s->qps[0] != s1->qps[0])
01813             memcpy(&s->bounding_values_array, &s1->bounding_values_array, sizeof(s->bounding_values_array));
01814 
01815         if (qps_changed)
01816             copy_fields(s, s1, qps, superblock_count);
01817 #undef copy_fields
01818     }
01819 
01820     update_frames(dst);
01821 
01822     return 0;
01823 }
01824 
01825 /*
01826  * This is the ffmpeg/libavcodec API frame decode function.
01827  */
01828 static int vp3_decode_frame(AVCodecContext *avctx,
01829                             void *data, int *data_size,
01830                             AVPacket *avpkt)
01831 {
01832     const uint8_t *buf = avpkt->data;
01833     int buf_size = avpkt->size;
01834     Vp3DecodeContext *s = avctx->priv_data;
01835     GetBitContext gb;
01836     int i;
01837 
01838     init_get_bits(&gb, buf, buf_size * 8);
01839 
01840     if (s->theora && get_bits1(&gb))
01841     {
01842         av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
01843         return -1;
01844     }
01845 
01846     s->keyframe = !get_bits1(&gb);
01847     if (!s->theora)
01848         skip_bits(&gb, 1);
01849     for (i = 0; i < 3; i++)
01850         s->last_qps[i] = s->qps[i];
01851 
01852     s->nqps=0;
01853     do{
01854         s->qps[s->nqps++]= get_bits(&gb, 6);
01855     } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
01856     for (i = s->nqps; i < 3; i++)
01857         s->qps[i] = -1;
01858 
01859     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
01860         av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
01861             s->keyframe?"key":"", avctx->frame_number+1, s->qps[0]);
01862 
01863     s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
01864         avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY);
01865 
01866     if (s->qps[0] != s->last_qps[0])
01867         init_loop_filter(s);
01868 
01869     for (i = 0; i < s->nqps; i++)
01870         // reinit all dequantizers if the first one changed, because
01871         // the DC of the first quantizer must be used for all matrices
01872         if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
01873             init_dequantizer(s, i);
01874 
01875     if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
01876         return buf_size;
01877 
01878     s->current_frame.reference = 3;
01879     s->current_frame.pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
01880     if (ff_thread_get_buffer(avctx, &s->current_frame) < 0) {
01881         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
01882         goto error;
01883     }
01884 
01885     if (!s->edge_emu_buffer)
01886         s->edge_emu_buffer = av_malloc(9*FFABS(s->current_frame.linesize[0]));
01887 
01888     if (s->keyframe) {
01889         if (!s->theora)
01890         {
01891             skip_bits(&gb, 4); /* width code */
01892             skip_bits(&gb, 4); /* height code */
01893             if (s->version)
01894             {
01895                 s->version = get_bits(&gb, 5);
01896                 if (avctx->frame_number == 0)
01897                     av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
01898             }
01899         }
01900         if (s->version || s->theora)
01901         {
01902                 if (get_bits1(&gb))
01903                     av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
01904             skip_bits(&gb, 2); /* reserved? */
01905         }
01906     } else {
01907         if (!s->golden_frame.data[0]) {
01908             av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
01909 
01910             s->golden_frame.reference = 3;
01911             s->golden_frame.pict_type = AV_PICTURE_TYPE_I;
01912             if (ff_thread_get_buffer(avctx, &s->golden_frame) < 0) {
01913                 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
01914                 goto error;
01915             }
01916             s->last_frame = s->golden_frame;
01917             s->last_frame.type = FF_BUFFER_TYPE_COPY;
01918             ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
01919         }
01920     }
01921 
01922     memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
01923     ff_thread_finish_setup(avctx);
01924 
01925     if (unpack_superblocks(s, &gb)){
01926         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
01927         goto error;
01928     }
01929     if (unpack_modes(s, &gb)){
01930         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
01931         goto error;
01932     }
01933     if (unpack_vectors(s, &gb)){
01934         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
01935         goto error;
01936     }
01937     if (unpack_block_qpis(s, &gb)){
01938         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
01939         goto error;
01940     }
01941     if (unpack_dct_coeffs(s, &gb)){
01942         av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
01943         goto error;
01944     }
01945 
01946     for (i = 0; i < 3; i++) {
01947         int height = s->height >> (i && s->chroma_y_shift);
01948         if (s->flipped_image)
01949             s->data_offset[i] = 0;
01950         else
01951             s->data_offset[i] = (height-1) * s->current_frame.linesize[i];
01952     }
01953 
01954     s->last_slice_end = 0;
01955     for (i = 0; i < s->c_superblock_height; i++)
01956         render_slice(s, i);
01957 
01958     // filter the last row
01959     for (i = 0; i < 3; i++) {
01960         int row = (s->height >> (3+(i && s->chroma_y_shift))) - 1;
01961         apply_loop_filter(s, i, row, row+1);
01962     }
01963     vp3_draw_horiz_band(s, s->avctx->height);
01964 
01965     *data_size=sizeof(AVFrame);
01966     *(AVFrame*)data= s->current_frame;
01967 
01968     if (!HAVE_PTHREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
01969         update_frames(avctx);
01970 
01971     return buf_size;
01972 
01973 error:
01974     ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
01975 
01976     if (!HAVE_PTHREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
01977         avctx->release_buffer(avctx, &s->current_frame);
01978 
01979     return -1;
01980 }
01981 
01982 /*
01983  * This is the ffmpeg/libavcodec API module cleanup function.
01984  */
01985 static av_cold int vp3_decode_end(AVCodecContext *avctx)
01986 {
01987     Vp3DecodeContext *s = avctx->priv_data;
01988     int i;
01989 
01990     if (avctx->is_copy && !s->current_frame.data[0])
01991         return 0;
01992 
01993     av_free(s->superblock_coding);
01994     av_free(s->all_fragments);
01995     av_free(s->coded_fragment_list[0]);
01996     av_free(s->dct_tokens_base);
01997     av_free(s->superblock_fragments);
01998     av_free(s->macroblock_coding);
01999     av_free(s->motion_val[0]);
02000     av_free(s->motion_val[1]);
02001     av_free(s->edge_emu_buffer);
02002 
02003     if (avctx->is_copy) return 0;
02004 
02005     for (i = 0; i < 16; i++) {
02006         free_vlc(&s->dc_vlc[i]);
02007         free_vlc(&s->ac_vlc_1[i]);
02008         free_vlc(&s->ac_vlc_2[i]);
02009         free_vlc(&s->ac_vlc_3[i]);
02010         free_vlc(&s->ac_vlc_4[i]);
02011     }
02012 
02013     free_vlc(&s->superblock_run_length_vlc);
02014     free_vlc(&s->fragment_run_length_vlc);
02015     free_vlc(&s->mode_code_vlc);
02016     free_vlc(&s->motion_vector_vlc);
02017 
02018     /* release all frames */
02019     if (s->golden_frame.data[0])
02020         ff_thread_release_buffer(avctx, &s->golden_frame);
02021     if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
02022         ff_thread_release_buffer(avctx, &s->last_frame);
02023     /* no need to release the current_frame since it will always be pointing
02024      * to the same frame as either the golden or last frame */
02025 
02026     return 0;
02027 }
02028 
02029 static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
02030 {
02031     Vp3DecodeContext *s = avctx->priv_data;
02032 
02033     if (get_bits1(gb)) {
02034         int token;
02035         if (s->entries >= 32) { /* overflow */
02036             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
02037             return -1;
02038         }
02039         token = get_bits(gb, 5);
02040         //av_log(avctx, AV_LOG_DEBUG, "hti %d hbits %x token %d entry : %d size %d\n", s->hti, s->hbits, token, s->entries, s->huff_code_size);
02041         s->huffman_table[s->hti][token][0] = s->hbits;
02042         s->huffman_table[s->hti][token][1] = s->huff_code_size;
02043         s->entries++;
02044     }
02045     else {
02046         if (s->huff_code_size >= 32) {/* overflow */
02047             av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
02048             return -1;
02049         }
02050         s->huff_code_size++;
02051         s->hbits <<= 1;
02052         if (read_huffman_tree(avctx, gb))
02053             return -1;
02054         s->hbits |= 1;
02055         if (read_huffman_tree(avctx, gb))
02056             return -1;
02057         s->hbits >>= 1;
02058         s->huff_code_size--;
02059     }
02060     return 0;
02061 }
02062 
02063 #if CONFIG_THEORA_DECODER
02064 static const enum PixelFormat theora_pix_fmts[4] = {
02065     PIX_FMT_YUV420P, PIX_FMT_NONE, PIX_FMT_YUV422P, PIX_FMT_YUV444P
02066 };
02067 
02068 static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
02069 {
02070     Vp3DecodeContext *s = avctx->priv_data;
02071     int visible_width, visible_height, colorspace;
02072     int offset_x = 0, offset_y = 0;
02073     AVRational fps, aspect;
02074 
02075     s->theora = get_bits_long(gb, 24);
02076     av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
02077 
02078     /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
02079     /* but previous versions have the image flipped relative to vp3 */
02080     if (s->theora < 0x030200)
02081     {
02082         s->flipped_image = 1;
02083         av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
02084     }
02085 
02086     visible_width  = s->width  = get_bits(gb, 16) << 4;
02087     visible_height = s->height = get_bits(gb, 16) << 4;
02088 
02089     if(av_image_check_size(s->width, s->height, 0, avctx)){
02090         av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
02091         s->width= s->height= 0;
02092         return -1;
02093     }
02094 
02095     if (s->theora >= 0x030200) {
02096         visible_width  = get_bits_long(gb, 24);
02097         visible_height = get_bits_long(gb, 24);
02098 
02099         offset_x = get_bits(gb, 8); /* offset x */
02100         offset_y = get_bits(gb, 8); /* offset y, from bottom */
02101     }
02102 
02103     fps.num = get_bits_long(gb, 32);
02104     fps.den = get_bits_long(gb, 32);
02105     if (fps.num && fps.den) {
02106         av_reduce(&avctx->time_base.num, &avctx->time_base.den,
02107                   fps.den, fps.num, 1<<30);
02108     }
02109 
02110     aspect.num = get_bits_long(gb, 24);
02111     aspect.den = get_bits_long(gb, 24);
02112     if (aspect.num && aspect.den) {
02113         av_reduce(&avctx->sample_aspect_ratio.num,
02114                   &avctx->sample_aspect_ratio.den,
02115                   aspect.num, aspect.den, 1<<30);
02116     }
02117 
02118     if (s->theora < 0x030200)
02119         skip_bits(gb, 5); /* keyframe frequency force */
02120     colorspace = get_bits(gb, 8);
02121     skip_bits(gb, 24); /* bitrate */
02122 
02123     skip_bits(gb, 6); /* quality hint */
02124 
02125     if (s->theora >= 0x030200)
02126     {
02127         skip_bits(gb, 5); /* keyframe frequency force */
02128         avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
02129         skip_bits(gb, 3); /* reserved */
02130     }
02131 
02132 //    align_get_bits(gb);
02133 
02134     if (   visible_width  <= s->width  && visible_width  > s->width-16
02135         && visible_height <= s->height && visible_height > s->height-16
02136         && !offset_x && (offset_y == s->height - visible_height))
02137         avcodec_set_dimensions(avctx, visible_width, visible_height);
02138     else
02139         avcodec_set_dimensions(avctx, s->width, s->height);
02140 
02141     if (colorspace == 1) {
02142         avctx->color_primaries = AVCOL_PRI_BT470M;
02143     } else if (colorspace == 2) {
02144         avctx->color_primaries = AVCOL_PRI_BT470BG;
02145     }
02146     if (colorspace == 1 || colorspace == 2) {
02147         avctx->colorspace = AVCOL_SPC_BT470BG;
02148         avctx->color_trc  = AVCOL_TRC_BT709;
02149     }
02150 
02151     return 0;
02152 }
02153 
02154 static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
02155 {
02156     Vp3DecodeContext *s = avctx->priv_data;
02157     int i, n, matrices, inter, plane;
02158 
02159     if (s->theora >= 0x030200) {
02160         n = get_bits(gb, 3);
02161         /* loop filter limit values table */
02162         if (n)
02163             for (i = 0; i < 64; i++)
02164                 s->filter_limit_values[i] = get_bits(gb, n);
02165     }
02166 
02167     if (s->theora >= 0x030200)
02168         n = get_bits(gb, 4) + 1;
02169     else
02170         n = 16;
02171     /* quality threshold table */
02172     for (i = 0; i < 64; i++)
02173         s->coded_ac_scale_factor[i] = get_bits(gb, n);
02174 
02175     if (s->theora >= 0x030200)
02176         n = get_bits(gb, 4) + 1;
02177     else
02178         n = 16;
02179     /* dc scale factor table */
02180     for (i = 0; i < 64; i++)
02181         s->coded_dc_scale_factor[i] = get_bits(gb, n);
02182 
02183     if (s->theora >= 0x030200)
02184         matrices = get_bits(gb, 9) + 1;
02185     else
02186         matrices = 3;
02187 
02188     if(matrices > 384){
02189         av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
02190         return -1;
02191     }
02192 
02193     for(n=0; n<matrices; n++){
02194         for (i = 0; i < 64; i++)
02195             s->base_matrix[n][i]= get_bits(gb, 8);
02196     }
02197 
02198     for (inter = 0; inter <= 1; inter++) {
02199         for (plane = 0; plane <= 2; plane++) {
02200             int newqr= 1;
02201             if (inter || plane > 0)
02202                 newqr = get_bits1(gb);
02203             if (!newqr) {
02204                 int qtj, plj;
02205                 if(inter && get_bits1(gb)){
02206                     qtj = 0;
02207                     plj = plane;
02208                 }else{
02209                     qtj= (3*inter + plane - 1) / 3;
02210                     plj= (plane + 2) % 3;
02211                 }
02212                 s->qr_count[inter][plane]= s->qr_count[qtj][plj];
02213                 memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
02214                 memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
02215             } else {
02216                 int qri= 0;
02217                 int qi = 0;
02218 
02219                 for(;;){
02220                     i= get_bits(gb, av_log2(matrices-1)+1);
02221                     if(i>= matrices){
02222                         av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
02223                         return -1;
02224                     }
02225                     s->qr_base[inter][plane][qri]= i;
02226                     if(qi >= 63)
02227                         break;
02228                     i = get_bits(gb, av_log2(63-qi)+1) + 1;
02229                     s->qr_size[inter][plane][qri++]= i;
02230                     qi += i;
02231                 }
02232 
02233                 if (qi > 63) {
02234                     av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
02235                     return -1;
02236                 }
02237                 s->qr_count[inter][plane]= qri;
02238             }
02239         }
02240     }
02241 
02242     /* Huffman tables */
02243     for (s->hti = 0; s->hti < 80; s->hti++) {
02244         s->entries = 0;
02245         s->huff_code_size = 1;
02246         if (!get_bits1(gb)) {
02247             s->hbits = 0;
02248             if(read_huffman_tree(avctx, gb))
02249                 return -1;
02250             s->hbits = 1;
02251             if(read_huffman_tree(avctx, gb))
02252                 return -1;
02253         }
02254     }
02255 
02256     s->theora_tables = 1;
02257 
02258     return 0;
02259 }
02260 
02261 static av_cold int theora_decode_init(AVCodecContext *avctx)
02262 {
02263     Vp3DecodeContext *s = avctx->priv_data;
02264     GetBitContext gb;
02265     int ptype;
02266     uint8_t *header_start[3];
02267     int header_len[3];
02268     int i;
02269 
02270     s->theora = 1;
02271 
02272     if (!avctx->extradata_size)
02273     {
02274         av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
02275         return -1;
02276     }
02277 
02278     if (ff_split_xiph_headers(avctx->extradata, avctx->extradata_size,
02279                               42, header_start, header_len) < 0) {
02280         av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
02281         return -1;
02282     }
02283 
02284   for(i=0;i<3;i++) {
02285     init_get_bits(&gb, header_start[i], header_len[i] * 8);
02286 
02287     ptype = get_bits(&gb, 8);
02288 
02289      if (!(ptype & 0x80))
02290      {
02291         av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
02292 //        return -1;
02293      }
02294 
02295     // FIXME: Check for this as well.
02296     skip_bits_long(&gb, 6*8); /* "theora" */
02297 
02298     switch(ptype)
02299     {
02300         case 0x80:
02301             theora_decode_header(avctx, &gb);
02302                 break;
02303         case 0x81:
02304 // FIXME: is this needed? it breaks sometimes
02305 //            theora_decode_comments(avctx, gb);
02306             break;
02307         case 0x82:
02308             if (theora_decode_tables(avctx, &gb))
02309                 return -1;
02310             break;
02311         default:
02312             av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
02313             break;
02314     }
02315     if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
02316         av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
02317     if (s->theora < 0x030200)
02318         break;
02319   }
02320 
02321     return vp3_decode_init(avctx);
02322 }
02323 
02324 static void vp3_decode_flush(AVCodecContext *avctx)
02325 {
02326     Vp3DecodeContext *s = avctx->priv_data;
02327 
02328     if (s->golden_frame.data[0]) {
02329         if (s->golden_frame.data[0] == s->last_frame.data[0])
02330             memset(&s->last_frame, 0, sizeof(AVFrame));
02331         if (s->current_frame.data[0] == s->golden_frame.data[0])
02332             memset(&s->current_frame, 0, sizeof(AVFrame));
02333         ff_thread_release_buffer(avctx, &s->golden_frame);
02334     }
02335     if (s->last_frame.data[0]) {
02336         if (s->current_frame.data[0] == s->last_frame.data[0])
02337             memset(&s->current_frame, 0, sizeof(AVFrame));
02338         ff_thread_release_buffer(avctx, &s->last_frame);
02339     }
02340     if (s->current_frame.data[0])
02341         ff_thread_release_buffer(avctx, &s->current_frame);
02342 }
02343 
02344 AVCodec ff_theora_decoder = {
02345     "theora",
02346     AVMEDIA_TYPE_VIDEO,
02347     CODEC_ID_THEORA,
02348     sizeof(Vp3DecodeContext),
02349     theora_decode_init,
02350     NULL,
02351     vp3_decode_end,
02352     vp3_decode_frame,
02353     CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_FRAME_THREADS,
02354     NULL,
02355     .flush = vp3_decode_flush,
02356     .long_name = NULL_IF_CONFIG_SMALL("Theora"),
02357     .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
02358 };
02359 #endif
02360 
02361 AVCodec ff_vp3_decoder = {
02362     "vp3",
02363     AVMEDIA_TYPE_VIDEO,
02364     CODEC_ID_VP3,
02365     sizeof(Vp3DecodeContext),
02366     vp3_decode_init,
02367     NULL,
02368     vp3_decode_end,
02369     vp3_decode_frame,
02370     CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_FRAME_THREADS,
02371     NULL,
02372     .flush = vp3_decode_flush,
02373     .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
02374     .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
02375 };