Statistics
| Branch: | Revision:

ffmpeg / libavcodec / vp3.c @ 4a5a1689

History | View | Annotate | Download (81.5 KB)

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