]> git.sesse.net Git - ffmpeg/blob - libavcodec/vp8.c
725bf55980f6f29284b2e083e269a80b9687369d
[ffmpeg] / libavcodec / vp8.c
1 /**
2  * VP8 compatible video decoder
3  *
4  * Copyright (C) 2010 David Conrad
5  * Copyright (C) 2010 Ronald S. Bultje
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include "avcodec.h"
25 #include "vp56.h"
26 #include "vp8data.h"
27 #include "vp8dsp.h"
28 #include "h264pred.h"
29 #include "rectangle.h"
30
31 typedef struct {
32     uint8_t segment;
33     uint8_t skip;
34     // todo: make it possible to check for at least (i4x4 or split_mv)
35     // in one op. are others needed?
36     uint8_t mode;
37     uint8_t ref_frame;
38     uint8_t partitioning;
39     VP56mv mv;
40     VP56mv bmv[16];
41 } VP8Macroblock;
42
43 typedef struct {
44     AVCodecContext *avctx;
45     DSPContext dsp;
46     VP8DSPContext vp8dsp;
47     H264PredContext hpc;
48     vp8_mc_func put_pixels_tab[3][3][3];
49     AVFrame frames[4];
50     AVFrame *framep[4];
51     uint8_t *edge_emu_buffer;
52     VP56RangeCoder c;   ///< header context, includes mb modes and motion vectors
53     int profile;
54
55     int mb_width;   /* number of horizontal MB */
56     int mb_height;  /* number of vertical MB */
57     int linesize;
58     int uvlinesize;
59
60     int keyframe;
61     int invisible;
62     int update_last;    ///< update VP56_FRAME_PREVIOUS with the current one
63     int update_golden;  ///< VP56_FRAME_NONE if not updated, or which frame to copy if so
64     int update_altref;
65     int deblock_filter;
66
67     /**
68      * If this flag is not set, all the probability updates
69      * are discarded after this frame is decoded.
70      */
71     int update_probabilities;
72
73     /**
74      * All coefficients are contained in separate arith coding contexts.
75      * There can be 1, 2, 4, or 8 of these after the header context.
76      */
77     int num_coeff_partitions;
78     VP56RangeCoder coeff_partition[8];
79
80     VP8Macroblock *macroblocks;
81     VP8Macroblock *macroblocks_base;
82     int mb_stride;
83
84     uint8_t *intra4x4_pred_mode;
85     uint8_t *intra4x4_pred_mode_base;
86     int b4_stride;
87
88     /**
89      * Cache of the top row needed for intra prediction
90      * 16 for luma, 8 for each chroma plane
91      */
92     uint8_t (*top_border)[16+8+8];
93
94     /**
95      * For coeff decode, we need to know whether the above block had non-zero
96      * coefficients. This means for each macroblock, we need data for 4 luma
97      * blocks, 2 u blocks, 2 v blocks, and the luma dc block, for a total of 9
98      * per macroblock. We keep the last row in top_nnz.
99      */
100     uint8_t (*top_nnz)[9];
101     DECLARE_ALIGNED(8, uint8_t, left_nnz)[9];
102
103     /**
104      * This is the index plus one of the last non-zero coeff
105      * for each of the blocks in the current macroblock.
106      * So, 0 -> no coeffs
107      *     1 -> dc-only (special transform)
108      *     2+-> full transform
109      */
110     DECLARE_ALIGNED(16, uint8_t, non_zero_count_cache)[6][4];
111     DECLARE_ALIGNED(16, DCTELEM, block)[6][4][16];
112     uint8_t intra4x4_pred_mode_mb[16];
113
114     int chroma_pred_mode;    ///< 8x8c pred mode of the current macroblock
115
116     int mbskip_enabled;
117     int sign_bias[4]; ///< one state [0, 1] per ref frame type
118
119     /**
120      * Base parameters for segmentation, i.e. per-macroblock parameters.
121      * These must be kept unchanged even if segmentation is not used for
122      * a frame, since the values persist between interframes.
123      */
124     struct {
125         int enabled;
126         int absolute_vals;
127         int update_map;
128         int8_t base_quant[4];
129         int8_t filter_level[4];     ///< base loop filter level
130     } segmentation;
131
132     /**
133      * Macroblocks can have one of 4 different quants in a frame when
134      * segmentation is enabled.
135      * If segmentation is disabled, only the first segment's values are used.
136      */
137     struct {
138         // [0] - DC qmul  [1] - AC qmul
139         int16_t luma_qmul[2];
140         int16_t luma_dc_qmul[2];    ///< luma dc-only block quant
141         int16_t chroma_qmul[2];
142     } qmat[4];
143
144     struct {
145         int simple;
146         int level;
147         int sharpness;
148     } filter;
149
150     struct {
151         int enabled;    ///< whether each mb can have a different strength based on mode/ref
152
153         /**
154          * filter strength adjustment for the following macroblock modes:
155          * [0] - i4x4
156          * [1] - zero mv
157          * [2] - inter modes except for zero or split mv
158          * [3] - split mv
159          *  i16x16 modes never have any adjustment
160          */
161         int8_t mode[4];
162
163         /**
164          * filter strength adjustment for macroblocks that reference:
165          * [0] - intra / VP56_FRAME_CURRENT
166          * [1] - VP56_FRAME_PREVIOUS
167          * [2] - VP56_FRAME_GOLDEN
168          * [3] - altref / VP56_FRAME_GOLDEN2
169          */
170         int8_t ref[4];
171     } lf_delta;
172
173     /**
174      * These are all of the updatable probabilities for binary decisions.
175      * They are only implictly reset on keyframes, making it quite likely
176      * for an interframe to desync if a prior frame's header was corrupt
177      * or missing outright!
178      */
179     struct {
180         uint8_t segmentid[3];
181         uint8_t mbskip;
182         uint8_t intra;
183         uint8_t last;
184         uint8_t golden;
185         uint8_t pred16x16[4];
186         uint8_t pred8x8c[3];
187         uint8_t token[4][8][3][NUM_DCT_TOKENS-1];
188         uint8_t mvc[2][19];
189     } prob[2];
190 } VP8Context;
191
192 #define RL24(p) (AV_RL16(p) + ((p)[2] << 16))
193
194 static void vp8_decode_flush(AVCodecContext *avctx)
195 {
196     VP8Context *s = avctx->priv_data;
197     int i;
198
199     for (i = 0; i < 4; i++)
200         if (s->frames[i].data[0])
201             avctx->release_buffer(avctx, &s->frames[i]);
202     memset(s->framep, 0, sizeof(s->framep));
203
204     av_freep(&s->macroblocks_base);
205     av_freep(&s->intra4x4_pred_mode_base);
206     av_freep(&s->top_nnz);
207     av_freep(&s->edge_emu_buffer);
208     av_freep(&s->top_border);
209
210     s->macroblocks        = NULL;
211     s->intra4x4_pred_mode = NULL;
212 }
213
214 static int update_dimensions(VP8Context *s, int width, int height)
215 {
216     int i;
217
218     if (avcodec_check_dimensions(s->avctx, width, height))
219         return AVERROR_INVALIDDATA;
220
221     vp8_decode_flush(s->avctx);
222
223     avcodec_set_dimensions(s->avctx, width, height);
224
225     s->mb_width  = (s->avctx->coded_width +15) / 16;
226     s->mb_height = (s->avctx->coded_height+15) / 16;
227
228     // we allocate a border around the top/left of intra4x4 modes
229     // this is 4 blocks for intra4x4 to keep 4-byte alignment for fill_rectangle
230     s->mb_stride = s->mb_width+1;
231     s->b4_stride = 4*s->mb_stride;
232
233     s->macroblocks_base        = av_mallocz(s->mb_stride*(s->mb_height+1)*sizeof(*s->macroblocks));
234     s->intra4x4_pred_mode_base = av_mallocz(s->b4_stride*(4*s->mb_height+1));
235     s->top_nnz                 = av_mallocz(s->mb_width*sizeof(*s->top_nnz));
236     s->top_border              = av_mallocz((s->mb_width+1)*sizeof(*s->top_border));
237
238     if (!s->macroblocks_base || !s->intra4x4_pred_mode_base || !s->top_nnz || !s->top_border)
239         return AVERROR(ENOMEM);
240
241     s->macroblocks        = s->macroblocks_base        + 1 + s->mb_stride;
242     s->intra4x4_pred_mode = s->intra4x4_pred_mode_base + 4 + s->b4_stride;
243
244     memset(s->intra4x4_pred_mode_base, DC_PRED, s->b4_stride);
245     for (i = 0; i < 4*s->mb_height; i++)
246         s->intra4x4_pred_mode[i*s->b4_stride-1] = DC_PRED;
247
248     return 0;
249 }
250
251 static void parse_segment_info(VP8Context *s)
252 {
253     VP56RangeCoder *c = &s->c;
254     int i;
255
256     s->segmentation.update_map = vp8_rac_get(c);
257
258     if (vp8_rac_get(c)) { // update segment feature data
259         s->segmentation.absolute_vals = vp8_rac_get(c);
260
261         for (i = 0; i < 4; i++)
262             s->segmentation.base_quant[i]   = vp8_rac_get_sint(c, 7);
263
264         for (i = 0; i < 4; i++)
265             s->segmentation.filter_level[i] = vp8_rac_get_sint(c, 6);
266     }
267     if (s->segmentation.update_map)
268         for (i = 0; i < 3; i++)
269             s->prob->segmentid[i] = vp8_rac_get(c) ? vp8_rac_get_uint(c, 8) : 255;
270 }
271
272 static void update_lf_deltas(VP8Context *s)
273 {
274     VP56RangeCoder *c = &s->c;
275     int i;
276
277     for (i = 0; i < 4; i++)
278         s->lf_delta.ref[i]  = vp8_rac_get_sint(c, 6);
279
280     for (i = 0; i < 4; i++)
281         s->lf_delta.mode[i] = vp8_rac_get_sint(c, 6);
282 }
283
284 static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size)
285 {
286     const uint8_t *sizes = buf;
287     int i;
288
289     s->num_coeff_partitions = 1 << vp8_rac_get_uint(&s->c, 2);
290
291     buf      += 3*(s->num_coeff_partitions-1);
292     buf_size -= 3*(s->num_coeff_partitions-1);
293     if (buf_size < 0)
294         return -1;
295
296     for (i = 0; i < s->num_coeff_partitions-1; i++) {
297         int size = RL24(sizes + 3*i);
298         if (buf_size - size < 0)
299             return -1;
300
301         vp56_init_range_decoder(&s->coeff_partition[i], buf, size);
302         buf      += size;
303         buf_size -= size;
304     }
305     vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size);
306
307     return 0;
308 }
309
310 static void get_quants(VP8Context *s)
311 {
312     VP56RangeCoder *c = &s->c;
313     int i, base_qi;
314
315     int yac_qi     = vp8_rac_get_uint(c, 7);
316     int ydc_delta  = vp8_rac_get_sint(c, 4);
317     int y2dc_delta = vp8_rac_get_sint(c, 4);
318     int y2ac_delta = vp8_rac_get_sint(c, 4);
319     int uvdc_delta = vp8_rac_get_sint(c, 4);
320     int uvac_delta = vp8_rac_get_sint(c, 4);
321
322     for (i = 0; i < 4; i++) {
323         if (s->segmentation.enabled) {
324             base_qi = s->segmentation.base_quant[i];
325             if (!s->segmentation.absolute_vals)
326                 base_qi += yac_qi;
327         } else
328             base_qi = yac_qi;
329
330         s->qmat[i].luma_qmul[0]    =       vp8_dc_qlookup[av_clip(base_qi + ydc_delta , 0, 127)];
331         s->qmat[i].luma_qmul[1]    =       vp8_ac_qlookup[av_clip(base_qi             , 0, 127)];
332         s->qmat[i].luma_dc_qmul[0] =   2 * vp8_dc_qlookup[av_clip(base_qi + y2dc_delta, 0, 127)];
333         s->qmat[i].luma_dc_qmul[1] = 155 * vp8_ac_qlookup[av_clip(base_qi + y2ac_delta, 0, 127)] / 100;
334         s->qmat[i].chroma_qmul[0]  =       vp8_dc_qlookup[av_clip(base_qi + uvdc_delta, 0, 127)];
335         s->qmat[i].chroma_qmul[1]  =       vp8_ac_qlookup[av_clip(base_qi + uvac_delta, 0, 127)];
336
337         s->qmat[i].luma_dc_qmul[1] = FFMAX(s->qmat[i].luma_dc_qmul[1], 8);
338         s->qmat[i].chroma_qmul[0]  = FFMIN(s->qmat[i].chroma_qmul[0], 132);
339     }
340 }
341
342 /**
343  * Determine which buffers golden and altref should be updated with after this frame.
344  * The spec isn't clear here, so I'm going by my understanding of what libvpx does
345  *
346  * Intra frames update all 3 references
347  * Inter frames update VP56_FRAME_PREVIOUS if the update_last flag is set
348  * If the update (golden|altref) flag is set, it's updated with the current frame
349  *      if update_last is set, and VP56_FRAME_PREVIOUS otherwise.
350  * If the flag is not set, the number read means:
351  *      0: no update
352  *      1: VP56_FRAME_PREVIOUS
353  *      2: update golden with altref, or update altref with golden
354  */
355 static VP56Frame ref_to_update(VP8Context *s, int update, VP56Frame ref)
356 {
357     VP56RangeCoder *c = &s->c;
358
359     if (update)
360         return VP56_FRAME_CURRENT;
361
362     switch (vp8_rac_get_uint(c, 2)) {
363     case 1:
364         return VP56_FRAME_PREVIOUS;
365     case 2:
366         return (ref == VP56_FRAME_GOLDEN) ? VP56_FRAME_GOLDEN2 : VP56_FRAME_GOLDEN;
367     }
368     return VP56_FRAME_NONE;
369 }
370
371 static void update_refs(VP8Context *s)
372 {
373     VP56RangeCoder *c = &s->c;
374
375     int update_golden = vp8_rac_get(c);
376     int update_altref = vp8_rac_get(c);
377
378     s->update_golden = ref_to_update(s, update_golden, VP56_FRAME_GOLDEN);
379     s->update_altref = ref_to_update(s, update_altref, VP56_FRAME_GOLDEN2);
380 }
381
382 static int decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size)
383 {
384     VP56RangeCoder *c = &s->c;
385     int header_size, hscale, vscale, i, j, k, l, ret;
386     int width  = s->avctx->width;
387     int height = s->avctx->height;
388
389     s->keyframe  = !(buf[0] & 1);
390     s->profile   =  (buf[0]>>1) & 7;
391     s->invisible = !(buf[0] & 0x10);
392     header_size  = RL24(buf) >> 5;
393     buf      += 3;
394     buf_size -= 3;
395
396     if (s->profile > 3)
397         av_log(s->avctx, AV_LOG_WARNING, "Unknown profile %d\n", s->profile);
398
399     if (!s->profile)
400         memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, sizeof(s->put_pixels_tab));
401     else    // profile 1-3 use bilinear, 4+ aren't defined so whatever
402         memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_bilinear_pixels_tab, sizeof(s->put_pixels_tab));
403
404     if (header_size > buf_size - 7*s->keyframe) {
405         av_log(s->avctx, AV_LOG_ERROR, "Header size larger than data provided\n");
406         return AVERROR_INVALIDDATA;
407     }
408
409     if (s->keyframe) {
410         if (RL24(buf) != 0x2a019d) {
411             av_log(s->avctx, AV_LOG_ERROR, "Invalid start code 0x%x\n", RL24(buf));
412             return AVERROR_INVALIDDATA;
413         }
414         width  = AV_RL16(buf+3) & 0x3fff;
415         height = AV_RL16(buf+5) & 0x3fff;
416         hscale = buf[4] >> 6;
417         vscale = buf[6] >> 6;
418         buf      += 7;
419         buf_size -= 7;
420
421         if (hscale || vscale)
422             av_log_missing_feature(s->avctx, "Upscaling", 1);
423
424         s->update_golden = s->update_altref = VP56_FRAME_CURRENT;
425         memcpy(s->prob->token    , vp8_token_default_probs , sizeof(s->prob->token));
426         memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter, sizeof(s->prob->pred16x16));
427         memcpy(s->prob->pred8x8c , vp8_pred8x8c_prob_inter , sizeof(s->prob->pred8x8c));
428         memcpy(s->prob->mvc      , vp8_mv_default_prob     , sizeof(s->prob->mvc));
429         memset(&s->segmentation, 0, sizeof(s->segmentation));
430     }
431
432     if (!s->macroblocks_base || /* first frame */
433         width != s->avctx->width || height != s->avctx->height) {
434         if ((ret = update_dimensions(s, width, height) < 0))
435             return ret;
436     }
437
438     vp56_init_range_decoder(c, buf, header_size);
439     buf      += header_size;
440     buf_size -= header_size;
441
442     if (s->keyframe) {
443         if (vp8_rac_get(c))
444             av_log(s->avctx, AV_LOG_WARNING, "Unspecified colorspace\n");
445         vp8_rac_get(c); // whether we can skip clamping in dsp functions
446     }
447
448     if ((s->segmentation.enabled = vp8_rac_get(c)))
449         parse_segment_info(s);
450     else
451         s->segmentation.update_map = 0; // FIXME: move this to some init function?
452
453     s->filter.simple    = vp8_rac_get(c);
454     s->filter.level     = vp8_rac_get_uint(c, 6);
455     s->filter.sharpness = vp8_rac_get_uint(c, 3);
456
457     if ((s->lf_delta.enabled = vp8_rac_get(c)))
458         if (vp8_rac_get(c))
459             update_lf_deltas(s);
460
461     if (setup_partitions(s, buf, buf_size)) {
462         av_log(s->avctx, AV_LOG_ERROR, "Invalid partitions\n");
463         return AVERROR_INVALIDDATA;
464     }
465
466     get_quants(s);
467
468     if (!s->keyframe) {
469         update_refs(s);
470         s->sign_bias[VP56_FRAME_GOLDEN]               = vp8_rac_get(c);
471         s->sign_bias[VP56_FRAME_GOLDEN2 /* altref */] = vp8_rac_get(c);
472     }
473
474     // if we aren't saving this frame's probabilities for future frames,
475     // make a copy of the current probabilities
476     if (!(s->update_probabilities = vp8_rac_get(c)))
477         s->prob[1] = s->prob[0];
478
479     s->update_last = s->keyframe || vp8_rac_get(c);
480
481     for (i = 0; i < 4; i++)
482         for (j = 0; j < 8; j++)
483             for (k = 0; k < 3; k++)
484                 for (l = 0; l < NUM_DCT_TOKENS-1; l++)
485                     if (vp56_rac_get_prob(c, vp8_token_update_probs[i][j][k][l]))
486                         s->prob->token[i][j][k][l] = vp8_rac_get_uint(c, 8);
487
488     if ((s->mbskip_enabled = vp8_rac_get(c)))
489         s->prob->mbskip = vp8_rac_get_uint(c, 8);
490
491     if (!s->keyframe) {
492         s->prob->intra  = vp8_rac_get_uint(c, 8);
493         s->prob->last   = vp8_rac_get_uint(c, 8);
494         s->prob->golden = vp8_rac_get_uint(c, 8);
495
496         if (vp8_rac_get(c))
497             for (i = 0; i < 4; i++)
498                 s->prob->pred16x16[i] = vp8_rac_get_uint(c, 8);
499         if (vp8_rac_get(c))
500             for (i = 0; i < 3; i++)
501                 s->prob->pred8x8c[i]  = vp8_rac_get_uint(c, 8);
502
503         // 17.2 MV probability update
504         for (i = 0; i < 2; i++)
505             for (j = 0; j < 19; j++)
506                 if (vp56_rac_get_prob(c, vp8_mv_update_prob[i][j]))
507                     s->prob->mvc[i][j] = vp8_rac_get_nn(c);
508     }
509
510     return 0;
511 }
512
513 static inline void clamp_mv(VP8Context *s, VP56mv *dst, const VP56mv *src,
514                             int mb_x, int mb_y)
515 {
516 #define MARGIN (16 << 2)
517     dst->x = av_clip(src->x, -((mb_x << 6) + MARGIN),
518                      ((s->mb_width  - 1 - mb_x) << 6) + MARGIN);
519     dst->y = av_clip(src->y, -((mb_y << 6) + MARGIN),
520                      ((s->mb_height - 1 - mb_y) << 6) + MARGIN);
521 }
522
523 static void find_near_mvs(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y,
524                           VP56mv near[2], VP56mv *best, uint8_t cnt[4])
525 {
526     int mb_stride = s->mb_stride;
527     VP8Macroblock *mb_edge[3] = { mb - mb_stride     /* top */,
528                                   mb - 1             /* left */,
529                                   mb - mb_stride - 1 /* top-left */ };
530     enum { EDGE_TOP, EDGE_LEFT, EDGE_TOPLEFT };
531     VP56mv near_mv[4]  = {{ 0 }};
532     enum { CNT_ZERO, CNT_NEAREST, CNT_NEAR, CNT_SPLITMV };
533     int idx = CNT_ZERO;
534     int best_idx = CNT_ZERO;
535     int cur_sign_bias = s->sign_bias[mb->ref_frame];
536     int *sign_bias = s->sign_bias;
537
538     /* Process MB on top, left and top-left */
539     #define MV_EDGE_CHECK(n)\
540     {\
541         VP8Macroblock *edge = mb_edge[n];\
542         int edge_ref = edge->ref_frame;\
543         if (edge_ref != VP56_FRAME_CURRENT) {\
544             uint32_t mv = AV_RN32A(&edge->mv);\
545             if (mv) {\
546                 if (cur_sign_bias != sign_bias[edge_ref]) {\
547                     /* SWAR negate of the values in mv. */\
548                     mv = ((mv&0x80008000) + 0x00010001) ^ (mv&0x7fff7fff);\
549                 }\
550                 if (!n || mv != AV_RN32A(&near_mv[idx]))\
551                     AV_WN32A(&near_mv[++idx], mv);\
552                 cnt[idx]      += 1 + (n != 2);\
553             } else\
554                 cnt[CNT_ZERO] += 1 + (n != 2);\
555         }\
556     }
557     MV_EDGE_CHECK(0)
558     MV_EDGE_CHECK(1)
559     MV_EDGE_CHECK(2)
560
561     /* If we have three distinct MVs, merge first and last if they're the same */
562     if (cnt[CNT_SPLITMV] && AV_RN32A(&near_mv[1+EDGE_TOP]) == AV_RN32A(&near_mv[1+EDGE_TOPLEFT]))
563         cnt[CNT_NEAREST] += 1;
564
565     cnt[CNT_SPLITMV] = ((mb_edge[EDGE_LEFT]->mode   == VP8_MVMODE_SPLIT) +
566                         (mb_edge[EDGE_TOP]->mode    == VP8_MVMODE_SPLIT)) * 2 +
567                        (mb_edge[EDGE_TOPLEFT]->mode == VP8_MVMODE_SPLIT);
568
569     /* Swap near and nearest if necessary */
570     if (cnt[CNT_NEAR] > cnt[CNT_NEAREST]) {
571         FFSWAP(uint8_t,     cnt[CNT_NEAREST],     cnt[CNT_NEAR]);
572         FFSWAP( VP56mv, near_mv[CNT_NEAREST], near_mv[CNT_NEAR]);
573     }
574
575     /* Choose the best mv out of 0,0 and the nearest mv */
576     if (cnt[CNT_NEAREST] >= cnt[CNT_ZERO])
577         best_idx = CNT_NEAREST;
578
579     clamp_mv(s, best, &near_mv[best_idx], mb_x, mb_y);
580     near[0] = near_mv[CNT_NEAREST];
581     near[1] = near_mv[CNT_NEAR];
582 }
583
584 /**
585  * Motion vector coding, 17.1.
586  */
587 static int read_mv_component(VP56RangeCoder *c, const uint8_t *p)
588 {
589     int x = 0;
590
591     if (vp56_rac_get_prob(c, p[0])) {
592         int i;
593
594         for (i = 0; i < 3; i++)
595             x += vp56_rac_get_prob(c, p[9 + i]) << i;
596         for (i = 9; i > 3; i--)
597             x += vp56_rac_get_prob(c, p[9 + i]) << i;
598         if (!(x & 0xFFF0) || vp56_rac_get_prob(c, p[12]))
599             x += 8;
600     } else
601         x = vp8_rac_get_tree(c, vp8_small_mvtree, &p[2]);
602
603     return (x && vp56_rac_get_prob(c, p[1])) ? -x : x;
604 }
605
606 static const uint8_t *get_submv_prob(uint32_t left, uint32_t top)
607 {
608     if (left == top)
609         return vp8_submv_prob[4-!!left];
610     if (!top)
611         return vp8_submv_prob[2];
612     return vp8_submv_prob[1-!!left];
613 }
614
615 /**
616  * Split motion vector prediction, 16.4.
617  * @returns the number of motion vectors parsed (2, 4 or 16)
618  */
619 static int decode_splitmvs(VP8Context    *s,  VP56RangeCoder *c,
620                             VP8Macroblock *mb, VP56mv         *base_mv)
621 {
622     int part_idx = mb->partitioning =
623         vp8_rac_get_tree(c, vp8_mbsplit_tree, vp8_mbsplit_prob);
624     int n, num = vp8_mbsplit_count[part_idx];
625     VP8Macroblock *top_mb  = &mb[-s->mb_stride];
626     VP8Macroblock *left_mb = &mb[-1];
627     const uint8_t *mbsplits_left = vp8_mbsplits[left_mb->partitioning],
628                   *mbsplits_top = vp8_mbsplits[top_mb->partitioning],
629                   *mbsplits_cur = vp8_mbsplits[part_idx],
630                   *firstidx = vp8_mbfirstidx[part_idx];
631     VP56mv *top_mv   = top_mb->bmv;
632     VP56mv *left_mv  = left_mb->bmv;
633     VP56mv *cur_mv   = mb->bmv;
634
635     for (n = 0; n < num; n++) {
636         int k = firstidx[n];
637         uint32_t left, above;
638         const uint8_t *submv_prob;
639
640         if (!(k & 3))
641             left = AV_RN32A(&left_mv[mbsplits_left[k + 3]]);
642         else
643             left  = AV_RN32A(&cur_mv[mbsplits_cur[k - 1]]);
644         if (k <= 3)
645             above = AV_RN32A(&top_mv[mbsplits_top[k + 12]]);
646         else
647             above = AV_RN32A(&cur_mv[mbsplits_cur[k - 4]]);
648
649         submv_prob = get_submv_prob(left, above);
650
651         switch (vp8_rac_get_tree(c, vp8_submv_ref_tree, submv_prob)) {
652         case VP8_SUBMVMODE_NEW4X4:
653             mb->bmv[n].y = base_mv->y + read_mv_component(c, s->prob->mvc[0]);
654             mb->bmv[n].x = base_mv->x + read_mv_component(c, s->prob->mvc[1]);
655             break;
656         case VP8_SUBMVMODE_ZERO4X4:
657             AV_WN32A(&mb->bmv[n], 0);
658             break;
659         case VP8_SUBMVMODE_LEFT4X4:
660             AV_WN32A(&mb->bmv[n], left);
661             break;
662         case VP8_SUBMVMODE_TOP4X4:
663             AV_WN32A(&mb->bmv[n], above);
664             break;
665         }
666     }
667
668     return num;
669 }
670
671 static inline void decode_intra4x4_modes(VP56RangeCoder *c, uint8_t *intra4x4,
672                                          int stride, int keyframe)
673 {
674     int x, y, t, l, i;
675
676     if (keyframe) {
677         const uint8_t *ctx;
678         for (y = 0; y < 4; y++) {
679             for (x = 0; x < 4; x++) {
680                 t = intra4x4[x - stride];
681                 l = intra4x4[x - 1];
682                 ctx = vp8_pred4x4_prob_intra[t][l];
683                 intra4x4[x] = vp8_rac_get_tree(c, vp8_pred4x4_tree, ctx);
684             }
685             intra4x4 += stride;
686         }
687     } else {
688         for (i = 0; i < 16; i++)
689             intra4x4[i] = vp8_rac_get_tree(c, vp8_pred4x4_tree, vp8_pred4x4_prob_inter);
690     }
691 }
692
693 static void decode_mb_mode(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y,
694                            uint8_t *intra4x4)
695 {
696     VP56RangeCoder *c = &s->c;
697
698     if (s->segmentation.update_map)
699         mb->segment = vp8_rac_get_tree(c, vp8_segmentid_tree, s->prob->segmentid);
700
701     mb->skip = s->mbskip_enabled ? vp56_rac_get_prob(c, s->prob->mbskip) : 0;
702
703     if (s->keyframe) {
704         mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_intra, vp8_pred16x16_prob_intra);
705
706         if (mb->mode == MODE_I4x4) {
707             decode_intra4x4_modes(c, intra4x4, s->b4_stride, 1);
708         } else
709             fill_rectangle(intra4x4, 4, 4, s->b4_stride, vp8_pred4x4_mode[mb->mode], 1);
710
711         s->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, vp8_pred8x8c_prob_intra);
712         mb->ref_frame = VP56_FRAME_CURRENT;
713     } else if (vp56_rac_get_prob(c, s->prob->intra)) {
714         VP56mv near[2], best;
715         uint8_t cnt[4] = { 0 };
716         uint8_t p[4];
717
718         // inter MB, 16.2
719         if (vp56_rac_get_prob(c, s->prob->last))
720             mb->ref_frame = vp56_rac_get_prob(c, s->prob->golden) ?
721                 VP56_FRAME_GOLDEN2 /* altref */ : VP56_FRAME_GOLDEN;
722         else
723             mb->ref_frame = VP56_FRAME_PREVIOUS;
724
725         // motion vectors, 16.3
726         find_near_mvs(s, mb, mb_x, mb_y, near, &best, cnt);
727         p[0] = vp8_mode_contexts[cnt[0]][0];
728         p[1] = vp8_mode_contexts[cnt[1]][1];
729         p[2] = vp8_mode_contexts[cnt[2]][2];
730         p[3] = vp8_mode_contexts[cnt[3]][3];
731         mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_mvinter, p);
732         switch (mb->mode) {
733         case VP8_MVMODE_SPLIT:
734             mb->mv = mb->bmv[decode_splitmvs(s, c, mb, &best) - 1];
735             break;
736         case VP8_MVMODE_ZERO:
737             mb->mv.x = 0;
738             mb->mv.y = 0;
739             break;
740         case VP8_MVMODE_NEAREST:
741             clamp_mv(s, &mb->mv, &near[0], mb_x, mb_y);
742             break;
743         case VP8_MVMODE_NEAR:
744             clamp_mv(s, &mb->mv, &near[1], mb_x, mb_y);
745             break;
746         case VP8_MVMODE_NEW:
747             mb->mv.y = best.y + read_mv_component(c, s->prob->mvc[0]);
748             mb->mv.x = best.x + read_mv_component(c, s->prob->mvc[1]);
749             break;
750         }
751         if (mb->mode != VP8_MVMODE_SPLIT) {
752             mb->partitioning = VP8_SPLITMVMODE_NONE;
753             mb->bmv[0] = mb->mv;
754         }
755     } else {
756         // intra MB, 16.1
757         mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_inter, s->prob->pred16x16);
758
759         if (mb->mode == MODE_I4x4)
760             decode_intra4x4_modes(c, intra4x4, 4, 0);
761
762         s->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, s->prob->pred8x8c);
763         mb->ref_frame = VP56_FRAME_CURRENT;
764     }
765 }
766
767 /**
768  * @param c arithmetic bitstream reader context
769  * @param block destination for block coefficients
770  * @param probs probabilities to use when reading trees from the bitstream
771  * @param i initial coeff index, 0 unless a separate DC block is coded
772  * @param zero_nhood the initial prediction context for number of surrounding
773  *                   all-zero blocks (only left/top, so 0-2)
774  * @param qmul array holding the dc/ac dequant factor at position 0/1
775  * @return 0 if no coeffs were decoded
776  *         otherwise, the index of the last coeff decoded plus one
777  */
778 static int decode_block_coeffs(VP56RangeCoder *c, DCTELEM block[16],
779                                uint8_t probs[8][3][NUM_DCT_TOKENS-1],
780                                int i, int zero_nhood, int16_t qmul[2])
781 {
782     int token, nonzero = 0;
783     int offset = 0;
784
785     for (; i < 16; i++) {
786         token = vp8_rac_get_tree_with_offset(c, vp8_coeff_tree, probs[vp8_coeff_band[i]][zero_nhood], offset);
787
788         if (token == DCT_EOB)
789             break;
790         else if (token >= DCT_CAT1) {
791             int cat = token-DCT_CAT1;
792             token = vp8_rac_get_coeff(c, vp8_dct_cat_prob[cat]);
793             token += vp8_dct_cat_offset[cat];
794         }
795
796         // after the first token, the non-zero prediction context becomes
797         // based on the last decoded coeff
798         if (!token) {
799             zero_nhood = 0;
800             offset = 1;
801             continue;
802         } else if (token == 1)
803             zero_nhood = 1;
804         else
805             zero_nhood = 2;
806
807         // todo: full [16] qmat? load into register?
808         block[zigzag_scan[i]] = (vp8_rac_get(c) ? -token : token) * qmul[!!i];
809         nonzero = i+1;
810         offset = 0;
811     }
812     return nonzero;
813 }
814
815 static void decode_mb_coeffs(VP8Context *s, VP56RangeCoder *c, VP8Macroblock *mb,
816                              uint8_t t_nnz[9], uint8_t l_nnz[9])
817 {
818     LOCAL_ALIGNED_16(DCTELEM, dc,[16]);
819     int i, x, y, luma_start = 0, luma_ctx = 3;
820     int nnz_pred, nnz, nnz_total = 0;
821     int segment = s->segmentation.enabled ? mb->segment : 0;
822
823     s->dsp.clear_blocks((DCTELEM *)s->block);
824
825     if (mb->mode != MODE_I4x4 && mb->mode != VP8_MVMODE_SPLIT) {
826         AV_ZERO128(dc);
827         AV_ZERO128(dc+8);
828         nnz_pred = t_nnz[8] + l_nnz[8];
829
830         // decode DC values and do hadamard
831         nnz = decode_block_coeffs(c, dc, s->prob->token[1], 0, nnz_pred,
832                                   s->qmat[segment].luma_dc_qmul);
833         l_nnz[8] = t_nnz[8] = !!nnz;
834         nnz_total += nnz;
835         s->vp8dsp.vp8_luma_dc_wht(s->block, dc);
836         luma_start = 1;
837         luma_ctx = 0;
838     }
839
840     // luma blocks
841     for (y = 0; y < 4; y++)
842         for (x = 0; x < 4; x++) {
843             nnz_pred = l_nnz[y] + t_nnz[x];
844             nnz = decode_block_coeffs(c, s->block[y][x], s->prob->token[luma_ctx], luma_start,
845                                       nnz_pred, s->qmat[segment].luma_qmul);
846             // nnz+luma_start may be one more than the actual last index, but we don't care
847             s->non_zero_count_cache[y][x] = nnz + luma_start;
848             t_nnz[x] = l_nnz[y] = !!nnz;
849             nnz_total += nnz;
850         }
851
852     // chroma blocks
853     // TODO: what to do about dimensions? 2nd dim for luma is x,
854     // but for chroma it's (y<<1)|x
855     for (i = 4; i < 6; i++)
856         for (y = 0; y < 2; y++)
857             for (x = 0; x < 2; x++) {
858                 nnz_pred = l_nnz[i+2*y] + t_nnz[i+2*x];
859                 nnz = decode_block_coeffs(c, s->block[i][(y<<1)+x], s->prob->token[2], 0,
860                                           nnz_pred, s->qmat[segment].chroma_qmul);
861                 s->non_zero_count_cache[i][(y<<1)+x] = nnz;
862                 t_nnz[i+2*x] = l_nnz[i+2*y] = !!nnz;
863                 nnz_total += nnz;
864             }
865
866     // if there were no coded coeffs despite the macroblock not being marked skip,
867     // we MUST not do the inner loop filter and should not do IDCT
868     // Since skip isn't used for bitstream prediction, just manually set it.
869     if (!nnz_total)
870         mb->skip = 1;
871 }
872
873 static av_always_inline
874 void backup_mb_border(uint8_t *top_border, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr,
875                       int linesize, int uvlinesize, int simple)
876 {
877     AV_COPY128(top_border, src_y + 15*linesize);
878     if (!simple) {
879         AV_COPY64(top_border+16, src_cb + 7*uvlinesize);
880         AV_COPY64(top_border+24, src_cr + 7*uvlinesize);
881     }
882 }
883
884 static av_always_inline
885 void xchg_mb_border(uint8_t *top_border, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr,
886                     int linesize, int uvlinesize, int mb_x, int mb_y, int mb_width,
887                     int simple, int xchg)
888 {
889     uint8_t *top_border_m1 = top_border-32;     // for TL prediction
890     src_y  -=   linesize;
891     src_cb -= uvlinesize;
892     src_cr -= uvlinesize;
893
894 #define XCHG(a,b,xchg) do {                     \
895         if (xchg) AV_SWAP64(b,a);               \
896         else      AV_COPY64(b,a);               \
897     } while (0)
898
899     XCHG(top_border_m1+8, src_y-8, xchg);
900     XCHG(top_border,      src_y,   xchg);
901     XCHG(top_border+8,    src_y+8, 1);
902     if (mb_x < mb_width-1)
903         XCHG(top_border+32, src_y+16, 1);
904
905     // only copy chroma for normal loop filter
906     // or to initialize the top row to 127
907     if (!simple || !mb_y) {
908         XCHG(top_border_m1+16, src_cb-8, xchg);
909         XCHG(top_border_m1+24, src_cr-8, xchg);
910         XCHG(top_border+16,    src_cb, 1);
911         XCHG(top_border+24,    src_cr, 1);
912     }
913 }
914
915 static int check_intra_pred_mode(int mode, int mb_x, int mb_y)
916 {
917     if (mode == DC_PRED8x8) {
918         if (!(mb_x|mb_y))
919             mode = DC_128_PRED8x8;
920         else if (!mb_y)
921             mode = LEFT_DC_PRED8x8;
922         else if (!mb_x)
923             mode = TOP_DC_PRED8x8;
924     }
925     return mode;
926 }
927
928 static void intra_predict(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb,
929                           uint8_t *intra4x4, int mb_x, int mb_y)
930 {
931     int x, y, mode, nnz, tr;
932
933     // for the first row, we need to run xchg_mb_border to init the top edge to 127
934     // otherwise, skip it if we aren't going to deblock
935     if (s->deblock_filter || !mb_y)
936         xchg_mb_border(s->top_border[mb_x+1], dst[0], dst[1], dst[2],
937                        s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width,
938                        s->filter.simple, 1);
939
940     if (mb->mode < MODE_I4x4) {
941         mode = check_intra_pred_mode(mb->mode, mb_x, mb_y);
942         s->hpc.pred16x16[mode](dst[0], s->linesize);
943     } else {
944         uint8_t *ptr = dst[0];
945         int stride = s->keyframe ? s->b4_stride : 4;
946
947         // all blocks on the right edge of the macroblock use bottom edge
948         // the top macroblock for their topright edge
949         uint8_t *tr_right = ptr - s->linesize + 16;
950
951         // if we're on the right edge of the frame, said edge is extended
952         // from the top macroblock
953         if (mb_x == s->mb_width-1) {
954             tr = tr_right[-1]*0x01010101;
955             tr_right = (uint8_t *)&tr;
956         }
957
958         for (y = 0; y < 4; y++) {
959             uint8_t *topright = ptr + 4 - s->linesize;
960             for (x = 0; x < 4; x++) {
961                 if (x == 3)
962                     topright = tr_right;
963
964                 s->hpc.pred4x4[intra4x4[x]](ptr+4*x, topright, s->linesize);
965
966                 nnz = s->non_zero_count_cache[y][x];
967                 if (nnz) {
968                     if (nnz == 1)
969                         s->vp8dsp.vp8_idct_dc_add(ptr+4*x, s->block[y][x], s->linesize);
970                     else
971                         s->vp8dsp.vp8_idct_add(ptr+4*x, s->block[y][x], s->linesize);
972                 }
973                 topright += 4;
974             }
975
976             ptr   += 4*s->linesize;
977             intra4x4 += stride;
978         }
979     }
980
981     mode = check_intra_pred_mode(s->chroma_pred_mode, mb_x, mb_y);
982     s->hpc.pred8x8[mode](dst[1], s->uvlinesize);
983     s->hpc.pred8x8[mode](dst[2], s->uvlinesize);
984
985     if (s->deblock_filter || !mb_y)
986         xchg_mb_border(s->top_border[mb_x+1], dst[0], dst[1], dst[2],
987                        s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width,
988                        s->filter.simple, 0);
989 }
990
991 /**
992  * Generic MC function.
993  *
994  * @param s VP8 decoding context
995  * @param luma 1 for luma (Y) planes, 0 for chroma (Cb/Cr) planes
996  * @param dst target buffer for block data at block position
997  * @param src reference picture buffer at origin (0, 0)
998  * @param mv motion vector (relative to block position) to get pixel data from
999  * @param x_off horizontal position of block from origin (0, 0)
1000  * @param y_off vertical position of block from origin (0, 0)
1001  * @param block_w width of block (16, 8 or 4)
1002  * @param block_h height of block (always same as block_w)
1003  * @param width width of src/dst plane data
1004  * @param height height of src/dst plane data
1005  * @param linesize size of a single line of plane data, including padding
1006  * @param mc_func motion compensation function pointers (bilinear or sixtap MC)
1007  */
1008 static inline void vp8_mc(VP8Context *s, int luma,
1009                           uint8_t *dst, uint8_t *src, const VP56mv *mv,
1010                           int x_off, int y_off, int block_w, int block_h,
1011                           int width, int height, int linesize,
1012                           vp8_mc_func mc_func[3][3])
1013 {
1014     if (AV_RN32A(mv)) {
1015         static const uint8_t idx[8] = { 0, 1, 2, 1, 2, 1, 2, 1 };
1016         int mx = (mv->x << luma)&7, mx_idx = idx[mx];
1017         int my = (mv->y << luma)&7, my_idx = idx[my];
1018
1019         x_off += mv->x >> (3 - luma);
1020         y_off += mv->y >> (3 - luma);
1021
1022         // edge emulation
1023         src += y_off * linesize + x_off;
1024         if (x_off < 2 || x_off >= width  - block_w - 3 ||
1025             y_off < 2 || y_off >= height - block_h - 3) {
1026             ff_emulated_edge_mc(s->edge_emu_buffer, src - 2 * linesize - 2, linesize,
1027                                 block_w + 5, block_h + 5,
1028                                 x_off - 2, y_off - 2, width, height);
1029             src = s->edge_emu_buffer + 2 + linesize * 2;
1030         }
1031         mc_func[my_idx][mx_idx](dst, linesize, src, linesize, block_h, mx, my);
1032     } else
1033         mc_func[0][0](dst, linesize, src + y_off * linesize + x_off, linesize, block_h, 0, 0);
1034 }
1035
1036 static inline void vp8_mc_part(VP8Context *s, uint8_t *dst[3],
1037                                AVFrame *ref_frame, int x_off, int y_off,
1038                                int bx_off, int by_off,
1039                                int block_w, int block_h,
1040                                int width, int height, VP56mv *mv)
1041 {
1042     VP56mv uvmv = *mv;
1043
1044     /* Y */
1045     vp8_mc(s, 1, dst[0] + by_off * s->linesize + bx_off,
1046            ref_frame->data[0], mv, x_off + bx_off, y_off + by_off,
1047            block_w, block_h, width, height, s->linesize,
1048            s->put_pixels_tab[block_w == 8]);
1049
1050     /* U/V */
1051     if (s->profile == 3) {
1052         uvmv.x &= ~7;
1053         uvmv.y &= ~7;
1054     }
1055     x_off   >>= 1; y_off   >>= 1;
1056     bx_off  >>= 1; by_off  >>= 1;
1057     width   >>= 1; height  >>= 1;
1058     block_w >>= 1; block_h >>= 1;
1059     vp8_mc(s, 0, dst[1] + by_off * s->uvlinesize + bx_off,
1060            ref_frame->data[1], &uvmv, x_off + bx_off, y_off + by_off,
1061            block_w, block_h, width, height, s->uvlinesize,
1062            s->put_pixels_tab[1 + (block_w == 4)]);
1063     vp8_mc(s, 0, dst[2] + by_off * s->uvlinesize + bx_off,
1064            ref_frame->data[2], &uvmv, x_off + bx_off, y_off + by_off,
1065            block_w, block_h, width, height, s->uvlinesize,
1066            s->put_pixels_tab[1 + (block_w == 4)]);
1067 }
1068
1069 /* Fetch pixels for estimated mv 4 macroblocks ahead.
1070  * Optimized for 64-byte cache lines.  Inspired by ffh264 prefetch_motion. */
1071 static inline void prefetch_motion(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y, int x_off, int y_off, int ref)
1072 {
1073     if (mb->ref_frame != VP56_FRAME_CURRENT) {
1074         int mx = mb->mv.x + x_off + 8;
1075         int my = mb->mv.y + y_off;
1076         uint8_t **src= s->framep[mb->ref_frame]->data;
1077         int off= mx + (my + (mb_x&3)*4)*s->linesize + 64;
1078         s->dsp.prefetch(src[0]+off, s->linesize, 4);
1079         off= (mx>>1) + ((my>>1) + (mb_x&7))*s->uvlinesize + 64;
1080         s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
1081     }
1082 }
1083
1084 /**
1085  * Apply motion vectors to prediction buffer, chapter 18.
1086  */
1087 static void inter_predict(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb,
1088                           int mb_x, int mb_y)
1089 {
1090     int x_off = mb_x << 4, y_off = mb_y << 4;
1091     int width = 16*s->mb_width, height = 16*s->mb_height;
1092
1093     prefetch_motion(s, mb, mb_x, mb_y, x_off, y_off, VP56_FRAME_PREVIOUS);
1094
1095     if (mb->mode < VP8_MVMODE_SPLIT) {
1096         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1097                     0, 0, 16, 16, width, height, &mb->mv);
1098     } else switch (mb->partitioning) {
1099     case VP8_SPLITMVMODE_4x4: {
1100         int x, y;
1101         VP56mv uvmv;
1102
1103         /* Y */
1104         for (y = 0; y < 4; y++) {
1105             for (x = 0; x < 4; x++) {
1106                 vp8_mc(s, 1, dst[0] + 4*y*s->linesize + x*4,
1107                        s->framep[mb->ref_frame]->data[0], &mb->bmv[4*y + x],
1108                        4*x + x_off, 4*y + y_off, 4, 4,
1109                        width, height, s->linesize,
1110                        s->put_pixels_tab[2]);
1111             }
1112         }
1113
1114         /* U/V */
1115         x_off >>= 1; y_off >>= 1; width >>= 1; height >>= 1;
1116         for (y = 0; y < 2; y++) {
1117             for (x = 0; x < 2; x++) {
1118                 uvmv.x = mb->bmv[ 2*y    * 4 + 2*x  ].x +
1119                          mb->bmv[ 2*y    * 4 + 2*x+1].x +
1120                          mb->bmv[(2*y+1) * 4 + 2*x  ].x +
1121                          mb->bmv[(2*y+1) * 4 + 2*x+1].x;
1122                 uvmv.y = mb->bmv[ 2*y    * 4 + 2*x  ].y +
1123                          mb->bmv[ 2*y    * 4 + 2*x+1].y +
1124                          mb->bmv[(2*y+1) * 4 + 2*x  ].y +
1125                          mb->bmv[(2*y+1) * 4 + 2*x+1].y;
1126                 uvmv.x = (uvmv.x + 2 + (uvmv.x >> (INT_BIT-1))) >> 2;
1127                 uvmv.y = (uvmv.y + 2 + (uvmv.y >> (INT_BIT-1))) >> 2;
1128                 if (s->profile == 3) {
1129                     uvmv.x &= ~7;
1130                     uvmv.y &= ~7;
1131                 }
1132                 vp8_mc(s, 0, dst[1] + 4*y*s->uvlinesize + x*4,
1133                        s->framep[mb->ref_frame]->data[1], &uvmv,
1134                        4*x + x_off, 4*y + y_off, 4, 4,
1135                        width, height, s->uvlinesize,
1136                        s->put_pixels_tab[2]);
1137                 vp8_mc(s, 0, dst[2] + 4*y*s->uvlinesize + x*4,
1138                        s->framep[mb->ref_frame]->data[2], &uvmv,
1139                        4*x + x_off, 4*y + y_off, 4, 4,
1140                        width, height, s->uvlinesize,
1141                        s->put_pixels_tab[2]);
1142             }
1143         }
1144         break;
1145     }
1146     case VP8_SPLITMVMODE_16x8:
1147         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1148                     0, 0, 16, 8, width, height, &mb->bmv[0]);
1149         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1150                     0, 8, 16, 8, width, height, &mb->bmv[1]);
1151         break;
1152     case VP8_SPLITMVMODE_8x16:
1153         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1154                     0, 0, 8, 16, width, height, &mb->bmv[0]);
1155         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1156                     8, 0, 8, 16, width, height, &mb->bmv[1]);
1157         break;
1158     case VP8_SPLITMVMODE_8x8:
1159         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1160                     0, 0, 8, 8, width, height, &mb->bmv[0]);
1161         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1162                     8, 0, 8, 8, width, height, &mb->bmv[1]);
1163         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1164                     0, 8, 8, 8, width, height, &mb->bmv[2]);
1165         vp8_mc_part(s, dst, s->framep[mb->ref_frame], x_off, y_off,
1166                     8, 8, 8, 8, width, height, &mb->bmv[3]);
1167         break;
1168     }
1169
1170     prefetch_motion(s, mb, mb_x, mb_y, x_off, y_off, VP56_FRAME_GOLDEN);
1171 }
1172
1173 static void idct_mb(VP8Context *s, uint8_t *y_dst, uint8_t *u_dst, uint8_t *v_dst,
1174                     VP8Macroblock *mb)
1175 {
1176     int x, y, nnz;
1177
1178     if (mb->mode != MODE_I4x4)
1179         for (y = 0; y < 4; y++) {
1180             for (x = 0; x < 4; x++) {
1181                 nnz = s->non_zero_count_cache[y][x];
1182                 if (nnz) {
1183                     if (nnz == 1)
1184                         s->vp8dsp.vp8_idct_dc_add(y_dst+4*x, s->block[y][x], s->linesize);
1185                     else
1186                         s->vp8dsp.vp8_idct_add(y_dst+4*x, s->block[y][x], s->linesize);
1187                 }
1188             }
1189             y_dst += 4*s->linesize;
1190         }
1191
1192     for (y = 0; y < 2; y++) {
1193         for (x = 0; x < 2; x++) {
1194             nnz = s->non_zero_count_cache[4][(y<<1)+x];
1195             if (nnz) {
1196                 if (nnz == 1)
1197                     s->vp8dsp.vp8_idct_dc_add(u_dst+4*x, s->block[4][(y<<1)+x], s->uvlinesize);
1198                 else
1199                     s->vp8dsp.vp8_idct_add(u_dst+4*x, s->block[4][(y<<1)+x], s->uvlinesize);
1200             }
1201
1202             nnz = s->non_zero_count_cache[5][(y<<1)+x];
1203             if (nnz) {
1204                 if (nnz == 1)
1205                     s->vp8dsp.vp8_idct_dc_add(v_dst+4*x, s->block[5][(y<<1)+x], s->uvlinesize);
1206                 else
1207                     s->vp8dsp.vp8_idct_add(v_dst+4*x, s->block[5][(y<<1)+x], s->uvlinesize);
1208             }
1209         }
1210         u_dst += 4*s->uvlinesize;
1211         v_dst += 4*s->uvlinesize;
1212     }
1213 }
1214
1215 static void filter_level_for_mb(VP8Context *s, VP8Macroblock *mb, int *level, int *inner, int *hev_thresh)
1216 {
1217     int interior_limit, filter_level;
1218
1219     if (s->segmentation.enabled) {
1220         filter_level = s->segmentation.filter_level[mb->segment];
1221         if (!s->segmentation.absolute_vals)
1222             filter_level += s->filter.level;
1223     } else
1224         filter_level = s->filter.level;
1225
1226     if (s->lf_delta.enabled) {
1227         filter_level += s->lf_delta.ref[mb->ref_frame];
1228
1229         if (mb->ref_frame == VP56_FRAME_CURRENT) {
1230             if (mb->mode == MODE_I4x4)
1231                 filter_level += s->lf_delta.mode[0];
1232         } else {
1233             if (mb->mode == VP8_MVMODE_ZERO)
1234                 filter_level += s->lf_delta.mode[1];
1235             else if (mb->mode == VP8_MVMODE_SPLIT)
1236                 filter_level += s->lf_delta.mode[3];
1237             else
1238                 filter_level += s->lf_delta.mode[2];
1239         }
1240     }
1241     filter_level = av_clip(filter_level, 0, 63);
1242
1243     interior_limit = filter_level;
1244     if (s->filter.sharpness) {
1245         interior_limit >>= s->filter.sharpness > 4 ? 2 : 1;
1246         interior_limit = FFMIN(interior_limit, 9 - s->filter.sharpness);
1247     }
1248     interior_limit = FFMAX(interior_limit, 1);
1249
1250     *level = filter_level;
1251     *inner = interior_limit;
1252
1253     if (hev_thresh) {
1254         *hev_thresh = filter_level >= 15;
1255
1256         if (s->keyframe) {
1257             if (filter_level >= 40)
1258                 *hev_thresh = 2;
1259         } else {
1260             if (filter_level >= 40)
1261                 *hev_thresh = 3;
1262             else if (filter_level >= 20)
1263                 *hev_thresh = 2;
1264         }
1265     }
1266 }
1267
1268 static void filter_mb(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb, int mb_x, int mb_y)
1269 {
1270     int filter_level, inner_limit, hev_thresh, mbedge_lim, bedge_lim;
1271
1272     filter_level_for_mb(s, mb, &filter_level, &inner_limit, &hev_thresh);
1273     if (!filter_level)
1274         return;
1275
1276     mbedge_lim = 2*(filter_level+2) + inner_limit;
1277      bedge_lim = 2* filter_level    + inner_limit;
1278
1279     if (mb_x) {
1280         s->vp8dsp.vp8_h_loop_filter16y(dst[0],     s->linesize,
1281                                        mbedge_lim, inner_limit, hev_thresh);
1282         s->vp8dsp.vp8_h_loop_filter8uv(dst[1],     dst[2],      s->uvlinesize,
1283                                        mbedge_lim, inner_limit, hev_thresh);
1284     }
1285
1286     if (!mb->skip || mb->mode == MODE_I4x4 || mb->mode == VP8_MVMODE_SPLIT) {
1287         s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0]+ 4, s->linesize, bedge_lim,
1288                                              inner_limit,   hev_thresh);
1289         s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0]+ 8, s->linesize, bedge_lim,
1290                                              inner_limit,   hev_thresh);
1291         s->vp8dsp.vp8_h_loop_filter16y_inner(dst[0]+12, s->linesize, bedge_lim,
1292                                              inner_limit,   hev_thresh);
1293         s->vp8dsp.vp8_h_loop_filter8uv_inner(dst[1] + 4,    dst[2] + 4,
1294                                              s->uvlinesize, bedge_lim,
1295                                              inner_limit,   hev_thresh);
1296     }
1297
1298     if (mb_y) {
1299         s->vp8dsp.vp8_v_loop_filter16y(dst[0],     s->linesize,
1300                                        mbedge_lim, inner_limit, hev_thresh);
1301         s->vp8dsp.vp8_v_loop_filter8uv(dst[1],     dst[2],      s->uvlinesize,
1302                                        mbedge_lim, inner_limit, hev_thresh);
1303     }
1304
1305     if (!mb->skip || mb->mode == MODE_I4x4 || mb->mode == VP8_MVMODE_SPLIT) {
1306         s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0]+ 4*s->linesize,
1307                                              s->linesize,   bedge_lim,
1308                                              inner_limit,   hev_thresh);
1309         s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0]+ 8*s->linesize,
1310                                              s->linesize,   bedge_lim,
1311                                              inner_limit,   hev_thresh);
1312         s->vp8dsp.vp8_v_loop_filter16y_inner(dst[0]+12*s->linesize,
1313                                              s->linesize,   bedge_lim,
1314                                              inner_limit, hev_thresh);
1315         s->vp8dsp.vp8_v_loop_filter8uv_inner(dst[1] + 4 * s->uvlinesize,
1316                                              dst[2] + 4 * s->uvlinesize,
1317                                              s->uvlinesize, bedge_lim,
1318                                              inner_limit,   hev_thresh);
1319     }
1320 }
1321
1322 static void filter_mb_simple(VP8Context *s, uint8_t *dst, VP8Macroblock *mb, int mb_x, int mb_y)
1323 {
1324     int filter_level, inner_limit, mbedge_lim, bedge_lim;
1325
1326     filter_level_for_mb(s, mb, &filter_level, &inner_limit, NULL);
1327     if (!filter_level)
1328         return;
1329
1330     mbedge_lim = 2*(filter_level+2) + inner_limit;
1331      bedge_lim = 2* filter_level    + inner_limit;
1332
1333     if (mb_x)
1334         s->vp8dsp.vp8_h_loop_filter_simple(dst, s->linesize, mbedge_lim);
1335     if (!mb->skip || mb->mode == MODE_I4x4 || mb->mode == VP8_MVMODE_SPLIT) {
1336         s->vp8dsp.vp8_h_loop_filter_simple(dst+ 4, s->linesize, bedge_lim);
1337         s->vp8dsp.vp8_h_loop_filter_simple(dst+ 8, s->linesize, bedge_lim);
1338         s->vp8dsp.vp8_h_loop_filter_simple(dst+12, s->linesize, bedge_lim);
1339     }
1340
1341     if (mb_y)
1342         s->vp8dsp.vp8_v_loop_filter_simple(dst, s->linesize, mbedge_lim);
1343     if (!mb->skip || mb->mode == MODE_I4x4 || mb->mode == VP8_MVMODE_SPLIT) {
1344         s->vp8dsp.vp8_v_loop_filter_simple(dst+ 4*s->linesize, s->linesize, bedge_lim);
1345         s->vp8dsp.vp8_v_loop_filter_simple(dst+ 8*s->linesize, s->linesize, bedge_lim);
1346         s->vp8dsp.vp8_v_loop_filter_simple(dst+12*s->linesize, s->linesize, bedge_lim);
1347     }
1348 }
1349
1350 static void filter_mb_row(VP8Context *s, int mb_y)
1351 {
1352     VP8Macroblock *mb = s->macroblocks + mb_y*s->mb_stride;
1353     uint8_t *dst[3] = {
1354         s->framep[VP56_FRAME_CURRENT]->data[0] + 16*mb_y*s->linesize,
1355         s->framep[VP56_FRAME_CURRENT]->data[1] +  8*mb_y*s->uvlinesize,
1356         s->framep[VP56_FRAME_CURRENT]->data[2] +  8*mb_y*s->uvlinesize
1357     };
1358     int mb_x;
1359
1360     for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1361         backup_mb_border(s->top_border[mb_x+1], dst[0], dst[1], dst[2], s->linesize, s->uvlinesize, 0);
1362         filter_mb(s, dst, mb++, mb_x, mb_y);
1363         dst[0] += 16;
1364         dst[1] += 8;
1365         dst[2] += 8;
1366     }
1367 }
1368
1369 static void filter_mb_row_simple(VP8Context *s, int mb_y)
1370 {
1371     uint8_t *dst = s->framep[VP56_FRAME_CURRENT]->data[0] + 16*mb_y*s->linesize;
1372     VP8Macroblock *mb = s->macroblocks + mb_y*s->mb_stride;
1373     int mb_x;
1374
1375     for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1376         backup_mb_border(s->top_border[mb_x+1], dst, NULL, NULL, s->linesize, 0, 1);
1377         filter_mb_simple(s, dst, mb++, mb_x, mb_y);
1378         dst += 16;
1379     }
1380 }
1381
1382 static int vp8_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
1383                             AVPacket *avpkt)
1384 {
1385     VP8Context *s = avctx->priv_data;
1386     int ret, mb_x, mb_y, i, y, referenced;
1387     enum AVDiscard skip_thresh;
1388     AVFrame *curframe;
1389
1390     if ((ret = decode_frame_header(s, avpkt->data, avpkt->size)) < 0)
1391         return ret;
1392
1393     referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT
1394                                 || s->update_altref == VP56_FRAME_CURRENT;
1395
1396     skip_thresh = !referenced ? AVDISCARD_NONREF :
1397                     !s->keyframe ? AVDISCARD_NONKEY : AVDISCARD_ALL;
1398
1399     if (avctx->skip_frame >= skip_thresh) {
1400         s->invisible = 1;
1401         goto skip_decode;
1402     }
1403     s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;
1404
1405     for (i = 0; i < 4; i++)
1406         if (&s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
1407             &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&
1408             &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) {
1409             curframe = s->framep[VP56_FRAME_CURRENT] = &s->frames[i];
1410             break;
1411         }
1412     if (curframe->data[0])
1413         avctx->release_buffer(avctx, curframe);
1414
1415     curframe->key_frame = s->keyframe;
1416     curframe->pict_type = s->keyframe ? FF_I_TYPE : FF_P_TYPE;
1417     curframe->reference = referenced ? 3 : 0;
1418     if ((ret = avctx->get_buffer(avctx, curframe))) {
1419         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed!\n");
1420         return ret;
1421     }
1422
1423     // Given that arithmetic probabilities are updated every frame, it's quite likely
1424     // that the values we have on a random interframe are complete junk if we didn't
1425     // start decode on a keyframe. So just don't display anything rather than junk.
1426     if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||
1427                          !s->framep[VP56_FRAME_GOLDEN] ||
1428                          !s->framep[VP56_FRAME_GOLDEN2])) {
1429         av_log(avctx, AV_LOG_WARNING, "Discarding interframe without a prior keyframe!\n");
1430         return AVERROR_INVALIDDATA;
1431     }
1432
1433     s->linesize   = curframe->linesize[0];
1434     s->uvlinesize = curframe->linesize[1];
1435
1436     if (!s->edge_emu_buffer)
1437         s->edge_emu_buffer = av_malloc(21*s->linesize);
1438
1439     memset(s->top_nnz, 0, s->mb_width*sizeof(*s->top_nnz));
1440
1441     // top edge of 127 for intra prediction
1442     memset(s->top_border, 127, (s->mb_width+1)*sizeof(*s->top_border));
1443
1444     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1445         VP56RangeCoder *c = &s->coeff_partition[mb_y & (s->num_coeff_partitions-1)];
1446         VP8Macroblock *mb = s->macroblocks + mb_y*s->mb_stride;
1447         uint8_t *intra4x4 = s->intra4x4_pred_mode + 4*mb_y*s->b4_stride;
1448         uint8_t *dst[3] = {
1449             curframe->data[0] + 16*mb_y*s->linesize,
1450             curframe->data[1] +  8*mb_y*s->uvlinesize,
1451             curframe->data[2] +  8*mb_y*s->uvlinesize
1452         };
1453
1454         memset(s->left_nnz, 0, sizeof(s->left_nnz));
1455
1456         // left edge of 129 for intra prediction
1457         if (!(avctx->flags & CODEC_FLAG_EMU_EDGE))
1458             for (i = 0; i < 3; i++)
1459                 for (y = 0; y < 16>>!!i; y++)
1460                     dst[i][y*curframe->linesize[i]-1] = 129;
1461         if (mb_y)
1462             memset(s->top_border, 129, sizeof(*s->top_border));
1463
1464         for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1465             uint8_t *intra4x4_mb = s->keyframe ? intra4x4 + 4*mb_x : s->intra4x4_pred_mode_mb;
1466
1467             /* Prefetch the current frame, 4 MBs ahead */
1468             s->dsp.prefetch(dst[0] + (mb_x&3)*4*s->linesize + 64, s->linesize, 4);
1469             s->dsp.prefetch(dst[1] + (mb_x&7)*s->uvlinesize + 64, dst[2] - dst[1], 2);
1470
1471             decode_mb_mode(s, mb, mb_x, mb_y, intra4x4_mb);
1472
1473             if (!mb->skip)
1474                 decode_mb_coeffs(s, c, mb, s->top_nnz[mb_x], s->left_nnz);
1475             else {
1476                 AV_ZERO128(s->non_zero_count_cache);    // luma
1477                 AV_ZERO64(s->non_zero_count_cache[4]);  // chroma
1478             }
1479
1480             if (mb->mode <= MODE_I4x4) {
1481                 intra_predict(s, dst, mb, intra4x4_mb, mb_x, mb_y);
1482                 memset(mb->bmv, 0, sizeof(mb->bmv));
1483             } else {
1484                 inter_predict(s, dst, mb, mb_x, mb_y);
1485             }
1486
1487             if (!mb->skip) {
1488                 idct_mb(s, dst[0], dst[1], dst[2], mb);
1489             } else {
1490                 AV_ZERO64(s->left_nnz);
1491                 AV_WN64(s->top_nnz[mb_x], 0);   // array of 9, so unaligned
1492
1493                 // Reset DC block predictors if they would exist if the mb had coefficients
1494                 if (mb->mode != MODE_I4x4 && mb->mode != VP8_MVMODE_SPLIT) {
1495                     s->left_nnz[8]      = 0;
1496                     s->top_nnz[mb_x][8] = 0;
1497                 }
1498             }
1499
1500             dst[0] += 16;
1501             dst[1] += 8;
1502             dst[2] += 8;
1503             mb++;
1504         }
1505         if (s->deblock_filter) {
1506             if (s->filter.simple)
1507                 filter_mb_row_simple(s, mb_y);
1508             else
1509                 filter_mb_row(s, mb_y);
1510         }
1511     }
1512
1513 skip_decode:
1514     // if future frames don't use the updated probabilities,
1515     // reset them to the values we saved
1516     if (!s->update_probabilities)
1517         s->prob[0] = s->prob[1];
1518
1519     // check if golden and altref are swapped
1520     if (s->update_altref == VP56_FRAME_GOLDEN &&
1521         s->update_golden == VP56_FRAME_GOLDEN2)
1522         FFSWAP(AVFrame *, s->framep[VP56_FRAME_GOLDEN], s->framep[VP56_FRAME_GOLDEN2]);
1523     else {
1524         if (s->update_altref != VP56_FRAME_NONE)
1525             s->framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];
1526
1527         if (s->update_golden != VP56_FRAME_NONE)
1528             s->framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];
1529     }
1530
1531     if (s->update_last) // move cur->prev
1532         s->framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_CURRENT];
1533
1534     // release no longer referenced frames
1535     for (i = 0; i < 4; i++)
1536         if (s->frames[i].data[0] &&
1537             &s->frames[i] != s->framep[VP56_FRAME_CURRENT] &&
1538             &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
1539             &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&
1540             &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])
1541             avctx->release_buffer(avctx, &s->frames[i]);
1542
1543     if (!s->invisible) {
1544         *(AVFrame*)data = *s->framep[VP56_FRAME_CURRENT];
1545         *data_size = sizeof(AVFrame);
1546     }
1547
1548     return avpkt->size;
1549 }
1550
1551 static av_cold int vp8_decode_init(AVCodecContext *avctx)
1552 {
1553     VP8Context *s = avctx->priv_data;
1554
1555     s->avctx = avctx;
1556     avctx->pix_fmt = PIX_FMT_YUV420P;
1557
1558     dsputil_init(&s->dsp, avctx);
1559     ff_h264_pred_init(&s->hpc, CODEC_ID_VP8);
1560     ff_vp8dsp_init(&s->vp8dsp);
1561
1562     // intra pred needs edge emulation among other things
1563     if (avctx->flags&CODEC_FLAG_EMU_EDGE) {
1564         av_log(avctx, AV_LOG_ERROR, "Edge emulation not supported\n");
1565         return AVERROR_PATCHWELCOME;
1566     }
1567
1568     return 0;
1569 }
1570
1571 static av_cold int vp8_decode_free(AVCodecContext *avctx)
1572 {
1573     vp8_decode_flush(avctx);
1574     return 0;
1575 }
1576
1577 AVCodec vp8_decoder = {
1578     "vp8",
1579     AVMEDIA_TYPE_VIDEO,
1580     CODEC_ID_VP8,
1581     sizeof(VP8Context),
1582     vp8_decode_init,
1583     NULL,
1584     vp8_decode_free,
1585     vp8_decode_frame,
1586     CODEC_CAP_DR1,
1587     .flush = vp8_decode_flush,
1588     .long_name = NULL_IF_CONFIG_SMALL("On2 VP8"),
1589 };