Statistics
| Branch: | Revision:

ffmpeg / libavcodec / vp3.c @ d23845f3

History | View | Annotate | Download (81.5 KB)

1
/*
2
 * Copyright (C) 2003-2004 the ffmpeg project
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
 */
20

    
21
/**
22
 * @file
23
 * On2 VP3 Video Decoder
24
 *
25
 * VP3 Video Decoder by Mike Melanson (mike at multimedia.cx)
26
 * For more information about the VP3 coding process, visit:
27
 *   http://wiki.multimedia.cx/index.php?title=On2_VP3
28
 *
29
 * Theora decoder by Alex Beregszaszi
30
 */
31

    
32
#include <stdio.h>
33
#include <stdlib.h>
34
#include <string.h>
35

    
36
#include "libavcore/imgutils.h"
37
#include "avcodec.h"
38
#include "dsputil.h"
39
#include "get_bits.h"
40

    
41
#include "vp3data.h"
42
#include "xiph.h"
43
#include "thread.h"
44

    
45
#define FRAGMENT_PIXELS 8
46

    
47
static av_cold int vp3_decode_end(AVCodecContext *avctx);
48

    
49
//FIXME split things out into their own arrays
50
typedef struct Vp3Fragment {
51
    int16_t dc;
52
    uint8_t coding_method;
53
    uint8_t qpi;
54
} Vp3Fragment;
55

    
56
#define SB_NOT_CODED        0
57
#define SB_PARTIALLY_CODED  1
58
#define SB_FULLY_CODED      2
59

    
60
// 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
#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
static const int ModeAlphabet[6][CODING_MODE_COUNT] =
80
{
81
    /* scheme 1: Last motion vector dominates */
82
    {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
83
         MODE_INTER_PLUS_MV,    MODE_INTER_NO_MV,
84
         MODE_INTRA,            MODE_USING_GOLDEN,
85
         MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
86

    
87
    /* scheme 2 */
88
    {    MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
89
         MODE_INTER_NO_MV,      MODE_INTER_PLUS_MV,
90
         MODE_INTRA,            MODE_USING_GOLDEN,
91
         MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
92

    
93
    /* scheme 3 */
94
    {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
95
         MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
96
         MODE_INTRA,            MODE_USING_GOLDEN,
97
         MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
98

    
99
    /* scheme 4 */
100
    {    MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
101
         MODE_INTER_NO_MV,      MODE_INTER_PRIOR_LAST,
102
         MODE_INTRA,            MODE_USING_GOLDEN,
103
         MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
104

    
105
    /* scheme 5: No motion vector dominates */
106
    {    MODE_INTER_NO_MV,      MODE_INTER_LAST_MV,
107
         MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
108
         MODE_INTRA,            MODE_USING_GOLDEN,
109
         MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
110

    
111
    /* scheme 6 */
112
    {    MODE_INTER_NO_MV,      MODE_USING_GOLDEN,
113
         MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
114
         MODE_INTER_PLUS_MV,    MODE_INTRA,
115
         MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
116

    
117
};
118

    
119
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
#define MIN_DEQUANT_VAL 2
127

    
128
typedef struct Vp3DecodeContext {
129
    AVCodecContext *avctx;
130
    int theora, theora_tables;
131
    int version;
132
    int width, height;
133
    int chroma_x_shift, chroma_y_shift;
134
    AVFrame golden_frame;
135
    AVFrame last_frame;
136
    AVFrame current_frame;
137
    int keyframe;
138
    DSPContext dsp;
139
    int flipped_image;
140
    int last_slice_end;
141
    int skip_loop_filter;
142

    
143
    int qps[3];
144
    int nqps;
145
    int last_qps[3];
146

    
147
    int superblock_count;
148
    int y_superblock_width;
149
    int y_superblock_height;
150
    int y_superblock_count;
151
    int c_superblock_width;
152
    int c_superblock_height;
153
    int c_superblock_count;
154
    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
    int fragment_width[2];
164
    int fragment_height[2];
165

    
166
    Vp3Fragment *all_fragments;
167
    int fragment_start[3];
168
    int data_offset[3];
169

    
170
    int8_t (*motion_val[2])[2];
171

    
172
    ScanTable scantable;
173

    
174
    /* tables */
175
    uint16_t coded_dc_scale_factor[64];
176
    uint32_t coded_ac_scale_factor[64];
177
    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

    
182
    /**
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
    /* this is a list of indexes into the all_fragments array indicating
212
     * which of the fragments are coded */
213
    int *coded_fragment_list[3];
214

    
215
    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
    VLC superblock_run_length_vlc;
222
    VLC fragment_run_length_vlc;
223
    VLC mode_code_vlc;
224
    VLC motion_vector_vlc;
225

    
226
    /* these arrays need to be on 16-byte boundaries since SSE2 operations
227
     * index into them */
228
    DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64];     //<qmat[qpi][is_inter][plane]
229

    
230
    /* This table contains superblock_count * 16 entries. Each set of 16
231
     * numbers corresponds to the fragment indexes 0..15 of the superblock.
232
     * An entry will be -1 to indicate that no entry corresponds to that
233
     * index. */
234
    int *superblock_fragments;
235

    
236
    /* This is an array that indicates how a particular macroblock
237
     * is coded. */
238
    unsigned char *macroblock_coding;
239

    
240
    uint8_t edge_emu_buffer[9*2048]; //FIXME dynamic alloc
241
    int8_t qscale_table[2048]; //FIXME dynamic alloc (width+15)/16
242

    
243
    /* Huffman decode */
244
    int hti;
245
    unsigned int hbits;
246
    int entries;
247
    int huff_code_size;
248
    uint32_t huffman_table[80][32][2];
249

    
250
    uint8_t filter_limit_values[64];
251
    DECLARE_ALIGNED(8, int, bounding_values_array)[256+2];
252
} 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
 *
263
 * @return 0 is successful; returns 1 if *anything* went wrong.
264
 */
265
static int init_block_mapping(Vp3DecodeContext *s)
266
{
267
    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
        int frag_width  = s->fragment_width[!!plane];
274
        int frag_height = s->fragment_height[!!plane];
275

    
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
    }
288

    
289
    return 0;  /* successful path out */
290
}
291

    
292
/*
293
 * This function sets up the dequantization tables used for a particular
294
 * frame.
295
 */
296
static void init_dequantizer(Vp3DecodeContext *s, int qpi)
297
{
298
    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
    int i, plane, inter, qri, bmi, bmj, qistart;
301

    
302
    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
                if(s->qps[qpi] <= sum)
308
                    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
                int coeff= (  2*(sum    -s->qps[qpi])*s->base_matrix[bmi][i]
315
                            - 2*(qistart-s->qps[qpi])*s->base_matrix[bmj][i]
316
                            + s->qr_size[inter][plane][qri])
317
                           / (2*s->qr_size[inter][plane][qri]);
318

    
319
                int qmin= 8<<(inter + !i);
320
                int qscale= i ? ac_scale_factor : dc_scale_factor;
321

    
322
                s->qmat[qpi][inter][plane][s->dsp.idct_permutation[i]]= av_clip((qscale * coeff)/100 * 4, qmin, 4096);
323
            }
324
            // 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
        }
327
    }
328

    
329
    memset(s->qscale_table, (FFMAX(s->qmat[0][0][0][1], s->qmat[0][0][1][1])+8)/16, 512); //FIXME finetune
330
}
331

    
332
/*
333
 * This function initializes the loop filter boundary limits if the frame's
334
 * quality index is different from the previous frame's.
335
 *
336
 * The filter_limit_values may not be larger than 127.
337
 */
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
    int value;
344

    
345
    filter_limit = s->filter_limit_values[s->qps[0]];
346

    
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
    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
    bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
360
}
361

    
362
/*
363
 * This function unpacks all of the superblock/macroblock/fragment coding
364
 * information from the bitstream.
365
 */
366
static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
367
{
368
    int superblock_starts[3] = { 0, s->u_superblock_start, s->v_superblock_start };
369
    int bit = 0;
370
    int current_superblock = 0;
371
    int current_run = 0;
372
    int num_partial_superblocks = 0;
373

    
374
    int i, j;
375
    int current_fragment;
376
    int plane;
377

    
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
        bit = get_bits1(gb) ^ 1;
385
        current_run = 0;
386

    
387
        while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
388
            if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
389
                bit = get_bits1(gb);
390
            else
391
                bit ^= 1;
392

    
393
                current_run = get_vlc2(gb,
394
                    s->superblock_run_length_vlc.table, 6, 2) + 1;
395
                if (current_run == 34)
396
                    current_run += get_bits(gb, 12);
397

    
398
            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
            if (bit)
407
                num_partial_superblocks += current_run;
408
        }
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
        if (num_partial_superblocks < s->superblock_count) {
413
            int superblocks_decoded = 0;
414

    
415
            current_superblock = 0;
416
            bit = get_bits1(gb) ^ 1;
417
            current_run = 0;
418

    
419
            while (superblocks_decoded < s->superblock_count - num_partial_superblocks
420
                   && get_bits_left(gb) > 0) {
421

    
422
                if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
423
                    bit = get_bits1(gb);
424
                else
425
                    bit ^= 1;
426

    
427
                        current_run = get_vlc2(gb,
428
                            s->superblock_run_length_vlc.table, 6, 2) + 1;
429
                        if (current_run == 34)
430
                            current_run += get_bits(gb, 12);
431

    
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
                    }
437

    
438
                /* skip any superblocks already marked as partially coded */
439
                if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
440
                    s->superblock_coding[current_superblock] = 2*bit;
441
                    j++;
442
                }
443
                }
444
                superblocks_decoded += current_run;
445
            }
446
        }
447

    
448
        /* if there were partial blocks, initialize bitstream for
449
         * unpacking fragment codings */
450
        if (num_partial_superblocks) {
451

    
452
            current_run = 0;
453
            bit = get_bits1(gb);
454
            /* toggle the bit because as soon as the first run length is
455
             * 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
    s->total_num_coded_frags = 0;
463
    memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
464

    
465
    for (plane = 0; plane < 3; plane++) {
466
        int sb_start = superblock_starts[plane];
467
        int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);
468
        int num_coded_frags = 0;
469

    
470
    for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
471

    
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
                int coded = s->superblock_coding[i];
479

    
480
                if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
481

    
482
                    /* fragment may or may not be coded; this is the case
483
                     * that cares about the fragment coding runs */
484
                    if (current_run-- == 0) {
485
                        bit ^= 1;
486
                        current_run = get_vlc2(gb,
487
                            s->fragment_run_length_vlc.table, 5, 2);
488
                    }
489
                    coded = bit;
490
                }
491

    
492
                    if (coded) {
493
                        /* default mode; actual mode will be decoded in
494
                         * the next phase */
495
                        s->all_fragments[current_fragment].coding_method =
496
                            MODE_INTER_NO_MV;
497
                        s->coded_fragment_list[plane][num_coded_frags++] =
498
                            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
        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
    }
513
    return 0;
514
}
515

    
516
/*
517
 * This function unpacks all the coding mode data for individual macroblocks
518
 * from the bitstream.
519
 */
520
static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
521
{
522
    int i, j, k, sb_x, sb_y;
523
    int scheme;
524
    int current_macroblock;
525
    int current_fragment;
526
    int coding_mode;
527
    int custom_mode_alphabet[CODING_MODE_COUNT];
528
    const int *alphabet;
529
    Vp3Fragment *frag;
530

    
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
                custom_mode_alphabet[i] = MODE_INTER_NO_MV;
544
            for (i = 0; i < 8; i++)
545
                custom_mode_alphabet[get_bits(gb, 3)] = i;
546
            alphabet = custom_mode_alphabet;
547
        } else
548
            alphabet = ModeAlphabet[scheme-1];
549

    
550
        /* iterate through all of the macroblocks that contain 1 or more
551
         * coded fragments */
552
        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
                if (get_bits_left(gb) <= 0)
555
                    return -1;
556

    
557
            for (j = 0; j < 4; j++) {
558
                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
                if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height)
563
                    continue;
564

    
565
#define BLOCK_X (2*mb_x + (k&1))
566
#define BLOCK_Y (2*mb_y + (k>>1))
567
                /* 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
                    current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
571
                    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

    
579
                /* mode 7 means get 3 bits for each coding mode */
580
                if (scheme == 7)
581
                    coding_mode = get_bits(gb, 3);
582
                else
583
                    coding_mode = alphabet
584
                        [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
585

    
586
                s->macroblock_coding[current_macroblock] = coding_mode;
587
                for (k = 0; k < 4; k++) {
588
                    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
                }
592

    
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
                }
614
            }
615
            }
616
        }
617
    }
618

    
619
    return 0;
620
}
621

    
622
/*
623
 * This function unpacks all the motion vectors for the individual
624
 * macroblocks from the bitstream.
625
 */
626
static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
627
{
628
    int j, k, sb_x, sb_y;
629
    int coding_mode;
630
    int motion_x[4];
631
    int motion_y[4];
632
    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
    int frag;
639

    
640
    if (s->keyframe)
641
        return 0;
642

    
643
    /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
644
    coding_mode = get_bits1(gb);
645

    
646
    /* iterate through all of the macroblocks that contain 1 or more
647
     * coded fragments */
648
    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
            if (get_bits_left(gb) <= 0)
651
                return -1;
652

    
653
        for (j = 0; j < 4; j++) {
654
            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
                (s->macroblock_coding[current_macroblock] == MODE_COPY))
660
                continue;
661

    
662
            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
                }
674

    
675
                /* vector maintenance, only on MODE_INTER_PLUS_MV */
676
                if (s->macroblock_coding[current_macroblock] ==
677
                    MODE_INTER_PLUS_MV) {
678
                    prior_last_motion_x = last_motion_x;
679
                    prior_last_motion_y = last_motion_y;
680
                    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
                    current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
694
                    if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
695
                        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
                        } else {
699
                            motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
700
                            motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
701
                        }
702
                        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
                    }
708
                }
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

    
716
                /* 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

    
726
                /* 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

    
733
            default:
734
                /* covers intra, inter without MV, golden without MV */
735
                motion_x[0] = 0;
736
                motion_y[0] = 0;
737

    
738
                /* no vector maintenance */
739
                break;
740
            }
741

    
742
            /* assign the motion vectors to the correct fragments */
743
            for (k = 0; k < 4; k++) {
744
                current_fragment =
745
                    BLOCK_Y*s->fragment_width[0] + BLOCK_X;
746
                if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
747
                    s->motion_val[0][current_fragment][0] = motion_x[k];
748
                    s->motion_val[0][current_fragment][1] = motion_y[k];
749
                } else {
750
                    s->motion_val[0][current_fragment][0] = motion_x[0];
751
                    s->motion_val[0][current_fragment][1] = motion_y[0];
752
                }
753
            }
754

    
755
            if (s->chroma_y_shift) {
756
                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
                motion_x[0] = (motion_x[0]>>1) | (motion_x[0]&1);
761
                motion_y[0] = (motion_y[0]>>1) | (motion_y[0]&1);
762
                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
            } 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
                frag = 2*mb_y*s->fragment_width[1] + mb_x;
779
                for (k = 0; k < 2; k++) {
780
                    s->motion_val[1][frag][0] = motion_x[k];
781
                    s->motion_val[1][frag][1] = motion_y[k];
782
                    frag += s->fragment_width[1];
783
                }
784
            } else {
785
                for (k = 0; k < 4; k++) {
786
                    frag = BLOCK_Y*s->fragment_width[1] + BLOCK_X;
787
                    if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
788
                        s->motion_val[1][frag][0] = motion_x[k];
789
                        s->motion_val[1][frag][1] = motion_y[k];
790
                    } else {
791
                        s->motion_val[1][frag][0] = motion_x[0];
792
                        s->motion_val[1][frag][1] = motion_y[0];
793
                    }
794
                }
795
            }
796
        }
797
        }
798
    }
799

    
800
    return 0;
801
}
802

    
803
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
    int num_blocks = s->total_num_coded_frags;
807

    
808
    for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
809
        i = blocks_decoded = num_blocks_at_qpi = 0;
810

    
811
        bit = get_bits1(gb) ^ 1;
812
        run_length = 0;
813

    
814
        do {
815
            if (run_length == MAXIMUM_LONG_BIT_RUN)
816
                bit = get_bits1(gb);
817
            else
818
                bit ^= 1;
819

    
820
            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
                if (i >= s->total_num_coded_frags)
830
                    return -1;
831

    
832
                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
                    j++;
835
                }
836
            }
837
        } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
838

    
839
        num_blocks -= num_blocks_at_qpi;
840
    }
841

    
842
    return 0;
843
}
844

    
845
/*
846
 * 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
                        int plane,
860
                        int eob_run)
861
{
862
    int i, j = 0;
863
    int token;
864
    int zero_run = 0;
865
    DCTELEM coeff = 0;
866
    int bits_to_get;
867
    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

    
872
    /* local references to structure members to avoid repeated deferences */
873
    int *coded_fragment_list = s->coded_fragment_list[plane];
874
    Vp3Fragment *all_fragments = s->all_fragments;
875
    VLC_TYPE (*vlc_table)[2] = table->table;
876

    
877
    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
    } else {
884
        coeff_i = blocks_ended = eob_run;
885
        eob_run = 0;
886
    }
887

    
888
    // insert fake EOB token to cover the split between planes or zzi
889
    if (blocks_ended)
890
        dct_tokens[j++] = blocks_ended << 2;
891

    
892
    while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
893
            /* decode a VLC into a token */
894
            token = get_vlc2(gb, vlc_table, 11, 3);
895
            /* use the token to get a zero run, a coefficient, and an eob run */
896
            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

    
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
            } else {
915
                bits_to_get = coeff_get_bits[token];
916
                if (bits_to_get)
917
                    bits_to_get = get_bits(gb, bits_to_get);
918
                coeff = coeff_tables[token][bits_to_get];
919

    
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

    
924
                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
                    av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
939
                           " %d coeffs left\n", zero_run, 64-coeff_index);
940
                    zero_run = 64 - coeff_index;
941
                }
942

    
943
                // 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
    }
950

    
951
    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
    return eob_run;
967
}
968

    
969
static void reverse_dc_prediction(Vp3DecodeContext *s,
970
                                  int first_fragment,
971
                                  int fragment_width,
972
                                  int fragment_height);
973
/*
974
 * This function unpacks all of the DCT coefficient data from the
975
 * bitstream.
976
 */
977
static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
978
{
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
    VLC *y_tables[64];
986
    VLC *c_tables[64];
987

    
988
    s->dct_tokens[0][0] = s->dct_tokens_base;
989

    
990
    /* fetch the DC table indexes */
991
    dc_y_table = get_bits(gb, 4);
992
    dc_c_table = get_bits(gb, 4);
993

    
994
    /* unpack the Y plane DC coefficients */
995
    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
996
        0, residual_eob_run);
997

    
998
    /* reverse prediction of the Y-plane DC coefficients */
999
    reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1000

    
1001
    /* unpack the C plane DC coefficients */
1002
    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
1003
        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

    
1007
    /* 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
            s->fragment_width[1], s->fragment_height[1]);
1012
        reverse_dc_prediction(s, s->fragment_start[2],
1013
            s->fragment_width[1], s->fragment_height[1]);
1014
    }
1015

    
1016
    /* fetch the AC table indexes */
1017
    ac_y_table = get_bits(gb, 4);
1018
    ac_c_table = get_bits(gb, 4);
1019

    
1020
    /* build tables of AC VLC tables */
1021
    for (i = 1; i <= 5; i++) {
1022
        y_tables[i] = &s->ac_vlc_1[ac_y_table];
1023
        c_tables[i] = &s->ac_vlc_1[ac_c_table];
1024
    }
1025
    for (i = 6; i <= 14; i++) {
1026
        y_tables[i] = &s->ac_vlc_2[ac_y_table];
1027
        c_tables[i] = &s->ac_vlc_2[ac_c_table];
1028
    }
1029
    for (i = 15; i <= 27; i++) {
1030
        y_tables[i] = &s->ac_vlc_3[ac_y_table];
1031
        c_tables[i] = &s->ac_vlc_3[ac_c_table];
1032
    }
1033
    for (i = 28; i <= 63; i++) {
1034
        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
                0, residual_eob_run);
1042

    
1043
            residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1044
                1, residual_eob_run);
1045
            residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1046
                2, residual_eob_run);
1047
    }
1048

    
1049
    return 0;
1050
}
1051

    
1052
/*
1053
 * This function reverses the DC prediction for each coded fragment in
1054
 * the frame. Much of this function is adapted directly from the original
1055
 * VP3 source code.
1056
 */
1057
#define COMPATIBLE_FRAME(x) \
1058
  (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1059
#define DC_COEFF(u) s->all_fragments[u].dc
1060

    
1061
static void reverse_dc_prediction(Vp3DecodeContext *s,
1062
                                  int first_fragment,
1063
                                  int fragment_width,
1064
                                  int fragment_height)
1065
{
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
    int predicted_dc;
1076

    
1077
    /* DC values for the left, up-left, up, and up-right fragments */
1078
    int vl, vul, vu, vur;
1079

    
1080
    /* indexes for the left, up-left, up, and up-right fragments */
1081
    int l, ul, u, ur;
1082

    
1083
    /*
1084
     * The 6 fields mean:
1085
     *   0: up-left multiplier
1086
     *   1: up multiplier
1087
     *   2: up-right multiplier
1088
     *   3: left multiplier
1089
     */
1090
    static const int predictor_transform[16][4] = {
1091
        {  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
    };
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
     * from other INTRA blocks. There are 2 golden frame coding types;
1113
     * blocks encoding in these modes can only predict from other blocks
1114
     * that were encoded with these 1 of these 2 modes. */
1115
    static const unsigned char compatible_frame[9] = {
1116
        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
        1,    /* MODE_INTER_FOUR_MV */
1124
        3     /* MODE_COPY */
1125
    };
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
                current_frame_type =
1146
                    compatible_frame[s->all_fragments[i].coding_method];
1147

    
1148
                transform= 0;
1149
                if(x){
1150
                    l= i-1;
1151
                    vl = DC_COEFF(l);
1152
                    if(COMPATIBLE_FRAME(l))
1153
                        transform |= PL;
1154
                }
1155
                if(y){
1156
                    u= i-fragment_width;
1157
                    vu = DC_COEFF(u);
1158
                    if(COMPATIBLE_FRAME(u))
1159
                        transform |= PU;
1160
                    if(x){
1161
                        ul= i-fragment_width-1;
1162
                        vul = DC_COEFF(ul);
1163
                        if(COMPATIBLE_FRAME(ul))
1164
                            transform |= PUL;
1165
                    }
1166
                    if(x + 1 < fragment_width){
1167
                        ur= i-fragment_width+1;
1168
                        vur = DC_COEFF(ur);
1169
                        if(COMPATIBLE_FRAME(ur))
1170
                            transform |= PUR;
1171
                    }
1172
                }
1173

    
1174
                if (transform == 0) {
1175

    
1176
                    /* if there were no fragments to predict from, use last
1177
                     * DC saved */
1178
                    predicted_dc = last_dc[current_frame_type];
1179
                } 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
                    predicted_dc /= 128;
1189

    
1190
                    /* check for outranging on the [ul u l] and
1191
                     * [ul u ur l] predictors */
1192
                    if ((transform == 15) || (transform == 13)) {
1193
                        if (FFABS(predicted_dc - vu) > 128)
1194
                            predicted_dc = vu;
1195
                        else if (FFABS(predicted_dc - vl) > 128)
1196
                            predicted_dc = vl;
1197
                        else if (FFABS(predicted_dc - vul) > 128)
1198
                            predicted_dc = vul;
1199
                    }
1200
                }
1201

    
1202
                /* at long last, apply the predictor */
1203
                DC_COEFF(i) += predicted_dc;
1204
                /* save the DC */
1205
                last_dc[current_frame_type] = DC_COEFF(i);
1206
            }
1207
        }
1208
    }
1209
}
1210

    
1211
static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
1212
{
1213
    int x, y;
1214
    int *bounding_values= s->bounding_values_array+127;
1215

    
1216
    int width           = s->fragment_width[!!plane];
1217
    int height          = s->fragment_height[!!plane];
1218
    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
    plane_data += s->data_offset[plane] + 8*ystart*stride;
1223

    
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
                        plane_data + 8*x,
1237
                        stride, bounding_values);
1238
                }
1239

    
1240
                /* do not perform top edge filter for top row fragments */
1241
                if (y > 0) {
1242
                    s->dsp.vp3_v_loop_filter(
1243
                        plane_data + 8*x,
1244
                        stride, bounding_values);
1245
                }
1246

    
1247
                /* 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
                        plane_data + 8*x + 8,
1254
                        stride, bounding_values);
1255
                }
1256

    
1257
                /* 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
                        plane_data + 8*x + 8*stride,
1264
                        stride, bounding_values);
1265
                }
1266
            }
1267

    
1268
            fragment++;
1269
        }
1270
        plane_data += 8*stride;
1271
    }
1272
}
1273

    
1274
/**
1275
 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1276
 * 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
        default: // shouldn't happen
1305
            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
 * 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
    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
    if(s->avctx->draw_horiz_band==NULL)
1332
        return;
1333

    
1334
    h= y - s->last_slice_end;
1335
    s->last_slice_end= y;
1336
    y -= h;
1337

    
1338
    if (!s->flipped_image) {
1339
        y = s->avctx->height - y - h;
1340
    }
1341

    
1342
    cy = y >> s->chroma_y_shift;
1343
    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
/**
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
/*
1375
 * Perform the final rendering for a particular slice of data.
1376
 * The slice number ranges from 0..(c_superblock_height - 1).
1377
 */
1378
static void render_slice(Vp3DecodeContext *s, int slice)
1379
{
1380
    int x, y, i, j, fragment;
1381
    LOCAL_ALIGNED_16(DCTELEM, block, [64]);
1382
    int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1383
    int motion_halfpel_index;
1384
    uint8_t *motion_source;
1385
    int plane, first_pixel;
1386

    
1387
    if (slice >= s->c_superblock_height)
1388
        return;
1389

    
1390
    for (plane = 0; plane < 3; plane++) {
1391
        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
        int stride            = s->current_frame.linesize[plane];
1395
        int plane_width       = s->width  >> (plane && s->chroma_x_shift);
1396
        int plane_height      = s->height >> (plane && s->chroma_y_shift);
1397
        int8_t (*motion_val)[2] = s->motion_val[!!plane];
1398

    
1399
        int sb_x, sb_y        = slice << (!plane && s->chroma_y_shift);
1400
        int slice_height      = sb_y + 1 + (!plane && s->chroma_y_shift);
1401
        int slice_width       = plane ? s->c_superblock_width : s->y_superblock_width;
1402

    
1403
        int fragment_width    = s->fragment_width[!!plane];
1404
        int fragment_height   = s->fragment_height[!!plane];
1405
        int fragment_start    = s->fragment_start[plane];
1406
        int do_await          = !plane && HAVE_PTHREADS && (s->avctx->active_thread_type&FF_THREAD_FRAME);
1407

    
1408
        if (!s->flipped_image) stride = -stride;
1409
        if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
1410
            continue;
1411

    
1412

    
1413
        if(FFABS(stride) > 2048)
1414
            return; //various tables are fixed size
1415

    
1416
        /* for each superblock row in the slice (both of them)... */
1417
        for (; sb_y < slice_height; sb_y++) {
1418

    
1419
            /* for each superblock in a row... */
1420
            for (sb_x = 0; sb_x < slice_width; sb_x++) {
1421

    
1422
                /* 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
                    fragment = y*fragment_width + x;
1427

    
1428
                    i = fragment_start + fragment;
1429

    
1430
                    // bounds check
1431
                    if (x >= fragment_width || y >= fragment_height)
1432
                        continue;
1433

    
1434
                first_pixel = 8*y*stride + 8*x;
1435

    
1436
                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
                /* transform if this block was coded */
1440
                if (s->all_fragments[i].coding_method != MODE_COPY) {
1441
                    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
                    else
1445
                        motion_source= last_plane;
1446

    
1447
                    motion_source += first_pixel;
1448
                    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
                        motion_x = motion_val[fragment][0];
1456
                        motion_y = motion_val[fragment][1];
1457

    
1458
                        src_x= (motion_x>>1) + 8*x;
1459
                        src_y= (motion_y>>1) + 8*y;
1460

    
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
                            s->dsp.emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
1473
                            motion_source= temp;
1474
                        }
1475
                    }
1476

    
1477

    
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
                        /* 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
                           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
                                output_plane + first_pixel,
1488
                                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
                                output_plane + first_pixel,
1493
                                motion_source - d,
1494
                                motion_source + stride + 1 + d,
1495
                                stride, 8);
1496
                        }
1497
                    }
1498

    
1499
                        s->dsp.clear_block(block);
1500

    
1501
                    /* invert DCT and place (or add) in final output */
1502

    
1503
                    if (s->all_fragments[i].coding_method == MODE_INTRA) {
1504
                        vp3_dequant(s, s->all_fragments + i, plane, 0, block);
1505
                        if(s->avctx->idct_algo!=FF_IDCT_VP3)
1506
                            block[0] += 128<<3;
1507
                        s->dsp.idct_put(
1508
                            output_plane + first_pixel,
1509
                            stride,
1510
                            block);
1511
                    } else {
1512
                        if (vp3_dequant(s, s->all_fragments + i, plane, 1, block)) {
1513
                        s->dsp.idct_add(
1514
                            output_plane + first_pixel,
1515
                            stride,
1516
                            block);
1517
                        } else {
1518
                            s->dsp.vp3_idct_dc_add(output_plane + first_pixel, stride, block);
1519
                        }
1520
                    }
1521
                } else {
1522

    
1523
                    /* copy directly from the previous frame */
1524
                    s->dsp.put_pixels_tab[1][0](
1525
                        output_plane + first_pixel,
1526
                        last_plane + first_pixel,
1527
                        stride, 8);
1528

    
1529
                }
1530
                }
1531
            }
1532

    
1533
            // Filter up to the last row in the superblock row
1534
            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
        }
1537
    }
1538

    
1539
     /* this looks like a good place for slice dispatch... */
1540
     /* algorithm:
1541
      *   if (slice == s->macroblock_height - 1)
1542
      *     dispatch (both last slice & 2nd-to-last slice);
1543
      *   else if (slice > 0)
1544
      *     dispatch (slice - 1);
1545
      */
1546

    
1547
    vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) -16, s->height-16));
1548
}
1549

    
1550
/// 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
/*
1583
 * This is the ffmpeg/libavcodec API init function.
1584
 */
1585
static av_cold int vp3_decode_init(AVCodecContext *avctx)
1586
{
1587
    Vp3DecodeContext *s = avctx->priv_data;
1588
    int i, inter, plane;
1589
    int c_width;
1590
    int c_height;
1591
    int y_fragment_count, c_fragment_count;
1592

    
1593
    if (avctx->codec_tag == MKTAG('V','P','3','0'))
1594
        s->version = 0;
1595
    else
1596
        s->version = 1;
1597

    
1598
    s->avctx = avctx;
1599
    s->width = FFALIGN(avctx->width, 16);
1600
    s->height = FFALIGN(avctx->height, 16);
1601
    if (avctx->pix_fmt == PIX_FMT_NONE)
1602
        avctx->pix_fmt = PIX_FMT_YUV420P;
1603
    avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1604
    if(avctx->idct_algo==FF_IDCT_AUTO)
1605
        avctx->idct_algo=FF_IDCT_VP3;
1606
    dsputil_init(&s->dsp, avctx);
1607

    
1608
    ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
1609

    
1610
    /* initialize to an impossible value which will force a recalculation
1611
     * in the first frame decode */
1612
    for (i = 0; i < 3; i++)
1613
        s->qps[i] = -1;
1614

    
1615
    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1616

    
1617
    s->y_superblock_width = (s->width + 31) / 32;
1618
    s->y_superblock_height = (s->height + 31) / 32;
1619
    s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1620

    
1621
    /* work out the dimensions for the C planes */
1622
    c_width = s->width >> s->chroma_x_shift;
1623
    c_height = s->height >> s->chroma_y_shift;
1624
    s->c_superblock_width = (c_width + 31) / 32;
1625
    s->c_superblock_height = (c_height + 31) / 32;
1626
    s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1627

    
1628
    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

    
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
    s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1637
    s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1638
    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

    
1641
    /* fragment count covers all 8x8 blocks for all 3 planes */
1642
    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

    
1648
    if (!s->theora_tables)
1649
    {
1650
        for (i = 0; i < 64; i++) {
1651
            s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1652
            s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1653
            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
            s->filter_limit_values[i] = vp31_filter_limit_values[i];
1657
        }
1658

    
1659
        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
        /* init VLC tables */
1669
        for (i = 0; i < 16; i++) {
1670

    
1671
            /* DC histograms */
1672
            init_vlc(&s->dc_vlc[i], 11, 32,
1673
                &dc_bias[i][0][1], 4, 2,
1674
                &dc_bias[i][0][0], 4, 2, 0);
1675

    
1676
            /* group 1 AC histograms */
1677
            init_vlc(&s->ac_vlc_1[i], 11, 32,
1678
                &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
            init_vlc(&s->ac_vlc_2[i], 11, 32,
1683
                &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
            init_vlc(&s->ac_vlc_3[i], 11, 32,
1688
                &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
            init_vlc(&s->ac_vlc_4[i], 11, 32,
1693
                &ac_bias_3[i][0][1], 4, 2,
1694
                &ac_bias_3[i][0][0], 4, 2, 0);
1695
        }
1696
    } else {
1697

    
1698
        for (i = 0; i < 16; i++) {
1699
            /* DC histograms */
1700
            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
                goto vlc_fail;
1704

    
1705
            /* group 1 AC histograms */
1706
            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
                goto vlc_fail;
1710

    
1711
            /* group 2 AC histograms */
1712
            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
                goto vlc_fail;
1716

    
1717
            /* group 3 AC histograms */
1718
            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
                goto vlc_fail;
1722

    
1723
            /* group 4 AC histograms */
1724
            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
                goto vlc_fail;
1728
        }
1729
    }
1730

    
1731
    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
    init_vlc(&s->fragment_run_length_vlc, 5, 30,
1736
        &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
    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
    }
1752

    
1753
    return allocate_tables(avctx);
1754

    
1755
vlc_fail:
1756
    av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1757
    return -1;
1758
}
1759

    
1760
/// 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
/*
1836
 * This is the ffmpeg/libavcodec API frame decode function.
1837
 */
1838
static int vp3_decode_frame(AVCodecContext *avctx,
1839
                            void *data, int *data_size,
1840
                            AVPacket *avpkt)
1841
{
1842
    const uint8_t *buf = avpkt->data;
1843
    int buf_size = avpkt->size;
1844
    Vp3DecodeContext *s = avctx->priv_data;
1845
    GetBitContext gb;
1846
    int i;
1847

    
1848
    init_get_bits(&gb, buf, buf_size * 8);
1849

    
1850
    if (s->theora && get_bits1(&gb))
1851
    {
1852
        av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1853
        return -1;
1854
    }
1855

    
1856
    s->keyframe = !get_bits1(&gb);
1857
    if (!s->theora)
1858
        skip_bits(&gb, 1);
1859
    for (i = 0; i < 3; i++)
1860
        s->last_qps[i] = s->qps[i];
1861

    
1862
    s->nqps=0;
1863
    do{
1864
        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

    
1869
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1870
        av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
1871
            s->keyframe?"key":"", avctx->frame_number+1, s->qps[0]);
1872

    
1873
    s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
1874
        avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY);
1875

    
1876
    if (s->qps[0] != s->last_qps[0])
1877
        init_loop_filter(s);
1878

    
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

    
1885
    if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
1886
        return buf_size;
1887

    
1888
    s->current_frame.reference = 3;
1889
    s->current_frame.pict_type = s->keyframe ? FF_I_TYPE : FF_P_TYPE;
1890
    if (ff_thread_get_buffer(avctx, &s->current_frame) < 0) {
1891
        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1892
        goto error;
1893
    }
1894

    
1895
    if (s->keyframe) {
1896
        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
                if (avctx->frame_number == 0)
1904
                    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
    } else {
1914
        if (!s->golden_frame.data[0]) {
1915
            av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
1916

    
1917
            s->golden_frame.reference = 3;
1918
            s->golden_frame.pict_type = FF_I_TYPE;
1919
            if (ff_thread_get_buffer(avctx, &s->golden_frame) < 0) {
1920
                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
        }
1926
    }
1927

    
1928
    s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame
1929
    s->current_frame.qstride= 0;
1930

    
1931
    memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
1932
    ff_thread_finish_setup(avctx);
1933

    
1934
    if (unpack_superblocks(s, &gb)){
1935
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
1936
        goto error;
1937
    }
1938
    if (unpack_modes(s, &gb)){
1939
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
1940
        goto error;
1941
    }
1942
    if (unpack_vectors(s, &gb)){
1943
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
1944
        goto error;
1945
    }
1946
    if (unpack_block_qpis(s, &gb)){
1947
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
1948
        goto error;
1949
    }
1950
    if (unpack_dct_coeffs(s, &gb)){
1951
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
1952
        goto error;
1953
    }
1954

    
1955
    for (i = 0; i < 3; i++) {
1956
        int height = s->height >> (i && s->chroma_y_shift);
1957
        if (s->flipped_image)
1958
            s->data_offset[i] = 0;
1959
        else
1960
            s->data_offset[i] = (height-1) * s->current_frame.linesize[i];
1961
    }
1962

    
1963
    s->last_slice_end = 0;
1964
    for (i = 0; i < s->c_superblock_height; i++)
1965
        render_slice(s, i);
1966

    
1967
    // filter the last row
1968
    for (i = 0; i < 3; i++) {
1969
        int row = (s->height >> (3+(i && s->chroma_y_shift))) - 1;
1970
        apply_loop_filter(s, i, row, row+1);
1971
    }
1972
    vp3_draw_horiz_band(s, s->avctx->height);
1973

    
1974
    *data_size=sizeof(AVFrame);
1975
    *(AVFrame*)data= s->current_frame;
1976

    
1977
    if (!HAVE_PTHREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
1978
        update_frames(avctx);
1979

    
1980
    return buf_size;
1981

    
1982
error:
1983
    ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
1984

    
1985
    if (!HAVE_PTHREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))
1986
        avctx->release_buffer(avctx, &s->current_frame);
1987

    
1988
    return -1;
1989
}
1990

    
1991
/*
1992
 * This is the ffmpeg/libavcodec API module cleanup function.
1993
 */
1994
static av_cold int vp3_decode_end(AVCodecContext *avctx)
1995
{
1996
    Vp3DecodeContext *s = avctx->priv_data;
1997
    int i;
1998

    
1999
    if (avctx->is_copy && !s->current_frame.data[0])
2000
        return 0;
2001

    
2002
    av_free(s->superblock_coding);
2003
    av_free(s->all_fragments);
2004
    av_free(s->coded_fragment_list[0]);
2005
    av_free(s->dct_tokens_base);
2006
    av_free(s->superblock_fragments);
2007
    av_free(s->macroblock_coding);
2008
    av_free(s->motion_val[0]);
2009
    av_free(s->motion_val[1]);
2010

    
2011
    if (avctx->is_copy) return 0;
2012

    
2013
    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
    /* release all frames */
2027
    if (s->golden_frame.data[0])
2028
        ff_thread_release_buffer(avctx, &s->golden_frame);
2029
    if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
2030
        ff_thread_release_buffer(avctx, &s->last_frame);
2031
    /* 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

    
2034
    return 0;
2035
}
2036

    
2037
static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2038
{
2039
    Vp3DecodeContext *s = avctx->priv_data;
2040

    
2041
    if (get_bits1(gb)) {
2042
        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
        if (read_huffman_tree(avctx, gb))
2061
            return -1;
2062
        s->hbits |= 1;
2063
        if (read_huffman_tree(avctx, gb))
2064
            return -1;
2065
        s->hbits >>= 1;
2066
        s->huff_code_size--;
2067
    }
2068
    return 0;
2069
}
2070

    
2071
#if CONFIG_THEORA_DECODER
2072
static const enum PixelFormat theora_pix_fmts[4] = {
2073
    PIX_FMT_YUV420P, PIX_FMT_NONE, PIX_FMT_YUV422P, PIX_FMT_YUV444P
2074
};
2075

    
2076
static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2077
{
2078
    Vp3DecodeContext *s = avctx->priv_data;
2079
    int visible_width, visible_height, colorspace;
2080
    int offset_x = 0, offset_y = 0;
2081
    AVRational fps, aspect;
2082

    
2083
    s->theora = get_bits_long(gb, 24);
2084
    av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2085

    
2086
    /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
2087
    /* but previous versions have the image flipped relative to vp3 */
2088
    if (s->theora < 0x030200)
2089
    {
2090
        s->flipped_image = 1;
2091
        av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
2092
    }
2093

    
2094
    visible_width  = s->width  = get_bits(gb, 16) << 4;
2095
    visible_height = s->height = get_bits(gb, 16) << 4;
2096

    
2097
    if(av_image_check_size(s->width, s->height, 0, avctx)){
2098
        av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
2099
        s->width= s->height= 0;
2100
        return -1;
2101
    }
2102

    
2103
    if (s->theora >= 0x030200) {
2104
        visible_width  = get_bits_long(gb, 24);
2105
        visible_height = get_bits_long(gb, 24);
2106

    
2107
        offset_x = get_bits(gb, 8); /* offset x */
2108
        offset_y = get_bits(gb, 8); /* offset y, from bottom */
2109
    }
2110

    
2111
    fps.num = get_bits_long(gb, 32);
2112
    fps.den = get_bits_long(gb, 32);
2113
    if (fps.num && fps.den) {
2114
        av_reduce(&avctx->time_base.num, &avctx->time_base.den,
2115
                  fps.den, fps.num, 1<<30);
2116
    }
2117

    
2118
    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

    
2126
    if (s->theora < 0x030200)
2127
        skip_bits(gb, 5); /* keyframe frequency force */
2128
    colorspace = get_bits(gb, 8);
2129
    skip_bits(gb, 24); /* bitrate */
2130

    
2131
    skip_bits(gb, 6); /* quality hint */
2132

    
2133
    if (s->theora >= 0x030200)
2134
    {
2135
        skip_bits(gb, 5); /* keyframe frequency force */
2136
        avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2137
        skip_bits(gb, 3); /* reserved */
2138
    }
2139

    
2140
//    align_get_bits(gb);
2141

    
2142
    if (   visible_width  <= s->width  && visible_width  > s->width-16
2143
        && visible_height <= s->height && visible_height > s->height-16
2144
        && !offset_x && (offset_y == s->height - visible_height))
2145
        avcodec_set_dimensions(avctx, visible_width, visible_height);
2146
    else
2147
        avcodec_set_dimensions(avctx, s->width, s->height);
2148

    
2149
    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
    return 0;
2160
}
2161

    
2162
static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2163
{
2164
    Vp3DecodeContext *s = avctx->priv_data;
2165
    int i, n, matrices, inter, plane;
2166

    
2167
    if (s->theora >= 0x030200) {
2168
        n = get_bits(gb, 3);
2169
        /* loop filter limit values table */
2170
        if (n)
2171
            for (i = 0; i < 64; i++)
2172
                s->filter_limit_values[i] = get_bits(gb, n);
2173
    }
2174

    
2175
    if (s->theora >= 0x030200)
2176
        n = get_bits(gb, 4) + 1;
2177
    else
2178
        n = 16;
2179
    /* quality threshold table */
2180
    for (i = 0; i < 64; i++)
2181
        s->coded_ac_scale_factor[i] = get_bits(gb, n);
2182

    
2183
    if (s->theora >= 0x030200)
2184
        n = get_bits(gb, 4) + 1;
2185
    else
2186
        n = 16;
2187
    /* dc scale factor table */
2188
    for (i = 0; i < 64; i++)
2189
        s->coded_dc_scale_factor[i] = get_bits(gb, n);
2190

    
2191
    if (s->theora >= 0x030200)
2192
        matrices = get_bits(gb, 9) + 1;
2193
    else
2194
        matrices = 3;
2195

    
2196
    if(matrices > 384){
2197
        av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2198
        return -1;
2199
    }
2200

    
2201
    for(n=0; n<matrices; n++){
2202
        for (i = 0; i < 64; i++)
2203
            s->base_matrix[n][i]= get_bits(gb, 8);
2204
    }
2205

    
2206
    for (inter = 0; inter <= 1; inter++) {
2207
        for (plane = 0; plane <= 2; plane++) {
2208
            int newqr= 1;
2209
            if (inter || plane > 0)
2210
                newqr = get_bits1(gb);
2211
            if (!newqr) {
2212
                int qtj, plj;
2213
                if(inter && get_bits1(gb)){
2214
                    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
                int qi = 0;
2226

    
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
                }
2240

    
2241
                if (qi > 63) {
2242
                    av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2243
                    return -1;
2244
                }
2245
                s->qr_count[inter][plane]= qri;
2246
            }
2247
        }
2248
    }
2249

    
2250
    /* Huffman tables */
2251
    for (s->hti = 0; s->hti < 80; s->hti++) {
2252
        s->entries = 0;
2253
        s->huff_code_size = 1;
2254
        if (!get_bits1(gb)) {
2255
            s->hbits = 0;
2256
            if(read_huffman_tree(avctx, gb))
2257
                return -1;
2258
            s->hbits = 1;
2259
            if(read_huffman_tree(avctx, gb))
2260
                return -1;
2261
        }
2262
    }
2263

    
2264
    s->theora_tables = 1;
2265

    
2266
    return 0;
2267
}
2268

    
2269
static av_cold int theora_decode_init(AVCodecContext *avctx)
2270
{
2271
    Vp3DecodeContext *s = avctx->priv_data;
2272
    GetBitContext gb;
2273
    int ptype;
2274
    uint8_t *header_start[3];
2275
    int header_len[3];
2276
    int i;
2277

    
2278
    s->theora = 1;
2279

    
2280
    if (!avctx->extradata_size)
2281
    {
2282
        av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2283
        return -1;
2284
    }
2285

    
2286
    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

    
2292
  for(i=0;i<3;i++) {
2293
    init_get_bits(&gb, header_start[i], header_len[i] * 8);
2294

    
2295
    ptype = get_bits(&gb, 8);
2296

    
2297
     if (!(ptype & 0x80))
2298
     {
2299
        av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2300
//        return -1;
2301
     }
2302

    
2303
    // FIXME: Check for this as well.
2304
    skip_bits_long(&gb, 6*8); /* "theora" */
2305

    
2306
    switch(ptype)
2307
    {
2308
        case 0x80:
2309
            theora_decode_header(avctx, &gb);
2310
                break;
2311
        case 0x81:
2312
// FIXME: is this needed? it breaks sometimes
2313
//            theora_decode_comments(avctx, gb);
2314
            break;
2315
        case 0x82:
2316
            if (theora_decode_tables(avctx, &gb))
2317
                return -1;
2318
            break;
2319
        default:
2320
            av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2321
            break;
2322
    }
2323
    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
    if (s->theora < 0x030200)
2326
        break;
2327
  }
2328

    
2329
    return vp3_decode_init(avctx);
2330
}
2331

    
2332
AVCodec ff_theora_decoder = {
2333
    "theora",
2334
    AVMEDIA_TYPE_VIDEO,
2335
    CODEC_ID_THEORA,
2336
    sizeof(Vp3DecodeContext),
2337
    theora_decode_init,
2338
    NULL,
2339
    vp3_decode_end,
2340
    vp3_decode_frame,
2341
    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_FRAME_THREADS,
2342
    NULL,
2343
    .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2344
    .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
2345
};
2346
#endif
2347

    
2348
AVCodec ff_vp3_decoder = {
2349
    "vp3",
2350
    AVMEDIA_TYPE_VIDEO,
2351
    CODEC_ID_VP3,
2352
    sizeof(Vp3DecodeContext),
2353
    vp3_decode_init,
2354
    NULL,
2355
    vp3_decode_end,
2356
    vp3_decode_frame,
2357
    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_FRAME_THREADS,
2358
    NULL,
2359
    .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2360
    .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
2361
};