GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/vp3.c Lines: 1241 1545 80.3 %
Date: 2020-10-23 17:01:47 Branches: 818 1122 72.9 %

Line Branch Exec Source
1
/*
2
 * Copyright (C) 2003-2004 The FFmpeg project
3
 * Copyright (C) 2019 Peter Ross
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22
/**
23
 * @file
24
 * On2 VP3/VP4 Video Decoder
25
 *
26
 * VP3 Video Decoder by Mike Melanson (mike at multimedia.cx)
27
 * For more information about the VP3 coding process, visit:
28
 *   http://wiki.multimedia.cx/index.php?title=On2_VP3
29
 *
30
 * Theora decoder by Alex Beregszaszi
31
 */
32
33
#include <stdio.h>
34
#include <stdlib.h>
35
#include <string.h>
36
37
#include "libavutil/imgutils.h"
38
39
#include "avcodec.h"
40
#include "get_bits.h"
41
#include "hpeldsp.h"
42
#include "internal.h"
43
#include "mathops.h"
44
#include "thread.h"
45
#include "videodsp.h"
46
#include "vp3data.h"
47
#include "vp4data.h"
48
#include "vp3dsp.h"
49
#include "xiph.h"
50
51
#define FRAGMENT_PIXELS 8
52
53
// FIXME split things out into their own arrays
54
typedef struct Vp3Fragment {
55
    int16_t dc;
56
    uint8_t coding_method;
57
    uint8_t qpi;
58
} Vp3Fragment;
59
60
#define SB_NOT_CODED        0
61
#define SB_PARTIALLY_CODED  1
62
#define SB_FULLY_CODED      2
63
64
// This is the maximum length of a single long bit run that can be encoded
65
// for superblock coding or block qps. Theora special-cases this to read a
66
// bit instead of flipping the current bit to allow for runs longer than 4129.
67
#define MAXIMUM_LONG_BIT_RUN 4129
68
69
#define MODE_INTER_NO_MV      0
70
#define MODE_INTRA            1
71
#define MODE_INTER_PLUS_MV    2
72
#define MODE_INTER_LAST_MV    3
73
#define MODE_INTER_PRIOR_LAST 4
74
#define MODE_USING_GOLDEN     5
75
#define MODE_GOLDEN_MV        6
76
#define MODE_INTER_FOURMV     7
77
#define CODING_MODE_COUNT     8
78
79
/* special internal mode */
80
#define MODE_COPY             8
81
82
static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
83
static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
84
85
86
/* There are 6 preset schemes, plus a free-form scheme */
87
static const int ModeAlphabet[6][CODING_MODE_COUNT] = {
88
    /* scheme 1: Last motion vector dominates */
89
    { MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
90
      MODE_INTER_PLUS_MV,    MODE_INTER_NO_MV,
91
      MODE_INTRA,            MODE_USING_GOLDEN,
92
      MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
93
94
    /* scheme 2 */
95
    { MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
96
      MODE_INTER_NO_MV,      MODE_INTER_PLUS_MV,
97
      MODE_INTRA,            MODE_USING_GOLDEN,
98
      MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
99
100
    /* scheme 3 */
101
    { MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
102
      MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
103
      MODE_INTRA,            MODE_USING_GOLDEN,
104
      MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
105
106
    /* scheme 4 */
107
    { MODE_INTER_LAST_MV,    MODE_INTER_PLUS_MV,
108
      MODE_INTER_NO_MV,      MODE_INTER_PRIOR_LAST,
109
      MODE_INTRA,            MODE_USING_GOLDEN,
110
      MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
111
112
    /* scheme 5: No motion vector dominates */
113
    { MODE_INTER_NO_MV,      MODE_INTER_LAST_MV,
114
      MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
115
      MODE_INTRA,            MODE_USING_GOLDEN,
116
      MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
117
118
    /* scheme 6 */
119
    { MODE_INTER_NO_MV,      MODE_USING_GOLDEN,
120
      MODE_INTER_LAST_MV,    MODE_INTER_PRIOR_LAST,
121
      MODE_INTER_PLUS_MV,    MODE_INTRA,
122
      MODE_GOLDEN_MV,        MODE_INTER_FOURMV },
123
};
124
125
static const uint8_t hilbert_offset[16][2] = {
126
    { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
127
    { 0, 2 }, { 0, 3 }, { 1, 3 }, { 1, 2 },
128
    { 2, 2 }, { 2, 3 }, { 3, 3 }, { 3, 2 },
129
    { 3, 1 }, { 2, 1 }, { 2, 0 }, { 3, 0 }
130
};
131
132
enum {
133
    VP4_DC_INTRA  = 0,
134
    VP4_DC_INTER  = 1,
135
    VP4_DC_GOLDEN = 2,
136
    NB_VP4_DC_TYPES,
137
    VP4_DC_UNDEFINED = NB_VP4_DC_TYPES
138
};
139
140
static const uint8_t vp4_pred_block_type_map[8] = {
141
    [MODE_INTER_NO_MV]      = VP4_DC_INTER,
142
    [MODE_INTRA]            = VP4_DC_INTRA,
143
    [MODE_INTER_PLUS_MV]    = VP4_DC_INTER,
144
    [MODE_INTER_LAST_MV]    = VP4_DC_INTER,
145
    [MODE_INTER_PRIOR_LAST] = VP4_DC_INTER,
146
    [MODE_USING_GOLDEN]     = VP4_DC_GOLDEN,
147
    [MODE_GOLDEN_MV]        = VP4_DC_GOLDEN,
148
    [MODE_INTER_FOURMV]     = VP4_DC_INTER,
149
};
150
151
typedef struct {
152
    int dc;
153
    int type;
154
} VP4Predictor;
155
156
#define MIN_DEQUANT_VAL 2
157
158
typedef struct Vp3DecodeContext {
159
    AVCodecContext *avctx;
160
    int theora, theora_tables, theora_header;
161
    int version;
162
    int width, height;
163
    int chroma_x_shift, chroma_y_shift;
164
    ThreadFrame golden_frame;
165
    ThreadFrame last_frame;
166
    ThreadFrame current_frame;
167
    int keyframe;
168
    uint8_t idct_permutation[64];
169
    uint8_t idct_scantable[64];
170
    HpelDSPContext hdsp;
171
    VideoDSPContext vdsp;
172
    VP3DSPContext vp3dsp;
173
    DECLARE_ALIGNED(16, int16_t, block)[64];
174
    int flipped_image;
175
    int last_slice_end;
176
    int skip_loop_filter;
177
178
    int qps[3];
179
    int nqps;
180
    int last_qps[3];
181
182
    int superblock_count;
183
    int y_superblock_width;
184
    int y_superblock_height;
185
    int y_superblock_count;
186
    int c_superblock_width;
187
    int c_superblock_height;
188
    int c_superblock_count;
189
    int u_superblock_start;
190
    int v_superblock_start;
191
    unsigned char *superblock_coding;
192
193
    int macroblock_count; /* y macroblock count */
194
    int macroblock_width;
195
    int macroblock_height;
196
    int c_macroblock_count;
197
    int c_macroblock_width;
198
    int c_macroblock_height;
199
    int yuv_macroblock_count; /* y+u+v macroblock count */
200
201
    int fragment_count;
202
    int fragment_width[2];
203
    int fragment_height[2];
204
205
    Vp3Fragment *all_fragments;
206
    int fragment_start[3];
207
    int data_offset[3];
208
    uint8_t offset_x;
209
    uint8_t offset_y;
210
    int offset_x_warned;
211
212
    int8_t (*motion_val[2])[2];
213
214
    /* tables */
215
    uint16_t coded_dc_scale_factor[2][64];
216
    uint32_t coded_ac_scale_factor[64];
217
    uint8_t base_matrix[384][64];
218
    uint8_t qr_count[2][3];
219
    uint8_t qr_size[2][3][64];
220
    uint16_t qr_base[2][3][64];
221
222
    /**
223
     * This is a list of all tokens in bitstream order. Reordering takes place
224
     * by pulling from each level during IDCT. As a consequence, IDCT must be
225
     * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
226
     * otherwise. The 32 different tokens with up to 12 bits of extradata are
227
     * collapsed into 3 types, packed as follows:
228
     *   (from the low to high bits)
229
     *
230
     * 2 bits: type (0,1,2)
231
     *   0: EOB run, 14 bits for run length (12 needed)
232
     *   1: zero run, 7 bits for run length
233
     *                7 bits for the next coefficient (3 needed)
234
     *   2: coefficient, 14 bits (11 needed)
235
     *
236
     * Coefficients are signed, so are packed in the highest bits for automatic
237
     * sign extension.
238
     */
239
    int16_t *dct_tokens[3][64];
240
    int16_t *dct_tokens_base;
241
#define TOKEN_EOB(eob_run)              ((eob_run) << 2)
242
#define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) * 512) + ((zero_run) << 2) + 1)
243
#define TOKEN_COEFF(coeff)              (((coeff) * 4) + 2)
244
245
    /**
246
     * number of blocks that contain DCT coefficients at
247
     * the given level or higher
248
     */
249
    int num_coded_frags[3][64];
250
    int total_num_coded_frags;
251
252
    /* this is a list of indexes into the all_fragments array indicating
253
     * which of the fragments are coded */
254
    int *coded_fragment_list[3];
255
256
    int *kf_coded_fragment_list;
257
    int *nkf_coded_fragment_list;
258
    int num_kf_coded_fragment[3];
259
260
    /* The first 16 of the following VLCs are for the dc coefficients;
261
       the others are four groups of 16 VLCs each for ac coefficients. */
262
    VLC coeff_vlc[5 * 16];
263
264
    VLC superblock_run_length_vlc; /* version < 2 */
265
    VLC fragment_run_length_vlc; /* version < 2 */
266
    VLC block_pattern_vlc[2]; /* version >= 2*/
267
    VLC mode_code_vlc;
268
    VLC motion_vector_vlc; /* version < 2 */
269
    VLC vp4_mv_vlc[2][7]; /* version >=2 */
270
271
    /* these arrays need to be on 16-byte boundaries since SSE2 operations
272
     * index into them */
273
    DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64];     ///< qmat[qpi][is_inter][plane]
274
275
    /* This table contains superblock_count * 16 entries. Each set of 16
276
     * numbers corresponds to the fragment indexes 0..15 of the superblock.
277
     * An entry will be -1 to indicate that no entry corresponds to that
278
     * index. */
279
    int *superblock_fragments;
280
281
    /* This is an array that indicates how a particular macroblock
282
     * is coded. */
283
    unsigned char *macroblock_coding;
284
285
    uint8_t *edge_emu_buffer;
286
287
    /* Huffman decode */
288
    int hti;
289
    unsigned int hbits;
290
    int entries;
291
    int huff_code_size;
292
    uint32_t huffman_table[80][32][2];
293
294
    uint8_t filter_limit_values[64];
295
    DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
296
297
    VP4Predictor * dc_pred_row; /* dc_pred_row[y_superblock_width * 4] */
298
} Vp3DecodeContext;
299
300
/************************************************************************
301
 * VP3 specific functions
302
 ************************************************************************/
303
304
24
static av_cold void free_tables(AVCodecContext *avctx)
305
{
306
24
    Vp3DecodeContext *s = avctx->priv_data;
307
308
24
    av_freep(&s->superblock_coding);
309
24
    av_freep(&s->all_fragments);
310
24
    av_freep(&s->nkf_coded_fragment_list);
311
24
    av_freep(&s->kf_coded_fragment_list);
312
24
    av_freep(&s->dct_tokens_base);
313
24
    av_freep(&s->superblock_fragments);
314
24
    av_freep(&s->macroblock_coding);
315
24
    av_freep(&s->dc_pred_row);
316
24
    av_freep(&s->motion_val[0]);
317
24
    av_freep(&s->motion_val[1]);
318
24
}
319
320
12
static void vp3_decode_flush(AVCodecContext *avctx)
321
{
322
12
    Vp3DecodeContext *s = avctx->priv_data;
323
324
12
    if (s->golden_frame.f)
325
12
        ff_thread_release_buffer(avctx, &s->golden_frame);
326
12
    if (s->last_frame.f)
327
12
        ff_thread_release_buffer(avctx, &s->last_frame);
328
12
    if (s->current_frame.f)
329
12
        ff_thread_release_buffer(avctx, &s->current_frame);
330
12
}
331
332
12
static av_cold int vp3_decode_end(AVCodecContext *avctx)
333
{
334
12
    Vp3DecodeContext *s = avctx->priv_data;
335
    int i, j;
336
337
12
    free_tables(avctx);
338
12
    av_freep(&s->edge_emu_buffer);
339
340
12
    s->theora_tables = 0;
341
342
    /* release all frames */
343
12
    vp3_decode_flush(avctx);
344
12
    av_frame_free(&s->current_frame.f);
345
12
    av_frame_free(&s->last_frame.f);
346
12
    av_frame_free(&s->golden_frame.f);
347
348
972
    for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++)
349
960
        ff_free_vlc(&s->coeff_vlc[i]);
350
351
12
    ff_free_vlc(&s->superblock_run_length_vlc);
352
12
    ff_free_vlc(&s->fragment_run_length_vlc);
353
12
    ff_free_vlc(&s->mode_code_vlc);
354
12
    ff_free_vlc(&s->motion_vector_vlc);
355
356
36
    for (j = 0; j < 2; j++)
357
192
        for (i = 0; i < 7; i++)
358
168
            ff_free_vlc(&s->vp4_mv_vlc[j][i]);
359
360
36
    for (i = 0; i < 2; i++)
361
24
        ff_free_vlc(&s->block_pattern_vlc[i]);
362
12
    return 0;
363
}
364
365
/**
366
 * This function sets up all of the various blocks mappings:
367
 * superblocks <-> fragments, macroblocks <-> fragments,
368
 * superblocks <-> macroblocks
369
 *
370
 * @return 0 is successful; returns 1 if *anything* went wrong.
371
 */
372
12
static int init_block_mapping(Vp3DecodeContext *s)
373
{
374
    int sb_x, sb_y, plane;
375
12
    int x, y, i, j = 0;
376
377
48
    for (plane = 0; plane < 3; plane++) {
378
36
        int sb_width    = plane ? s->c_superblock_width
379
36
                                : s->y_superblock_width;
380
36
        int sb_height   = plane ? s->c_superblock_height
381
36
                                : s->y_superblock_height;
382
36
        int frag_width  = s->fragment_width[!!plane];
383
36
        int frag_height = s->fragment_height[!!plane];
384
385
551
        for (sb_y = 0; sb_y < sb_height; sb_y++)
386
26730
            for (sb_x = 0; sb_x < sb_width; sb_x++)
387
445655
                for (i = 0; i < 16; i++) {
388
419440
                    x = 4 * sb_x + hilbert_offset[i][0];
389
419440
                    y = 4 * sb_y + hilbert_offset[i][1];
390
391

419440
                    if (x < frag_width && y < frag_height)
392
404850
                        s->superblock_fragments[j++] = s->fragment_start[plane] +
393
404850
                                                       y * frag_width + x;
394
                    else
395
14590
                        s->superblock_fragments[j++] = -1;
396
                }
397
    }
398
399
12
    return 0;  /* successful path out */
400
}
401
402
/*
403
 * This function sets up the dequantization tables used for a particular
404
 * frame.
405
 */
406
62
static void init_dequantizer(Vp3DecodeContext *s, int qpi)
407
{
408
62
    int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
409
    int i, plane, inter, qri, bmi, bmj, qistart;
410
411
186
    for (inter = 0; inter < 2; inter++) {
412
496
        for (plane = 0; plane < 3; plane++) {
413
372
            int dc_scale_factor = s->coded_dc_scale_factor[!!plane][s->qps[qpi]];
414
372
            int sum = 0;
415
408
            for (qri = 0; qri < s->qr_count[inter][plane]; qri++) {
416
408
                sum += s->qr_size[inter][plane][qri];
417
408
                if (s->qps[qpi] <= sum)
418
372
                    break;
419
            }
420
372
            qistart = sum - s->qr_size[inter][plane][qri];
421
372
            bmi     = s->qr_base[inter][plane][qri];
422
372
            bmj     = s->qr_base[inter][plane][qri + 1];
423
24180
            for (i = 0; i < 64; i++) {
424
23808
                int coeff = (2 * (sum     - s->qps[qpi]) * s->base_matrix[bmi][i] -
425
23808
                             2 * (qistart - s->qps[qpi]) * s->base_matrix[bmj][i] +
426
23808
                             s->qr_size[inter][plane][qri]) /
427
23808
                            (2 * s->qr_size[inter][plane][qri]);
428
429
23808
                int qmin   = 8 << (inter + !i);
430
23808
                int qscale = i ? ac_scale_factor : dc_scale_factor;
431
23808
                int qbias = (1 + inter) * 3;
432
47616
                s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
433
23808
                    (i == 0 || s->version < 2) ? av_clip((qscale * coeff) / 100 * 4, qmin, 4096)
434
1512
                                               : (qscale * (coeff - qbias) / 100 + qbias) * 4;
435
            }
436
            /* all DC coefficients use the same quant so as not to interfere
437
             * with DC prediction */
438
372
            s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
439
        }
440
    }
441
62
}
442
443
/*
444
 * This function initializes the loop filter boundary limits if the frame's
445
 * quality index is different from the previous frame's.
446
 *
447
 * The filter_limit_values may not be larger than 127.
448
 */
449
62
static void init_loop_filter(Vp3DecodeContext *s)
450
{
451
62
    ff_vp3dsp_set_bounding_values(s->bounding_values_array, s->filter_limit_values[s->qps[0]]);
452
62
}
453
454
/*
455
 * This function unpacks all of the superblock/macroblock/fragment coding
456
 * information from the bitstream.
457
 */
458
140
static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
459
{
460
140
    int superblock_starts[3] = {
461
140
        0, s->u_superblock_start, s->v_superblock_start
462
    };
463
140
    int bit = 0;
464
140
    int current_superblock = 0;
465
140
    int current_run = 0;
466
140
    int num_partial_superblocks = 0;
467
468
    int i, j;
469
    int current_fragment;
470
    int plane;
471
140
    int plane0_num_coded_frags = 0;
472
473
140
    if (s->keyframe) {
474
4
        memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
475
    } else {
476
        /* unpack the list of partially-coded superblocks */
477
136
        bit         = get_bits1(gb) ^ 1;
478
136
        current_run = 0;
479
480

8681
        while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
481

8545
            if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
482
                bit = get_bits1(gb);
483
            else
484
8545
                bit ^= 1;
485
486
8545
            current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
487
                                   6, 2) + 1;
488
8545
            if (current_run == 34)
489
437
                current_run += get_bits(gb, 12);
490
491
8545
            if (current_run > s->superblock_count - current_superblock) {
492
                av_log(s->avctx, AV_LOG_ERROR,
493
                       "Invalid partially coded superblock run length\n");
494
                return -1;
495
            }
496
497
8545
            memset(s->superblock_coding + current_superblock, bit, current_run);
498
499
8545
            current_superblock += current_run;
500
8545
            if (bit)
501
4237
                num_partial_superblocks += current_run;
502
        }
503
504
        /* unpack the list of fully coded superblocks if any of the blocks were
505
         * not marked as partially coded in the previous step */
506
136
        if (num_partial_superblocks < s->superblock_count) {
507
136
            int superblocks_decoded = 0;
508
509
136
            current_superblock = 0;
510
136
            bit                = get_bits1(gb) ^ 1;
511
136
            current_run        = 0;
512
513

2240
            while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
514
1052
                   get_bits_left(gb) > 0) {
515

1052
                if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
516
6
                    bit = get_bits1(gb);
517
                else
518
1046
                    bit ^= 1;
519
520
1052
                current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
521
                                       6, 2) + 1;
522
1052
                if (current_run == 34)
523
218
                    current_run += get_bits(gb, 12);
524
525
105952
                for (j = 0; j < current_run; current_superblock++) {
526
104900
                    if (current_superblock >= s->superblock_count) {
527
                        av_log(s->avctx, AV_LOG_ERROR,
528
                               "Invalid fully coded superblock run length\n");
529
                        return -1;
530
                    }
531
532
                    /* skip any superblocks already marked as partially coded */
533
104900
                    if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
534
88554
                        s->superblock_coding[current_superblock] = 2 * bit;
535
88554
                        j++;
536
                    }
537
                }
538
1052
                superblocks_decoded += current_run;
539
            }
540
        }
541
542
        /* if there were partial blocks, initialize bitstream for
543
         * unpacking fragment codings */
544
136
        if (num_partial_superblocks) {
545
128
            current_run = 0;
546
128
            bit         = get_bits1(gb);
547
            /* toggle the bit because as soon as the first run length is
548
             * fetched the bit will be toggled again */
549
128
            bit ^= 1;
550
        }
551
    }
552
553
    /* figure out which fragments are coded; iterate through each
554
     * superblock (all planes) */
555
140
    s->total_num_coded_frags = 0;
556
140
    memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
557
558
280
    s->coded_fragment_list[0] = s->keyframe ? s->kf_coded_fragment_list
559
140
                                            : s->nkf_coded_fragment_list;
560
561
560
    for (plane = 0; plane < 3; plane++) {
562
420
        int sb_start = superblock_starts[plane];
563
420
        int sb_end   = sb_start + (plane ? s->c_superblock_count
564
420
                                         : s->y_superblock_count);
565
420
        int num_coded_frags = 0;
566
567
420
        if (s->keyframe) {
568
12
            if (s->num_kf_coded_fragment[plane] == -1) {
569
10538
                for (i = sb_start; i < sb_end; i++) {
570
                    /* iterate through all 16 fragments in a superblock */
571
178942
                    for (j = 0; j < 16; j++) {
572
                        /* if the fragment is in bounds, check its coding status */
573
168416
                        current_fragment = s->superblock_fragments[i * 16 + j];
574
168416
                        if (current_fragment != -1) {
575
162492
                            s->coded_fragment_list[plane][num_coded_frags++] =
576
                                current_fragment;
577
                        }
578
                    }
579
                }
580
12
                s->num_kf_coded_fragment[plane] = num_coded_frags;
581
            } else
582
                num_coded_frags = s->num_kf_coded_fragment[plane];
583
        } else {
584

105594
            for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
585
105186
                if (get_bits_left(gb) < plane0_num_coded_frags >> 2) {
586
                    return AVERROR_INVALIDDATA;
587
                }
588
                /* iterate through all 16 fragments in a superblock */
589
1788162
                for (j = 0; j < 16; j++) {
590
                    /* if the fragment is in bounds, check its coding status */
591
1682976
                    current_fragment = s->superblock_fragments[i * 16 + j];
592
1682976
                    if (current_fragment != -1) {
593
1598148
                        int coded = s->superblock_coding[i];
594
595
1598148
                        if (coded == SB_PARTIALLY_CODED) {
596
                            /* fragment may or may not be coded; this is the case
597
                             * that cares about the fragment coding runs */
598
241844
                            if (current_run-- == 0) {
599
70601
                                bit        ^= 1;
600
70601
                                current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
601
                            }
602
241844
                            coded = bit;
603
                        }
604
605
1598148
                        if (coded) {
606
                            /* default mode; actual mode will be decoded in
607
                             * the next phase */
608
370084
                            s->all_fragments[current_fragment].coding_method =
609
                                MODE_INTER_NO_MV;
610
370084
                            s->coded_fragment_list[plane][num_coded_frags++] =
611
                                current_fragment;
612
                        } else {
613
                            /* not coded; copy this fragment from the prior frame */
614
1228064
                            s->all_fragments[current_fragment].coding_method =
615
                                MODE_COPY;
616
                        }
617
                    }
618
                }
619
            }
620
        }
621
420
        if (!plane)
622
140
            plane0_num_coded_frags = num_coded_frags;
623
420
        s->total_num_coded_frags += num_coded_frags;
624
27300
        for (i = 0; i < 64; i++)
625
26880
            s->num_coded_frags[plane][i] = num_coded_frags;
626
420
        if (plane < 2)
627
280
            s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
628
                                                num_coded_frags;
629
    }
630
140
    return 0;
631
}
632
633
#define BLOCK_X (2 * mb_x + (k & 1))
634
#define BLOCK_Y (2 * mb_y + (k >> 1))
635
636
#if CONFIG_VP4_DECODER
637
/**
638
 * @return number of blocks, or > yuv_macroblock_count on error.
639
 *         return value is always >= 1.
640
 */
641
7007
static int vp4_get_mb_count(Vp3DecodeContext *s, GetBitContext *gb)
642
{
643
7007
    int v = 1;
644
    int bits;
645
7007
    while ((bits = show_bits(gb, 9)) == 0x1ff) {
646
        skip_bits(gb, 9);
647
        v += 256;
648
        if (v > s->yuv_macroblock_count) {
649
            av_log(s->avctx, AV_LOG_ERROR, "Invalid run length\n");
650
            return v;
651
        }
652
    }
653
#define body(n) { \
654
    skip_bits(gb, 2 + n); \
655
    v += (1 << n) + get_bits(gb, n); }
656
#define thresh(n) (0x200 - (0x80 >> n))
657
#define else_if(n) else if (bits < thresh(n)) body(n)
658
7007
    if (bits < 0x100) {
659
2784
        skip_bits(gb, 1);
660
4223
    } else if (bits < thresh(0)) {
661
1763
        skip_bits(gb, 2);
662
1763
        v += 1;
663
    }
664
2460
    else_if(1)
665
1466
    else_if(2)
666
799
    else_if(3)
667
316
    else_if(4)
668
92
    else_if(5)
669
4
    else_if(6)
670
    else body(7)
671
#undef body
672
#undef thresh
673
#undef else_if
674
7007
    return v;
675
}
676
677
4556
static int vp4_get_block_pattern(Vp3DecodeContext *s, GetBitContext *gb, int *next_block_pattern_table)
678
{
679
4556
    int v = get_vlc2(gb, s->block_pattern_vlc[*next_block_pattern_table].table, 3, 2);
680
4556
    if (v == -1) {
681
        av_log(s->avctx, AV_LOG_ERROR, "Invalid block pattern\n");
682
        *next_block_pattern_table = 0;
683
        return 0;
684
    }
685
4556
    *next_block_pattern_table = vp4_block_pattern_table_selector[v];
686
4556
    return v + 1;
687
}
688
689
24
static int vp4_unpack_macroblocks(Vp3DecodeContext *s, GetBitContext *gb)
690
{
691
    int plane, i, j, k, fragment;
692
    int next_block_pattern_table;
693
    int bit, current_run, has_partial;
694
695
24
    memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
696
697
24
    if (s->keyframe)
698
2
        return 0;
699
700
22
    has_partial = 0;
701
22
    bit         = get_bits1(gb);
702
4154
    for (i = 0; i < s->yuv_macroblock_count; i += current_run) {
703
4132
        if (get_bits_left(gb) <= 0)
704
            return AVERROR_INVALIDDATA;
705
4132
        current_run = vp4_get_mb_count(s, gb);
706
4132
        if (current_run > s->yuv_macroblock_count - i)
707
            return -1;
708
4132
        memset(s->superblock_coding + i, 2 * bit, current_run);
709
4132
        bit ^= 1;
710
4132
        has_partial |= bit;
711
    }
712
713
22
    if (has_partial) {
714
22
        if (get_bits_left(gb) <= 0)
715
            return AVERROR_INVALIDDATA;
716
22
        bit  = get_bits1(gb);
717
22
        current_run = vp4_get_mb_count(s, gb);
718
20086
        for (i = 0; i < s->yuv_macroblock_count; i++) {
719
20064
            if (!s->superblock_coding[i]) {
720
8403
                if (!current_run) {
721
2853
                    bit ^= 1;
722
2853
                    current_run = vp4_get_mb_count(s, gb);
723
                }
724
8403
                s->superblock_coding[i] = bit;
725
8403
                current_run--;
726
            }
727
        }
728
22
        if (current_run) /* handle situation when vp4_get_mb_count() fails */
729
            return -1;
730
    }
731
732
22
    next_block_pattern_table = 0;
733
22
    i = 0;
734
88
    for (plane = 0; plane < 3; plane++) {
735
        int sb_x, sb_y;
736
66
        int sb_width = plane ? s->c_superblock_width : s->y_superblock_width;
737
66
        int sb_height = plane ? s->c_superblock_height : s->y_superblock_height;
738
66
        int mb_width = plane ? s->c_macroblock_width : s->macroblock_width;
739
66
        int mb_height = plane ? s->c_macroblock_height : s->macroblock_height;
740
66
        int fragment_width = s->fragment_width[!!plane];
741
66
        int fragment_height = s->fragment_height[!!plane];
742
743
418
        for (sb_y = 0; sb_y < sb_height; sb_y++) {
744
5456
            for (sb_x = 0; sb_x < sb_width; sb_x++) {
745
25520
                for (j = 0; j < 4; j++) {
746
20416
                    int mb_x = 2 * sb_x + (j >> 1);
747
20416
                    int mb_y = 2 * sb_y + (j >> 1) ^ (j & 1);
748
                    int mb_coded, pattern, coded;
749
750

20416
                    if (mb_x >= mb_width || mb_y >= mb_height)
751
352
                        continue;
752
753
20064
                    mb_coded = s->superblock_coding[i++];
754
755
20064
                    if (mb_coded == SB_FULLY_CODED)
756
11661
                        pattern = 0xF;
757
8403
                    else if (mb_coded == SB_PARTIALLY_CODED)
758
4556
                        pattern = vp4_get_block_pattern(s, gb, &next_block_pattern_table);
759
                    else
760
3847
                        pattern = 0;
761
762
100320
                    for (k = 0; k < 4; k++) {
763

80256
                        if (BLOCK_X >= fragment_width || BLOCK_Y >= fragment_height)
764
                            continue;
765
80256
                        fragment = s->fragment_start[plane] + BLOCK_Y * fragment_width + BLOCK_X;
766
80256
                        coded = pattern & (8 >> k);
767
                        /* MODE_INTER_NO_MV is the default for coded fragments.
768
                           the actual method is decoded in the next phase. */
769
80256
                        s->all_fragments[fragment].coding_method = coded ? MODE_INTER_NO_MV : MODE_COPY;
770
                    }
771
                }
772
            }
773
        }
774
    }
775
22
    return 0;
776
}
777
#endif
778
779
/*
780
 * This function unpacks all the coding mode data for individual macroblocks
781
 * from the bitstream.
782
 */
783
164
static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
784
{
785
    int i, j, k, sb_x, sb_y;
786
    int scheme;
787
    int current_macroblock;
788
    int current_fragment;
789
    int coding_mode;
790
    int custom_mode_alphabet[CODING_MODE_COUNT];
791
    const int *alphabet;
792
    Vp3Fragment *frag;
793
794
164
    if (s->keyframe) {
795
169794
        for (i = 0; i < s->fragment_count; i++)
796
169788
            s->all_fragments[i].coding_method = MODE_INTRA;
797
    } else {
798
        /* fetch the mode coding scheme for this frame */
799
158
        scheme = get_bits(gb, 3);
800
801
        /* is it a custom coding scheme? */
802
158
        if (scheme == 0) {
803
207
            for (i = 0; i < 8; i++)
804
184
                custom_mode_alphabet[i] = MODE_INTER_NO_MV;
805
207
            for (i = 0; i < 8; i++)
806
184
                custom_mode_alphabet[get_bits(gb, 3)] = i;
807
23
            alphabet = custom_mode_alphabet;
808
        } else
809
135
            alphabet = ModeAlphabet[scheme - 1];
810
811
        /* iterate through all of the macroblocks that contain 1 or more
812
         * coded fragments */
813
2038
        for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
814
73930
            for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
815
72050
                if (get_bits_left(gb) <= 0)
816
                    return -1;
817
818
360250
                for (j = 0; j < 4; j++) {
819
288200
                    int mb_x = 2 * sb_x + (j >> 1);
820
288200
                    int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
821
288200
                    current_macroblock = mb_y * s->macroblock_width + mb_x;
822
823
288200
                    if (mb_x >= s->macroblock_width ||
824
287276
                        mb_y >= s->macroblock_height)
825
8466
                        continue;
826
827
                    /* coding modes are only stored if the macroblock has
828
                     * at least one luma block coded, otherwise it must be
829
                     * INTER_NO_MV */
830
1073976
                    for (k = 0; k < 4; k++) {
831
878591
                        current_fragment = BLOCK_Y *
832
878591
                                           s->fragment_width[0] + BLOCK_X;
833
878591
                        if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
834
84349
                            break;
835
                    }
836
279734
                    if (k == 4) {
837
195385
                        s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
838
195385
                        continue;
839
                    }
840
841
                    /* mode 7 means get 3 bits for each coding mode */
842
84349
                    if (scheme == 7)
843
2750
                        coding_mode = get_bits(gb, 3);
844
                    else
845
81599
                        coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
846
847
84349
                    s->macroblock_coding[current_macroblock] = coding_mode;
848
421745
                    for (k = 0; k < 4; k++) {
849
337396
                        frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
850
337396
                        if (frag->coding_method != MODE_COPY)
851
307251
                            frag->coding_method = coding_mode;
852
                    }
853
854
#define SET_CHROMA_MODES                                                      \
855
    if (frag[s->fragment_start[1]].coding_method != MODE_COPY)                \
856
        frag[s->fragment_start[1]].coding_method = coding_mode;               \
857
    if (frag[s->fragment_start[2]].coding_method != MODE_COPY)                \
858
        frag[s->fragment_start[2]].coding_method = coding_mode;
859
860
84349
                    if (s->chroma_y_shift) {
861
84349
                        frag = s->all_fragments + mb_y *
862
84349
                               s->fragment_width[1] + mb_x;
863

84349
                        SET_CHROMA_MODES
864
                    } else if (s->chroma_x_shift) {
865
                        frag = s->all_fragments +
866
                               2 * mb_y * s->fragment_width[1] + mb_x;
867
                        for (k = 0; k < 2; k++) {
868
                            SET_CHROMA_MODES
869
                            frag += s->fragment_width[1];
870
                        }
871
                    } else {
872
                        for (k = 0; k < 4; k++) {
873
                            frag = s->all_fragments +
874
                                   BLOCK_Y * s->fragment_width[1] + BLOCK_X;
875
                            SET_CHROMA_MODES
876
                        }
877
                    }
878
                }
879
            }
880
        }
881
    }
882
883
164
    return 0;
884
}
885
886
3758
static int vp4_get_mv(Vp3DecodeContext *s, GetBitContext *gb, int axis, int last_motion)
887
{
888
3758
    int v = get_vlc2(gb, s->vp4_mv_vlc[axis][vp4_mv_table_selector[FFABS(last_motion)]].table, 6, 2) - 31;
889
3758
    return last_motion < 0 ? -v : v;
890
}
891
892
/*
893
 * This function unpacks all the motion vectors for the individual
894
 * macroblocks from the bitstream.
895
 */
896
164
static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
897
{
898
    int j, k, sb_x, sb_y;
899
    int coding_mode;
900
    int motion_x[4];
901
    int motion_y[4];
902
164
    int last_motion_x = 0;
903
164
    int last_motion_y = 0;
904
164
    int prior_last_motion_x = 0;
905
164
    int prior_last_motion_y = 0;
906
164
    int last_gold_motion_x = 0;
907
164
    int last_gold_motion_y = 0;
908
    int current_macroblock;
909
    int current_fragment;
910
    int frag;
911
912
164
    if (s->keyframe)
913
6
        return 0;
914
915
    /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme; 2 is VP4 code scheme */
916
158
    coding_mode = s->version < 2 ? get_bits1(gb) : 2;
917
918
    /* iterate through all of the macroblocks that contain 1 or more
919
     * coded fragments */
920
2038
    for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
921
73930
        for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
922
72050
            if (get_bits_left(gb) <= 0)
923
                return -1;
924
925
360250
            for (j = 0; j < 4; j++) {
926
288200
                int mb_x = 2 * sb_x + (j >> 1);
927
288200
                int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
928
288200
                current_macroblock = mb_y * s->macroblock_width + mb_x;
929
930
288200
                if (mb_x >= s->macroblock_width  ||
931
287276
                    mb_y >= s->macroblock_height ||
932
279734
                    s->macroblock_coding[current_macroblock] == MODE_COPY)
933
8466
                    continue;
934
935

279734
                switch (s->macroblock_coding[current_macroblock]) {
936
711
                case MODE_GOLDEN_MV:
937
711
                    if (coding_mode == 2) { /* VP4 */
938
337
                        last_gold_motion_x = motion_x[0] = vp4_get_mv(s, gb, 0, last_gold_motion_x);
939
337
                        last_gold_motion_y = motion_y[0] = vp4_get_mv(s, gb, 1, last_gold_motion_y);
940
337
                        break;
941
                    } /* otherwise fall through */
942
                case MODE_INTER_PLUS_MV:
943
                    /* all 6 fragments use the same motion vector */
944
14558
                    if (coding_mode == 0) {
945
13074
                        motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
946
13074
                        motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
947
1484
                    } else if (coding_mode == 1) {
948
42
                        motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
949
42
                        motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
950
                    } else { /* VP4 */
951
1442
                        motion_x[0] = vp4_get_mv(s, gb, 0, last_motion_x);
952
1442
                        motion_y[0] = vp4_get_mv(s, gb, 1, last_motion_y);
953
                    }
954
955
                    /* vector maintenance, only on MODE_INTER_PLUS_MV */
956
14558
                    if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
957
14184
                        prior_last_motion_x = last_motion_x;
958
14184
                        prior_last_motion_y = last_motion_y;
959
14184
                        last_motion_x       = motion_x[0];
960
14184
                        last_motion_y       = motion_y[0];
961
                    }
962
14558
                    break;
963
964
63
                case MODE_INTER_FOURMV:
965
                    /* vector maintenance */
966
63
                    prior_last_motion_x = last_motion_x;
967
63
                    prior_last_motion_y = last_motion_y;
968
969
                    /* fetch 4 vectors from the bitstream, one for each
970
                     * Y fragment, then average for the C fragment vectors */
971
315
                    for (k = 0; k < 4; k++) {
972
252
                        current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
973
252
                        if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
974
252
                            if (coding_mode == 0) {
975
48
                                motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
976
48
                                motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
977
204
                            } else if (coding_mode == 1) {
978
104
                                motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
979
104
                                motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
980
                            } else { /* VP4 */
981
100
                                motion_x[k] = vp4_get_mv(s, gb, 0, prior_last_motion_x);
982
100
                                motion_y[k] = vp4_get_mv(s, gb, 1, prior_last_motion_y);
983
                            }
984
252
                            last_motion_x = motion_x[k];
985
252
                            last_motion_y = motion_y[k];
986
                        } else {
987
                            motion_x[k] = 0;
988
                            motion_y[k] = 0;
989
                        }
990
                    }
991
63
                    break;
992
993
42307
                case MODE_INTER_LAST_MV:
994
                    /* all 6 fragments use the last motion vector */
995
42307
                    motion_x[0] = last_motion_x;
996
42307
                    motion_y[0] = last_motion_y;
997
998
                    /* no vector maintenance (last vector remains the
999
                     * last vector) */
1000
42307
                    break;
1001
1002
11934
                case MODE_INTER_PRIOR_LAST:
1003
                    /* all 6 fragments use the motion vector prior to the
1004
                     * last motion vector */
1005
11934
                    motion_x[0] = prior_last_motion_x;
1006
11934
                    motion_y[0] = prior_last_motion_y;
1007
1008
                    /* vector maintenance */
1009
11934
                    prior_last_motion_x = last_motion_x;
1010
11934
                    prior_last_motion_y = last_motion_y;
1011
11934
                    last_motion_x       = motion_x[0];
1012
11934
                    last_motion_y       = motion_y[0];
1013
11934
                    break;
1014
1015
210535
                default:
1016
                    /* covers intra, inter without MV, golden without MV */
1017
210535
                    motion_x[0] = 0;
1018
210535
                    motion_y[0] = 0;
1019
1020
                    /* no vector maintenance */
1021
210535
                    break;
1022
                }
1023
1024
                /* assign the motion vectors to the correct fragments */
1025
1398670
                for (k = 0; k < 4; k++) {
1026
1118936
                    current_fragment =
1027
1118936
                        BLOCK_Y * s->fragment_width[0] + BLOCK_X;
1028
1118936
                    if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1029
252
                        s->motion_val[0][current_fragment][0] = motion_x[k];
1030
252
                        s->motion_val[0][current_fragment][1] = motion_y[k];
1031
                    } else {
1032
1118684
                        s->motion_val[0][current_fragment][0] = motion_x[0];
1033
1118684
                        s->motion_val[0][current_fragment][1] = motion_y[0];
1034
                    }
1035
                }
1036
1037
279734
                if (s->chroma_y_shift) {
1038
279734
                    if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1039
63
                        motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
1040
                                             motion_x[2] + motion_x[3], 2);
1041
63
                        motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
1042
                                             motion_y[2] + motion_y[3], 2);
1043
                    }
1044
279734
                    if (s->version <= 2) {
1045
266358
                        motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1046
266358
                        motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
1047
                    }
1048
279734
                    frag = mb_y * s->fragment_width[1] + mb_x;
1049
279734
                    s->motion_val[1][frag][0] = motion_x[0];
1050
279734
                    s->motion_val[1][frag][1] = motion_y[0];
1051
                } else if (s->chroma_x_shift) {
1052
                    if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1053
                        motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
1054
                        motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
1055
                        motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
1056
                        motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
1057
                    } else {
1058
                        motion_x[1] = motion_x[0];
1059
                        motion_y[1] = motion_y[0];
1060
                    }
1061
                    if (s->version <= 2) {
1062
                        motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
1063
                        motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
1064
                    }
1065
                    frag = 2 * mb_y * s->fragment_width[1] + mb_x;
1066
                    for (k = 0; k < 2; k++) {
1067
                        s->motion_val[1][frag][0] = motion_x[k];
1068
                        s->motion_val[1][frag][1] = motion_y[k];
1069
                        frag += s->fragment_width[1];
1070
                    }
1071
                } else {
1072
                    for (k = 0; k < 4; k++) {
1073
                        frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
1074
                        if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
1075
                            s->motion_val[1][frag][0] = motion_x[k];
1076
                            s->motion_val[1][frag][1] = motion_y[k];
1077
                        } else {
1078
                            s->motion_val[1][frag][0] = motion_x[0];
1079
                            s->motion_val[1][frag][1] = motion_y[0];
1080
                        }
1081
                    }
1082
                }
1083
            }
1084
        }
1085
    }
1086
1087
158
    return 0;
1088
}
1089
1090
164
static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
1091
{
1092
    int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
1093
164
    int num_blocks = s->total_num_coded_frags;
1094
1095

164
    for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
1096
        i = blocks_decoded = num_blocks_at_qpi = 0;
1097
1098
        bit        = get_bits1(gb) ^ 1;
1099
        run_length = 0;
1100
1101
        do {
1102
            if (run_length == MAXIMUM_LONG_BIT_RUN)
1103
                bit = get_bits1(gb);
1104
            else
1105
                bit ^= 1;
1106
1107
            run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
1108
            if (run_length == 34)
1109
                run_length += get_bits(gb, 12);
1110
            blocks_decoded += run_length;
1111
1112
            if (!bit)
1113
                num_blocks_at_qpi += run_length;
1114
1115
            for (j = 0; j < run_length; i++) {
1116
                if (i >= s->total_num_coded_frags)
1117
                    return -1;
1118
1119
                if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
1120
                    s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
1121
                    j++;
1122
                }
1123
            }
1124
        } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
1125
1126
        num_blocks -= num_blocks_at_qpi;
1127
    }
1128
1129
164
    return 0;
1130
}
1131
1132
259052
static inline int get_eob_run(GetBitContext *gb, int token)
1133
{
1134
259052
    int v = eob_run_table[token].base;
1135
259052
    if (eob_run_table[token].bits)
1136
33652
        v += get_bits(gb, eob_run_table[token].bits);
1137
259052
    return v;
1138
}
1139
1140
2755489
static inline int get_coeff(GetBitContext *gb, int token, int16_t *coeff)
1141
{
1142
    int bits_to_get, zero_run;
1143
1144
2755489
    bits_to_get = coeff_get_bits[token];
1145
2755489
    if (bits_to_get)
1146
1617513
        bits_to_get = get_bits(gb, bits_to_get);
1147
2755489
    *coeff = coeff_tables[token][bits_to_get];
1148
1149
2755489
    zero_run = zero_run_base[token];
1150
2755489
    if (zero_run_get_bits[token])
1151
342682
        zero_run += get_bits(gb, zero_run_get_bits[token]);
1152
1153
2755489
    return zero_run;
1154
}
1155
1156
/*
1157
 * This function is called by unpack_dct_coeffs() to extract the VLCs from
1158
 * the bitstream. The VLCs encode tokens which are used to unpack DCT
1159
 * data. This function unpacks all the VLCs for either the Y plane or both
1160
 * C planes, and is called for DC coefficients or different AC coefficient
1161
 * levels (since different coefficient types require different VLC tables.
1162
 *
1163
 * This function returns a residual eob run. E.g, if a particular token gave
1164
 * instructions to EOB the next 5 fragments and there were only 2 fragments
1165
 * left in the current fragment range, 3 would be returned so that it could
1166
 * be passed into the next call to this same function.
1167
 */
1168
26880
static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1169
                       VLC *table, int coeff_index,
1170
                       int plane,
1171
                       int eob_run)
1172
{
1173
26880
    int i, j = 0;
1174
    int token;
1175
26880
    int zero_run  = 0;
1176
26880
    int16_t coeff = 0;
1177
    int blocks_ended;
1178
26880
    int coeff_i = 0;
1179
26880
    int num_coeffs      = s->num_coded_frags[plane][coeff_index];
1180
26880
    int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
1181
1182
    /* local references to structure members to avoid repeated dereferences */
1183
26880
    int *coded_fragment_list   = s->coded_fragment_list[plane];
1184
26880
    Vp3Fragment *all_fragments = s->all_fragments;
1185
26880
    VLC_TYPE(*vlc_table)[2] = table->table;
1186
1187
26880
    if (num_coeffs < 0) {
1188
        av_log(s->avctx, AV_LOG_ERROR,
1189
               "Invalid number of coefficients at level %d\n", coeff_index);
1190
        return AVERROR_INVALIDDATA;
1191
    }
1192
1193
26880
    if (eob_run > num_coeffs) {
1194
3487
        coeff_i      =
1195
3487
        blocks_ended = num_coeffs;
1196
3487
        eob_run     -= num_coeffs;
1197
    } else {
1198
23393
        coeff_i      =
1199
23393
        blocks_ended = eob_run;
1200
23393
        eob_run      = 0;
1201
    }
1202
1203
    // insert fake EOB token to cover the split between planes or zzi
1204
26880
    if (blocks_ended)
1205
2019
        dct_tokens[j++] = blocks_ended << 2;
1206
1207

2087120
    while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
1208
        /* decode a VLC into a token */
1209
2060240
        token = get_vlc2(gb, vlc_table, 11, 3);
1210
        /* use the token to get a zero run, a coefficient, and an eob run */
1211
2060240
        if ((unsigned) token <= 6U) {
1212
220061
            eob_run = get_eob_run(gb, token);
1213
220061
            if (!eob_run)
1214
                eob_run = INT_MAX;
1215
1216
            // record only the number of blocks ended in this plane,
1217
            // any spill will be recorded in the next plane.
1218
220061
            if (eob_run > num_coeffs - coeff_i) {
1219
1656
                dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
1220
1656
                blocks_ended   += num_coeffs - coeff_i;
1221
1656
                eob_run        -= num_coeffs - coeff_i;
1222
1656
                coeff_i         = num_coeffs;
1223
            } else {
1224
218405
                dct_tokens[j++] = TOKEN_EOB(eob_run);
1225
218405
                blocks_ended   += eob_run;
1226
218405
                coeff_i        += eob_run;
1227
218405
                eob_run         = 0;
1228
            }
1229
1840179
        } else if (token >= 0) {
1230
1840179
            zero_run = get_coeff(gb, token, &coeff);
1231
1232
1840179
            if (zero_run) {
1233
601916
                dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
1234
            } else {
1235
                // Save DC into the fragment structure. DC prediction is
1236
                // done in raster order, so the actual DC can't be in with
1237
                // other tokens. We still need the token in dct_tokens[]
1238
                // however, or else the structure collapses on itself.
1239
1238263
                if (!coeff_index)
1240
241967
                    all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
1241
1242
1238263
                dct_tokens[j++] = TOKEN_COEFF(coeff);
1243
            }
1244
1245
1840179
            if (coeff_index + zero_run > 64) {
1246
                av_log(s->avctx, AV_LOG_DEBUG,
1247
                       "Invalid zero run of %d with %d coeffs left\n",
1248
                       zero_run, 64 - coeff_index);
1249
                zero_run = 64 - coeff_index;
1250
            }
1251
1252
            // zero runs code multiple coefficients,
1253
            // so don't try to decode coeffs for those higher levels
1254
4381268
            for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
1255
2541089
                s->num_coded_frags[plane][i]--;
1256
1840179
            coeff_i++;
1257
        } else {
1258
            av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1259
            return -1;
1260
        }
1261
    }
1262
1263
26880
    if (blocks_ended > s->num_coded_frags[plane][coeff_index])
1264
        av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
1265
1266
    // decrement the number of blocks that have higher coefficients for each
1267
    // EOB run at this level
1268
26880
    if (blocks_ended)
1269
381061
        for (i = coeff_index + 1; i < 64; i++)
1270
372769
            s->num_coded_frags[plane][i] -= blocks_ended;
1271
1272
    // setup the next buffer
1273
26880
    if (plane < 2)
1274
17920
        s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
1275
8960
    else if (coeff_index < 63)
1276
8820
        s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
1277
1278
26880
    return eob_run;
1279
}
1280
1281
static void reverse_dc_prediction(Vp3DecodeContext *s,
1282
                                  int first_fragment,
1283
                                  int fragment_width,
1284
                                  int fragment_height);
1285
/*
1286
 * This function unpacks all of the DCT coefficient data from the
1287
 * bitstream.
1288
 */
1289
140
static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1290
{
1291
    int i;
1292
    int dc_y_table;
1293
    int dc_c_table;
1294
    int ac_y_table;
1295
    int ac_c_table;
1296
140
    int residual_eob_run = 0;
1297
    VLC *y_tables[64];
1298
    VLC *c_tables[64];
1299
1300
140
    s->dct_tokens[0][0] = s->dct_tokens_base;
1301
1302
140
    if (get_bits_left(gb) < 16)
1303
        return AVERROR_INVALIDDATA;
1304
1305
    /* fetch the DC table indexes */
1306
140
    dc_y_table = get_bits(gb, 4);
1307
140
    dc_c_table = get_bits(gb, 4);
1308
1309
    /* unpack the Y plane DC coefficients */
1310
140
    residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_y_table], 0,
1311
                                   0, residual_eob_run);
1312
140
    if (residual_eob_run < 0)
1313
        return residual_eob_run;
1314
140
    if (get_bits_left(gb) < 8)
1315
        return AVERROR_INVALIDDATA;
1316
1317
    /* reverse prediction of the Y-plane DC coefficients */
1318
140
    reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
1319
1320
    /* unpack the C plane DC coefficients */
1321
140
    residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1322
                                   1, residual_eob_run);
1323
140
    if (residual_eob_run < 0)
1324
        return residual_eob_run;
1325
140
    residual_eob_run = unpack_vlcs(s, gb, &s->coeff_vlc[dc_c_table], 0,
1326
                                   2, residual_eob_run);
1327
140
    if (residual_eob_run < 0)
1328
        return residual_eob_run;
1329
1330
    /* reverse prediction of the C-plane DC coefficients */
1331
140
    if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
1332
140
        reverse_dc_prediction(s, s->fragment_start[1],
1333
                              s->fragment_width[1], s->fragment_height[1]);
1334
140
        reverse_dc_prediction(s, s->fragment_start[2],
1335
                              s->fragment_width[1], s->fragment_height[1]);
1336
    }
1337
1338
140
    if (get_bits_left(gb) < 8)
1339
        return AVERROR_INVALIDDATA;
1340
    /* fetch the AC table indexes */
1341
140
    ac_y_table = get_bits(gb, 4);
1342
140
    ac_c_table = get_bits(gb, 4);
1343
1344
    /* build tables of AC VLC tables */
1345
840
    for (i = 1; i <= 5; i++) {
1346
        /* AC VLC table group 1 */
1347
700
        y_tables[i] = &s->coeff_vlc[ac_y_table + 16];
1348
700
        c_tables[i] = &s->coeff_vlc[ac_c_table + 16];
1349
    }
1350
1400
    for (i = 6; i <= 14; i++) {
1351
        /* AC VLC table group 2 */
1352
1260
        y_tables[i] = &s->coeff_vlc[ac_y_table + 32];
1353
1260
        c_tables[i] = &s->coeff_vlc[ac_c_table + 32];
1354
    }
1355
1960
    for (i = 15; i <= 27; i++) {
1356
        /* AC VLC table group 3 */
1357
1820
        y_tables[i] = &s->coeff_vlc[ac_y_table + 48];
1358
1820
        c_tables[i] = &s->coeff_vlc[ac_c_table + 48];
1359
    }
1360
5180
    for (i = 28; i <= 63; i++) {
1361
        /* AC VLC table group 4 */
1362
5040
        y_tables[i] = &s->coeff_vlc[ac_y_table + 64];
1363
5040
        c_tables[i] = &s->coeff_vlc[ac_c_table + 64];
1364
    }
1365
1366
    /* decode all AC coefficients */
1367
8960
    for (i = 1; i <= 63; i++) {
1368
8820
        residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
1369
                                       0, residual_eob_run);
1370
8820
        if (residual_eob_run < 0)
1371
            return residual_eob_run;
1372
1373
8820
        residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1374
                                       1, residual_eob_run);
1375
8820
        if (residual_eob_run < 0)
1376
            return residual_eob_run;
1377
8820
        residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
1378
                                       2, residual_eob_run);
1379
8820
        if (residual_eob_run < 0)
1380
            return residual_eob_run;
1381
    }
1382
1383
140
    return 0;
1384
}
1385
1386
#if CONFIG_VP4_DECODER
1387
/**
1388
 * eob_tracker[] is instead of TOKEN_EOB(value)
1389
 * a dummy TOKEN_EOB(0) value is used to make vp3_dequant work
1390
 *
1391
 * @return < 0 on error
1392
 */
1393
63252
static int vp4_unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
1394
                       VLC *vlc_tables[64],
1395
                       int plane, int eob_tracker[64], int fragment)
1396
{
1397
    int token;
1398
63252
    int zero_run  = 0;
1399
63252
    int16_t coeff = 0;
1400
63252
    int coeff_i = 0;
1401
    int eob_run;
1402
1403
973472
    while (!eob_tracker[coeff_i]) {
1404
954301
        if (get_bits_left(gb) < 1)
1405
            return AVERROR_INVALIDDATA;
1406
1407
954301
        token = get_vlc2(gb, vlc_tables[coeff_i]->table, 11, 3);
1408
1409
        /* use the token to get a zero run, a coefficient, and an eob run */
1410
954301
        if ((unsigned) token <= 6U) {
1411
38991
            eob_run = get_eob_run(gb, token);
1412
38991
            *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1413
38991
            eob_tracker[coeff_i] = eob_run - 1;
1414
38991
            return 0;
1415
915310
        } else if (token >= 0) {
1416
915310
            zero_run = get_coeff(gb, token, &coeff);
1417
1418
915310
            if (zero_run) {
1419
311952
                if (coeff_i + zero_run > 64) {
1420
                    av_log(s->avctx, AV_LOG_DEBUG,
1421
                        "Invalid zero run of %d with %d coeffs left\n",
1422
                        zero_run, 64 - coeff_i);
1423
                    zero_run = 64 - coeff_i;
1424
                }
1425
311952
                *s->dct_tokens[plane][coeff_i]++ = TOKEN_ZERO_RUN(coeff, zero_run);
1426
311952
                coeff_i += zero_run;
1427
            } else {
1428
603358
                if (!coeff_i)
1429
40795
                    s->all_fragments[fragment].dc = coeff;
1430
1431
603358
                *s->dct_tokens[plane][coeff_i]++ = TOKEN_COEFF(coeff);
1432
            }
1433
915310
            coeff_i++;
1434
915310
            if (coeff_i >= 64) /* > 64 occurs when there is a zero_run overflow */
1435
5090
                return 0; /* stop */
1436
        } else {
1437
            av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
1438
            return -1;
1439
        }
1440
    }
1441
19171
    *s->dct_tokens[plane][coeff_i]++ = TOKEN_EOB(0);
1442
19171
    eob_tracker[coeff_i]--;
1443
19171
    return 0;
1444
}
1445
1446
95328
static void vp4_dc_predictor_reset(VP4Predictor *p)
1447
{
1448
95328
    p->dc = 0;
1449
95328
    p->type = VP4_DC_UNDEFINED;
1450
95328
}
1451
1452
5568
static void vp4_dc_pred_before(const Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1453
{
1454
    int i, j;
1455
1456
27840
    for (i = 0; i < 4; i++)
1457
22272
        dc_pred[0][i + 1] = s->dc_pred_row[sb_x * 4 + i];
1458
1459
27840
    for (j = 1; j < 5; j++)
1460
111360
        for (i = 0; i < 4; i++)
1461
89088
            vp4_dc_predictor_reset(&dc_pred[j][i + 1]);
1462
5568
}
1463
1464
5568
static void vp4_dc_pred_after(Vp3DecodeContext *s, VP4Predictor dc_pred[6][6], int sb_x)
1465
{
1466
    int i;
1467
1468
27840
    for (i = 0; i < 4; i++)
1469
22272
        s->dc_pred_row[sb_x * 4 + i] = dc_pred[4][i + 1];
1470
1471
27840
    for (i = 1; i < 5; i++)
1472
22272
        dc_pred[i][0] = dc_pred[i][4];
1473
5568
}
1474
1475
/* note: dc_pred points to the current block */
1476
63252
static int vp4_dc_pred(const Vp3DecodeContext *s, const VP4Predictor * dc_pred, const int * last_dc, int type, int plane)
1477
{
1478
63252
    int count = 0;
1479
63252
    int dc = 0;
1480
1481
63252
    if (dc_pred[-6].type == type) {
1482
29726
        dc += dc_pred[-6].dc;
1483
29726
        count++;
1484
    }
1485
1486
63252
    if (dc_pred[6].type == type) {
1487
19581
        dc += dc_pred[6].dc;
1488
19581
        count++;
1489
    }
1490
1491

63252
    if (count != 2 && dc_pred[-1].type == type) {
1492
38121
        dc += dc_pred[-1].dc;
1493
38121
        count++;
1494
    }
1495
1496

63252
    if (count != 2 && dc_pred[1].type == type) {
1497
2073
        dc += dc_pred[1].dc;
1498
2073
        count++;
1499
    }
1500
1501
    /* using division instead of shift to correctly handle negative values */
1502
63252
    return count == 2 ? dc / 2 : last_dc[type];
1503
}
1504
1505
48
static void vp4_set_tokens_base(Vp3DecodeContext *s)
1506
{
1507
    int plane, i;
1508
48
    int16_t *base = s->dct_tokens_base;
1509
192
    for (plane = 0; plane < 3; plane++) {
1510
9360
        for (i = 0; i < 64; i++) {
1511
9216
            s->dct_tokens[plane][i] = base;
1512
9216
            base += s->fragment_width[!!plane] * s->fragment_height[!!plane];
1513
        }
1514
    }
1515
48
}
1516
1517
24
static int vp4_unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
1518
{
1519
    int i, j;
1520
    int dc_y_table;
1521
    int dc_c_table;
1522
    int ac_y_table;
1523
    int ac_c_table;
1524
    VLC *tables[2][64];
1525
    int plane, sb_y, sb_x;
1526
    int eob_tracker[64];
1527
    VP4Predictor dc_pred[6][6];
1528
    int last_dc[NB_VP4_DC_TYPES];
1529
1530
24
    if (get_bits_left(gb) < 16)
1531
        return AVERROR_INVALIDDATA;
1532
1533
    /* fetch the DC table indexes */
1534
24
    dc_y_table = get_bits(gb, 4);
1535
24
    dc_c_table = get_bits(gb, 4);
1536
1537
24
    ac_y_table = get_bits(gb, 4);
1538
24
    ac_c_table = get_bits(gb, 4);
1539
1540
    /* build tables of DC/AC VLC tables */
1541
1542
    /* DC table group */
1543
24
    tables[0][0] = &s->coeff_vlc[dc_y_table];
1544
24
    tables[1][0] = &s->coeff_vlc[dc_c_table];
1545
144
    for (i = 1; i <= 5; i++) {
1546
        /* AC VLC table group 1 */
1547
120
        tables[0][i] = &s->coeff_vlc[ac_y_table + 16];
1548
120
        tables[1][i] = &s->coeff_vlc[ac_c_table + 16];
1549
    }
1550
240
    for (i = 6; i <= 14; i++) {
1551
        /* AC VLC table group 2 */
1552
216
        tables[0][i] = &s->coeff_vlc[ac_y_table + 32];
1553
216
        tables[1][i] = &s->coeff_vlc[ac_c_table + 32];
1554
    }
1555
336
    for (i = 15; i <= 27; i++) {
1556
        /* AC VLC table group 3 */
1557
312
        tables[0][i] = &s->coeff_vlc[ac_y_table + 48];
1558
312
        tables[1][i] = &s->coeff_vlc[ac_c_table + 48];
1559
    }
1560
888
    for (i = 28; i <= 63; i++) {
1561
        /* AC VLC table group 4 */
1562
864
        tables[0][i] = &s->coeff_vlc[ac_y_table + 64];
1563
864
        tables[1][i] = &s->coeff_vlc[ac_c_table + 64];
1564
    }
1565
1566
24
    vp4_set_tokens_base(s);
1567
1568
24
    memset(last_dc, 0, sizeof(last_dc));
1569
1570

96
    for (plane = 0; plane < ((s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 1 : 3); plane++) {
1571
72
        memset(eob_tracker, 0, sizeof(eob_tracker));
1572
1573
        /* initialise dc prediction */
1574
3720
        for (i = 0; i < s->fragment_width[!!plane]; i++)
1575
3648
            vp4_dc_predictor_reset(&s->dc_pred_row[i]);
1576
1577
504
        for (j = 0; j < 6; j++)
1578
3024
            for (i = 0; i < 6; i++)
1579
2592
                vp4_dc_predictor_reset(&dc_pred[j][i]);
1580
1581
456
        for (sb_y = 0; sb_y * 4 < s->fragment_height[!!plane]; sb_y++) {
1582
5952
            for (sb_x = 0; sb_x *4 < s->fragment_width[!!plane]; sb_x++) {
1583
5568
                vp4_dc_pred_before(s, dc_pred, sb_x);
1584
94656
                for (j = 0; j < 16; j++) {
1585
89088
                        int hx = hilbert_offset[j][0];
1586
89088
                        int hy = hilbert_offset[j][1];
1587
89088
                        int x  = 4 * sb_x + hx;
1588
89088
                        int y  = 4 * sb_y + hy;
1589
89088
                        VP4Predictor *this_dc_pred = &dc_pred[hy + 1][hx + 1];
1590
                        int fragment, dc_block_type;
1591
1592

89088
                        if (x >= s->fragment_width[!!plane] || y >= s->fragment_height[!!plane])
1593
1536
                            continue;
1594
1595
87552
                        fragment = s->fragment_start[plane] + y * s->fragment_width[!!plane] + x;
1596
1597
87552
                        if (s->all_fragments[fragment].coding_method == MODE_COPY)
1598
24300
                            continue;
1599
1600
63252
                        if (vp4_unpack_vlcs(s, gb, tables[!!plane], plane, eob_tracker, fragment) < 0)
1601
                            return -1;
1602
1603
63252
                        dc_block_type = vp4_pred_block_type_map[s->all_fragments[fragment].coding_method];
1604
1605
63252
                        s->all_fragments[fragment].dc +=
1606
63252
                            vp4_dc_pred(s, this_dc_pred, last_dc, dc_block_type, plane);
1607
1608
63252
                        this_dc_pred->type = dc_block_type,
1609
63252
                        this_dc_pred->dc   = last_dc[dc_block_type] = s->all_fragments[fragment].dc;
1610
                }
1611
5568
                vp4_dc_pred_after(s, dc_pred, sb_x);
1612
            }
1613
        }
1614
    }
1615
1616
24
    vp4_set_tokens_base(s);
1617
1618
24
    return 0;
1619
}
1620
#endif
1621
1622
/*
1623
 * This function reverses the DC prediction for each coded fragment in
1624
 * the frame. Much of this function is adapted directly from the original
1625
 * VP3 source code.
1626
 */
1627
#define COMPATIBLE_FRAME(x)                                                   \
1628
    (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
1629
#define DC_COEFF(u) s->all_fragments[u].dc
1630
1631
420
static void reverse_dc_prediction(Vp3DecodeContext *s,
1632
                                  int first_fragment,
1633
                                  int fragment_width,
1634
                                  int fragment_height)
1635
{
1636
#define PUL 8
1637
#define PU 4
1638
#define PUR 2
1639
#define PL 1
1640
1641
    int x, y;
1642
420
    int i = first_fragment;
1643
1644
    int predicted_dc;
1645
1646
    /* DC values for the left, up-left, up, and up-right fragments */
1647
    int vl, vul, vu, vur;
1648
1649
    /* indexes for the left, up-left, up, and up-right fragments */
1650
    int l, ul, u, ur;
1651
1652
    /*
1653
     * The 6 fields mean:
1654
     *   0: up-left multiplier
1655
     *   1: up multiplier
1656
     *   2: up-right multiplier
1657
     *   3: left multiplier
1658
     */
1659
    static const int predictor_transform[16][4] = {
1660
        {    0,   0,   0,   0 },
1661
        {    0,   0,   0, 128 }, // PL
1662
        {    0,   0, 128,   0 }, // PUR
1663
        {    0,   0,  53,  75 }, // PUR|PL
1664
        {    0, 128,   0,   0 }, // PU
1665
        {    0,  64,   0,  64 }, // PU |PL
1666
        {    0, 128,   0,   0 }, // PU |PUR
1667
        {    0,   0,  53,  75 }, // PU |PUR|PL
1668
        {  128,   0,   0,   0 }, // PUL
1669
        {    0,   0,   0, 128 }, // PUL|PL
1670
        {   64,   0,  64,   0 }, // PUL|PUR
1671
        {    0,   0,  53,  75 }, // PUL|PUR|PL
1672
        {    0, 128,   0,   0 }, // PUL|PU
1673
        { -104, 116,   0, 116 }, // PUL|PU |PL
1674
        {   24,  80,  24,   0 }, // PUL|PU |PUR
1675
        { -104, 116,   0, 116 }  // PUL|PU |PUR|PL
1676
    };
1677
1678
    /* This table shows which types of blocks can use other blocks for
1679
     * prediction. For example, INTRA is the only mode in this table to
1680
     * have a frame number of 0. That means INTRA blocks can only predict
1681
     * from other INTRA blocks. There are 2 golden frame coding types;
1682
     * blocks encoding in these modes can only predict from other blocks
1683
     * that were encoded with these 1 of these 2 modes. */
1684
    static const unsigned char compatible_frame[9] = {
1685
        1,    /* MODE_INTER_NO_MV */
1686
        0,    /* MODE_INTRA */
1687
        1,    /* MODE_INTER_PLUS_MV */
1688
        1,    /* MODE_INTER_LAST_MV */
1689
        1,    /* MODE_INTER_PRIOR_MV */
1690
        2,    /* MODE_USING_GOLDEN */
1691
        2,    /* MODE_GOLDEN_MV */
1692
        1,    /* MODE_INTER_FOUR_MV */
1693
        3     /* MODE_COPY */
1694
    };
1695
    int current_frame_type;
1696
1697
    /* there is a last DC predictor for each of the 3 frame types */
1698
    short last_dc[3];
1699
1700
420
    int transform = 0;
1701
1702
420
    vul =
1703
420
    vu  =
1704
420
    vur =
1705
420
    vl  = 0;
1706
420
    last_dc[0] =
1707
420
    last_dc[1] =
1708
420
    last_dc[2] = 0;
1709
1710
    /* for each fragment row... */
1711
14292
    for (y = 0; y < fragment_height; y++) {
1712
        /* for each fragment in a row... */
1713
1774512
        for (x = 0; x < fragment_width; x++, i++) {
1714
1715
            /* reverse prediction if this block was coded */
1716
1760640
            if (s->all_fragments[i].coding_method != MODE_COPY) {
1717
532576
                current_frame_type =
1718
532576
                    compatible_frame[s->all_fragments[i].coding_method];
1719
1720
532576
                transform = 0;
1721
532576
                if (x) {
1722
528445
                    l  = i - 1;
1723
528445
                    vl = DC_COEFF(l);
1724
528445
                    if (COMPATIBLE_FRAME(l))
1725
483186
                        transform |= PL;
1726
                }
1727
532576
                if (y) {
1728
513468
                    u  = i - fragment_width;
1729
513468
                    vu = DC_COEFF(u);
1730
513468
                    if (COMPATIBLE_FRAME(u))
1731
476069
                        transform |= PU;
1732
513468
                    if (x) {
1733
509661
                        ul  = i - fragment_width - 1;
1734
509661
                        vul = DC_COEFF(ul);
1735
509661
                        if (COMPATIBLE_FRAME(ul))
1736
461368
                            transform |= PUL;
1737
                    }
1738
513468
                    if (x + 1 < fragment_width) {
1739
505812
                        ur  = i - fragment_width + 1;
1740
505812
                        vur = DC_COEFF(ur);
1741
505812
                        if (COMPATIBLE_FRAME(ur))
1742
459980
                            transform |= PUR;
1743
                    }
1744
                }
1745
1746
532576
                if (transform == 0) {
1747
                    /* if there were no fragments to predict from, use last
1748
                     * DC saved */
1749
10817
                    predicted_dc = last_dc[current_frame_type];
1750
                } else {
1751
                    /* apply the appropriate predictor transform */
1752
521759
                    predicted_dc =
1753
521759
                        (predictor_transform[transform][0] * vul) +
1754
521759
                        (predictor_transform[transform][1] * vu) +
1755
521759
                        (predictor_transform[transform][2] * vur) +
1756
521759
                        (predictor_transform[transform][3] * vl);
1757
1758
521759
                    predicted_dc /= 128;
1759
1760
                    /* check for outranging on the [ul u l] and
1761
                     * [ul u ur l] predictors */
1762

521759
                    if ((transform == 15) || (transform == 13)) {
1763
434711
                        if (FFABS(predicted_dc - vu) > 128)
1764
2351
                            predicted_dc = vu;
1765
432360
                        else if (FFABS(predicted_dc - vl) > 128)
1766
1111
                            predicted_dc = vl;
1767
431249
                        else if (FFABS(predicted_dc - vul) > 128)
1768
2253
                            predicted_dc = vul;
1769
                    }
1770
                }
1771
1772
                /* at long last, apply the predictor */
1773
532576
                DC_COEFF(i) += predicted_dc;
1774
                /* save the DC */
1775
532576
                last_dc[current_frame_type] = DC_COEFF(i);
1776
            }
1777
        }
1778
    }
1779
420
}
1780
1781
2700
static void apply_loop_filter(Vp3DecodeContext *s, int plane,
1782
                              int ystart, int yend)
1783
{
1784
    int x, y;
1785
2700
    int *bounding_values = s->bounding_values_array + 127;
1786
1787
2700
    int width           = s->fragment_width[!!plane];
1788
2700
    int height          = s->fragment_height[!!plane];
1789
2700
    int fragment        = s->fragment_start[plane] + ystart * width;
1790
2700
    ptrdiff_t stride    = s->current_frame.f->linesize[plane];
1791
2700
    uint8_t *plane_data = s->current_frame.f->data[plane];
1792
2700
    if (!s->flipped_image)
1793
2700
        stride = -stride;
1794
2700
    plane_data += s->data_offset[plane] + 8 * ystart * stride;
1795
1796
10530
    for (y = ystart; y < yend; y++) {
1797
486710
        for (x = 0; x < width; x++) {
1798
            /* This code basically just deblocks on the edges of coded blocks.
1799
             * However, it has to be much more complicated because of the
1800
             * brain damaged deblock ordering used in VP3/Theora. Order matters
1801
             * because some pixels get filtered twice. */
1802
478880
            if (s->all_fragments[fragment].coding_method != MODE_COPY) {
1803
                /* do not perform left edge filter for left columns frags */
1804
367025
                if (x > 0) {
1805
363601
                    s->vp3dsp.h_loop_filter(
1806
363601
                        plane_data + 8 * x,
1807
                        stride, bounding_values);
1808
                }
1809
1810
                /* do not perform top edge filter for top row fragments */
1811
367025
                if (y > 0) {
1812
349625
                    s->vp3dsp.v_loop_filter(
1813
349625
                        plane_data + 8 * x,
1814
                        stride, bounding_values);
1815
                }
1816
1817
                /* do not perform right edge filter for right column
1818
                 * fragments or if right fragment neighbor is also coded
1819
                 * in this frame (it will be filtered in next iteration) */
1820
367025
                if ((x < width - 1) &&
1821
359725
                    (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
1822
32268
                    s->vp3dsp.h_loop_filter(
1823
32268
                        plane_data + 8 * x + 8,
1824
                        stride, bounding_values);
1825
                }
1826
1827
                /* do not perform bottom edge filter for bottom row
1828
                 * fragments or if bottom fragment neighbor is also coded
1829
                 * in this frame (it will be filtered in the next row) */
1830
367025
                if ((y < height - 1) &&
1831
352272
                    (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
1832
32946
                    s->vp3dsp.v_loop_filter(
1833
32946
                        plane_data + 8 * x + 8 * stride,
1834
                        stride, bounding_values);
1835
                }
1836
            }
1837
1838
478880
            fragment++;
1839
        }
1840
7830
        plane_data += 8 * stride;
1841
    }
1842
2700
}
1843
1844
/**
1845
 * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
1846
 * for the next block in coding order
1847
 */
1848
595828
static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
1849
                              int plane, int inter, int16_t block[64])
1850
{
1851
595828
    int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
1852
595828
    uint8_t *perm = s->idct_scantable;
1853
595828
    int i = 0;
1854
1855
    do {
1856
3343039
        int token = *s->dct_tokens[plane][i];
1857

3343039
        switch (token & 3) {
1858
587550
        case 0: // EOB
1859
587550
            if (--token < 4) // 0-3 are token types so the EOB run must now be 0
1860
280242
                s->dct_tokens[plane][i]++;
1861
            else
1862
307308
                *s->dct_tokens[plane][i] = token & ~3;
1863
587550
            goto end;
1864
913868
        case 1: // zero run
1865
913868
            s->dct_tokens[plane][i]++;
1866
913868
            i += (token >> 2) & 0x7f;
1867
913868
            if (i > 63) {
1868
                av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
1869
                return i;
1870
            }
1871
913868
            block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
1872
913868
            i++;
1873
913868
            break;
1874
1841621
        case 2: // coeff
1875
1841621
            block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
1876
1841621
            s->dct_tokens[plane][i++]++;
1877
1841621
            break;
1878
        default: // shouldn't happen
1879
            return i;
1880
        }
1881
2755489
    } while (i < 64);
1882
    // return value is expected to be a valid level
1883
8278
    i--;
1884
595828
end:
1885
    // the actual DC+prediction is in the fragment structure
1886
595828
    block[0] = frag->dc * s->qmat[0][inter][plane][0];
1887
595828
    return i;
1888
}
1889
1890
/**
1891
 * called when all pixels up to row y are complete
1892
 */
1893
1232
static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
1894
{
1895
    int h, cy, i;
1896
    int offset[AV_NUM_DATA_POINTERS];
1897
1898
1232
    if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
1899
        int y_flipped = s->flipped_image ? s->height - y : y;
1900
1901
        /* At the end of the frame, report INT_MAX instead of the height of
1902
         * the frame. This makes the other threads' ff_thread_await_progress()
1903
         * calls cheaper, because they don't have to clip their values. */
1904
        ff_thread_report_progress(&s->current_frame,
1905
                                  y_flipped == s->height ? INT_MAX
1906
                                                         : y_flipped - 1,
1907
                                  0);
1908
    }
1909
1910
1232
    if (!s->avctx->draw_horiz_band)
1911
1232
        return;
1912
1913
    h = y - s->last_slice_end;
1914
    s->last_slice_end = y;
1915
    y -= h;
1916
1917
    if (!s->flipped_image)
1918
        y = s->height - y - h;
1919
1920
    cy        = y >> s->chroma_y_shift;
1921
    offset[0] = s->current_frame.f->linesize[0] * y;
1922
    offset[1] = s->current_frame.f->linesize[1] * cy;
1923
    offset[2] = s->current_frame.f->linesize[2] * cy;
1924
    for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
1925
        offset[i] = 0;
1926
1927
    emms_c();
1928
    s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
1929
}
1930
1931
/**
1932
 * Wait for the reference frame of the current fragment.
1933
 * The progress value is in luma pixel rows.
1934
 */
1935
static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
1936
                                int motion_y, int y)
1937
{
1938
    ThreadFrame *ref_frame;
1939
    int ref_row;
1940
    int border = motion_y & 1;
1941
1942
    if (fragment->coding_method == MODE_USING_GOLDEN ||
1943
        fragment->coding_method == MODE_GOLDEN_MV)
1944
        ref_frame = &s->golden_frame;
1945
    else
1946
        ref_frame = &s->last_frame;
1947
1948
    ref_row = y + (motion_y >> 1);
1949
    ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
1950
1951
    ff_thread_await_progress(ref_frame, ref_row, 0);
1952
}
1953
1954
#if CONFIG_VP4_DECODER
1955
/**
1956
 * @return non-zero if temp (edge_emu_buffer) was populated
1957
 */
1958
36568
static int vp4_mc_loop_filter(Vp3DecodeContext *s, int plane, int motion_x, int motion_y, int bx, int by,
1959
       uint8_t * motion_source, int stride, int src_x, int src_y, uint8_t *temp)
1960
{
1961
36568
    int motion_shift = plane ? 4 : 2;
1962
36568
    int subpel_mask = plane ? 3 : 1;
1963
36568
    int *bounding_values = s->bounding_values_array + 127;
1964
1965
    int i;
1966
    int x, y;
1967
    int x2, y2;
1968
    int x_subpel, y_subpel;
1969
    int x_offset, y_offset;
1970
1971
36568
    int block_width = plane ? 8 : 16;
1972

36568
    int plane_width  = s->width  >> (plane && s->chroma_x_shift);
1973

36568
    int plane_height = s->height >> (plane && s->chroma_y_shift);
1974
1975
#define loop_stride 12
1976
    uint8_t loop[12 * loop_stride];
1977
1978
    /* using division instead of shift to correctly handle negative values */
1979
36568
    x = 8 * bx + motion_x / motion_shift;
1980
36568
    y = 8 * by + motion_y / motion_shift;
1981
1982
36568
    x_subpel = motion_x & subpel_mask;
1983
36568
    y_subpel = motion_y & subpel_mask;
1984
1985

36568
    if (x_subpel || y_subpel) {
1986
30063
        x--;
1987
30063
        y--;
1988
1989
30063
        if (x_subpel)
1990

22774
            x = FFMIN(x, x + FFSIGN(motion_x));
1991
1992
30063
        if (y_subpel)
1993

15343
            y = FFMIN(y, y + FFSIGN(motion_y));
1994
1995
30063
        x2 = x + block_width;
1996
30063
        y2 = y + block_width;
1997
1998


30063
        if (x2 < 0 || x2 >= plane_width || y2 < 0 || y2 >= plane_height)
1999
596
            return 0;
2000
2001
29467
        x_offset = (-(x + 2) & 7) + 2;
2002
29467
        y_offset = (-(y + 2) & 7) + 2;
2003
2004

29467
        if (x_offset > 8 + x_subpel && y_offset > 8 + y_subpel)
2005
            return 0;
2006
2007
29467
        s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2008
             loop_stride, stride,
2009
             12, 12, src_x - 1, src_y - 1,
2010
             plane_width,
2011
             plane_height);
2012
2013
29467
        if (x_offset <= 8 + x_subpel)
2014
25000
            ff_vp3dsp_h_loop_filter_12(loop + x_offset, loop_stride, bounding_values);
2015
2016
29467
        if (y_offset <= 8 + y_subpel)
2017
17032
            ff_vp3dsp_v_loop_filter_12(loop + y_offset*loop_stride, loop_stride, bounding_values);
2018
2019
    } else {
2020
2021
6505
        x_offset = -x & 7;
2022
6505
        y_offset = -y & 7;
2023
2024

6505
        if (!x_offset && !y_offset)
2025
118
            return 0;
2026
2027
6387
        s->vdsp.emulated_edge_mc(loop, motion_source - stride - 1,
2028
             loop_stride, stride,
2029
             12, 12, src_x - 1, src_y - 1,
2030
             plane_width,
2031
             plane_height);
2032
2033
#define safe_loop_filter(name, ptr, stride, bounding_values) \
2034
    if ((uintptr_t)(ptr) & 7) \
2035
        s->vp3dsp.name##_unaligned(ptr, stride, bounding_values); \
2036
    else \
2037
        s->vp3dsp.name(ptr, stride, bounding_values);
2038
2039
6387
        if (x_offset)
2040
5671
            safe_loop_filter(h_loop_filter, loop + loop_stride + x_offset + 1, loop_stride, bounding_values);
2041
2042
6387
        if (y_offset)
2043
3055
            safe_loop_filter(v_loop_filter, loop + (y_offset + 1)*loop_stride + 1, loop_stride, bounding_values);
2044
    }
2045
2046
358540
    for (i = 0; i < 9; i++)
2047
322686
        memcpy(temp + i*stride, loop + (i + 1) * loop_stride + 1, 9);
2048
2049
35854
    return 1;
2050
}
2051
#endif
2052
2053
/*
2054
 * Perform the final rendering for a particular slice of data.
2055
 * The slice number ranges from 0..(c_superblock_height - 1).
2056
 */
2057
1068
static void render_slice(Vp3DecodeContext *s, int slice)
2058
{
2059
    int x, y, i, j, fragment;
2060
1068
    int16_t *block = s->block;
2061
1068
    int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
2062
    int motion_halfpel_index;
2063
    uint8_t *motion_source;
2064
    int plane, first_pixel;
2065
2066
1068
    if (slice >= s->c_superblock_height)
2067
        return;
2068
2069
4272
    for (plane = 0; plane < 3; plane++) {
2070
3204
        uint8_t *output_plane = s->current_frame.f->data[plane] +
2071
3204
                                s->data_offset[plane];
2072
3204
        uint8_t *last_plane = s->last_frame.f->data[plane] +
2073
3204
                              s->data_offset[plane];
2074
3204
        uint8_t *golden_plane = s->golden_frame.f->data[plane] +
2075
3204
                                s->data_offset[plane];
2076
3204
        ptrdiff_t stride = s->current_frame.f->linesize[plane];
2077

3204
        int plane_width  = s->width  >> (plane && s->chroma_x_shift);
2078

3204
        int plane_height = s->height >> (plane && s->chroma_y_shift);
2079
3204
        int8_t(*motion_val)[2] = s->motion_val[!!plane];
2080
2081

3204
        int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
2082

3204
        int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
2083
3204
        int slice_width  = plane ? s->c_superblock_width
2084
3204
                                 : s->y_superblock_width;
2085
2086
3204
        int fragment_width  = s->fragment_width[!!plane];
2087
3204
        int fragment_height = s->fragment_height[!!plane];
2088
3204
        int fragment_start  = s->fragment_start[plane];
2089
2090
4272
        int do_await = !plane && HAVE_THREADS &&
2091
1068
                       (s->avctx->active_thread_type & FF_THREAD_FRAME);
2092
2093
3204
        if (!s->flipped_image)
2094
3204
            stride = -stride;
2095
        if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
2096
            continue;
2097
2098
        /* for each superblock row in the slice (both of them)... */
2099
7476
        for (; sb_y < slice_height; sb_y++) {
2100
            /* for each superblock in a row... */
2101
129560
            for (sb_x = 0; sb_x < slice_width; sb_x++) {
2102
                /* for each block in a superblock... */
2103
2129896
                for (j = 0; j < 16; j++) {
2104
2004608
                    x        = 4 * sb_x + hilbert_offset[j][0];
2105
2004608
                    y        = 4 * sb_y + hilbert_offset[j][1];
2106
2004608
                    fragment = y * fragment_width + x;
2107
2108
2004608
                    i = fragment_start + fragment;
2109
2110
                    // bounds check
2111

2004608
                    if (x >= fragment_width || y >= fragment_height)
2112
156416
                        continue;
2113
2114
1848192
                    first_pixel = 8 * y * stride + 8 * x;
2115
2116
1848192
                    if (do_await &&
2117
                        s->all_fragments[i].coding_method != MODE_INTRA)
2118
                        await_reference_row(s, &s->all_fragments[i],
2119
                                            motion_val[fragment][1],
2120
                                            (16 * y) >> s->chroma_y_shift);
2121
2122
                    /* transform if this block was coded */
2123
1848192
                    if (s->all_fragments[i].coding_method != MODE_COPY) {
2124
595828
                        if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
2125
592182
                            (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
2126
7685
                            motion_source = golden_plane;
2127
                        else
2128
588143
                            motion_source = last_plane;
2129
2130
595828
                        motion_source       += first_pixel;
2131
595828
                        motion_halfpel_index = 0;
2132
2133
                        /* sort out the motion vector if this fragment is coded
2134
                         * using a motion vector method */
2135
595828
                        if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
2136
377836
                            (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
2137
                            int src_x, src_y;
2138
374190
                            int standard_mc = 1;
2139
374190
                            motion_x = motion_val[fragment][0];
2140
374190
                            motion_y = motion_val[fragment][1];
2141
#if CONFIG_VP4_DECODER
2142

374190
                            if (plane && s->version >= 2) {
2143
11931
                                motion_x = (motion_x >> 1) | (motion_x & 1);
2144
11931
                                motion_y = (motion_y >> 1) | (motion_y & 1);
2145
                            }
2146
#endif
2147
2148
374190
                            src_x = (motion_x >> 1) + 8 * x;
2149
374190
                            src_y = (motion_y >> 1) + 8 * y;
2150
2151
374190
                            motion_halfpel_index = motion_x & 0x01;
2152
374190
                            motion_source       += (motion_x >> 1);
2153
2154
374190
                            motion_halfpel_index |= (motion_y & 0x01) << 1;
2155
374190
                            motion_source        += ((motion_y >> 1) * stride);
2156
2157
#if CONFIG_VP4_DECODER
2158
374190
                            if (s->version >= 2) {
2159
36568
                                uint8_t *temp = s->edge_emu_buffer;
2160
36568
                                if (stride < 0)
2161
36568
                                    temp -= 8 * stride;
2162
36568
                                if (vp4_mc_loop_filter(s, plane, motion_val[fragment][0], motion_val[fragment][1], x, y, motion_source, stride, src_x, src_y, temp)) {
2163
35854
                                    motion_source = temp;
2164
35854
                                    standard_mc = 0;
2165
                                }
2166
                            }
2167
#endif
2168
2169

374190
                            if (standard_mc && (
2170
336975
                                src_x < 0 || src_y < 0 ||
2171
322220
                                src_x + 9 >= plane_width ||
2172
315161
                                src_y + 9 >= plane_height)) {
2173
34786
                                uint8_t *temp = s->edge_emu_buffer;
2174
34786
                                if (stride < 0)
2175
34786
                                    temp -= 8 * stride;
2176
2177
34786
                                s->vdsp.emulated_edge_mc(temp, motion_source,
2178
                                                         stride, stride,
2179
                                                         9, 9, src_x, src_y,
2180
                                                         plane_width,
2181
                                                         plane_height);
2182
34786
                                motion_source = temp;
2183
                            }
2184
                        }
2185
2186
                        /* first, take care of copying a block from either the
2187
                         * previous or the golden frame */
2188
595828
                        if (s->all_fragments[i].coding_method != MODE_INTRA) {
2189
                            /* Note, it is possible to implement all MC cases
2190
                             * with put_no_rnd_pixels_l2 which would look more
2191
                             * like the VP3 source but this would be slower as
2192
                             * put_no_rnd_pixels_tab is better optimized */
2193
411494
                            if (motion_halfpel_index != 3) {
2194
293916
                                s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
2195
                                    output_plane + first_pixel,
2196
                                    motion_source, stride, 8);
2197
                            } else {
2198
                                /* d is 0 if motion_x and _y have the same sign,
2199
                                 * else -1 */
2200
117578
                                int d = (motion_x ^ motion_y) >> 31;
2201
117578
                                s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
2202
117578
                                                               motion_source - d,
2203
117578
                                                               motion_source + stride + 1 + d,
2204
                                                               stride, 8);
2205
                            }
2206
                        }
2207
2208
                        /* invert DCT and place (or add) in final output */
2209
2210
595828
                        if (s->all_fragments[i].coding_method == MODE_INTRA) {
2211
184334
                            vp3_dequant(s, s->all_fragments + i,
2212
                                        plane, 0, block);
2213
184334
                            s->vp3dsp.idct_put(output_plane + first_pixel,
2214
                                               stride,
2215
                                               block);
2216
                        } else {
2217
411494
                            if (vp3_dequant(s, s->all_fragments + i,
2218
                                            plane, 1, block)) {
2219
284346
                                s->vp3dsp.idct_add(output_plane + first_pixel,
2220
                                                   stride,
2221
                                                   block);
2222
                            } else {
2223
127148
                                s->vp3dsp.idct_dc_add(output_plane + first_pixel,
2224
                                                      stride, block);
2225
                            }
2226
                        }
2227
                    } else {
2228
                        /* copy directly from the previous frame */
2229
1252364
                        s->hdsp.put_pixels_tab[1][0](
2230
                            output_plane + first_pixel,
2231
1252364
                            last_plane + first_pixel,
2232
                            stride, 8);
2233
                    }
2234
                }
2235
            }
2236
2237
            // Filter up to the last row in the superblock row
2238

4272
            if (s->version < 2 && !s->skip_loop_filter)
2239
2280
                apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
2240
2280
                                  FFMIN(4 * sb_y + 3, fragment_height - 1));
2241
        }
2242
    }
2243
2244
    /* this looks like a good place for slice dispatch... */
2245
    /* algorithm:
2246
     *   if (slice == s->macroblock_height - 1)
2247
     *     dispatch (both last slice & 2nd-to-last slice);
2248
     *   else if (slice > 0)
2249
     *     dispatch (slice - 1);
2250
     */
2251
2252
1068
    vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
2253
                                 s->height - 16));
2254
}
2255
2256
/// Allocate tables for per-frame data in Vp3DecodeContext
2257
12
static av_cold int allocate_tables(AVCodecContext *avctx)
2258
{
2259
12
    Vp3DecodeContext *s = avctx->priv_data;
2260
    int y_fragment_count, c_fragment_count;
2261
2262
12
    free_tables(avctx);
2263
2264
12
    y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
2265
12
    c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
2266
2267
    /* superblock_coding is used by unpack_superblocks (VP3/Theora) and vp4_unpack_macroblocks (VP4) */
2268
12
    s->superblock_coding = av_mallocz(FFMAX(s->superblock_count, s->yuv_macroblock_count));
2269
12
    s->all_fragments     = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
2270
2271
12
    s-> kf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2272
12
    s->nkf_coded_fragment_list = av_mallocz_array(s->fragment_count, sizeof(int));
2273
12
    memset(s-> num_kf_coded_fragment, -1, sizeof(s-> num_kf_coded_fragment));
2274
2275
12
    s->dct_tokens_base = av_mallocz_array(s->fragment_count,
2276
                                          64 * sizeof(*s->dct_tokens_base));
2277
12
    s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
2278
12
    s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
2279
2280
    /* work out the block mapping tables */
2281
12
    s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
2282
12
    s->macroblock_coding    = av_mallocz(s->macroblock_count + 1);
2283
2284
12
    s->dc_pred_row = av_malloc_array(s->y_superblock_width * 4, sizeof(*s->dc_pred_row));
2285
2286

12
    if (!s->superblock_coding    || !s->all_fragments          ||
2287

12
        !s->dct_tokens_base      || !s->kf_coded_fragment_list ||
2288
12
        !s->nkf_coded_fragment_list ||
2289

12
        !s->superblock_fragments || !s->macroblock_coding      ||
2290
12
        !s->dc_pred_row ||
2291

12
        !s->motion_val[0]        || !s->motion_val[1]) {
2292
        return -1;
2293
    }
2294
2295
12
    init_block_mapping(s);
2296
2297
12
    return 0;
2298
}
2299
2300
12
static av_cold int init_frames(Vp3DecodeContext *s)
2301
{
2302
12
    s->current_frame.f = av_frame_alloc();
2303
12
    s->last_frame.f    = av_frame_alloc();
2304
12
    s->golden_frame.f  = av_frame_alloc();
2305
2306

12
    if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f)
2307
        return AVERROR(ENOMEM);
2308
2309
12
    return 0;
2310
}
2311
2312
12
static av_cold int vp3_decode_init(AVCodecContext *avctx)
2313
{
2314
12
    Vp3DecodeContext *s = avctx->priv_data;
2315
    int i, inter, plane, ret;
2316
    int c_width;
2317
    int c_height;
2318
    int y_fragment_count, c_fragment_count;
2319
#if CONFIG_VP4_DECODER
2320
    int j;
2321
#endif
2322
2323
12
    ret = init_frames(s);
2324
12
    if (ret < 0)
2325
        return ret;
2326
2327
12
    if (avctx->codec_tag == MKTAG('V', 'P', '4', '0'))
2328
2
        s->version = 3;
2329
10
    else if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
2330
        s->version = 0;
2331
    else
2332
10
        s->version = 1;
2333
2334
12
    s->avctx  = avctx;
2335
12
    s->width  = FFALIGN(avctx->coded_width, 16);
2336
12
    s->height = FFALIGN(avctx->coded_height, 16);
2337
12
    if (avctx->codec_id != AV_CODEC_ID_THEORA)
2338
5
        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2339
12
    avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
2340
12
    ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
2341
12
    ff_videodsp_init(&s->vdsp, 8);
2342
12
    ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
2343
2344
780
    for (i = 0; i < 64; i++) {
2345
#define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
2346
768
        s->idct_permutation[i] = TRANSPOSE(i);
2347
768
        s->idct_scantable[i]   = TRANSPOSE(ff_zigzag_direct[i]);
2348
#undef TRANSPOSE
2349
    }
2350
2351
    /* initialize to an impossible value which will force a recalculation
2352
     * in the first frame decode */
2353
48
    for (i = 0; i < 3; i++)
2354
36
        s->qps[i] = -1;
2355
2356
12
    ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
2357
12
    if (ret)
2358
        return ret;
2359
2360
12
    s->y_superblock_width  = (s->width  + 31) / 32;
2361
12
    s->y_superblock_height = (s->height + 31) / 32;
2362
12
    s->y_superblock_count  = s->y_superblock_width * s->y_superblock_height;
2363
2364
    /* work out the dimensions for the C planes */
2365
12
    c_width                = s->width >> s->chroma_x_shift;
2366
12
    c_height               = s->height >> s->chroma_y_shift;
2367
12
    s->c_superblock_width  = (c_width  + 31) / 32;
2368
12
    s->c_superblock_height = (c_height + 31) / 32;
2369
12
    s->c_superblock_count  = s->c_superblock_width * s->c_superblock_height;
2370
2371
12
    s->superblock_count   = s->y_superblock_count + (s->c_superblock_count * 2);
2372
12
    s->u_superblock_start = s->y_superblock_count;
2373
12
    s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
2374
2375
12
    s->macroblock_width  = (s->width  + 15) / 16;
2376
12
    s->macroblock_height = (s->height + 15) / 16;
2377
12
    s->macroblock_count  = s->macroblock_width * s->macroblock_height;
2378
12
    s->c_macroblock_width  = (c_width  + 15) / 16;
2379
12
    s->c_macroblock_height = (c_height + 15) / 16;
2380
12
    s->c_macroblock_count  = s->c_macroblock_width * s->c_macroblock_height;
2381
12
    s->yuv_macroblock_count = s->macroblock_count + 2 * s->c_macroblock_count;
2382
2383
12
    s->fragment_width[0]  = s->width / FRAGMENT_PIXELS;
2384
12
    s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
2385
12
    s->fragment_width[1]  = s->fragment_width[0] >> s->chroma_x_shift;
2386
12
    s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
2387
2388
    /* fragment count covers all 8x8 blocks for all 3 planes */
2389
12
    y_fragment_count     = s->fragment_width[0] * s->fragment_height[0];
2390
12
    c_fragment_count     = s->fragment_width[1] * s->fragment_height[1];
2391
12
    s->fragment_count    = y_fragment_count + 2 * c_fragment_count;
2392
12
    s->fragment_start[1] = y_fragment_count;
2393
12
    s->fragment_start[2] = y_fragment_count + c_fragment_count;
2394
2395
12
    if (!s->theora_tables) {
2396
325
        for (i = 0; i < 64; i++) {
2397
320
            s->coded_dc_scale_factor[0][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_y_dc_scale_factor[i];
2398
320
            s->coded_dc_scale_factor[1][i] = s->version < 2 ? vp31_dc_scale_factor[i] : vp4_uv_dc_scale_factor[i];
2399
320
            s->coded_ac_scale_factor[i] = s->version < 2 ? vp31_ac_scale_factor[i] : vp4_ac_scale_factor[i];
2400
320
            s->base_matrix[0][i]        = s->version < 2 ? vp31_intra_y_dequant[i] : vp4_generic_dequant[i];
2401
320
            s->base_matrix[1][i]        = s->version < 2 ? vp31_intra_c_dequant[i] : vp4_generic_dequant[i];
2402
320
            s->base_matrix[2][i]        = s->version < 2 ? vp31_inter_dequant[i]   : vp4_generic_dequant[i];
2403
320
            s->filter_limit_values[i]   = s->version < 2 ? vp31_filter_limit_values[i] : vp4_filter_limit_values[i];
2404
        }
2405
2406
15
        for (inter = 0; inter < 2; inter++) {
2407
40
            for (plane = 0; plane < 3; plane++) {
2408
30
                s->qr_count[inter][plane]   = 1;
2409
30
                s->qr_size[inter][plane][0] = 63;
2410
30
                s->qr_base[inter][plane][0] =
2411
30
                s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
2412
            }
2413
        }
2414
2415
        /* init VLC tables */
2416
5
        if (s->version < 2) {
2417
243
            for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2418
240
                if ((ret = init_vlc(&s->coeff_vlc[i], 11, 32,
2419
                                    &vp3_bias[i][0][1], 4, 2,
2420
                                    &vp3_bias[i][0][0], 4, 2, 0)) < 0)
2421
                    return ret;
2422
            }
2423
#if CONFIG_VP4_DECODER
2424
        } else { /* version >= 2 */
2425
162
            for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2426
160
                if ((ret = init_vlc(&s->coeff_vlc[i], 11, 32,
2427
                                    &vp4_bias[i][0][1], 4, 2,
2428
                                    &vp4_bias[i][0][0], 4, 2, 0)) < 0)
2429
                    return ret;
2430
            }
2431
#endif
2432
        }
2433
    } else {
2434
567
        for (i = 0; i < FF_ARRAY_ELEMS(s->coeff_vlc); i++) {
2435
560
            if (init_vlc(&s->coeff_vlc[i], 11, 32,
2436
                         &s->huffman_table[i][0][1], 8, 4,
2437
                         &s->huffman_table[i][0][0], 8, 4, 0) < 0)
2438
                goto vlc_fail;
2439
        }
2440
    }
2441
2442
12
    if ((ret = init_vlc(&s->superblock_run_length_vlc, 6, 34,
2443
                        &superblock_run_length_vlc_table[0][1], 4, 2,
2444
                        &superblock_run_length_vlc_table[0][0], 4, 2, 0)) < 0)
2445
        return ret;
2446
2447
12
    if ((ret = init_vlc(&s->fragment_run_length_vlc, 5, 30,
2448
                        &fragment_run_length_vlc_table[0][1], 4, 2,
2449
                        &fragment_run_length_vlc_table[0][0], 4, 2, 0)) < 0)
2450
        return ret;
2451
2452
12
    if ((ret = init_vlc(&s->mode_code_vlc, 3, 8,
2453
                        &mode_code_vlc_table[0][1], 2, 1,
2454
                        &mode_code_vlc_table[0][0], 2, 1, 0)) < 0)
2455
        return ret;
2456
2457
12
    if ((ret = init_vlc(&s->motion_vector_vlc, 6, 63,
2458
                        &motion_vector_vlc_table[0][1], 2, 1,
2459
                        &motion_vector_vlc_table[0][0], 2, 1, 0)) < 0)
2460
        return ret;
2461
2462
#if CONFIG_VP4_DECODER
2463
36
    for (j = 0; j < 2; j++)
2464
192
        for (i = 0; i < 7; i++)
2465
168
            if ((ret = init_vlc(&s->vp4_mv_vlc[j][i], 6, 63,
2466
                                &vp4_mv_vlc[j][i][0][1], 4, 2,
2467
                                &vp4_mv_vlc[j][i][0][0], 4, 2, 0)) < 0)
2468
                return ret;
2469
2470
    /* version >= 2 */
2471
36
    for (i = 0; i < 2; i++)
2472
24
        if ((ret = init_vlc(&s->block_pattern_vlc[i], 3, 14,
2473
                            &vp4_block_pattern_vlc[i][0][1], 2, 1,
2474
                            &vp4_block_pattern_vlc[i][0][0], 2, 1, 0)) < 0)
2475
            return ret;
2476
#endif
2477
2478
12
    return allocate_tables(avctx);
2479
2480
vlc_fail:
2481
    av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
2482
    return -1;
2483
}
2484
2485
/// Release and shuffle frames after decode finishes
2486
164
static int update_frames(AVCodecContext *avctx)
2487
{
2488
164
    Vp3DecodeContext *s = avctx->priv_data;
2489
164
    int ret = 0;
2490
2491
    /* shuffle frames (last = current) */
2492
164
    ff_thread_release_buffer(avctx, &s->last_frame);
2493
164
    ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
2494
164
    if (ret < 0)
2495
        goto fail;
2496
2497
164
    if (s->keyframe) {
2498
6
        ff_thread_release_buffer(avctx, &s->golden_frame);
2499
6
        ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
2500
    }
2501
2502
158
fail:
2503
164
    ff_thread_release_buffer(avctx, &s->current_frame);
2504
164
    return ret;
2505
}
2506
2507
#if HAVE_THREADS
2508
static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
2509
{
2510
    ff_thread_release_buffer(s->avctx, dst);
2511
    if (src->f->data[0])
2512
        return ff_thread_ref_frame(dst, src);
2513
    return 0;
2514
}
2515
2516
static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
2517
{
2518
    int ret;
2519
    if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
2520
        (ret = ref_frame(dst, &dst->golden_frame,  &src->golden_frame)) < 0  ||
2521
        (ret = ref_frame(dst, &dst->last_frame,    &src->last_frame)) < 0)
2522
        return ret;
2523
    return 0;
2524
}
2525
2526
static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
2527
{
2528
    Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
2529
    int qps_changed = 0, i, err;
2530
2531
    if (!s1->current_frame.f->data[0] ||
2532
        s->width != s1->width || s->height != s1->height) {
2533
        if (s != s1)
2534
            ref_frames(s, s1);
2535
        return -1;
2536
    }
2537
2538
    if (s != s1) {
2539
        // copy previous frame data
2540
        if ((err = ref_frames(s, s1)) < 0)
2541
            return err;
2542
2543
        s->keyframe = s1->keyframe;
2544
2545
        // copy qscale data if necessary
2546
        for (i = 0; i < 3; i++) {
2547
            if (s->qps[i] != s1->qps[1]) {
2548
                qps_changed = 1;
2549
                memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
2550
            }
2551
        }
2552
2553
        if (s->qps[0] != s1->qps[0])
2554
            memcpy(&s->bounding_values_array, &s1->bounding_values_array,
2555
                   sizeof(s->bounding_values_array));
2556
2557
        if (qps_changed) {
2558
            memcpy(s->qps,      s1->qps,      sizeof(s->qps));
2559
            memcpy(s->last_qps, s1->last_qps, sizeof(s->last_qps));
2560
            s->nqps = s1->nqps;
2561
        }
2562
    }
2563
2564
    return update_frames(dst);
2565
}
2566
#endif
2567
2568
164
static int vp3_decode_frame(AVCodecContext *avctx,
2569
                            void *data, int *got_frame,
2570
                            AVPacket *avpkt)
2571
{
2572
164
    AVFrame     *frame  = data;
2573
164
    const uint8_t *buf  = avpkt->data;
2574
164
    int buf_size        = avpkt->size;
2575
164
    Vp3DecodeContext *s = avctx->priv_data;
2576
    GetBitContext gb;
2577
    int i, ret;
2578
2579
164
    if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
2580
        return ret;
2581
2582
#if CONFIG_THEORA_DECODER
2583

164
    if (s->theora && get_bits1(&gb)) {
2584
        int type = get_bits(&gb, 7);
2585
        skip_bits_long(&gb, 6*8); /* "theora" */
2586
2587
        if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
2588
            av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
2589
            return AVERROR_PATCHWELCOME;
2590
        }
2591
        if (type == 0) {
2592
            vp3_decode_end(avctx);
2593
            ret = theora_decode_header(avctx, &gb);
2594
2595
            if (ret >= 0)
2596
                ret = vp3_decode_init(avctx);
2597
            if (ret < 0) {
2598
                vp3_decode_end(avctx);
2599
                return ret;
2600
            }
2601
            return buf_size;
2602
        } else if (type == 2) {
2603
            vp3_decode_end(avctx);
2604
            ret = theora_decode_tables(avctx, &gb);
2605
            if (ret >= 0)
2606
                ret = vp3_decode_init(avctx);
2607
            if (ret < 0) {
2608
                vp3_decode_end(avctx);
2609
                return ret;
2610
            }
2611
            return buf_size;
2612
        }
2613
2614
        av_log(avctx, AV_LOG_ERROR,
2615
               "Header packet passed to frame decoder, skipping\n");
2616
        return -1;
2617
    }
2618
#endif
2619
2620
164
    s->keyframe = !get_bits1(&gb);
2621
164
    if (!s->all_fragments) {
2622
        av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
2623
        return -1;
2624
    }
2625
164
    if (!s->theora)
2626
138
        skip_bits(&gb, 1);
2627
656
    for (i = 0; i < 3; i++)
2628
492
        s->last_qps[i] = s->qps[i];
2629
2630
164
    s->nqps = 0;
2631
    do {
2632
164
        s->qps[s->nqps++] = get_bits(&gb, 6);
2633

164
    } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
2634
492
    for (i = s->nqps; i < 3; i++)
2635
328
        s->qps[i] = -1;
2636
2637
164
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2638
        av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
2639
               s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
2640
2641

302
    s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
2642
138
                          avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
2643
138
                                                                  : AVDISCARD_NONKEY);
2644
2645
164
    if (s->qps[0] != s->last_qps[0])
2646
62
        init_loop_filter(s);
2647
2648
328
    for (i = 0; i < s->nqps; i++)
2649
        // reinit all dequantizers if the first one changed, because
2650
        // the DC of the first quantizer must be used for all matrices
2651

164
        if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
2652
62
            init_dequantizer(s, i);
2653
2654

164
    if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
2655
        return buf_size;
2656
2657
328
    s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
2658
164
                                                : AV_PICTURE_TYPE_P;
2659
164
    s->current_frame.f->key_frame = s->keyframe;
2660
164
    if ((ret = ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF)) < 0)
2661
        goto error;
2662
2663
164
    if (!s->edge_emu_buffer)
2664
5
        s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
2665
2666
164
    if (s->keyframe) {
2667
6
        if (!s->theora) {
2668
3
            skip_bits(&gb, 4); /* width code */
2669
3
            skip_bits(&gb, 4); /* height code */
2670
3
            if (s->version) {
2671
3
                s->version = get_bits(&gb, 5);
2672
3
                if (avctx->frame_number == 0)
2673
2
                    av_log(s->avctx, AV_LOG_DEBUG,
2674
                           "VP version: %d\n", s->version);
2675
            }
2676
        }
2677

6
        if (s->version || s->theora) {
2678
6
            if (get_bits1(&gb))
2679
                av_log(s->avctx, AV_LOG_ERROR,
2680
                       "Warning, unsupported keyframe coding type?!\n");
2681
6
            skip_bits(&gb, 2); /* reserved? */
2682
2683
#if CONFIG_VP4_DECODER
2684
6
            if (s->version >= 2) {
2685
                int mb_height, mb_width;
2686
                int mb_width_mul, mb_width_div, mb_height_mul, mb_height_div;
2687
2688
2
                mb_height = get_bits(&gb, 8);
2689
2
                mb_width  = get_bits(&gb, 8);
2690
2
                if (mb_height != s->macroblock_height ||
2691
2
                    mb_width != s->macroblock_width)
2692
                    avpriv_request_sample(s->avctx, "macroblock dimension mismatch");
2693
2694
2
                mb_width_mul = get_bits(&gb, 5);
2695
2
                mb_width_div = get_bits(&gb, 3);
2696
2
                mb_height_mul = get_bits(&gb, 5);
2697
2
                mb_height_div = get_bits(&gb, 3);
2698


2
                if (mb_width_mul != 1 || mb_width_div != 1 || mb_height_mul != 1 || mb_height_div != 1)
2699
                    avpriv_request_sample(s->avctx, "unexpected macroblock dimension multipler/divider");
2700
2701
2
                if (get_bits(&gb, 2))
2702
                    avpriv_request_sample(s->avctx, "unknown bits");
2703
            }
2704
#endif
2705
        }
2706
    } else {
2707
158
        if (!s->golden_frame.f->data[0]) {
2708
            av_log(s->avctx, AV_LOG_WARNING,
2709
                   "vp3: first frame not a keyframe\n");
2710
2711
            s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
2712
            if ((ret = ff_thread_get_buffer(avctx, &s->golden_frame,
2713
                                     AV_GET_BUFFER_FLAG_REF)) < 0)
2714
                goto error;
2715
            ff_thread_release_buffer(avctx, &s->last_frame);
2716
            if ((ret = ff_thread_ref_frame(&s->last_frame,
2717
                                           &s->golden_frame)) < 0)
2718
                goto error;
2719
            ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
2720
        }
2721
    }
2722
2723
164
    memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
2724
164
    ff_thread_finish_setup(avctx);
2725
2726
164
    if (s->version < 2) {
2727
140
        if ((ret = unpack_superblocks(s, &gb)) < 0) {
2728
            av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
2729
            goto error;
2730
        }
2731
#if CONFIG_VP4_DECODER
2732
    } else {
2733
24
        if ((ret = vp4_unpack_macroblocks(s, &gb)) < 0) {
2734
            av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_macroblocks\n");
2735
            goto error;
2736
    }
2737
#endif
2738
    }
2739
164
    if ((ret = unpack_modes(s, &gb)) < 0) {
2740
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
2741
        goto error;
2742
    }
2743
164
    if (ret = unpack_vectors(s, &gb)) {
2744
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
2745
        goto error;
2746
    }
2747
164
    if ((ret = unpack_block_qpis(s, &gb)) < 0) {
2748
        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
2749
        goto error;
2750
    }
2751
2752
164
    if (s->version < 2) {
2753
140
        if ((ret = unpack_dct_coeffs(s, &gb)) < 0) {
2754
            av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
2755
            goto error;
2756
        }
2757
#if CONFIG_VP4_DECODER
2758
    } else {
2759
24
        if ((ret = vp4_unpack_dct_coeffs(s, &gb)) < 0) {
2760
            av_log(s->avctx, AV_LOG_ERROR, "error in vp4_unpack_dct_coeffs\n");
2761
            goto error;
2762
        }
2763
#endif
2764
    }
2765
2766
656
    for (i = 0; i < 3; i++) {
2767

492
        int height = s->height >> (i && s->chroma_y_shift);
2768
492
        if (s->flipped_image)
2769
            s->data_offset[i] = 0;
2770
        else
2771
492
            s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
2772
    }
2773
2774
164
    s->last_slice_end = 0;
2775
1232
    for (i = 0; i < s->c_superblock_height; i++)
2776
1068
        render_slice(s, i);
2777
2778
    // filter the last row
2779
164
    if (s->version < 2)
2780
560
        for (i = 0; i < 3; i++) {
2781

420
            int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
2782
420
            apply_loop_filter(s, i, row, row + 1);
2783
        }
2784
164
    vp3_draw_horiz_band(s, s->height);
2785
2786
    /* output frame, offset as needed */
2787
164
    if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
2788
        return ret;
2789
2790
164
    frame->crop_left   = s->offset_x;
2791
164
    frame->crop_right  = avctx->coded_width - avctx->width - s->offset_x;
2792
164
    frame->crop_top    = s->offset_y;
2793
164
    frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
2794
2795
164
    *got_frame = 1;
2796
2797
164
    if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
2798
164
        ret = update_frames(avctx);
2799
164
        if (ret < 0)
2800
            return ret;
2801
    }
2802
2803
164
    return buf_size;
2804
2805
error:
2806
    ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
2807
2808
    if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
2809
        av_frame_unref(s->current_frame.f);
2810
2811
    return ret;
2812
}
2813
2814
34720
static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
2815
{
2816
34720
    Vp3DecodeContext *s = avctx->priv_data;
2817
2818
34720
    if (get_bits1(gb)) {
2819
        int token;
2820
17920
        if (s->entries >= 32) { /* overflow */
2821
            av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2822
            return -1;
2823
        }
2824
17920
        token = get_bits(gb, 5);
2825
        ff_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
2826
                s->hti, s->hbits, token, s->entries, s->huff_code_size);
2827
17920
        s->huffman_table[s->hti][token][0] = s->hbits;
2828
17920
        s->huffman_table[s->hti][token][1] = s->huff_code_size;
2829
17920
        s->entries++;
2830
    } else {
2831
16800
        if (s->huff_code_size >= 32) { /* overflow */
2832
            av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
2833
            return -1;
2834
        }
2835
16800
        s->huff_code_size++;
2836
16800
        s->hbits <<= 1;
2837
16800
        if (read_huffman_tree(avctx, gb))
2838
            return -1;
2839
16800
        s->hbits |= 1;
2840
16800
        if (read_huffman_tree(avctx, gb))
2841
            return -1;
2842
16800
        s->hbits >>= 1;
2843
16800
        s->huff_code_size--;
2844
    }
2845
34720
    return 0;
2846
}
2847
2848
#if CONFIG_THEORA_DECODER
2849
static const enum AVPixelFormat theora_pix_fmts[4] = {
2850
    AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
2851
};
2852
2853
7
static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
2854
{
2855
7
    Vp3DecodeContext *s = avctx->priv_data;
2856
    int visible_width, visible_height, colorspace;
2857
7
    uint8_t offset_x = 0, offset_y = 0;
2858
    int ret;
2859
    AVRational fps, aspect;
2860
2861
7
    s->theora_header = 0;
2862
7
    s->theora = get_bits(gb, 24);
2863
7
    av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
2864
7
    if (!s->theora) {
2865
        s->theora = 1;
2866
        avpriv_request_sample(s->avctx, "theora 0");
2867
    }
2868
2869
    /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
2870
     * but previous versions have the image flipped relative to vp3 */
2871
7
    if (s->theora < 0x030200) {
2872
        s->flipped_image = 1;
2873
        av_log(avctx, AV_LOG_DEBUG,
2874
               "Old (<alpha3) Theora bitstream, flipped image\n");
2875
    }
2876
2877
7
    visible_width  =
2878
7
    s->width       = get_bits(gb, 16) << 4;
2879
7
    visible_height =
2880
7
    s->height      = get_bits(gb, 16) << 4;
2881
2882
7
    if (s->theora >= 0x030200) {
2883
7
        visible_width  = get_bits(gb, 24);
2884
7
        visible_height = get_bits(gb, 24);
2885
2886
7
        offset_x = get_bits(gb, 8); /* offset x */
2887
7
        offset_y = get_bits(gb, 8); /* offset y, from bottom */
2888
    }
2889
2890
    /* sanity check */
2891
7
    if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
2892
7
        visible_width  + offset_x > s->width ||
2893
7
        visible_height + offset_y > s->height) {
2894
        av_log(avctx, AV_LOG_ERROR,
2895
               "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
2896
               visible_width, visible_height, offset_x, offset_y,
2897
               s->width, s->height);
2898
        return AVERROR_INVALIDDATA;
2899
    }
2900
2901
7
    fps.num = get_bits_long(gb, 32);
2902
7
    fps.den = get_bits_long(gb, 32);
2903

7
    if (fps.num && fps.den) {
2904

7
        if (fps.num < 0 || fps.den < 0) {
2905
            av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
2906
            return AVERROR_INVALIDDATA;
2907
        }
2908
7
        av_reduce(&avctx->framerate.den, &avctx->framerate.num,
2909
7
                  fps.den, fps.num, 1 << 30);
2910
    }
2911
2912
7
    aspect.num = get_bits(gb, 24);
2913
7
    aspect.den = get_bits(gb, 24);
2914

7
    if (aspect.num && aspect.den) {
2915
5
        av_reduce(&avctx->sample_aspect_ratio.num,
2916
                  &avctx->sample_aspect_ratio.den,
2917
5
                  aspect.num, aspect.den, 1 << 30);
2918
5
        ff_set_sar(avctx, avctx->sample_aspect_ratio);
2919
    }
2920
2921
7
    if (s->theora < 0x030200)
2922
        skip_bits(gb, 5); /* keyframe frequency force */
2923
7
    colorspace = get_bits(gb, 8);
2924
7
    skip_bits(gb, 24); /* bitrate */
2925
2926
7
    skip_bits(gb, 6); /* quality hint */
2927
2928
7
    if (s->theora >= 0x030200) {
2929
7
        skip_bits(gb, 5); /* keyframe frequency force */
2930
7
        avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
2931
7
        if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
2932
            av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
2933
            return AVERROR_INVALIDDATA;
2934
        }
2935
7
        skip_bits(gb, 3); /* reserved */
2936
    } else
2937
        avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2938
2939
7
    ret = ff_set_dimensions(avctx, s->width, s->height);
2940
7
    if (ret < 0)
2941
        return ret;
2942
7
    if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
2943
7
        avctx->width  = visible_width;
2944
7
        avctx->height = visible_height;
2945
        // translate offsets from theora axis ([0,0] lower left)
2946
        // to normal axis ([0,0] upper left)
2947
7
        s->offset_x = offset_x;
2948
7
        s->offset_y = s->height - visible_height - offset_y;
2949
    }
2950
2951
7
    if (colorspace == 1)
2952
        avctx->color_primaries = AVCOL_PRI_BT470M;
2953
7
    else if (colorspace == 2)
2954
        avctx->color_primaries = AVCOL_PRI_BT470BG;
2955
2956

7
    if (colorspace == 1 || colorspace == 2) {
2957
        avctx->colorspace = AVCOL_SPC_BT470BG;
2958
        avctx->color_trc  = AVCOL_TRC_BT709;
2959
    }
2960
2961
7
    s->theora_header = 1;
2962
7
    return 0;
2963
}
2964
2965
7
static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
2966
{
2967
7
    Vp3DecodeContext *s = avctx->priv_data;
2968
    int i, n, matrices, inter, plane;
2969
2970
7
    if (!s->theora_header)
2971
        return AVERROR_INVALIDDATA;
2972
2973
7
    if (s->theora >= 0x030200) {
2974
7
        n = get_bits(gb, 3);
2975
        /* loop filter limit values table */
2976
7
        if (n)
2977
455
            for (i = 0; i < 64; i++)
2978
448
                s->filter_limit_values[i] = get_bits(gb, n);
2979
    }
2980
2981
7
    if (s->theora >= 0x030200)
2982
7
        n = get_bits(gb, 4) + 1;
2983
    else
2984
        n = 16;
2985
    /* quality threshold table */
2986
455
    for (i = 0; i < 64; i++)
2987
448
        s->coded_ac_scale_factor[i] = get_bits(gb, n);
2988
2989
7
    if (s->theora >= 0x030200)
2990
7
        n = get_bits(gb, 4) + 1;
2991
    else
2992
        n = 16;
2993
    /* dc scale factor table */
2994
455
    for (i = 0; i < 64; i++)
2995
448
        s->coded_dc_scale_factor[0][i] =
2996
448
        s->coded_dc_scale_factor[1][i] = get_bits(gb, n);
2997
2998
7
    if (s->theora >= 0x030200)
2999
7
        matrices = get_bits(gb, 9) + 1;
3000
    else
3001
        matrices = 3;
3002
3003
7
    if (matrices > 384) {
3004
        av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
3005
        return -1;
3006
    }
3007
3008
52
    for (n = 0; n < matrices; n++)
3009
2925
        for (i = 0; i < 64; i++)
3010
2880
            s->base_matrix[n][i] = get_bits(gb, 8);
3011
3012
21
    for (inter = 0; inter <= 1; inter++) {
3013
56
        for (plane = 0; plane <= 2; plane++) {
3014
42
            int newqr = 1;
3015

42
            if (inter || plane > 0)
3016
35
                newqr = get_bits1(gb);
3017
42
            if (!newqr) {
3018
                int qtj, plj;
3019

23
                if (inter && get_bits1(gb)) {
3020
6
                    qtj = 0;
3021
6
                    plj = plane;
3022
                } else {
3023
17
                    qtj = (3 * inter + plane - 1) / 3;
3024
17
                    plj = (plane + 2) % 3;
3025
                }
3026
23
                s->qr_count[inter][plane] = s->qr_count[qtj][plj];
3027
23
                memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
3028
                       sizeof(s->qr_size[0][0]));
3029
23
                memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
3030
                       sizeof(s->qr_base[0][0]));
3031
            } else {
3032
19
                int qri = 0;
3033
19
                int qi  = 0;
3034
3035
                for (;;) {
3036
62
                    i = get_bits(gb, av_log2(matrices - 1) + 1);
3037
62
                    if (i >= matrices) {
3038
                        av_log(avctx, AV_LOG_ERROR,
3039
                               "invalid base matrix index\n");
3040
                        return -1;
3041
                    }
3042
62
                    s->qr_base[inter][plane][qri] = i;
3043
62
                    if (qi >= 63)
3044
19
                        break;
3045
43
                    i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
3046
43
                    s->qr_size[inter][plane][qri++] = i;
3047
43
                    qi += i;
3048
                }
3049
3050
19
                if (qi > 63) {
3051
                    av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
3052
                    return -1;
3053
                }
3054
19
                s->qr_count[inter][plane] = qri;
3055
            }
3056
        }
3057
    }
3058
3059
    /* Huffman tables */
3060
567
    for (s->hti = 0; s->hti < 80; s->hti++) {
3061
560
        s->entries        = 0;
3062
560
        s->huff_code_size = 1;
3063
560
        if (!get_bits1(gb)) {
3064
560
            s->hbits = 0;
3065
560
            if (read_huffman_tree(avctx, gb))
3066
                return -1;
3067
560
            s->hbits = 1;
3068
560
            if (read_huffman_tree(avctx, gb))
3069
                return -1;
3070
        }
3071
    }
3072
3073
7
    s->theora_tables = 1;
3074
3075
7
    return 0;
3076
}
3077
3078
7
static av_cold int theora_decode_init(AVCodecContext *avctx)
3079
{
3080
7
    Vp3DecodeContext *s = avctx->priv_data;
3081
    GetBitContext gb;
3082
    int ptype;
3083
    const uint8_t *header_start[3];
3084
    int header_len[3];
3085
    int i;
3086
    int ret;
3087
3088
7
    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
3089
3090
7
    s->theora = 1;
3091
3092
7
    if (!avctx->extradata_size) {
3093
        av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
3094
        return -1;
3095
    }
3096
3097
7
    if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
3098
                                  42, header_start, header_len) < 0) {
3099
        av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
3100
        return -1;
3101
    }
3102
3103
28
    for (i = 0; i < 3; i++) {
3104
21
        if (header_len[i] <= 0)
3105
            continue;
3106
21
        ret = init_get_bits8(&gb, header_start[i], header_len[i]);
3107
21
        if (ret < 0)
3108
            return ret;
3109
3110
21
        ptype = get_bits(&gb, 8);
3111
3112
21
        if (!(ptype & 0x80)) {
3113
            av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
3114
//          return -1;
3115
        }
3116
3117
        // FIXME: Check for this as well.
3118
21
        skip_bits_long(&gb, 6 * 8); /* "theora" */
3119
3120

21
        switch (ptype) {
3121
7
        case 0x80:
3122
7
            if (theora_decode_header(avctx, &gb) < 0)
3123
                return -1;
3124
7
            break;
3125
7
        case 0x81:
3126
// FIXME: is this needed? it breaks sometimes
3127
//            theora_decode_comments(avctx, gb);
3128
7
            break;
3129
7
        case 0x82:
3130
7
            if (theora_decode_tables(avctx, &gb))
3131
                return -1;
3132
7
            break;
3133
        default:
3134
            av_log(avctx, AV_LOG_ERROR,
3135
                   "Unknown Theora config packet: %d\n", ptype & ~0x80);
3136
            break;
3137
        }
3138

21
        if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
3139
7
            av_log(avctx, AV_LOG_WARNING,
3140
                   "%d bits left in packet %X\n",
3141
7
                   8 * header_len[i] - get_bits_count(&gb), ptype);
3142
21
        if (s->theora < 0x030200)
3143
            break;
3144
    }
3145
3146
7
    return vp3_decode_init(avctx);
3147
}
3148
3149
AVCodec ff_theora_decoder = {
3150
    .name                  = "theora",
3151
    .long_name             = NULL_IF_CONFIG_SMALL("Theora"),
3152
    .type                  = AVMEDIA_TYPE_VIDEO,
3153
    .id                    = AV_CODEC_ID_THEORA,
3154
    .priv_data_size        = sizeof(Vp3DecodeContext),
3155
    .init                  = theora_decode_init,
3156
    .close                 = vp3_decode_end,
3157
    .decode                = vp3_decode_frame,
3158
    .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3159
                             AV_CODEC_CAP_FRAME_THREADS,
3160
    .flush                 = vp3_decode_flush,
3161
    .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3162
    .caps_internal         = FF_CODEC_CAP_EXPORTS_CROPPING | FF_CODEC_CAP_ALLOCATE_PROGRESS |
3163
                             FF_CODEC_CAP_INIT_CLEANUP,
3164
};
3165
#endif
3166
3167
AVCodec ff_vp3_decoder = {
3168
    .name                  = "vp3",
3169
    .long_name             = NULL_IF_CONFIG_SMALL("On2 VP3"),
3170
    .type                  = AVMEDIA_TYPE_VIDEO,
3171
    .id                    = AV_CODEC_ID_VP3,
3172
    .priv_data_size        = sizeof(Vp3DecodeContext),
3173
    .init                  = vp3_decode_init,
3174
    .close                 = vp3_decode_end,
3175
    .decode                = vp3_decode_frame,
3176
    .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3177
                             AV_CODEC_CAP_FRAME_THREADS,
3178
    .flush                 = vp3_decode_flush,
3179
    .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3180
    .caps_internal         = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,
3181
};
3182
3183
#if CONFIG_VP4_DECODER
3184
AVCodec ff_vp4_decoder = {
3185
    .name                  = "vp4",
3186
    .long_name             = NULL_IF_CONFIG_SMALL("On2 VP4"),
3187
    .type                  = AVMEDIA_TYPE_VIDEO,
3188
    .id                    = AV_CODEC_ID_VP4,
3189
    .priv_data_size        = sizeof(Vp3DecodeContext),
3190
    .init                  = vp3_decode_init,
3191
    .close                 = vp3_decode_end,
3192
    .decode                = vp3_decode_frame,
3193
    .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
3194
                             AV_CODEC_CAP_FRAME_THREADS,
3195
    .flush                 = vp3_decode_flush,
3196
    .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
3197
    .caps_internal         = FF_CODEC_CAP_ALLOCATE_PROGRESS | FF_CODEC_CAP_INIT_CLEANUP,
3198
};
3199
#endif