Statistics
| Branch: | Revision:

ffmpeg / libavcodec / vp3.c @ 57783884

History | View | Annotate | Download (73.9 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 libavcodec/vp3.c
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 "avcodec.h"
37
#include "dsputil.h"
38
#include "get_bits.h"
39

    
40
#include "vp3data.h"
41
#include "xiph.h"
42

    
43
#define FRAGMENT_PIXELS 8
44

    
45
static av_cold int vp3_decode_end(AVCodecContext *avctx);
46

    
47
//FIXME split things out into their own arrays
48
typedef struct Vp3Fragment {
49
    int16_t dc;
50
    uint8_t coding_method;
51
    int8_t motion_x;
52
    int8_t motion_y;
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
    AVFrame golden_frame;
134
    AVFrame last_frame;
135
    AVFrame current_frame;
136
    int keyframe;
137
    DSPContext dsp;
138
    int flipped_image;
139
    int last_slice_end;
140

    
141
    int qps[3];
142
    int nqps;
143
    int last_qps[3];
144

    
145
    int superblock_count;
146
    int y_superblock_width;
147
    int y_superblock_height;
148
    int y_superblock_count;
149
    int c_superblock_width;
150
    int c_superblock_height;
151
    int c_superblock_count;
152
    int u_superblock_start;
153
    int v_superblock_start;
154
    unsigned char *superblock_coding;
155

    
156
    int macroblock_count;
157
    int macroblock_width;
158
    int macroblock_height;
159

    
160
    int fragment_count;
161
    int fragment_width[2];
162
    int fragment_height[2];
163

    
164
    Vp3Fragment *all_fragments;
165
    int fragment_start[3];
166
    int data_offset[3];
167

    
168
    ScanTable scantable;
169

    
170
    /* tables */
171
    uint16_t coded_dc_scale_factor[64];
172
    uint32_t coded_ac_scale_factor[64];
173
    uint8_t base_matrix[384][64];
174
    uint8_t qr_count[2][3];
175
    uint8_t qr_size [2][3][64];
176
    uint16_t qr_base[2][3][64];
177

    
178
    /**
179
     * This is a list of all tokens in bitstream order. Reordering takes place
180
     * by pulling from each level during IDCT. As a consequence, IDCT must be
181
     * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
182
     * otherwise. The 32 different tokens with up to 12 bits of extradata are
183
     * collapsed into 3 types, packed as follows:
184
     *   (from the low to high bits)
185
     *
186
     * 2 bits: type (0,1,2)
187
     *   0: EOB run, 14 bits for run length (12 needed)
188
     *   1: zero run, 7 bits for run length
189
     *                7 bits for the next coefficient (3 needed)
190
     *   2: coefficient, 14 bits (11 needed)
191
     *
192
     * Coefficients are signed, so are packed in the highest bits for automatic
193
     * sign extension.
194
     */
195
    int16_t *dct_tokens[3][64];
196
    int16_t *dct_tokens_base;
197
#define TOKEN_EOB(eob_run)              ((eob_run) << 2)
198
#define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) << 9) + ((zero_run) << 2) + 1)
199
#define TOKEN_COEFF(coeff)              (((coeff) << 2) + 2)
200

    
201
    /**
202
     * number of blocks that contain DCT coefficients at the given level or higher
203
     */
204
    int num_coded_frags[3][64];
205
    int total_num_coded_frags;
206

    
207
    /* this is a list of indexes into the all_fragments array indicating
208
     * which of the fragments are coded */
209
    int *coded_fragment_list[3];
210

    
211
    VLC dc_vlc[16];
212
    VLC ac_vlc_1[16];
213
    VLC ac_vlc_2[16];
214
    VLC ac_vlc_3[16];
215
    VLC ac_vlc_4[16];
216

    
217
    VLC superblock_run_length_vlc;
218
    VLC fragment_run_length_vlc;
219
    VLC mode_code_vlc;
220
    VLC motion_vector_vlc;
221

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

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

    
232
    /* This is an array that indicates how a particular macroblock
233
     * is coded. */
234
    unsigned char *macroblock_coding;
235

    
236
    uint8_t edge_emu_buffer[9*2048]; //FIXME dynamic alloc
237
    int8_t qscale_table[2048]; //FIXME dynamic alloc (width+15)/16
238

    
239
    /* Huffman decode */
240
    int hti;
241
    unsigned int hbits;
242
    int entries;
243
    int huff_code_size;
244
    uint16_t huffman_table[80][32][2];
245

    
246
    uint8_t filter_limit_values[64];
247
    DECLARE_ALIGNED(8, int, bounding_values_array)[256+2];
248
} Vp3DecodeContext;
249

    
250
/************************************************************************
251
 * VP3 specific functions
252
 ************************************************************************/
253

    
254
/*
255
 * This function sets up all of the various blocks mappings:
256
 * superblocks <-> fragments, macroblocks <-> fragments,
257
 * superblocks <-> macroblocks
258
 *
259
 * Returns 0 is successful; returns 1 if *anything* went wrong.
260
 */
261
static int init_block_mapping(Vp3DecodeContext *s)
262
{
263
    int sb_x, sb_y, plane;
264
    int x, y, i, j = 0;
265

    
266
    for (plane = 0; plane < 3; plane++) {
267
        int sb_width    = plane ? s->c_superblock_width  : s->y_superblock_width;
268
        int sb_height   = plane ? s->c_superblock_height : s->y_superblock_height;
269
        int frag_width  = s->fragment_width[!!plane];
270
        int frag_height = s->fragment_height[!!plane];
271

    
272
        for (sb_y = 0; sb_y < sb_height; sb_y++)
273
            for (sb_x = 0; sb_x < sb_width; sb_x++)
274
                for (i = 0; i < 16; i++) {
275
                    x = 4*sb_x + hilbert_offset[i][0];
276
                    y = 4*sb_y + hilbert_offset[i][1];
277

    
278
                    if (x < frag_width && y < frag_height)
279
                        s->superblock_fragments[j++] = s->fragment_start[plane] + y*frag_width + x;
280
                    else
281
                        s->superblock_fragments[j++] = -1;
282
                }
283
    }
284

    
285
    return 0;  /* successful path out */
286
}
287

    
288
/*
289
 * This function sets up the dequantization tables used for a particular
290
 * frame.
291
 */
292
static void init_dequantizer(Vp3DecodeContext *s, int qpi)
293
{
294
    int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
295
    int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
296
    int i, plane, inter, qri, bmi, bmj, qistart;
297

    
298
    for(inter=0; inter<2; inter++){
299
        for(plane=0; plane<3; plane++){
300
            int sum=0;
301
            for(qri=0; qri<s->qr_count[inter][plane]; qri++){
302
                sum+= s->qr_size[inter][plane][qri];
303
                if(s->qps[qpi] <= sum)
304
                    break;
305
            }
306
            qistart= sum - s->qr_size[inter][plane][qri];
307
            bmi= s->qr_base[inter][plane][qri  ];
308
            bmj= s->qr_base[inter][plane][qri+1];
309
            for(i=0; i<64; i++){
310
                int coeff= (  2*(sum    -s->qps[qpi])*s->base_matrix[bmi][i]
311
                            - 2*(qistart-s->qps[qpi])*s->base_matrix[bmj][i]
312
                            + s->qr_size[inter][plane][qri])
313
                           / (2*s->qr_size[inter][plane][qri]);
314

    
315
                int qmin= 8<<(inter + !i);
316
                int qscale= i ? ac_scale_factor : dc_scale_factor;
317

    
318
                s->qmat[qpi][inter][plane][s->dsp.idct_permutation[i]]= av_clip((qscale * coeff)/100 * 4, qmin, 4096);
319
            }
320
            // all DC coefficients use the same quant so as not to interfere with DC prediction
321
            s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
322
        }
323
    }
324

    
325
    memset(s->qscale_table, (FFMAX(s->qmat[0][0][0][1], s->qmat[0][0][1][1])+8)/16, 512); //FIXME finetune
326
}
327

    
328
/*
329
 * This function initializes the loop filter boundary limits if the frame's
330
 * quality index is different from the previous frame's.
331
 *
332
 * The filter_limit_values may not be larger than 127.
333
 */
334
static void init_loop_filter(Vp3DecodeContext *s)
335
{
336
    int *bounding_values= s->bounding_values_array+127;
337
    int filter_limit;
338
    int x;
339
    int value;
340

    
341
    filter_limit = s->filter_limit_values[s->qps[0]];
342

    
343
    /* set up the bounding values */
344
    memset(s->bounding_values_array, 0, 256 * sizeof(int));
345
    for (x = 0; x < filter_limit; x++) {
346
        bounding_values[-x] = -x;
347
        bounding_values[x] = x;
348
    }
349
    for (x = value = filter_limit; x < 128 && value; x++, value--) {
350
        bounding_values[ x] =  value;
351
        bounding_values[-x] = -value;
352
    }
353
    if (value)
354
        bounding_values[128] = value;
355
    bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
356
}
357

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

    
370
    int i, j;
371
    int current_fragment;
372
    int plane;
373

    
374
    if (s->keyframe) {
375
        memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
376

    
377
    } else {
378

    
379
        /* unpack the list of partially-coded superblocks */
380
        bit = get_bits1(gb);
381
        while (current_superblock < s->superblock_count) {
382
                current_run = get_vlc2(gb,
383
                    s->superblock_run_length_vlc.table, 6, 2) + 1;
384
                if (current_run == 34)
385
                    current_run += get_bits(gb, 12);
386

    
387
            if (current_superblock + current_run > s->superblock_count) {
388
                av_log(s->avctx, AV_LOG_ERROR, "Invalid partially coded superblock run length\n");
389
                return -1;
390
            }
391

    
392
            memset(s->superblock_coding + current_superblock, bit, current_run);
393

    
394
            current_superblock += current_run;
395
            if (bit)
396
                num_partial_superblocks += current_run;
397

    
398
            if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
399
                bit = get_bits1(gb);
400
            else
401
                bit ^= 1;
402
        }
403

    
404
        /* unpack the list of fully coded superblocks if any of the blocks were
405
         * not marked as partially coded in the previous step */
406
        if (num_partial_superblocks < s->superblock_count) {
407
            int superblocks_decoded = 0;
408

    
409
            current_superblock = 0;
410
            bit = get_bits1(gb);
411
            while (superblocks_decoded < s->superblock_count - num_partial_superblocks) {
412
                        current_run = get_vlc2(gb,
413
                            s->superblock_run_length_vlc.table, 6, 2) + 1;
414
                        if (current_run == 34)
415
                            current_run += get_bits(gb, 12);
416

    
417
                for (j = 0; j < current_run; current_superblock++) {
418
                    if (current_superblock >= s->superblock_count) {
419
                        av_log(s->avctx, AV_LOG_ERROR, "Invalid fully coded superblock run length\n");
420
                        return -1;
421
                    }
422

    
423
                /* skip any superblocks already marked as partially coded */
424
                if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
425
                    s->superblock_coding[current_superblock] = 2*bit;
426
                    j++;
427
                }
428
                }
429
                superblocks_decoded += current_run;
430

    
431
                if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
432
                    bit = get_bits1(gb);
433
                else
434
                    bit ^= 1;
435
            }
436
        }
437

    
438
        /* if there were partial blocks, initialize bitstream for
439
         * unpacking fragment codings */
440
        if (num_partial_superblocks) {
441

    
442
            current_run = 0;
443
            bit = get_bits1(gb);
444
            /* toggle the bit because as soon as the first run length is
445
             * fetched the bit will be toggled again */
446
            bit ^= 1;
447
        }
448
    }
449

    
450
    /* figure out which fragments are coded; iterate through each
451
     * superblock (all planes) */
452
    s->total_num_coded_frags = 0;
453
    memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
454

    
455
    for (plane = 0; plane < 3; plane++) {
456
        int sb_start = superblock_starts[plane];
457
        int sb_end = sb_start + (plane ? s->c_superblock_count : s->y_superblock_count);
458
        int num_coded_frags = 0;
459

    
460
    for (i = sb_start; i < sb_end; i++) {
461

    
462
        /* iterate through all 16 fragments in a superblock */
463
        for (j = 0; j < 16; j++) {
464

    
465
            /* if the fragment is in bounds, check its coding status */
466
            current_fragment = s->superblock_fragments[i * 16 + j];
467
            if (current_fragment >= s->fragment_count) {
468
                av_log(s->avctx, AV_LOG_ERROR, "  vp3:unpack_superblocks(): bad fragment number (%d >= %d)\n",
469
                    current_fragment, s->fragment_count);
470
                return 1;
471
            }
472
            if (current_fragment != -1) {
473
                int coded = s->superblock_coding[i];
474

    
475
                if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
476

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

    
487
                    if (coded) {
488
                        /* default mode; actual mode will be decoded in
489
                         * the next phase */
490
                        s->all_fragments[current_fragment].coding_method =
491
                            MODE_INTER_NO_MV;
492
                        s->coded_fragment_list[plane][num_coded_frags++] =
493
                            current_fragment;
494
                    } else {
495
                        /* not coded; copy this fragment from the prior frame */
496
                        s->all_fragments[current_fragment].coding_method =
497
                            MODE_COPY;
498
                    }
499
            }
500
        }
501
    }
502
        s->total_num_coded_frags += num_coded_frags;
503
        for (i = 0; i < 64; i++)
504
            s->num_coded_frags[plane][i] = num_coded_frags;
505
        if (plane < 2)
506
            s->coded_fragment_list[plane+1] = s->coded_fragment_list[plane] + num_coded_frags;
507
    }
508
    return 0;
509
}
510

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

    
525
    if (s->keyframe) {
526
        for (i = 0; i < s->fragment_count; i++)
527
            s->all_fragments[i].coding_method = MODE_INTRA;
528

    
529
    } else {
530

    
531
        /* fetch the mode coding scheme for this frame */
532
        scheme = get_bits(gb, 3);
533

    
534
        /* is it a custom coding scheme? */
535
        if (scheme == 0) {
536
            for (i = 0; i < 8; i++)
537
                custom_mode_alphabet[i] = MODE_INTER_NO_MV;
538
            for (i = 0; i < 8; i++)
539
                custom_mode_alphabet[get_bits(gb, 3)] = i;
540
            alphabet = custom_mode_alphabet;
541
        } else
542
            alphabet = ModeAlphabet[scheme-1];
543

    
544
        /* iterate through all of the macroblocks that contain 1 or more
545
         * coded fragments */
546
        for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
547
            for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
548

    
549
            for (j = 0; j < 4; j++) {
550
                int mb_x = 2*sb_x +   (j>>1);
551
                int mb_y = 2*sb_y + (((j>>1)+j)&1);
552
                current_macroblock = mb_y * s->macroblock_width + mb_x;
553

    
554
                if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height)
555
                    continue;
556

    
557
#define BLOCK_X (2*mb_x + (k&1))
558
#define BLOCK_Y (2*mb_y + (k>>1))
559
                /* coding modes are only stored if the macroblock has at least one
560
                 * luma block coded, otherwise it must be INTER_NO_MV */
561
                for (k = 0; k < 4; k++) {
562
                    current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
563
                    if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
564
                        break;
565
                }
566
                if (k == 4) {
567
                    s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
568
                    continue;
569
                }
570

    
571
                /* mode 7 means get 3 bits for each coding mode */
572
                if (scheme == 7)
573
                    coding_mode = get_bits(gb, 3);
574
                else
575
                    coding_mode = alphabet
576
                        [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
577

    
578
                s->macroblock_coding[current_macroblock] = coding_mode;
579
                for (k = 0; k < 4; k++) {
580
                    current_fragment =
581
                        BLOCK_Y*s->fragment_width[0] + BLOCK_X;
582
                    if (s->all_fragments[current_fragment].coding_method !=
583
                        MODE_COPY)
584
                        s->all_fragments[current_fragment].coding_method =
585
                            coding_mode;
586
                }
587
                for (k = 0; k < 2; k++) {
588
                    current_fragment = s->fragment_start[k+1] +
589
                        mb_y*s->fragment_width[1] + mb_x;
590
                    if (s->all_fragments[current_fragment].coding_method !=
591
                        MODE_COPY)
592
                        s->all_fragments[current_fragment].coding_method =
593
                            coding_mode;
594
                }
595
            }
596
            }
597
        }
598
    }
599

    
600
    return 0;
601
}
602

    
603
/*
604
 * This function unpacks all the motion vectors for the individual
605
 * macroblocks from the bitstream.
606
 */
607
static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
608
{
609
    int j, k, sb_x, sb_y;
610
    int coding_mode;
611
    int motion_x[4];
612
    int motion_y[4];
613
    int last_motion_x = 0;
614
    int last_motion_y = 0;
615
    int prior_last_motion_x = 0;
616
    int prior_last_motion_y = 0;
617
    int current_macroblock;
618
    int current_fragment;
619

    
620
    if (s->keyframe)
621
        return 0;
622

    
623
    /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
624
    coding_mode = get_bits1(gb);
625

    
626
    /* iterate through all of the macroblocks that contain 1 or more
627
     * coded fragments */
628
    for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
629
        for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
630

    
631
        for (j = 0; j < 4; j++) {
632
            int mb_x = 2*sb_x +   (j>>1);
633
            int mb_y = 2*sb_y + (((j>>1)+j)&1);
634
            current_macroblock = mb_y * s->macroblock_width + mb_x;
635

    
636
            if (mb_x >= s->macroblock_width || mb_y >= s->macroblock_height ||
637
                (s->macroblock_coding[current_macroblock] == MODE_COPY))
638
                continue;
639

    
640
            switch (s->macroblock_coding[current_macroblock]) {
641

    
642
            case MODE_INTER_PLUS_MV:
643
            case MODE_GOLDEN_MV:
644
                /* all 6 fragments use the same motion vector */
645
                if (coding_mode == 0) {
646
                    motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
647
                    motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
648
                } else {
649
                    motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
650
                    motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
651
                }
652

    
653
                /* vector maintenance, only on MODE_INTER_PLUS_MV */
654
                if (s->macroblock_coding[current_macroblock] ==
655
                    MODE_INTER_PLUS_MV) {
656
                    prior_last_motion_x = last_motion_x;
657
                    prior_last_motion_y = last_motion_y;
658
                    last_motion_x = motion_x[0];
659
                    last_motion_y = motion_y[0];
660
                }
661
                break;
662

    
663
            case MODE_INTER_FOURMV:
664
                /* vector maintenance */
665
                prior_last_motion_x = last_motion_x;
666
                prior_last_motion_y = last_motion_y;
667

    
668
                /* fetch 4 vectors from the bitstream, one for each
669
                 * Y fragment, then average for the C fragment vectors */
670
                for (k = 0; k < 4; k++) {
671
                    current_fragment = BLOCK_Y*s->fragment_width[0] + BLOCK_X;
672
                    if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
673
                        if (coding_mode == 0) {
674
                            motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
675
                            motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
676
                        } else {
677
                            motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
678
                            motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
679
                        }
680
                        last_motion_x = motion_x[k];
681
                        last_motion_y = motion_y[k];
682
                    } else {
683
                        motion_x[k] = 0;
684
                        motion_y[k] = 0;
685
                    }
686
                }
687
                break;
688

    
689
            case MODE_INTER_LAST_MV:
690
                /* all 6 fragments use the last motion vector */
691
                motion_x[0] = last_motion_x;
692
                motion_y[0] = last_motion_y;
693

    
694
                /* no vector maintenance (last vector remains the
695
                 * last vector) */
696
                break;
697

    
698
            case MODE_INTER_PRIOR_LAST:
699
                /* all 6 fragments use the motion vector prior to the
700
                 * last motion vector */
701
                motion_x[0] = prior_last_motion_x;
702
                motion_y[0] = prior_last_motion_y;
703

    
704
                /* vector maintenance */
705
                prior_last_motion_x = last_motion_x;
706
                prior_last_motion_y = last_motion_y;
707
                last_motion_x = motion_x[0];
708
                last_motion_y = motion_y[0];
709
                break;
710

    
711
            default:
712
                /* covers intra, inter without MV, golden without MV */
713
                motion_x[0] = 0;
714
                motion_y[0] = 0;
715

    
716
                /* no vector maintenance */
717
                break;
718
            }
719

    
720
            /* assign the motion vectors to the correct fragments */
721
            for (k = 0; k < 4; k++) {
722
                current_fragment =
723
                    BLOCK_Y*s->fragment_width[0] + BLOCK_X;
724
                if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
725
                    s->all_fragments[current_fragment].motion_x = motion_x[k];
726
                    s->all_fragments[current_fragment].motion_y = motion_y[k];
727
                } else {
728
                    s->all_fragments[current_fragment].motion_x = motion_x[0];
729
                    s->all_fragments[current_fragment].motion_y = motion_y[0];
730
                }
731
            }
732
                if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
733
                    motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] + motion_x[2] + motion_x[3], 2);
734
                    motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] + motion_y[2] + motion_y[3], 2);
735
                }
736
            for (k = 0; k < 2; k++) {
737
                current_fragment = s->fragment_start[k+1] +
738
                    mb_y*s->fragment_width[1] + mb_x;
739
                    s->all_fragments[current_fragment].motion_x = motion_x[0];
740
                    s->all_fragments[current_fragment].motion_y = motion_y[0];
741
            }
742
        }
743
        }
744
    }
745

    
746
    return 0;
747
}
748

    
749
static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
750
{
751
    int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
752
    int num_blocks = s->total_num_coded_frags;
753

    
754
    for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {
755
        i = blocks_decoded = num_blocks_at_qpi = 0;
756

    
757
        bit = get_bits1(gb);
758

    
759
        do {
760
            run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
761
            if (run_length == 34)
762
                run_length += get_bits(gb, 12);
763
            blocks_decoded += run_length;
764

    
765
            if (!bit)
766
                num_blocks_at_qpi += run_length;
767

    
768
            for (j = 0; j < run_length; i++) {
769
                if (i >= s->total_num_coded_frags)
770
                    return -1;
771

    
772
                if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
773
                    s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
774
                    j++;
775
                }
776
            }
777

    
778
            if (run_length == MAXIMUM_LONG_BIT_RUN)
779
                bit = get_bits1(gb);
780
            else
781
                bit ^= 1;
782
        } while (blocks_decoded < num_blocks);
783

    
784
        num_blocks -= num_blocks_at_qpi;
785
    }
786

    
787
    return 0;
788
}
789

    
790
/*
791
 * This function is called by unpack_dct_coeffs() to extract the VLCs from
792
 * the bitstream. The VLCs encode tokens which are used to unpack DCT
793
 * data. This function unpacks all the VLCs for either the Y plane or both
794
 * C planes, and is called for DC coefficients or different AC coefficient
795
 * levels (since different coefficient types require different VLC tables.
796
 *
797
 * This function returns a residual eob run. E.g, if a particular token gave
798
 * instructions to EOB the next 5 fragments and there were only 2 fragments
799
 * left in the current fragment range, 3 would be returned so that it could
800
 * be passed into the next call to this same function.
801
 */
802
static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
803
                        VLC *table, int coeff_index,
804
                        int plane,
805
                        int eob_run)
806
{
807
    int i, j = 0;
808
    int token;
809
    int zero_run = 0;
810
    DCTELEM coeff = 0;
811
    int bits_to_get;
812
    int blocks_ended;
813
    int coeff_i = 0;
814
    int num_coeffs = s->num_coded_frags[plane][coeff_index];
815
    int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
816

    
817
    /* local references to structure members to avoid repeated deferences */
818
    int *coded_fragment_list = s->coded_fragment_list[plane];
819
    Vp3Fragment *all_fragments = s->all_fragments;
820
    VLC_TYPE (*vlc_table)[2] = table->table;
821

    
822
    if (num_coeffs < 0)
823
        av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index);
824

    
825
    if (eob_run > num_coeffs) {
826
        coeff_i = blocks_ended = num_coeffs;
827
        eob_run -= num_coeffs;
828
    } else {
829
        coeff_i = blocks_ended = eob_run;
830
        eob_run = 0;
831
    }
832

    
833
    // insert fake EOB token to cover the split between planes or zzi
834
    if (blocks_ended)
835
        dct_tokens[j++] = blocks_ended << 2;
836

    
837
    while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
838
            /* decode a VLC into a token */
839
            token = get_vlc2(gb, vlc_table, 5, 3);
840
            /* use the token to get a zero run, a coefficient, and an eob run */
841
            if (token <= 6) {
842
                eob_run = eob_run_base[token];
843
                if (eob_run_get_bits[token])
844
                    eob_run += get_bits(gb, eob_run_get_bits[token]);
845

    
846
                // record only the number of blocks ended in this plane,
847
                // any spill will be recorded in the next plane.
848
                if (eob_run > num_coeffs - coeff_i) {
849
                    dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
850
                    blocks_ended   += num_coeffs - coeff_i;
851
                    eob_run        -= num_coeffs - coeff_i;
852
                    coeff_i         = num_coeffs;
853
                } else {
854
                    dct_tokens[j++] = TOKEN_EOB(eob_run);
855
                    blocks_ended   += eob_run;
856
                    coeff_i        += eob_run;
857
                    eob_run = 0;
858
                }
859
            } else {
860
                bits_to_get = coeff_get_bits[token];
861
                if (bits_to_get)
862
                    bits_to_get = get_bits(gb, bits_to_get);
863
                coeff = coeff_tables[token][bits_to_get];
864

    
865
                zero_run = zero_run_base[token];
866
                if (zero_run_get_bits[token])
867
                    zero_run += get_bits(gb, zero_run_get_bits[token]);
868

    
869
                if (zero_run) {
870
                    dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
871
                } else {
872
                    // Save DC into the fragment structure. DC prediction is
873
                    // done in raster order, so the actual DC can't be in with
874
                    // other tokens. We still need the token in dct_tokens[]
875
                    // however, or else the structure collapses on itself.
876
                    if (!coeff_index)
877
                        all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
878

    
879
                    dct_tokens[j++] = TOKEN_COEFF(coeff);
880
                }
881

    
882
                if (coeff_index + zero_run > 64) {
883
                    av_log(s->avctx, AV_LOG_DEBUG, "Invalid zero run of %d with"
884
                           " %d coeffs left\n", zero_run, 64-coeff_index);
885
                    zero_run = 64 - coeff_index;
886
                }
887

    
888
                // zero runs code multiple coefficients,
889
                // so don't try to decode coeffs for those higher levels
890
                for (i = coeff_index+1; i <= coeff_index+zero_run; i++)
891
                    s->num_coded_frags[plane][i]--;
892
                coeff_i++;
893
            }
894
    }
895

    
896
    if (blocks_ended > s->num_coded_frags[plane][coeff_index])
897
        av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
898

    
899
    // decrement the number of blocks that have higher coeffecients for each
900
    // EOB run at this level
901
    if (blocks_ended)
902
        for (i = coeff_index+1; i < 64; i++)
903
            s->num_coded_frags[plane][i] -= blocks_ended;
904

    
905
    // setup the next buffer
906
    if (plane < 2)
907
        s->dct_tokens[plane+1][coeff_index] = dct_tokens + j;
908
    else if (coeff_index < 63)
909
        s->dct_tokens[0][coeff_index+1] = dct_tokens + j;
910

    
911
    return eob_run;
912
}
913

    
914
static void reverse_dc_prediction(Vp3DecodeContext *s,
915
                                  int first_fragment,
916
                                  int fragment_width,
917
                                  int fragment_height);
918
/*
919
 * This function unpacks all of the DCT coefficient data from the
920
 * bitstream.
921
 */
922
static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
923
{
924
    int i;
925
    int dc_y_table;
926
    int dc_c_table;
927
    int ac_y_table;
928
    int ac_c_table;
929
    int residual_eob_run = 0;
930
    VLC *y_tables[64];
931
    VLC *c_tables[64];
932

    
933
    s->dct_tokens[0][0] = s->dct_tokens_base;
934

    
935
    /* fetch the DC table indexes */
936
    dc_y_table = get_bits(gb, 4);
937
    dc_c_table = get_bits(gb, 4);
938

    
939
    /* unpack the Y plane DC coefficients */
940
    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
941
        0, residual_eob_run);
942

    
943
    /* reverse prediction of the Y-plane DC coefficients */
944
    reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
945

    
946
    /* unpack the C plane DC coefficients */
947
    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
948
        1, residual_eob_run);
949
    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
950
        2, residual_eob_run);
951

    
952
    /* reverse prediction of the C-plane DC coefficients */
953
    if (!(s->avctx->flags & CODEC_FLAG_GRAY))
954
    {
955
        reverse_dc_prediction(s, s->fragment_start[1],
956
            s->fragment_width[1], s->fragment_height[1]);
957
        reverse_dc_prediction(s, s->fragment_start[2],
958
            s->fragment_width[1], s->fragment_height[1]);
959
    }
960

    
961
    /* fetch the AC table indexes */
962
    ac_y_table = get_bits(gb, 4);
963
    ac_c_table = get_bits(gb, 4);
964

    
965
    /* build tables of AC VLC tables */
966
    for (i = 1; i <= 5; i++) {
967
        y_tables[i] = &s->ac_vlc_1[ac_y_table];
968
        c_tables[i] = &s->ac_vlc_1[ac_c_table];
969
    }
970
    for (i = 6; i <= 14; i++) {
971
        y_tables[i] = &s->ac_vlc_2[ac_y_table];
972
        c_tables[i] = &s->ac_vlc_2[ac_c_table];
973
    }
974
    for (i = 15; i <= 27; i++) {
975
        y_tables[i] = &s->ac_vlc_3[ac_y_table];
976
        c_tables[i] = &s->ac_vlc_3[ac_c_table];
977
    }
978
    for (i = 28; i <= 63; i++) {
979
        y_tables[i] = &s->ac_vlc_4[ac_y_table];
980
        c_tables[i] = &s->ac_vlc_4[ac_c_table];
981
    }
982

    
983
    /* decode all AC coefficents */
984
    for (i = 1; i <= 63; i++) {
985
            residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
986
                0, residual_eob_run);
987

    
988
            residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
989
                1, residual_eob_run);
990
            residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
991
                2, residual_eob_run);
992
    }
993

    
994
    return 0;
995
}
996

    
997
/*
998
 * This function reverses the DC prediction for each coded fragment in
999
 * the frame. Much of this function is adapted directly from the original
1000
 * VP3 source code.
1001
 */
1002
#define COMPATIBLE_FRAME(x) \
1003
  (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1004
#define DC_COEFF(u) s->all_fragments[u].dc
1005

    
1006
static void reverse_dc_prediction(Vp3DecodeContext *s,
1007
                                  int first_fragment,
1008
                                  int fragment_width,
1009
                                  int fragment_height)
1010
{
1011

    
1012
#define PUL 8
1013
#define PU 4
1014
#define PUR 2
1015
#define PL 1
1016

    
1017
    int x, y;
1018
    int i = first_fragment;
1019

    
1020
    int predicted_dc;
1021

    
1022
    /* DC values for the left, up-left, up, and up-right fragments */
1023
    int vl, vul, vu, vur;
1024

    
1025
    /* indexes for the left, up-left, up, and up-right fragments */
1026
    int l, ul, u, ur;
1027

    
1028
    /*
1029
     * The 6 fields mean:
1030
     *   0: up-left multiplier
1031
     *   1: up multiplier
1032
     *   2: up-right multiplier
1033
     *   3: left multiplier
1034
     */
1035
    static const int predictor_transform[16][4] = {
1036
        {  0,  0,  0,  0},
1037
        {  0,  0,  0,128},        // PL
1038
        {  0,  0,128,  0},        // PUR
1039
        {  0,  0, 53, 75},        // PUR|PL
1040
        {  0,128,  0,  0},        // PU
1041
        {  0, 64,  0, 64},        // PU|PL
1042
        {  0,128,  0,  0},        // PU|PUR
1043
        {  0,  0, 53, 75},        // PU|PUR|PL
1044
        {128,  0,  0,  0},        // PUL
1045
        {  0,  0,  0,128},        // PUL|PL
1046
        { 64,  0, 64,  0},        // PUL|PUR
1047
        {  0,  0, 53, 75},        // PUL|PUR|PL
1048
        {  0,128,  0,  0},        // PUL|PU
1049
       {-104,116,  0,116},        // PUL|PU|PL
1050
        { 24, 80, 24,  0},        // PUL|PU|PUR
1051
       {-104,116,  0,116}         // PUL|PU|PUR|PL
1052
    };
1053

    
1054
    /* This table shows which types of blocks can use other blocks for
1055
     * prediction. For example, INTRA is the only mode in this table to
1056
     * have a frame number of 0. That means INTRA blocks can only predict
1057
     * from other INTRA blocks. There are 2 golden frame coding types;
1058
     * blocks encoding in these modes can only predict from other blocks
1059
     * that were encoded with these 1 of these 2 modes. */
1060
    static const unsigned char compatible_frame[9] = {
1061
        1,    /* MODE_INTER_NO_MV */
1062
        0,    /* MODE_INTRA */
1063
        1,    /* MODE_INTER_PLUS_MV */
1064
        1,    /* MODE_INTER_LAST_MV */
1065
        1,    /* MODE_INTER_PRIOR_MV */
1066
        2,    /* MODE_USING_GOLDEN */
1067
        2,    /* MODE_GOLDEN_MV */
1068
        1,    /* MODE_INTER_FOUR_MV */
1069
        3     /* MODE_COPY */
1070
    };
1071
    int current_frame_type;
1072

    
1073
    /* there is a last DC predictor for each of the 3 frame types */
1074
    short last_dc[3];
1075

    
1076
    int transform = 0;
1077

    
1078
    vul = vu = vur = vl = 0;
1079
    last_dc[0] = last_dc[1] = last_dc[2] = 0;
1080

    
1081
    /* for each fragment row... */
1082
    for (y = 0; y < fragment_height; y++) {
1083

    
1084
        /* for each fragment in a row... */
1085
        for (x = 0; x < fragment_width; x++, i++) {
1086

    
1087
            /* reverse prediction if this block was coded */
1088
            if (s->all_fragments[i].coding_method != MODE_COPY) {
1089

    
1090
                current_frame_type =
1091
                    compatible_frame[s->all_fragments[i].coding_method];
1092

    
1093
                transform= 0;
1094
                if(x){
1095
                    l= i-1;
1096
                    vl = DC_COEFF(l);
1097
                    if(COMPATIBLE_FRAME(l))
1098
                        transform |= PL;
1099
                }
1100
                if(y){
1101
                    u= i-fragment_width;
1102
                    vu = DC_COEFF(u);
1103
                    if(COMPATIBLE_FRAME(u))
1104
                        transform |= PU;
1105
                    if(x){
1106
                        ul= i-fragment_width-1;
1107
                        vul = DC_COEFF(ul);
1108
                        if(COMPATIBLE_FRAME(ul))
1109
                            transform |= PUL;
1110
                    }
1111
                    if(x + 1 < fragment_width){
1112
                        ur= i-fragment_width+1;
1113
                        vur = DC_COEFF(ur);
1114
                        if(COMPATIBLE_FRAME(ur))
1115
                            transform |= PUR;
1116
                    }
1117
                }
1118

    
1119
                if (transform == 0) {
1120

    
1121
                    /* if there were no fragments to predict from, use last
1122
                     * DC saved */
1123
                    predicted_dc = last_dc[current_frame_type];
1124
                } else {
1125

    
1126
                    /* apply the appropriate predictor transform */
1127
                    predicted_dc =
1128
                        (predictor_transform[transform][0] * vul) +
1129
                        (predictor_transform[transform][1] * vu) +
1130
                        (predictor_transform[transform][2] * vur) +
1131
                        (predictor_transform[transform][3] * vl);
1132

    
1133
                    predicted_dc /= 128;
1134

    
1135
                    /* check for outranging on the [ul u l] and
1136
                     * [ul u ur l] predictors */
1137
                    if ((transform == 15) || (transform == 13)) {
1138
                        if (FFABS(predicted_dc - vu) > 128)
1139
                            predicted_dc = vu;
1140
                        else if (FFABS(predicted_dc - vl) > 128)
1141
                            predicted_dc = vl;
1142
                        else if (FFABS(predicted_dc - vul) > 128)
1143
                            predicted_dc = vul;
1144
                    }
1145
                }
1146

    
1147
                /* at long last, apply the predictor */
1148
                DC_COEFF(i) += predicted_dc;
1149
                /* save the DC */
1150
                last_dc[current_frame_type] = DC_COEFF(i);
1151
            }
1152
        }
1153
    }
1154
}
1155

    
1156
static void apply_loop_filter(Vp3DecodeContext *s, int plane, int ystart, int yend)
1157
{
1158
    int x, y;
1159
    int *bounding_values= s->bounding_values_array+127;
1160

    
1161
    int width           = s->fragment_width[!!plane];
1162
    int height          = s->fragment_height[!!plane];
1163
    int fragment        = s->fragment_start        [plane] + ystart * width;
1164
    int stride          = s->current_frame.linesize[plane];
1165
    uint8_t *plane_data = s->current_frame.data    [plane];
1166
    if (!s->flipped_image) stride = -stride;
1167
    plane_data += s->data_offset[plane] + 8*ystart*stride;
1168

    
1169
    for (y = ystart; y < yend; y++) {
1170

    
1171
        for (x = 0; x < width; x++) {
1172
            /* This code basically just deblocks on the edges of coded blocks.
1173
             * However, it has to be much more complicated because of the
1174
             * braindamaged deblock ordering used in VP3/Theora. Order matters
1175
             * because some pixels get filtered twice. */
1176
            if( s->all_fragments[fragment].coding_method != MODE_COPY )
1177
            {
1178
                /* do not perform left edge filter for left columns frags */
1179
                if (x > 0) {
1180
                    s->dsp.vp3_h_loop_filter(
1181
                        plane_data + 8*x,
1182
                        stride, bounding_values);
1183
                }
1184

    
1185
                /* do not perform top edge filter for top row fragments */
1186
                if (y > 0) {
1187
                    s->dsp.vp3_v_loop_filter(
1188
                        plane_data + 8*x,
1189
                        stride, bounding_values);
1190
                }
1191

    
1192
                /* do not perform right edge filter for right column
1193
                 * fragments or if right fragment neighbor is also coded
1194
                 * in this frame (it will be filtered in next iteration) */
1195
                if ((x < width - 1) &&
1196
                    (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1197
                    s->dsp.vp3_h_loop_filter(
1198
                        plane_data + 8*x + 8,
1199
                        stride, bounding_values);
1200
                }
1201

    
1202
                /* do not perform bottom edge filter for bottom row
1203
                 * fragments or if bottom fragment neighbor is also coded
1204
                 * in this frame (it will be filtered in the next row) */
1205
                if ((y < height - 1) &&
1206
                    (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1207
                    s->dsp.vp3_v_loop_filter(
1208
                        plane_data + 8*x + 8*stride,
1209
                        stride, bounding_values);
1210
                }
1211
            }
1212

    
1213
            fragment++;
1214
        }
1215
        plane_data += 8*stride;
1216
    }
1217
}
1218

    
1219
/**
1220
 * Pulls DCT tokens from the 64 levels to decode and dequant the coefficients
1221
 * for the next block in coding order
1222
 */
1223
static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1224
                              int plane, int inter, DCTELEM block[64])
1225
{
1226
    int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1227
    uint8_t *perm = s->scantable.permutated;
1228
    int i = 0;
1229

    
1230
    do {
1231
        int token = *s->dct_tokens[plane][i];
1232
        switch (token & 3) {
1233
        case 0: // EOB
1234
            if (--token < 4) // 0-3 are token types, so the EOB run must now be 0
1235
                s->dct_tokens[plane][i]++;
1236
            else
1237
                *s->dct_tokens[plane][i] = token & ~3;
1238
            goto end;
1239
        case 1: // zero run
1240
            s->dct_tokens[plane][i]++;
1241
            i += (token >> 2) & 0x7f;
1242
            block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1243
            i++;
1244
            break;
1245
        case 2: // coeff
1246
            block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1247
            s->dct_tokens[plane][i++]++;
1248
            break;
1249
        default:
1250
            av_log(s->avctx, AV_LOG_ERROR, "internal: invalid token type\n");
1251
            return i;
1252
        }
1253
    } while (i < 64);
1254
end:
1255
    // the actual DC+prediction is in the fragment structure
1256
    block[0] = frag->dc * s->qmat[0][inter][plane][0];
1257
    return i;
1258
}
1259

    
1260
/**
1261
 * called when all pixels up to row y are complete
1262
 */
1263
static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1264
{
1265
    int h, cy;
1266
    int offset[4];
1267

    
1268
    if(s->avctx->draw_horiz_band==NULL)
1269
        return;
1270

    
1271
    h= y - s->last_slice_end;
1272
    y -= h;
1273

    
1274
    if (!s->flipped_image) {
1275
        if (y == 0)
1276
            h -= s->height - s->avctx->height;  // account for non-mod16
1277
        y = s->height - y - h;
1278
    }
1279

    
1280
    cy = y >> 1;
1281
    offset[0] = s->current_frame.linesize[0]*y;
1282
    offset[1] = s->current_frame.linesize[1]*cy;
1283
    offset[2] = s->current_frame.linesize[2]*cy;
1284
    offset[3] = 0;
1285

    
1286
    emms_c();
1287
    s->avctx->draw_horiz_band(s->avctx, &s->current_frame, offset, y, 3, h);
1288
    s->last_slice_end= y + h;
1289
}
1290

    
1291
/*
1292
 * Perform the final rendering for a particular slice of data.
1293
 * The slice number ranges from 0..(c_superblock_height - 1).
1294
 */
1295
static void render_slice(Vp3DecodeContext *s, int slice)
1296
{
1297
    int x, y, i, j;
1298
    LOCAL_ALIGNED_16(DCTELEM, block, [64]);
1299
    int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
1300
    int motion_halfpel_index;
1301
    uint8_t *motion_source;
1302
    int plane, first_pixel;
1303

    
1304
    if (slice >= s->c_superblock_height)
1305
        return;
1306

    
1307
    for (plane = 0; plane < 3; plane++) {
1308
        uint8_t *output_plane = s->current_frame.data    [plane] + s->data_offset[plane];
1309
        uint8_t *  last_plane = s->   last_frame.data    [plane] + s->data_offset[plane];
1310
        uint8_t *golden_plane = s-> golden_frame.data    [plane] + s->data_offset[plane];
1311
        int stride            = s->current_frame.linesize[plane];
1312
        int plane_width       = s->width  >> !!plane;
1313
        int plane_height      = s->height >> !!plane;
1314

    
1315
        int sb_x, sb_y        = slice << !plane;
1316
        int slice_height      = sb_y + (plane ? 1 : 2);
1317
        int slice_width       = plane ? s->c_superblock_width : s->y_superblock_width;
1318

    
1319
        int fragment_width    = s->fragment_width[!!plane];
1320
        int fragment_height   = s->fragment_height[!!plane];
1321
        int fragment_start    = s->fragment_start[plane];
1322

    
1323
        if (!s->flipped_image) stride = -stride;
1324
        if (CONFIG_GRAY && plane && (s->avctx->flags & CODEC_FLAG_GRAY))
1325
            continue;
1326

    
1327

    
1328
        if(FFABS(stride) > 2048)
1329
            return; //various tables are fixed size
1330

    
1331
        /* for each superblock row in the slice (both of them)... */
1332
        for (; sb_y < slice_height; sb_y++) {
1333

    
1334
            /* for each superblock in a row... */
1335
            for (sb_x = 0; sb_x < slice_width; sb_x++) {
1336

    
1337
                /* for each block in a superblock... */
1338
                for (j = 0; j < 16; j++) {
1339
                    x = 4*sb_x + hilbert_offset[j][0];
1340
                    y = 4*sb_y + hilbert_offset[j][1];
1341

    
1342
                    i = fragment_start + y*fragment_width + x;
1343

    
1344
                    // bounds check
1345
                    if (x >= fragment_width || y >= fragment_height)
1346
                        continue;
1347

    
1348
                first_pixel = 8*y*stride + 8*x;
1349

    
1350
                /* transform if this block was coded */
1351
                if (s->all_fragments[i].coding_method != MODE_COPY) {
1352
                    int intra = s->all_fragments[i].coding_method == MODE_INTRA;
1353

    
1354
                    if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
1355
                        (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
1356
                        motion_source= golden_plane;
1357
                    else
1358
                        motion_source= last_plane;
1359

    
1360
                    motion_source += first_pixel;
1361
                    motion_halfpel_index = 0;
1362

    
1363
                    /* sort out the motion vector if this fragment is coded
1364
                     * using a motion vector method */
1365
                    if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
1366
                        (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
1367
                        int src_x, src_y;
1368
                        motion_x = s->all_fragments[i].motion_x;
1369
                        motion_y = s->all_fragments[i].motion_y;
1370
                        if(plane){
1371
                            motion_x= (motion_x>>1) | (motion_x&1);
1372
                            motion_y= (motion_y>>1) | (motion_y&1);
1373
                        }
1374

    
1375
                        src_x= (motion_x>>1) + 8*x;
1376
                        src_y= (motion_y>>1) + 8*y;
1377

    
1378
                        motion_halfpel_index = motion_x & 0x01;
1379
                        motion_source += (motion_x >> 1);
1380

    
1381
                        motion_halfpel_index |= (motion_y & 0x01) << 1;
1382
                        motion_source += ((motion_y >> 1) * stride);
1383

    
1384
                        if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){
1385
                            uint8_t *temp= s->edge_emu_buffer;
1386
                            if(stride<0) temp -= 9*stride;
1387
                            else temp += 9*stride;
1388

    
1389
                            ff_emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);
1390
                            motion_source= temp;
1391
                        }
1392
                    }
1393

    
1394

    
1395
                    /* first, take care of copying a block from either the
1396
                     * previous or the golden frame */
1397
                    if (s->all_fragments[i].coding_method != MODE_INTRA) {
1398
                        /* Note, it is possible to implement all MC cases with
1399
                           put_no_rnd_pixels_l2 which would look more like the
1400
                           VP3 source but this would be slower as
1401
                           put_no_rnd_pixels_tab is better optimzed */
1402
                        if(motion_halfpel_index != 3){
1403
                            s->dsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
1404
                                output_plane + first_pixel,
1405
                                motion_source, stride, 8);
1406
                        }else{
1407
                            int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1
1408
                            s->dsp.put_no_rnd_pixels_l2[1](
1409
                                output_plane + first_pixel,
1410
                                motion_source - d,
1411
                                motion_source + stride + 1 + d,
1412
                                stride, 8);
1413
                        }
1414
                    }
1415

    
1416
                        s->dsp.clear_block(block);
1417
                        vp3_dequant(s, s->all_fragments + i, plane, !intra, block);
1418

    
1419
                    /* invert DCT and place (or add) in final output */
1420

    
1421
                    if (s->all_fragments[i].coding_method == MODE_INTRA) {
1422
                        if(s->avctx->idct_algo!=FF_IDCT_VP3)
1423
                            block[0] += 128<<3;
1424
                        s->dsp.idct_put(
1425
                            output_plane + first_pixel,
1426
                            stride,
1427
                            block);
1428
                    } else {
1429
                        s->dsp.idct_add(
1430
                            output_plane + first_pixel,
1431
                            stride,
1432
                            block);
1433
                    }
1434
                } else {
1435

    
1436
                    /* copy directly from the previous frame */
1437
                    s->dsp.put_pixels_tab[1][0](
1438
                        output_plane + first_pixel,
1439
                        last_plane + first_pixel,
1440
                        stride, 8);
1441

    
1442
                }
1443
                }
1444
            }
1445

    
1446
            // Filter up to the last row in the superblock row
1447
            apply_loop_filter(s, plane, 4*sb_y - !!sb_y, FFMIN(4*sb_y+3, fragment_height-1));
1448
        }
1449
    }
1450

    
1451
     /* this looks like a good place for slice dispatch... */
1452
     /* algorithm:
1453
      *   if (slice == s->macroblock_height - 1)
1454
      *     dispatch (both last slice & 2nd-to-last slice);
1455
      *   else if (slice > 0)
1456
      *     dispatch (slice - 1);
1457
      */
1458

    
1459
    vp3_draw_horiz_band(s, FFMIN(64*slice + 64-16, s->height-16));
1460
}
1461

    
1462
/*
1463
 * This is the ffmpeg/libavcodec API init function.
1464
 */
1465
static av_cold int vp3_decode_init(AVCodecContext *avctx)
1466
{
1467
    Vp3DecodeContext *s = avctx->priv_data;
1468
    int i, inter, plane;
1469
    int c_width;
1470
    int c_height;
1471

    
1472
    if (avctx->codec_tag == MKTAG('V','P','3','0'))
1473
        s->version = 0;
1474
    else
1475
        s->version = 1;
1476

    
1477
    s->avctx = avctx;
1478
    s->width = FFALIGN(avctx->width, 16);
1479
    s->height = FFALIGN(avctx->height, 16);
1480
    avctx->pix_fmt = PIX_FMT_YUV420P;
1481
    avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1482
    if(avctx->idct_algo==FF_IDCT_AUTO)
1483
        avctx->idct_algo=FF_IDCT_VP3;
1484
    dsputil_init(&s->dsp, avctx);
1485

    
1486
    ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
1487

    
1488
    /* initialize to an impossible value which will force a recalculation
1489
     * in the first frame decode */
1490
    for (i = 0; i < 3; i++)
1491
        s->qps[i] = -1;
1492

    
1493
    s->y_superblock_width = (s->width + 31) / 32;
1494
    s->y_superblock_height = (s->height + 31) / 32;
1495
    s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
1496

    
1497
    /* work out the dimensions for the C planes */
1498
    c_width = s->width / 2;
1499
    c_height = s->height / 2;
1500
    s->c_superblock_width = (c_width + 31) / 32;
1501
    s->c_superblock_height = (c_height + 31) / 32;
1502
    s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
1503

    
1504
    s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
1505
    s->u_superblock_start = s->y_superblock_count;
1506
    s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
1507
    s->superblock_coding = av_malloc(s->superblock_count);
1508

    
1509
    s->macroblock_width = (s->width + 15) / 16;
1510
    s->macroblock_height = (s->height + 15) / 16;
1511
    s->macroblock_count = s->macroblock_width * s->macroblock_height;
1512

    
1513
    s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
1514
    s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
1515
    s->fragment_width[1]  = s->fragment_width[0]  >> 1;
1516
    s->fragment_height[1] = s->fragment_height[0] >> 1;
1517

    
1518
    /* fragment count covers all 8x8 blocks for all 3 planes */
1519
    s->fragment_count = s->fragment_width[0] * s->fragment_height[0] * 3 / 2;
1520
    s->fragment_start[1] = s->fragment_width[0] * s->fragment_height[0];
1521
    s->fragment_start[2] = s->fragment_width[0] * s->fragment_height[0] * 5 / 4;
1522

    
1523
    s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));
1524
    s->coded_fragment_list[0] = av_malloc(s->fragment_count * sizeof(int));
1525
    s->dct_tokens_base = av_malloc(64*s->fragment_count * sizeof(*s->dct_tokens_base));
1526
    if (!s->superblock_coding || !s->all_fragments || !s->dct_tokens_base ||
1527
        !s->coded_fragment_list[0]) {
1528
        vp3_decode_end(avctx);
1529
        return -1;
1530
    }
1531

    
1532
    if (!s->theora_tables)
1533
    {
1534
        for (i = 0; i < 64; i++) {
1535
            s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
1536
            s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
1537
            s->base_matrix[0][i] = vp31_intra_y_dequant[i];
1538
            s->base_matrix[1][i] = vp31_intra_c_dequant[i];
1539
            s->base_matrix[2][i] = vp31_inter_dequant[i];
1540
            s->filter_limit_values[i] = vp31_filter_limit_values[i];
1541
        }
1542

    
1543
        for(inter=0; inter<2; inter++){
1544
            for(plane=0; plane<3; plane++){
1545
                s->qr_count[inter][plane]= 1;
1546
                s->qr_size [inter][plane][0]= 63;
1547
                s->qr_base [inter][plane][0]=
1548
                s->qr_base [inter][plane][1]= 2*inter + (!!plane)*!inter;
1549
            }
1550
        }
1551

    
1552
        /* init VLC tables */
1553
        for (i = 0; i < 16; i++) {
1554

    
1555
            /* DC histograms */
1556
            init_vlc(&s->dc_vlc[i], 5, 32,
1557
                &dc_bias[i][0][1], 4, 2,
1558
                &dc_bias[i][0][0], 4, 2, 0);
1559

    
1560
            /* group 1 AC histograms */
1561
            init_vlc(&s->ac_vlc_1[i], 5, 32,
1562
                &ac_bias_0[i][0][1], 4, 2,
1563
                &ac_bias_0[i][0][0], 4, 2, 0);
1564

    
1565
            /* group 2 AC histograms */
1566
            init_vlc(&s->ac_vlc_2[i], 5, 32,
1567
                &ac_bias_1[i][0][1], 4, 2,
1568
                &ac_bias_1[i][0][0], 4, 2, 0);
1569

    
1570
            /* group 3 AC histograms */
1571
            init_vlc(&s->ac_vlc_3[i], 5, 32,
1572
                &ac_bias_2[i][0][1], 4, 2,
1573
                &ac_bias_2[i][0][0], 4, 2, 0);
1574

    
1575
            /* group 4 AC histograms */
1576
            init_vlc(&s->ac_vlc_4[i], 5, 32,
1577
                &ac_bias_3[i][0][1], 4, 2,
1578
                &ac_bias_3[i][0][0], 4, 2, 0);
1579
        }
1580
    } else {
1581
        for (i = 0; i < 16; i++) {
1582

    
1583
            /* DC histograms */
1584
            if (init_vlc(&s->dc_vlc[i], 5, 32,
1585
                &s->huffman_table[i][0][1], 4, 2,
1586
                &s->huffman_table[i][0][0], 4, 2, 0) < 0)
1587
                goto vlc_fail;
1588

    
1589
            /* group 1 AC histograms */
1590
            if (init_vlc(&s->ac_vlc_1[i], 5, 32,
1591
                &s->huffman_table[i+16][0][1], 4, 2,
1592
                &s->huffman_table[i+16][0][0], 4, 2, 0) < 0)
1593
                goto vlc_fail;
1594

    
1595
            /* group 2 AC histograms */
1596
            if (init_vlc(&s->ac_vlc_2[i], 5, 32,
1597
                &s->huffman_table[i+16*2][0][1], 4, 2,
1598
                &s->huffman_table[i+16*2][0][0], 4, 2, 0) < 0)
1599
                goto vlc_fail;
1600

    
1601
            /* group 3 AC histograms */
1602
            if (init_vlc(&s->ac_vlc_3[i], 5, 32,
1603
                &s->huffman_table[i+16*3][0][1], 4, 2,
1604
                &s->huffman_table[i+16*3][0][0], 4, 2, 0) < 0)
1605
                goto vlc_fail;
1606

    
1607
            /* group 4 AC histograms */
1608
            if (init_vlc(&s->ac_vlc_4[i], 5, 32,
1609
                &s->huffman_table[i+16*4][0][1], 4, 2,
1610
                &s->huffman_table[i+16*4][0][0], 4, 2, 0) < 0)
1611
                goto vlc_fail;
1612
        }
1613
    }
1614

    
1615
    init_vlc(&s->superblock_run_length_vlc, 6, 34,
1616
        &superblock_run_length_vlc_table[0][1], 4, 2,
1617
        &superblock_run_length_vlc_table[0][0], 4, 2, 0);
1618

    
1619
    init_vlc(&s->fragment_run_length_vlc, 5, 30,
1620
        &fragment_run_length_vlc_table[0][1], 4, 2,
1621
        &fragment_run_length_vlc_table[0][0], 4, 2, 0);
1622

    
1623
    init_vlc(&s->mode_code_vlc, 3, 8,
1624
        &mode_code_vlc_table[0][1], 2, 1,
1625
        &mode_code_vlc_table[0][0], 2, 1, 0);
1626

    
1627
    init_vlc(&s->motion_vector_vlc, 6, 63,
1628
        &motion_vector_vlc_table[0][1], 2, 1,
1629
        &motion_vector_vlc_table[0][0], 2, 1, 0);
1630

    
1631
    /* work out the block mapping tables */
1632
    s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));
1633
    s->macroblock_coding = av_malloc(s->macroblock_count + 1);
1634
    if (!s->superblock_fragments || !s->macroblock_coding) {
1635
        vp3_decode_end(avctx);
1636
        return -1;
1637
    }
1638
    init_block_mapping(s);
1639

    
1640
    for (i = 0; i < 3; i++) {
1641
        s->current_frame.data[i] = NULL;
1642
        s->last_frame.data[i] = NULL;
1643
        s->golden_frame.data[i] = NULL;
1644
    }
1645

    
1646
    return 0;
1647

    
1648
vlc_fail:
1649
    av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
1650
    return -1;
1651
}
1652

    
1653
/*
1654
 * This is the ffmpeg/libavcodec API frame decode function.
1655
 */
1656
static int vp3_decode_frame(AVCodecContext *avctx,
1657
                            void *data, int *data_size,
1658
                            AVPacket *avpkt)
1659
{
1660
    const uint8_t *buf = avpkt->data;
1661
    int buf_size = avpkt->size;
1662
    Vp3DecodeContext *s = avctx->priv_data;
1663
    GetBitContext gb;
1664
    static int counter = 0;
1665
    int i;
1666

    
1667
    init_get_bits(&gb, buf, buf_size * 8);
1668

    
1669
    if (s->theora && get_bits1(&gb))
1670
    {
1671
        av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");
1672
        return -1;
1673
    }
1674

    
1675
    s->keyframe = !get_bits1(&gb);
1676
    if (!s->theora)
1677
        skip_bits(&gb, 1);
1678
    for (i = 0; i < 3; i++)
1679
        s->last_qps[i] = s->qps[i];
1680

    
1681
    s->nqps=0;
1682
    do{
1683
        s->qps[s->nqps++]= get_bits(&gb, 6);
1684
    } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));
1685
    for (i = s->nqps; i < 3; i++)
1686
        s->qps[i] = -1;
1687

    
1688
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1689
        av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
1690
            s->keyframe?"key":"", counter, s->qps[0]);
1691
    counter++;
1692

    
1693
    if (s->qps[0] != s->last_qps[0])
1694
        init_loop_filter(s);
1695

    
1696
    for (i = 0; i < s->nqps; i++)
1697
        // reinit all dequantizers if the first one changed, because
1698
        // the DC of the first quantizer must be used for all matrices
1699
        if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
1700
            init_dequantizer(s, i);
1701

    
1702
    if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
1703
        return buf_size;
1704

    
1705
    s->current_frame.reference = 3;
1706
    s->current_frame.pict_type = s->keyframe ? FF_I_TYPE : FF_P_TYPE;
1707
    if (avctx->get_buffer(avctx, &s->current_frame) < 0) {
1708
        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1709
        goto error;
1710
    }
1711

    
1712
    if (s->keyframe) {
1713
        if (!s->theora)
1714
        {
1715
            skip_bits(&gb, 4); /* width code */
1716
            skip_bits(&gb, 4); /* height code */
1717
            if (s->version)
1718
            {
1719
                s->version = get_bits(&gb, 5);
1720
                if (counter == 1)
1721
                    av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);
1722
            }
1723
        }
1724
        if (s->version || s->theora)
1725
        {
1726
                if (get_bits1(&gb))
1727
                    av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");
1728
            skip_bits(&gb, 2); /* reserved? */
1729
        }
1730
    } else {
1731
        if (!s->golden_frame.data[0]) {
1732
            av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");
1733

    
1734
            s->golden_frame.reference = 3;
1735
            s->golden_frame.pict_type = FF_I_TYPE;
1736
            if (avctx->get_buffer(avctx, &s->golden_frame) < 0) {
1737
                av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1738
                goto error;
1739
            }
1740
            s->last_frame = s->golden_frame;
1741
            s->last_frame.type = FF_BUFFER_TYPE_COPY;
1742
        }
1743
    }
1744

    
1745
    s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame
1746
    s->current_frame.qstride= 0;
1747

    
1748
    memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
1749

    
1750
    if (unpack_superblocks(s, &gb)){
1751
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
1752
        goto error;
1753
    }
1754
    if (unpack_modes(s, &gb)){
1755
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
1756
        goto error;
1757
    }
1758
    if (unpack_vectors(s, &gb)){
1759
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
1760
        goto error;
1761
    }
1762
    if (unpack_block_qpis(s, &gb)){
1763
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
1764
        goto error;
1765
    }
1766
    if (unpack_dct_coeffs(s, &gb)){
1767
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
1768
        goto error;
1769
    }
1770

    
1771
    for (i = 0; i < 3; i++) {
1772
        if (s->flipped_image)
1773
            s->data_offset[i] = 0;
1774
        else
1775
            s->data_offset[i] = ((s->height>>!!i)-1) * s->current_frame.linesize[i];
1776
    }
1777

    
1778
    s->last_slice_end = 0;
1779
    for (i = 0; i < s->c_superblock_height; i++)
1780
        render_slice(s, i);
1781

    
1782
    // filter the last row
1783
    for (i = 0; i < 3; i++) {
1784
        int row = (s->height >> (3+!!i)) - 1;
1785
        apply_loop_filter(s, i, row, row+1);
1786
    }
1787
    vp3_draw_horiz_band(s, s->height);
1788

    
1789
    *data_size=sizeof(AVFrame);
1790
    *(AVFrame*)data= s->current_frame;
1791

    
1792
    /* release the last frame, if it is allocated and if it is not the
1793
     * golden frame */
1794
    if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
1795
        avctx->release_buffer(avctx, &s->last_frame);
1796

    
1797
    /* shuffle frames (last = current) */
1798
    s->last_frame= s->current_frame;
1799

    
1800
    if (s->keyframe) {
1801
        if (s->golden_frame.data[0])
1802
            avctx->release_buffer(avctx, &s->golden_frame);
1803
        s->golden_frame = s->current_frame;
1804
        s->last_frame.type = FF_BUFFER_TYPE_COPY;
1805
    }
1806

    
1807
    s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */
1808

    
1809
    return buf_size;
1810

    
1811
error:
1812
    if (s->current_frame.data[0])
1813
        avctx->release_buffer(avctx, &s->current_frame);
1814
    return -1;
1815
}
1816

    
1817
/*
1818
 * This is the ffmpeg/libavcodec API module cleanup function.
1819
 */
1820
static av_cold int vp3_decode_end(AVCodecContext *avctx)
1821
{
1822
    Vp3DecodeContext *s = avctx->priv_data;
1823
    int i;
1824

    
1825
    av_free(s->superblock_coding);
1826
    av_free(s->all_fragments);
1827
    av_free(s->coded_fragment_list[0]);
1828
    av_free(s->dct_tokens_base);
1829
    av_free(s->superblock_fragments);
1830
    av_free(s->macroblock_coding);
1831

    
1832
    for (i = 0; i < 16; i++) {
1833
        free_vlc(&s->dc_vlc[i]);
1834
        free_vlc(&s->ac_vlc_1[i]);
1835
        free_vlc(&s->ac_vlc_2[i]);
1836
        free_vlc(&s->ac_vlc_3[i]);
1837
        free_vlc(&s->ac_vlc_4[i]);
1838
    }
1839

    
1840
    free_vlc(&s->superblock_run_length_vlc);
1841
    free_vlc(&s->fragment_run_length_vlc);
1842
    free_vlc(&s->mode_code_vlc);
1843
    free_vlc(&s->motion_vector_vlc);
1844

    
1845
    /* release all frames */
1846
    if (s->golden_frame.data[0])
1847
        avctx->release_buffer(avctx, &s->golden_frame);
1848
    if (s->last_frame.data[0] && s->last_frame.type != FF_BUFFER_TYPE_COPY)
1849
        avctx->release_buffer(avctx, &s->last_frame);
1850
    /* no need to release the current_frame since it will always be pointing
1851
     * to the same frame as either the golden or last frame */
1852

    
1853
    return 0;
1854
}
1855

    
1856
static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
1857
{
1858
    Vp3DecodeContext *s = avctx->priv_data;
1859

    
1860
    if (get_bits1(gb)) {
1861
        int token;
1862
        if (s->entries >= 32) { /* overflow */
1863
            av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1864
            return -1;
1865
        }
1866
        token = get_bits(gb, 5);
1867
        //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);
1868
        s->huffman_table[s->hti][token][0] = s->hbits;
1869
        s->huffman_table[s->hti][token][1] = s->huff_code_size;
1870
        s->entries++;
1871
    }
1872
    else {
1873
        if (s->huff_code_size >= 32) {/* overflow */
1874
            av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
1875
            return -1;
1876
        }
1877
        s->huff_code_size++;
1878
        s->hbits <<= 1;
1879
        if (read_huffman_tree(avctx, gb))
1880
            return -1;
1881
        s->hbits |= 1;
1882
        if (read_huffman_tree(avctx, gb))
1883
            return -1;
1884
        s->hbits >>= 1;
1885
        s->huff_code_size--;
1886
    }
1887
    return 0;
1888
}
1889

    
1890
#if CONFIG_THEORA_DECODER
1891
static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
1892
{
1893
    Vp3DecodeContext *s = avctx->priv_data;
1894
    int visible_width, visible_height, colorspace;
1895

    
1896
    s->theora = get_bits_long(gb, 24);
1897
    av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
1898

    
1899
    /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */
1900
    /* but previous versions have the image flipped relative to vp3 */
1901
    if (s->theora < 0x030200)
1902
    {
1903
        s->flipped_image = 1;
1904
        av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");
1905
    }
1906

    
1907
    visible_width  = s->width  = get_bits(gb, 16) << 4;
1908
    visible_height = s->height = get_bits(gb, 16) << 4;
1909

    
1910
    if(avcodec_check_dimensions(avctx, s->width, s->height)){
1911
        av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);
1912
        s->width= s->height= 0;
1913
        return -1;
1914
    }
1915

    
1916
    if (s->theora >= 0x030200) {
1917
        visible_width  = get_bits_long(gb, 24);
1918
        visible_height = get_bits_long(gb, 24);
1919

    
1920
        skip_bits(gb, 8); /* offset x */
1921
        skip_bits(gb, 8); /* offset y */
1922
    }
1923

    
1924
    skip_bits(gb, 32); /* fps numerator */
1925
    skip_bits(gb, 32); /* fps denumerator */
1926
    skip_bits(gb, 24); /* aspect numerator */
1927
    skip_bits(gb, 24); /* aspect denumerator */
1928

    
1929
    if (s->theora < 0x030200)
1930
        skip_bits(gb, 5); /* keyframe frequency force */
1931
    colorspace = get_bits(gb, 8);
1932
    skip_bits(gb, 24); /* bitrate */
1933

    
1934
    skip_bits(gb, 6); /* quality hint */
1935

    
1936
    if (s->theora >= 0x030200)
1937
    {
1938
        skip_bits(gb, 5); /* keyframe frequency force */
1939
        skip_bits(gb, 2); /* pixel format: 420,res,422,444 */
1940
        skip_bits(gb, 3); /* reserved */
1941
    }
1942

    
1943
//    align_get_bits(gb);
1944

    
1945
    if (   visible_width  <= s->width  && visible_width  > s->width-16
1946
        && visible_height <= s->height && visible_height > s->height-16)
1947
        avcodec_set_dimensions(avctx, visible_width, visible_height);
1948
    else
1949
        avcodec_set_dimensions(avctx, s->width, s->height);
1950

    
1951
    if (colorspace == 1) {
1952
        avctx->color_primaries = AVCOL_PRI_BT470M;
1953
    } else if (colorspace == 2) {
1954
        avctx->color_primaries = AVCOL_PRI_BT470BG;
1955
    }
1956
    if (colorspace == 1 || colorspace == 2) {
1957
        avctx->colorspace = AVCOL_SPC_BT470BG;
1958
        avctx->color_trc  = AVCOL_TRC_BT709;
1959
    }
1960

    
1961
    return 0;
1962
}
1963

    
1964
static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
1965
{
1966
    Vp3DecodeContext *s = avctx->priv_data;
1967
    int i, n, matrices, inter, plane;
1968

    
1969
    if (s->theora >= 0x030200) {
1970
        n = get_bits(gb, 3);
1971
        /* loop filter limit values table */
1972
        for (i = 0; i < 64; i++) {
1973
            s->filter_limit_values[i] = get_bits(gb, n);
1974
            if (s->filter_limit_values[i] > 127) {
1975
                av_log(avctx, AV_LOG_ERROR, "filter limit value too large (%i > 127), clamping\n", s->filter_limit_values[i]);
1976
                s->filter_limit_values[i] = 127;
1977
            }
1978
        }
1979
    }
1980

    
1981
    if (s->theora >= 0x030200)
1982
        n = get_bits(gb, 4) + 1;
1983
    else
1984
        n = 16;
1985
    /* quality threshold table */
1986
    for (i = 0; i < 64; i++)
1987
        s->coded_ac_scale_factor[i] = get_bits(gb, n);
1988

    
1989
    if (s->theora >= 0x030200)
1990
        n = get_bits(gb, 4) + 1;
1991
    else
1992
        n = 16;
1993
    /* dc scale factor table */
1994
    for (i = 0; i < 64; i++)
1995
        s->coded_dc_scale_factor[i] = get_bits(gb, n);
1996

    
1997
    if (s->theora >= 0x030200)
1998
        matrices = get_bits(gb, 9) + 1;
1999
    else
2000
        matrices = 3;
2001

    
2002
    if(matrices > 384){
2003
        av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
2004
        return -1;
2005
    }
2006

    
2007
    for(n=0; n<matrices; n++){
2008
        for (i = 0; i < 64; i++)
2009
            s->base_matrix[n][i]= get_bits(gb, 8);
2010
    }
2011

    
2012
    for (inter = 0; inter <= 1; inter++) {
2013
        for (plane = 0; plane <= 2; plane++) {
2014
            int newqr= 1;
2015
            if (inter || plane > 0)
2016
                newqr = get_bits1(gb);
2017
            if (!newqr) {
2018
                int qtj, plj;
2019
                if(inter && get_bits1(gb)){
2020
                    qtj = 0;
2021
                    plj = plane;
2022
                }else{
2023
                    qtj= (3*inter + plane - 1) / 3;
2024
                    plj= (plane + 2) % 3;
2025
                }
2026
                s->qr_count[inter][plane]= s->qr_count[qtj][plj];
2027
                memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj], sizeof(s->qr_size[0][0]));
2028
                memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj], sizeof(s->qr_base[0][0]));
2029
            } else {
2030
                int qri= 0;
2031
                int qi = 0;
2032

    
2033
                for(;;){
2034
                    i= get_bits(gb, av_log2(matrices-1)+1);
2035
                    if(i>= matrices){
2036
                        av_log(avctx, AV_LOG_ERROR, "invalid base matrix index\n");
2037
                        return -1;
2038
                    }
2039
                    s->qr_base[inter][plane][qri]= i;
2040
                    if(qi >= 63)
2041
                        break;
2042
                    i = get_bits(gb, av_log2(63-qi)+1) + 1;
2043
                    s->qr_size[inter][plane][qri++]= i;
2044
                    qi += i;
2045
                }
2046

    
2047
                if (qi > 63) {
2048
                    av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
2049
                    return -1;
2050
                }
2051
                s->qr_count[inter][plane]= qri;
2052
            }
2053
        }
2054
    }
2055

    
2056
    /* Huffman tables */
2057
    for (s->hti = 0; s->hti < 80; s->hti++) {
2058
        s->entries = 0;
2059
        s->huff_code_size = 1;
2060
        if (!get_bits1(gb)) {
2061
            s->hbits = 0;
2062
            if(read_huffman_tree(avctx, gb))
2063
                return -1;
2064
            s->hbits = 1;
2065
            if(read_huffman_tree(avctx, gb))
2066
                return -1;
2067
        }
2068
    }
2069

    
2070
    s->theora_tables = 1;
2071

    
2072
    return 0;
2073
}
2074

    
2075
static av_cold int theora_decode_init(AVCodecContext *avctx)
2076
{
2077
    Vp3DecodeContext *s = avctx->priv_data;
2078
    GetBitContext gb;
2079
    int ptype;
2080
    uint8_t *header_start[3];
2081
    int header_len[3];
2082
    int i;
2083

    
2084
    s->theora = 1;
2085

    
2086
    if (!avctx->extradata_size)
2087
    {
2088
        av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
2089
        return -1;
2090
    }
2091

    
2092
    if (ff_split_xiph_headers(avctx->extradata, avctx->extradata_size,
2093
                              42, header_start, header_len) < 0) {
2094
        av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
2095
        return -1;
2096
    }
2097

    
2098
  for(i=0;i<3;i++) {
2099
    init_get_bits(&gb, header_start[i], header_len[i] * 8);
2100

    
2101
    ptype = get_bits(&gb, 8);
2102

    
2103
     if (!(ptype & 0x80))
2104
     {
2105
        av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
2106
//        return -1;
2107
     }
2108

    
2109
    // FIXME: Check for this as well.
2110
    skip_bits_long(&gb, 6*8); /* "theora" */
2111

    
2112
    switch(ptype)
2113
    {
2114
        case 0x80:
2115
            theora_decode_header(avctx, &gb);
2116
                break;
2117
        case 0x81:
2118
// FIXME: is this needed? it breaks sometimes
2119
//            theora_decode_comments(avctx, gb);
2120
            break;
2121
        case 0x82:
2122
            if (theora_decode_tables(avctx, &gb))
2123
                return -1;
2124
            break;
2125
        default:
2126
            av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);
2127
            break;
2128
    }
2129
    if(ptype != 0x81 && 8*header_len[i] != get_bits_count(&gb))
2130
        av_log(avctx, AV_LOG_WARNING, "%d bits left in packet %X\n", 8*header_len[i] - get_bits_count(&gb), ptype);
2131
    if (s->theora < 0x030200)
2132
        break;
2133
  }
2134

    
2135
    return vp3_decode_init(avctx);
2136
}
2137

    
2138
AVCodec theora_decoder = {
2139
    "theora",
2140
    CODEC_TYPE_VIDEO,
2141
    CODEC_ID_THEORA,
2142
    sizeof(Vp3DecodeContext),
2143
    theora_decode_init,
2144
    NULL,
2145
    vp3_decode_end,
2146
    vp3_decode_frame,
2147
    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2148
    NULL,
2149
    .long_name = NULL_IF_CONFIG_SMALL("Theora"),
2150
};
2151
#endif
2152

    
2153
AVCodec vp3_decoder = {
2154
    "vp3",
2155
    CODEC_TYPE_VIDEO,
2156
    CODEC_ID_VP3,
2157
    sizeof(Vp3DecodeContext),
2158
    vp3_decode_init,
2159
    NULL,
2160
    vp3_decode_end,
2161
    vp3_decode_frame,
2162
    CODEC_CAP_DR1 | CODEC_CAP_DRAW_HORIZ_BAND,
2163
    NULL,
2164
    .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
2165
};