Don't allocate dqcoeff in MACROBLOCKD.
[platform/upstream/libvpx.git] / vp9 / decoder / vp9_decodeframe.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <assert.h>
12 #include <stdlib.h>  // qsort()
13
14 #include "./vp9_rtcd.h"
15 #include "./vpx_scale_rtcd.h"
16
17 #include "vpx_mem/vpx_mem.h"
18 #include "vpx_ports/mem.h"
19 #include "vpx_ports/mem_ops.h"
20 #include "vpx_scale/vpx_scale.h"
21 #include "vpx_util/vpx_thread.h"
22
23 #include "vp9/common/vp9_alloccommon.h"
24 #include "vp9/common/vp9_common.h"
25 #include "vp9/common/vp9_entropy.h"
26 #include "vp9/common/vp9_entropymode.h"
27 #include "vp9/common/vp9_idct.h"
28 #include "vp9/common/vp9_thread_common.h"
29 #include "vp9/common/vp9_pred_common.h"
30 #include "vp9/common/vp9_quant_common.h"
31 #include "vp9/common/vp9_reconintra.h"
32 #include "vp9/common/vp9_reconinter.h"
33 #include "vp9/common/vp9_seg_common.h"
34 #include "vp9/common/vp9_tile_common.h"
35
36 #include "vp9/decoder/vp9_decodeframe.h"
37 #include "vp9/decoder/vp9_detokenize.h"
38 #include "vp9/decoder/vp9_decodemv.h"
39 #include "vp9/decoder/vp9_decoder.h"
40 #include "vp9/decoder/vp9_dsubexp.h"
41 #include "vp9/decoder/vp9_read_bit_buffer.h"
42 #include "vp9/decoder/vp9_reader.h"
43
44 #define MAX_VP9_HEADER_SIZE 80
45
46 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
47   int i;
48   for (i = 1; i < REFS_PER_FRAME; ++i)
49     if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1])
50       return 1;
51
52   return 0;
53 }
54
55 static void setup_compound_reference_mode(VP9_COMMON *cm) {
56   if (cm->ref_frame_sign_bias[LAST_FRAME] ==
57           cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
58     cm->comp_fixed_ref = ALTREF_FRAME;
59     cm->comp_var_ref[0] = LAST_FRAME;
60     cm->comp_var_ref[1] = GOLDEN_FRAME;
61   } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
62                  cm->ref_frame_sign_bias[ALTREF_FRAME]) {
63     cm->comp_fixed_ref = GOLDEN_FRAME;
64     cm->comp_var_ref[0] = LAST_FRAME;
65     cm->comp_var_ref[1] = ALTREF_FRAME;
66   } else {
67     cm->comp_fixed_ref = LAST_FRAME;
68     cm->comp_var_ref[0] = GOLDEN_FRAME;
69     cm->comp_var_ref[1] = ALTREF_FRAME;
70   }
71 }
72
73 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
74   return len != 0 && len <= (size_t)(end - start);
75 }
76
77 static int decode_unsigned_max(struct vp9_read_bit_buffer *rb, int max) {
78   const int data = vp9_rb_read_literal(rb, get_unsigned_bits(max));
79   return data > max ? max : data;
80 }
81
82 static TX_MODE read_tx_mode(vp9_reader *r) {
83   TX_MODE tx_mode = vp9_read_literal(r, 2);
84   if (tx_mode == ALLOW_32X32)
85     tx_mode += vp9_read_bit(r);
86   return tx_mode;
87 }
88
89 static void read_tx_mode_probs(struct tx_probs *tx_probs, vp9_reader *r) {
90   int i, j;
91
92   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
93     for (j = 0; j < TX_SIZES - 3; ++j)
94       vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
95
96   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
97     for (j = 0; j < TX_SIZES - 2; ++j)
98       vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
99
100   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
101     for (j = 0; j < TX_SIZES - 1; ++j)
102       vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
103 }
104
105 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
106   int i, j;
107   for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
108     for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
109       vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
110 }
111
112 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
113   int i, j;
114   for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
115     for (j = 0; j < INTER_MODES - 1; ++j)
116       vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
117 }
118
119 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
120                                                 vp9_reader *r) {
121   if (is_compound_reference_allowed(cm)) {
122     return vp9_read_bit(r) ? (vp9_read_bit(r) ? REFERENCE_MODE_SELECT
123                                               : COMPOUND_REFERENCE)
124                            : SINGLE_REFERENCE;
125   } else {
126     return SINGLE_REFERENCE;
127   }
128 }
129
130 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vp9_reader *r) {
131   FRAME_CONTEXT *const fc = cm->fc;
132   int i;
133
134   if (cm->reference_mode == REFERENCE_MODE_SELECT)
135     for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
136       vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
137
138   if (cm->reference_mode != COMPOUND_REFERENCE)
139     for (i = 0; i < REF_CONTEXTS; ++i) {
140       vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
141       vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
142     }
143
144   if (cm->reference_mode != SINGLE_REFERENCE)
145     for (i = 0; i < REF_CONTEXTS; ++i)
146       vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
147 }
148
149 static void update_mv_probs(vp9_prob *p, int n, vp9_reader *r) {
150   int i;
151   for (i = 0; i < n; ++i)
152     if (vp9_read(r, MV_UPDATE_PROB))
153       p[i] = (vp9_read_literal(r, 7) << 1) | 1;
154 }
155
156 static void read_mv_probs(nmv_context *ctx, int allow_hp, vp9_reader *r) {
157   int i, j;
158
159   update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
160
161   for (i = 0; i < 2; ++i) {
162     nmv_component *const comp_ctx = &ctx->comps[i];
163     update_mv_probs(&comp_ctx->sign, 1, r);
164     update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
165     update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
166     update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
167   }
168
169   for (i = 0; i < 2; ++i) {
170     nmv_component *const comp_ctx = &ctx->comps[i];
171     for (j = 0; j < CLASS0_SIZE; ++j)
172       update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
173     update_mv_probs(comp_ctx->fp, 3, r);
174   }
175
176   if (allow_hp) {
177     for (i = 0; i < 2; ++i) {
178       nmv_component *const comp_ctx = &ctx->comps[i];
179       update_mv_probs(&comp_ctx->class0_hp, 1, r);
180       update_mv_probs(&comp_ctx->hp, 1, r);
181     }
182   }
183 }
184
185 static void inverse_transform_block(MACROBLOCKD* xd, int plane, int block,
186                                     TX_SIZE tx_size, uint8_t *dst, int stride,
187                                     int eob) {
188   struct macroblockd_plane *const pd = &xd->plane[plane];
189   if (eob > 0) {
190     TX_TYPE tx_type = DCT_DCT;
191     tran_low_t *const dqcoeff = pd->dqcoeff;
192 #if CONFIG_VP9_HIGHBITDEPTH
193     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
194       if (xd->lossless) {
195         tx_type = DCT_DCT;
196         vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
197       } else {
198         const PLANE_TYPE plane_type = pd->plane_type;
199         switch (tx_size) {
200           case TX_4X4:
201             tx_type = get_tx_type_4x4(plane_type, xd, block);
202             vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
203             break;
204           case TX_8X8:
205             tx_type = get_tx_type(plane_type, xd);
206             vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
207             break;
208           case TX_16X16:
209             tx_type = get_tx_type(plane_type, xd);
210             vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
211             break;
212           case TX_32X32:
213             tx_type = DCT_DCT;
214             vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
215             break;
216           default:
217             assert(0 && "Invalid transform size");
218         }
219       }
220     } else {
221       if (xd->lossless) {
222         tx_type = DCT_DCT;
223         vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
224       } else {
225         const PLANE_TYPE plane_type = pd->plane_type;
226         switch (tx_size) {
227           case TX_4X4:
228             tx_type = get_tx_type_4x4(plane_type, xd, block);
229             vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
230             break;
231           case TX_8X8:
232             tx_type = get_tx_type(plane_type, xd);
233             vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
234             break;
235           case TX_16X16:
236             tx_type = get_tx_type(plane_type, xd);
237             vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
238             break;
239           case TX_32X32:
240             tx_type = DCT_DCT;
241             vp9_idct32x32_add(dqcoeff, dst, stride, eob);
242             break;
243           default:
244             assert(0 && "Invalid transform size");
245             return;
246         }
247       }
248     }
249 #else
250     if (xd->lossless) {
251       tx_type = DCT_DCT;
252       vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
253     } else {
254       const PLANE_TYPE plane_type = pd->plane_type;
255       switch (tx_size) {
256         case TX_4X4:
257           tx_type = get_tx_type_4x4(plane_type, xd, block);
258           vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
259           break;
260         case TX_8X8:
261           tx_type = get_tx_type(plane_type, xd);
262           vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
263           break;
264         case TX_16X16:
265           tx_type = get_tx_type(plane_type, xd);
266           vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
267           break;
268         case TX_32X32:
269           tx_type = DCT_DCT;
270           vp9_idct32x32_add(dqcoeff, dst, stride, eob);
271           break;
272         default:
273           assert(0 && "Invalid transform size");
274           return;
275       }
276     }
277 #endif  // CONFIG_VP9_HIGHBITDEPTH
278
279     if (eob == 1) {
280       memset(dqcoeff, 0, 2 * sizeof(dqcoeff[0]));
281     } else {
282       if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
283         memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
284       else if (tx_size == TX_32X32 && eob <= 34)
285         memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
286       else
287         memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
288     }
289   }
290 }
291
292 struct intra_args {
293   MACROBLOCKD *xd;
294   vp9_reader *r;
295   int seg_id;
296 };
297
298 static void predict_and_reconstruct_intra_block(int plane, int block,
299                                                 BLOCK_SIZE plane_bsize,
300                                                 TX_SIZE tx_size, void *arg) {
301   struct intra_args *const args = (struct intra_args *)arg;
302   MACROBLOCKD *const xd = args->xd;
303   struct macroblockd_plane *const pd = &xd->plane[plane];
304   MODE_INFO *const mi = xd->mi[0];
305   const PREDICTION_MODE mode = (plane == 0) ? get_y_mode(mi, block)
306                                             : mi->mbmi.uv_mode;
307   int x, y;
308   uint8_t *dst;
309   txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x, &y);
310   dst = &pd->dst.buf[4 * y * pd->dst.stride + 4 * x];
311
312   vp9_predict_intra_block(xd, block >> (tx_size << 1),
313                           b_width_log2_lookup[plane_bsize], tx_size, mode,
314                           dst, pd->dst.stride, dst, pd->dst.stride,
315                           x, y, plane);
316
317   if (!mi->mbmi.skip) {
318     const scan_order *sc = (plane || xd->lossless) ?
319         &vp9_default_scan_orders[tx_size] :
320         &vp9_scan_orders[tx_size][intra_mode_to_tx_type_lookup[mode]];
321     const int eob = vp9_decode_block_tokens(xd, plane, sc,
322                                             plane_bsize, x, y, tx_size,
323                                             args->r, args->seg_id);
324     inverse_transform_block(xd, plane, block, tx_size, dst, pd->dst.stride,
325                             eob);
326   }
327 }
328
329 struct inter_args {
330   MACROBLOCKD *xd;
331   vp9_reader *r;
332   int *eobtotal;
333   int seg_id;
334 };
335
336 static void reconstruct_inter_block(int plane, int block,
337                                     BLOCK_SIZE plane_bsize,
338                                     TX_SIZE tx_size, void *arg) {
339   struct inter_args *args = (struct inter_args *)arg;
340   MACROBLOCKD *const xd = args->xd;
341   struct macroblockd_plane *const pd = &xd->plane[plane];
342   int x, y, eob;
343   const scan_order *sc = &vp9_default_scan_orders[tx_size];
344   txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x, &y);
345   eob = vp9_decode_block_tokens(xd, plane, sc, plane_bsize,
346                                 x, y, tx_size, args->r, args->seg_id);
347   inverse_transform_block(xd, plane, block, tx_size,
348                           &pd->dst.buf[4 * y * pd->dst.stride + 4 * x],
349                           pd->dst.stride, eob);
350   *args->eobtotal += eob;
351 }
352
353 static void build_mc_border(const uint8_t *src, int src_stride,
354                             uint8_t *dst, int dst_stride,
355                             int x, int y, int b_w, int b_h, int w, int h) {
356   // Get a pointer to the start of the real data for this row.
357   const uint8_t *ref_row = src - x - y * src_stride;
358
359   if (y >= h)
360     ref_row += (h - 1) * src_stride;
361   else if (y > 0)
362     ref_row += y * src_stride;
363
364   do {
365     int right = 0, copy;
366     int left = x < 0 ? -x : 0;
367
368     if (left > b_w)
369       left = b_w;
370
371     if (x + b_w > w)
372       right = x + b_w - w;
373
374     if (right > b_w)
375       right = b_w;
376
377     copy = b_w - left - right;
378
379     if (left)
380       memset(dst, ref_row[0], left);
381
382     if (copy)
383       memcpy(dst + left, ref_row + x + left, copy);
384
385     if (right)
386       memset(dst + left + copy, ref_row[w - 1], right);
387
388     dst += dst_stride;
389     ++y;
390
391     if (y > 0 && y < h)
392       ref_row += src_stride;
393   } while (--b_h);
394 }
395
396 #if CONFIG_VP9_HIGHBITDEPTH
397 static void high_build_mc_border(const uint8_t *src8, int src_stride,
398                                  uint16_t *dst, int dst_stride,
399                                  int x, int y, int b_w, int b_h,
400                                  int w, int h) {
401   // Get a pointer to the start of the real data for this row.
402   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
403   const uint16_t *ref_row = src - x - y * src_stride;
404
405   if (y >= h)
406     ref_row += (h - 1) * src_stride;
407   else if (y > 0)
408     ref_row += y * src_stride;
409
410   do {
411     int right = 0, copy;
412     int left = x < 0 ? -x : 0;
413
414     if (left > b_w)
415       left = b_w;
416
417     if (x + b_w > w)
418       right = x + b_w - w;
419
420     if (right > b_w)
421       right = b_w;
422
423     copy = b_w - left - right;
424
425     if (left)
426       vpx_memset16(dst, ref_row[0], left);
427
428     if (copy)
429       memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
430
431     if (right)
432       vpx_memset16(dst + left + copy, ref_row[w - 1], right);
433
434     dst += dst_stride;
435     ++y;
436
437     if (y > 0 && y < h)
438       ref_row += src_stride;
439   } while (--b_h);
440 }
441 #endif  // CONFIG_VP9_HIGHBITDEPTH
442
443 #if CONFIG_VP9_HIGHBITDEPTH
444 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
445                                int x0, int y0, int b_w, int b_h,
446                                int frame_width, int frame_height,
447                                int border_offset,
448                                uint8_t *const dst, int dst_buf_stride,
449                                int subpel_x, int subpel_y,
450                                const InterpKernel *kernel,
451                                const struct scale_factors *sf,
452                                MACROBLOCKD *xd,
453                                int w, int h, int ref, int xs, int ys) {
454   DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
455   const uint8_t *buf_ptr;
456
457   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
458     high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w,
459                          x0, y0, b_w, b_h, frame_width, frame_height);
460     buf_ptr = CONVERT_TO_BYTEPTR(mc_buf_high) + border_offset;
461   } else {
462     build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w,
463                     x0, y0, b_w, b_h, frame_width, frame_height);
464     buf_ptr = ((uint8_t *)mc_buf_high) + border_offset;
465   }
466
467   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
468     high_inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
469                          subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
470   } else {
471     inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
472                     subpel_y, sf, w, h, ref, kernel, xs, ys);
473   }
474 }
475 #else
476 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
477                                int x0, int y0, int b_w, int b_h,
478                                int frame_width, int frame_height,
479                                int border_offset,
480                                uint8_t *const dst, int dst_buf_stride,
481                                int subpel_x, int subpel_y,
482                                const InterpKernel *kernel,
483                                const struct scale_factors *sf,
484                                int w, int h, int ref, int xs, int ys) {
485   DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
486   const uint8_t *buf_ptr;
487
488   build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w,
489                   x0, y0, b_w, b_h, frame_width, frame_height);
490   buf_ptr = mc_buf + border_offset;
491
492   inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x,
493                   subpel_y, sf, w, h, ref, kernel, xs, ys);
494 }
495 #endif  // CONFIG_VP9_HIGHBITDEPTH
496
497 static void dec_build_inter_predictors(VP9Decoder *const pbi, MACROBLOCKD *xd,
498                                        int plane, int bw, int bh, int x,
499                                        int y, int w, int h, int mi_x, int mi_y,
500                                        const InterpKernel *kernel,
501                                        const struct scale_factors *sf,
502                                        struct buf_2d *pre_buf,
503                                        struct buf_2d *dst_buf, const MV* mv,
504                                        RefCntBuffer *ref_frame_buf,
505                                        int is_scaled, int ref) {
506   struct macroblockd_plane *const pd = &xd->plane[plane];
507   uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
508   MV32 scaled_mv;
509   int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height,
510       buf_stride, subpel_x, subpel_y;
511   uint8_t *ref_frame, *buf_ptr;
512
513   // Get reference frame pointer, width and height.
514   if (plane == 0) {
515     frame_width = ref_frame_buf->buf.y_crop_width;
516     frame_height = ref_frame_buf->buf.y_crop_height;
517     ref_frame = ref_frame_buf->buf.y_buffer;
518   } else {
519     frame_width = ref_frame_buf->buf.uv_crop_width;
520     frame_height = ref_frame_buf->buf.uv_crop_height;
521     ref_frame = plane == 1 ? ref_frame_buf->buf.u_buffer
522                          : ref_frame_buf->buf.v_buffer;
523   }
524
525   if (is_scaled) {
526     const MV mv_q4 = clamp_mv_to_umv_border_sb(xd, mv, bw, bh,
527                                                pd->subsampling_x,
528                                                pd->subsampling_y);
529     // Co-ordinate of containing block to pixel precision.
530     int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
531     int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
532
533     // Co-ordinate of the block to 1/16th pixel precision.
534     x0_16 = (x_start + x) << SUBPEL_BITS;
535     y0_16 = (y_start + y) << SUBPEL_BITS;
536
537     // Co-ordinate of current block in reference frame
538     // to 1/16th pixel precision.
539     x0_16 = sf->scale_value_x(x0_16, sf);
540     y0_16 = sf->scale_value_y(y0_16, sf);
541
542     // Map the top left corner of the block into the reference frame.
543     x0 = sf->scale_value_x(x_start + x, sf);
544     y0 = sf->scale_value_y(y_start + y, sf);
545
546     // Scale the MV and incorporate the sub-pixel offset of the block
547     // in the reference frame.
548     scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
549     xs = sf->x_step_q4;
550     ys = sf->y_step_q4;
551   } else {
552     // Co-ordinate of containing block to pixel precision.
553     x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
554     y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
555
556     // Co-ordinate of the block to 1/16th pixel precision.
557     x0_16 = x0 << SUBPEL_BITS;
558     y0_16 = y0 << SUBPEL_BITS;
559
560     scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
561     scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
562     xs = ys = 16;
563   }
564   subpel_x = scaled_mv.col & SUBPEL_MASK;
565   subpel_y = scaled_mv.row & SUBPEL_MASK;
566
567   // Calculate the top left corner of the best matching block in the
568   // reference frame.
569   x0 += scaled_mv.col >> SUBPEL_BITS;
570   y0 += scaled_mv.row >> SUBPEL_BITS;
571   x0_16 += scaled_mv.col;
572   y0_16 += scaled_mv.row;
573
574   // Get reference block pointer.
575   buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
576   buf_stride = pre_buf->stride;
577
578   // Do border extension if there is motion or the
579   // width/height is not a multiple of 8 pixels.
580   if (is_scaled || scaled_mv.col || scaled_mv.row ||
581       (frame_width & 0x7) || (frame_height & 0x7)) {
582     int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
583
584     // Get reference block bottom right horizontal coordinate.
585     int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
586     int x_pad = 0, y_pad = 0;
587
588     if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
589       x0 -= VP9_INTERP_EXTEND - 1;
590       x1 += VP9_INTERP_EXTEND;
591       x_pad = 1;
592     }
593
594     if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
595       y0 -= VP9_INTERP_EXTEND - 1;
596       y1 += VP9_INTERP_EXTEND;
597       y_pad = 1;
598     }
599
600     // Wait until reference block is ready. Pad 7 more pixels as last 7
601     // pixels of each superblock row can be changed by next superblock row.
602     if (pbi->frame_parallel_decode)
603       vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
604                            MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
605
606     // Skip border extension if block is inside the frame.
607     if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
608         y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
609       // Extend the border.
610       const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
611       const int b_w = x1 - x0 + 1;
612       const int b_h = y1 - y0 + 1;
613       const int border_offset = y_pad * 3 * b_w + x_pad * 3;
614
615       extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h,
616                          frame_width, frame_height, border_offset,
617                          dst, dst_buf->stride,
618                          subpel_x, subpel_y,
619                          kernel, sf,
620 #if CONFIG_VP9_HIGHBITDEPTH
621                          xd,
622 #endif
623                          w, h, ref, xs, ys);
624       return;
625     }
626   } else {
627     // Wait until reference block is ready. Pad 7 more pixels as last 7
628     // pixels of each superblock row can be changed by next superblock row.
629      if (pbi->frame_parallel_decode) {
630        const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
631        vp9_frameworker_wait(pbi->frame_worker_owner, ref_frame_buf,
632                             MAX(0, (y1 + 7)) << (plane == 0 ? 0 : 1));
633      }
634   }
635 #if CONFIG_VP9_HIGHBITDEPTH
636   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
637     high_inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
638                          subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
639   } else {
640     inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
641                     subpel_y, sf, w, h, ref, kernel, xs, ys);
642   }
643 #else
644   inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
645                   subpel_y, sf, w, h, ref, kernel, xs, ys);
646 #endif  // CONFIG_VP9_HIGHBITDEPTH
647 }
648
649 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
650                                           MACROBLOCKD *xd,
651                                           int mi_row, int mi_col,
652                                           BLOCK_SIZE bsize) {
653   int plane;
654   const int mi_x = mi_col * MI_SIZE;
655   const int mi_y = mi_row * MI_SIZE;
656   const MODE_INFO *mi = xd->mi[0];
657   const InterpKernel *kernel = vp9_filter_kernels[mi->mbmi.interp_filter];
658   const BLOCK_SIZE sb_type = mi->mbmi.sb_type;
659   const int is_compound = has_second_ref(&mi->mbmi);
660
661   for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
662     const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize,
663                                                         &xd->plane[plane]);
664     struct macroblockd_plane *const pd = &xd->plane[plane];
665     struct buf_2d *const dst_buf = &pd->dst;
666     const int num_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
667     const int num_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
668
669     const int bw = 4 * num_4x4_w;
670     const int bh = 4 * num_4x4_h;
671     int ref;
672
673     for (ref = 0; ref < 1 + is_compound; ++ref) {
674       const struct scale_factors *const sf = &xd->block_refs[ref]->sf;
675       struct buf_2d *const pre_buf = &pd->pre[ref];
676       const int idx = xd->block_refs[ref]->idx;
677       BufferPool *const pool = pbi->common.buffer_pool;
678       RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
679       const int is_scaled = vp9_is_scaled(sf);
680
681       if (sb_type < BLOCK_8X8) {
682         int i = 0, x, y;
683         assert(bsize == BLOCK_8X8);
684         for (y = 0; y < num_4x4_h; ++y) {
685           for (x = 0; x < num_4x4_w; ++x) {
686             const MV mv = average_split_mvs(pd, mi, ref, i++);
687             dec_build_inter_predictors(pbi, xd, plane, bw, bh,
688                                        4 * x, 4 * y, 4, 4, mi_x, mi_y, kernel,
689                                        sf, pre_buf, dst_buf, &mv,
690                                        ref_frame_buf, is_scaled, ref);
691           }
692         }
693       } else {
694         const MV mv = mi->mbmi.mv[ref].as_mv;
695         dec_build_inter_predictors(pbi, xd, plane, bw, bh,
696                                    0, 0, bw, bh, mi_x, mi_y, kernel,
697                                    sf, pre_buf, dst_buf, &mv, ref_frame_buf,
698                                    is_scaled, ref);
699       }
700     }
701   }
702 }
703
704 static MB_MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
705                                  BLOCK_SIZE bsize, int mi_row, int mi_col) {
706   const int bw = num_8x8_blocks_wide_lookup[bsize];
707   const int bh = num_8x8_blocks_high_lookup[bsize];
708   const int x_mis = MIN(bw, cm->mi_cols - mi_col);
709   const int y_mis = MIN(bh, cm->mi_rows - mi_row);
710   const int offset = mi_row * cm->mi_stride + mi_col;
711   int x, y;
712   const TileInfo *const tile = &xd->tile;
713
714   xd->mi = cm->mi_grid_visible + offset;
715   xd->mi[0] = &cm->mi[offset];
716   xd->mi[0]->mbmi.sb_type = bsize;
717   for (y = 0; y < y_mis; ++y)
718     for (x = !y; x < x_mis; ++x) {
719       xd->mi[y * cm->mi_stride + x] = xd->mi[0];
720     }
721
722   set_skip_context(xd, mi_row, mi_col);
723
724   // Distance of Mb to the various image edges. These are specified to 8th pel
725   // as they are always compared to values that are in 1/8th pel units
726   set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
727
728   vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
729   return &xd->mi[0]->mbmi;
730 }
731
732 static void decode_block(VP9Decoder *const pbi, MACROBLOCKD *const xd,
733                          int mi_row, int mi_col,
734                          vp9_reader *r, BLOCK_SIZE bsize) {
735   VP9_COMMON *const cm = &pbi->common;
736   const int less8x8 = bsize < BLOCK_8X8;
737   MB_MODE_INFO *mbmi = set_offsets(cm, xd, bsize, mi_row, mi_col);
738
739   if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
740     const BLOCK_SIZE uv_subsize =
741         ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
742     if (uv_subsize == BLOCK_INVALID)
743       vpx_internal_error(xd->error_info,
744                          VPX_CODEC_CORRUPT_FRAME, "Invalid block size.");
745   }
746
747   vp9_read_mode_info(pbi, xd, mi_row, mi_col, r);
748
749   if (less8x8)
750     bsize = BLOCK_8X8;
751
752   if (mbmi->skip) {
753     reset_skip_context(xd, bsize);
754   }
755
756   if (!is_inter_block(mbmi)) {
757     struct intra_args arg = {xd, r, mbmi->segment_id};
758     vp9_foreach_transformed_block(xd, bsize,
759                                   predict_and_reconstruct_intra_block, &arg);
760   } else {
761     // Prediction
762     dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col, bsize);
763
764     // Reconstruction
765     if (!mbmi->skip) {
766       int eobtotal = 0;
767       struct inter_args arg = {xd, r, &eobtotal, mbmi->segment_id};
768       vp9_foreach_transformed_block(xd, bsize, reconstruct_inter_block, &arg);
769       if (!less8x8 && eobtotal == 0)
770         mbmi->skip = 1;  // skip loopfilter
771     }
772   }
773
774   xd->corrupted |= vp9_reader_has_error(r);
775 }
776
777 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
778                                      BLOCK_SIZE bsize, vp9_reader *r,
779                                      int has_rows, int has_cols) {
780   const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
781   const vp9_prob *const probs = get_partition_probs(xd, ctx);
782   FRAME_COUNTS *counts = xd->counts;
783   PARTITION_TYPE p;
784
785   if (has_rows && has_cols)
786     p = (PARTITION_TYPE)vp9_read_tree(r, vp9_partition_tree, probs);
787   else if (!has_rows && has_cols)
788     p = vp9_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
789   else if (has_rows && !has_cols)
790     p = vp9_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
791   else
792     p = PARTITION_SPLIT;
793
794   if (counts)
795     ++counts->partition[ctx][p];
796
797   return p;
798 }
799
800 static void decode_partition(VP9Decoder *const pbi, MACROBLOCKD *const xd,
801                              int mi_row, int mi_col,
802                              vp9_reader* r, BLOCK_SIZE bsize) {
803   VP9_COMMON *const cm = &pbi->common;
804   const int hbs = num_8x8_blocks_wide_lookup[bsize] / 2;
805   PARTITION_TYPE partition;
806   BLOCK_SIZE subsize;
807   const int has_rows = (mi_row + hbs) < cm->mi_rows;
808   const int has_cols = (mi_col + hbs) < cm->mi_cols;
809
810   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
811     return;
812
813   partition = read_partition(xd, mi_row, mi_col, bsize, r, has_rows, has_cols);
814   subsize = get_subsize(bsize, partition);
815   if (bsize == BLOCK_8X8) {
816     decode_block(pbi, xd, mi_row, mi_col, r, subsize);
817   } else {
818     switch (partition) {
819       case PARTITION_NONE:
820         decode_block(pbi, xd, mi_row, mi_col, r, subsize);
821         break;
822       case PARTITION_HORZ:
823         decode_block(pbi, xd, mi_row, mi_col, r, subsize);
824         if (has_rows)
825           decode_block(pbi, xd, mi_row + hbs, mi_col, r, subsize);
826         break;
827       case PARTITION_VERT:
828         decode_block(pbi, xd, mi_row, mi_col, r, subsize);
829         if (has_cols)
830           decode_block(pbi, xd, mi_row, mi_col + hbs, r, subsize);
831         break;
832       case PARTITION_SPLIT:
833         decode_partition(pbi, xd, mi_row, mi_col, r, subsize);
834         decode_partition(pbi, xd, mi_row, mi_col + hbs, r, subsize);
835         decode_partition(pbi, xd, mi_row + hbs, mi_col, r, subsize);
836         decode_partition(pbi, xd, mi_row + hbs, mi_col + hbs, r, subsize);
837         break;
838       default:
839         assert(0 && "Invalid partition type");
840     }
841   }
842
843   // update partition context
844   if (bsize >= BLOCK_8X8 &&
845       (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
846     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
847 }
848
849 static void setup_token_decoder(const uint8_t *data,
850                                 const uint8_t *data_end,
851                                 size_t read_size,
852                                 struct vpx_internal_error_info *error_info,
853                                 vp9_reader *r,
854                                 vpx_decrypt_cb decrypt_cb,
855                                 void *decrypt_state) {
856   // Validate the calculated partition length. If the buffer
857   // described by the partition can't be fully read, then restrict
858   // it to the portion that can be (for EC mode) or throw an error.
859   if (!read_is_valid(data, read_size, data_end))
860     vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
861                        "Truncated packet or corrupt tile length");
862
863   if (vp9_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
864     vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
865                        "Failed to allocate bool decoder %d", 1);
866 }
867
868 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
869                                    vp9_reader *r) {
870   int i, j, k, l, m;
871
872   if (vp9_read_bit(r))
873     for (i = 0; i < PLANE_TYPES; ++i)
874       for (j = 0; j < REF_TYPES; ++j)
875         for (k = 0; k < COEF_BANDS; ++k)
876           for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
877             for (m = 0; m < UNCONSTRAINED_NODES; ++m)
878               vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
879 }
880
881 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
882                             vp9_reader *r) {
883     const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
884     TX_SIZE tx_size;
885     for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
886       read_coef_probs_common(fc->coef_probs[tx_size], r);
887 }
888
889 static void setup_segmentation(struct segmentation *seg,
890                                struct vp9_read_bit_buffer *rb) {
891   int i, j;
892
893   seg->update_map = 0;
894   seg->update_data = 0;
895
896   seg->enabled = vp9_rb_read_bit(rb);
897   if (!seg->enabled)
898     return;
899
900   // Segmentation map update
901   seg->update_map = vp9_rb_read_bit(rb);
902   if (seg->update_map) {
903     for (i = 0; i < SEG_TREE_PROBS; i++)
904       seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
905                                                : MAX_PROB;
906
907     seg->temporal_update = vp9_rb_read_bit(rb);
908     if (seg->temporal_update) {
909       for (i = 0; i < PREDICTION_PROBS; i++)
910         seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
911                                                  : MAX_PROB;
912     } else {
913       for (i = 0; i < PREDICTION_PROBS; i++)
914         seg->pred_probs[i] = MAX_PROB;
915     }
916   }
917
918   // Segmentation data update
919   seg->update_data = vp9_rb_read_bit(rb);
920   if (seg->update_data) {
921     seg->abs_delta = vp9_rb_read_bit(rb);
922
923     vp9_clearall_segfeatures(seg);
924
925     for (i = 0; i < MAX_SEGMENTS; i++) {
926       for (j = 0; j < SEG_LVL_MAX; j++) {
927         int data = 0;
928         const int feature_enabled = vp9_rb_read_bit(rb);
929         if (feature_enabled) {
930           vp9_enable_segfeature(seg, i, j);
931           data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
932           if (vp9_is_segfeature_signed(j))
933             data = vp9_rb_read_bit(rb) ? -data : data;
934         }
935         vp9_set_segdata(seg, i, j, data);
936       }
937     }
938   }
939 }
940
941 static void setup_loopfilter(struct loopfilter *lf,
942                              struct vp9_read_bit_buffer *rb) {
943   lf->filter_level = vp9_rb_read_literal(rb, 6);
944   lf->sharpness_level = vp9_rb_read_literal(rb, 3);
945
946   // Read in loop filter deltas applied at the MB level based on mode or ref
947   // frame.
948   lf->mode_ref_delta_update = 0;
949
950   lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
951   if (lf->mode_ref_delta_enabled) {
952     lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
953     if (lf->mode_ref_delta_update) {
954       int i;
955
956       for (i = 0; i < MAX_REF_LF_DELTAS; i++)
957         if (vp9_rb_read_bit(rb))
958           lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
959
960       for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
961         if (vp9_rb_read_bit(rb))
962           lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
963     }
964   }
965 }
966
967 static INLINE int read_delta_q(struct vp9_read_bit_buffer *rb) {
968   return vp9_rb_read_bit(rb) ? vp9_rb_read_signed_literal(rb, 4) : 0;
969 }
970
971 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
972                                struct vp9_read_bit_buffer *rb) {
973   cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
974   cm->y_dc_delta_q = read_delta_q(rb);
975   cm->uv_dc_delta_q = read_delta_q(rb);
976   cm->uv_ac_delta_q = read_delta_q(rb);
977   cm->dequant_bit_depth = cm->bit_depth;
978   xd->lossless = cm->base_qindex == 0 &&
979                  cm->y_dc_delta_q == 0 &&
980                  cm->uv_dc_delta_q == 0 &&
981                  cm->uv_ac_delta_q == 0;
982
983 #if CONFIG_VP9_HIGHBITDEPTH
984   xd->bd = (int)cm->bit_depth;
985 #endif
986 }
987
988 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
989   // Build y/uv dequant values based on segmentation.
990   if (cm->seg.enabled) {
991     int i;
992     for (i = 0; i < MAX_SEGMENTS; ++i) {
993       const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
994       cm->y_dequant[i][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q,
995                                          cm->bit_depth);
996       cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
997       cm->uv_dequant[i][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
998                                           cm->bit_depth);
999       cm->uv_dequant[i][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1000                                           cm->bit_depth);
1001     }
1002   } else {
1003     const int qindex = cm->base_qindex;
1004     // When segmentation is disabled, only the first value is used.  The
1005     // remaining are don't cares.
1006     cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1007     cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1008     cm->uv_dequant[0][0] = vp9_dc_quant(qindex, cm->uv_dc_delta_q,
1009                                         cm->bit_depth);
1010     cm->uv_dequant[0][1] = vp9_ac_quant(qindex, cm->uv_ac_delta_q,
1011                                         cm->bit_depth);
1012   }
1013 }
1014
1015 static INTERP_FILTER read_interp_filter(struct vp9_read_bit_buffer *rb) {
1016   const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
1017                                               EIGHTTAP,
1018                                               EIGHTTAP_SHARP,
1019                                               BILINEAR };
1020   return vp9_rb_read_bit(rb) ? SWITCHABLE
1021                              : literal_to_filter[vp9_rb_read_literal(rb, 2)];
1022 }
1023
1024 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1025   cm->display_width = cm->width;
1026   cm->display_height = cm->height;
1027   if (vp9_rb_read_bit(rb))
1028     vp9_read_frame_size(rb, &cm->display_width, &cm->display_height);
1029 }
1030
1031 static void resize_mv_buffer(VP9_COMMON *cm) {
1032   vpx_free(cm->cur_frame->mvs);
1033   cm->cur_frame->mi_rows = cm->mi_rows;
1034   cm->cur_frame->mi_cols = cm->mi_cols;
1035   cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1036                                             sizeof(*cm->cur_frame->mvs));
1037 }
1038
1039 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1040 #if CONFIG_SIZE_LIMIT
1041   if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1042     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1043                        "Dimensions of %dx%d beyond allowed size of %dx%d.",
1044                        width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1045 #endif
1046   if (cm->width != width || cm->height != height) {
1047     const int new_mi_rows =
1048         ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1049     const int new_mi_cols =
1050         ALIGN_POWER_OF_TWO(width,  MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1051
1052     // Allocations in vp9_alloc_context_buffers() depend on individual
1053     // dimensions as well as the overall size.
1054     if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1055       if (vp9_alloc_context_buffers(cm, width, height))
1056         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1057                            "Failed to allocate context buffers");
1058     } else {
1059       vp9_set_mb_mi(cm, width, height);
1060     }
1061     vp9_init_context_buffers(cm);
1062     cm->width = width;
1063     cm->height = height;
1064   }
1065   if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1066       cm->mi_cols > cm->cur_frame->mi_cols) {
1067     resize_mv_buffer(cm);
1068   }
1069 }
1070
1071 static void setup_frame_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1072   int width, height;
1073   BufferPool *const pool = cm->buffer_pool;
1074   vp9_read_frame_size(rb, &width, &height);
1075   resize_context_buffers(cm, width, height);
1076   setup_display_size(cm, rb);
1077
1078   lock_buffer_pool(pool);
1079   if (vp9_realloc_frame_buffer(
1080           get_frame_new_buffer(cm), cm->width, cm->height,
1081           cm->subsampling_x, cm->subsampling_y,
1082 #if CONFIG_VP9_HIGHBITDEPTH
1083           cm->use_highbitdepth,
1084 #endif
1085           VP9_DEC_BORDER_IN_PIXELS,
1086           cm->byte_alignment,
1087           &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1088           pool->cb_priv)) {
1089     unlock_buffer_pool(pool);
1090     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1091                        "Failed to allocate frame buffer");
1092   }
1093   unlock_buffer_pool(pool);
1094
1095   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1096   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1097   pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1098   pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1099 }
1100
1101 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1102                                           int ref_xss, int ref_yss,
1103                                           vpx_bit_depth_t this_bit_depth,
1104                                           int this_xss, int this_yss) {
1105   return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1106          ref_yss == this_yss;
1107 }
1108
1109 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1110                                        struct vp9_read_bit_buffer *rb) {
1111   int width, height;
1112   int found = 0, i;
1113   int has_valid_ref_frame = 0;
1114   BufferPool *const pool = cm->buffer_pool;
1115   for (i = 0; i < REFS_PER_FRAME; ++i) {
1116     if (vp9_rb_read_bit(rb)) {
1117       YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1118       width = buf->y_crop_width;
1119       height = buf->y_crop_height;
1120       found = 1;
1121       break;
1122     }
1123   }
1124
1125   if (!found)
1126     vp9_read_frame_size(rb, &width, &height);
1127
1128   if (width <= 0 || height <= 0)
1129     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1130                        "Invalid frame size");
1131
1132   // Check to make sure at least one of frames that this frame references
1133   // has valid dimensions.
1134   for (i = 0; i < REFS_PER_FRAME; ++i) {
1135     RefBuffer *const ref_frame = &cm->frame_refs[i];
1136     has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
1137                                                 ref_frame->buf->y_crop_height,
1138                                                 width, height);
1139   }
1140   if (!has_valid_ref_frame)
1141     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1142                        "Referenced frame has invalid size");
1143   for (i = 0; i < REFS_PER_FRAME; ++i) {
1144     RefBuffer *const ref_frame = &cm->frame_refs[i];
1145     if (!valid_ref_frame_img_fmt(
1146             ref_frame->buf->bit_depth,
1147             ref_frame->buf->subsampling_x,
1148             ref_frame->buf->subsampling_y,
1149             cm->bit_depth,
1150             cm->subsampling_x,
1151             cm->subsampling_y))
1152       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1153                          "Referenced frame has incompatible color format");
1154   }
1155
1156   resize_context_buffers(cm, width, height);
1157   setup_display_size(cm, rb);
1158
1159   lock_buffer_pool(pool);
1160   if (vp9_realloc_frame_buffer(
1161           get_frame_new_buffer(cm), cm->width, cm->height,
1162           cm->subsampling_x, cm->subsampling_y,
1163 #if CONFIG_VP9_HIGHBITDEPTH
1164           cm->use_highbitdepth,
1165 #endif
1166           VP9_DEC_BORDER_IN_PIXELS,
1167           cm->byte_alignment,
1168           &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1169           pool->cb_priv)) {
1170     unlock_buffer_pool(pool);
1171     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1172                        "Failed to allocate frame buffer");
1173   }
1174   unlock_buffer_pool(pool);
1175
1176   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1177   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1178   pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1179   pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1180 }
1181
1182 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1183   int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1184   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1185
1186   // columns
1187   max_ones = max_log2_tile_cols - min_log2_tile_cols;
1188   cm->log2_tile_cols = min_log2_tile_cols;
1189   while (max_ones-- && vp9_rb_read_bit(rb))
1190     cm->log2_tile_cols++;
1191
1192   if (cm->log2_tile_cols > 6)
1193     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1194                        "Invalid number of tile columns");
1195
1196   // rows
1197   cm->log2_tile_rows = vp9_rb_read_bit(rb);
1198   if (cm->log2_tile_rows)
1199     cm->log2_tile_rows += vp9_rb_read_bit(rb);
1200 }
1201
1202 typedef struct TileBuffer {
1203   const uint8_t *data;
1204   size_t size;
1205   int col;  // only used with multi-threaded decoding
1206 } TileBuffer;
1207
1208 // Reads the next tile returning its size and adjusting '*data' accordingly
1209 // based on 'is_last'.
1210 static void get_tile_buffer(const uint8_t *const data_end,
1211                             int is_last,
1212                             struct vpx_internal_error_info *error_info,
1213                             const uint8_t **data,
1214                             vpx_decrypt_cb decrypt_cb, void *decrypt_state,
1215                             TileBuffer *buf) {
1216   size_t size;
1217
1218   if (!is_last) {
1219     if (!read_is_valid(*data, 4, data_end))
1220       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1221                          "Truncated packet or corrupt tile length");
1222
1223     if (decrypt_cb) {
1224       uint8_t be_data[4];
1225       decrypt_cb(decrypt_state, *data, be_data, 4);
1226       size = mem_get_be32(be_data);
1227     } else {
1228       size = mem_get_be32(*data);
1229     }
1230     *data += 4;
1231
1232     if (size > (size_t)(data_end - *data))
1233       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1234                          "Truncated packet or corrupt tile size");
1235   } else {
1236     size = data_end - *data;
1237   }
1238
1239   buf->data = *data;
1240   buf->size = size;
1241
1242   *data += size;
1243 }
1244
1245 static void get_tile_buffers(VP9Decoder *pbi,
1246                              const uint8_t *data, const uint8_t *data_end,
1247                              int tile_cols, int tile_rows,
1248                              TileBuffer (*tile_buffers)[1 << 6]) {
1249   int r, c;
1250
1251   for (r = 0; r < tile_rows; ++r) {
1252     for (c = 0; c < tile_cols; ++c) {
1253       const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1254       TileBuffer *const buf = &tile_buffers[r][c];
1255       buf->col = c;
1256       get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1257                       pbi->decrypt_cb, pbi->decrypt_state, buf);
1258     }
1259   }
1260 }
1261
1262 static const uint8_t *decode_tiles(VP9Decoder *pbi,
1263                                    const uint8_t *data,
1264                                    const uint8_t *data_end) {
1265   VP9_COMMON *const cm = &pbi->common;
1266   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1267   const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1268   const int tile_cols = 1 << cm->log2_tile_cols;
1269   const int tile_rows = 1 << cm->log2_tile_rows;
1270   TileBuffer tile_buffers[4][1 << 6];
1271   int tile_row, tile_col;
1272   int mi_row, mi_col;
1273   TileData *tile_data = NULL;
1274
1275   if (cm->lf.filter_level && !cm->skip_loop_filter &&
1276       pbi->lf_worker.data1 == NULL) {
1277     CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1278                     vpx_memalign(32, sizeof(LFWorkerData)));
1279     pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1280     if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1281       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1282                          "Loop filter thread creation failed");
1283     }
1284   }
1285
1286   if (cm->lf.filter_level && !cm->skip_loop_filter) {
1287     LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1288     // Be sure to sync as we might be resuming after a failed frame decode.
1289     winterface->sync(&pbi->lf_worker);
1290     vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1291                                pbi->mb.plane);
1292   }
1293
1294   assert(tile_rows <= 4);
1295   assert(tile_cols <= (1 << 6));
1296
1297   // Note: this memset assumes above_context[0], [1] and [2]
1298   // are allocated as part of the same buffer.
1299   memset(cm->above_context, 0,
1300          sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1301
1302   memset(cm->above_seg_context, 0,
1303          sizeof(*cm->above_seg_context) * aligned_cols);
1304
1305   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1306
1307   if (pbi->tile_data == NULL ||
1308       (tile_cols * tile_rows) != pbi->total_tiles) {
1309     vpx_free(pbi->tile_data);
1310     CHECK_MEM_ERROR(
1311         cm,
1312         pbi->tile_data,
1313         vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
1314     pbi->total_tiles = tile_rows * tile_cols;
1315   }
1316
1317   // Load all tile information into tile_data.
1318   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1319     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1320       const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1321       tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
1322       tile_data->cm = cm;
1323       tile_data->xd = pbi->mb;
1324       tile_data->xd.corrupted = 0;
1325       tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1326                              NULL : &cm->counts;
1327       vp9_zero(tile_data->dqcoeff);
1328       vp9_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1329       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1330                           &tile_data->bit_reader, pbi->decrypt_cb,
1331                           pbi->decrypt_state);
1332       vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1333     }
1334   }
1335
1336   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1337     TileInfo tile;
1338     vp9_tile_set_row(&tile, cm, tile_row);
1339     for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1340          mi_row += MI_BLOCK_SIZE) {
1341       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1342         const int col = pbi->inv_tile_order ?
1343                         tile_cols - tile_col - 1 : tile_col;
1344         tile_data = pbi->tile_data + tile_cols * tile_row + col;
1345         vp9_tile_set_col(&tile, tile_data->cm, col);
1346         vp9_zero(tile_data->xd.left_context);
1347         vp9_zero(tile_data->xd.left_seg_context);
1348         for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1349              mi_col += MI_BLOCK_SIZE) {
1350           decode_partition(pbi, &tile_data->xd, mi_row, mi_col,
1351                            &tile_data->bit_reader, BLOCK_64X64);
1352         }
1353         pbi->mb.corrupted |= tile_data->xd.corrupted;
1354         if (pbi->mb.corrupted)
1355             vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1356                                "Failed to decode tile data");
1357       }
1358       // Loopfilter one row.
1359       if (cm->lf.filter_level && !cm->skip_loop_filter) {
1360         const int lf_start = mi_row - MI_BLOCK_SIZE;
1361         LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1362
1363         // delay the loopfilter by 1 macroblock row.
1364         if (lf_start < 0) continue;
1365
1366         // decoding has completed: finish up the loop filter in this thread.
1367         if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1368
1369         winterface->sync(&pbi->lf_worker);
1370         lf_data->start = lf_start;
1371         lf_data->stop = mi_row;
1372         if (pbi->max_threads > 1) {
1373           winterface->launch(&pbi->lf_worker);
1374         } else {
1375           winterface->execute(&pbi->lf_worker);
1376         }
1377       }
1378       // After loopfiltering, the last 7 row pixels in each superblock row may
1379       // still be changed by the longest loopfilter of the next superblock
1380       // row.
1381       if (pbi->frame_parallel_decode)
1382         vp9_frameworker_broadcast(pbi->cur_buf,
1383                                   mi_row << MI_BLOCK_SIZE_LOG2);
1384     }
1385   }
1386
1387   // Loopfilter remaining rows in the frame.
1388   if (cm->lf.filter_level && !cm->skip_loop_filter) {
1389     LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1390     winterface->sync(&pbi->lf_worker);
1391     lf_data->start = lf_data->stop;
1392     lf_data->stop = cm->mi_rows;
1393     winterface->execute(&pbi->lf_worker);
1394   }
1395
1396   // Get last tile data.
1397   tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1398
1399   if (pbi->frame_parallel_decode)
1400     vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1401   return vp9_reader_find_end(&tile_data->bit_reader);
1402 }
1403
1404 static int tile_worker_hook(TileWorkerData *const tile_data,
1405                             const TileInfo *const tile) {
1406   int mi_row, mi_col;
1407
1408   if (setjmp(tile_data->error_info.jmp)) {
1409     tile_data->error_info.setjmp = 0;
1410     tile_data->xd.corrupted = 1;
1411     return 0;
1412   }
1413
1414   tile_data->error_info.setjmp = 1;
1415   tile_data->xd.error_info = &tile_data->error_info;
1416
1417   for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1418        mi_row += MI_BLOCK_SIZE) {
1419     vp9_zero(tile_data->xd.left_context);
1420     vp9_zero(tile_data->xd.left_seg_context);
1421     for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1422          mi_col += MI_BLOCK_SIZE) {
1423       decode_partition(tile_data->pbi, &tile_data->xd,
1424                        mi_row, mi_col, &tile_data->bit_reader,
1425                        BLOCK_64X64);
1426     }
1427   }
1428   return !tile_data->xd.corrupted;
1429 }
1430
1431 // sorts in descending order
1432 static int compare_tile_buffers(const void *a, const void *b) {
1433   const TileBuffer *const buf1 = (const TileBuffer*)a;
1434   const TileBuffer *const buf2 = (const TileBuffer*)b;
1435   return (int)(buf2->size - buf1->size);
1436 }
1437
1438 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1439                                       const uint8_t *data,
1440                                       const uint8_t *data_end) {
1441   VP9_COMMON *const cm = &pbi->common;
1442   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1443   const uint8_t *bit_reader_end = NULL;
1444   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1445   const int tile_cols = 1 << cm->log2_tile_cols;
1446   const int tile_rows = 1 << cm->log2_tile_rows;
1447   const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1448   TileBuffer tile_buffers[1][1 << 6];
1449   int n;
1450   int final_worker = -1;
1451
1452   assert(tile_cols <= (1 << 6));
1453   assert(tile_rows == 1);
1454   (void)tile_rows;
1455
1456   // TODO(jzern): See if we can remove the restriction of passing in max
1457   // threads to the decoder.
1458   if (pbi->num_tile_workers == 0) {
1459     const int num_threads = pbi->max_threads & ~1;
1460     int i;
1461     CHECK_MEM_ERROR(cm, pbi->tile_workers,
1462                     vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1463     // Ensure tile data offsets will be properly aligned. This may fail on
1464     // platforms without DECLARE_ALIGNED().
1465     assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1466     CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1467                     vpx_memalign(32, num_threads *
1468                                  sizeof(*pbi->tile_worker_data)));
1469     CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1470                     vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1471     for (i = 0; i < num_threads; ++i) {
1472       VPxWorker *const worker = &pbi->tile_workers[i];
1473       ++pbi->num_tile_workers;
1474
1475       winterface->init(worker);
1476       if (i < num_threads - 1 && !winterface->reset(worker)) {
1477         vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1478                            "Tile decoder thread creation failed");
1479       }
1480     }
1481   }
1482
1483   // Reset tile decoding hook
1484   for (n = 0; n < num_workers; ++n) {
1485     VPxWorker *const worker = &pbi->tile_workers[n];
1486     winterface->sync(worker);
1487     worker->hook = (VPxWorkerHook)tile_worker_hook;
1488     worker->data1 = &pbi->tile_worker_data[n];
1489     worker->data2 = &pbi->tile_worker_info[n];
1490   }
1491
1492   // Note: this memset assumes above_context[0], [1] and [2]
1493   // are allocated as part of the same buffer.
1494   memset(cm->above_context, 0,
1495          sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1496   memset(cm->above_seg_context, 0,
1497          sizeof(*cm->above_seg_context) * aligned_mi_cols);
1498
1499   // Load tile data into tile_buffers
1500   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1501
1502   // Sort the buffers based on size in descending order.
1503   qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1504         compare_tile_buffers);
1505
1506   // Rearrange the tile buffers such that per-tile group the largest, and
1507   // presumably the most difficult, tile will be decoded in the main thread.
1508   // This should help minimize the number of instances where the main thread is
1509   // waiting for a worker to complete.
1510   {
1511     int group_start = 0;
1512     while (group_start < tile_cols) {
1513       const TileBuffer largest = tile_buffers[0][group_start];
1514       const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1515       memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1516               (group_end - group_start) * sizeof(tile_buffers[0][0]));
1517       tile_buffers[0][group_end] = largest;
1518       group_start = group_end + 1;
1519     }
1520   }
1521
1522   // Initialize thread frame counts.
1523   if (!cm->frame_parallel_decoding_mode) {
1524     int i;
1525
1526     for (i = 0; i < num_workers; ++i) {
1527       TileWorkerData *const tile_data =
1528           (TileWorkerData*)pbi->tile_workers[i].data1;
1529       vp9_zero(tile_data->counts);
1530     }
1531   }
1532
1533   n = 0;
1534   while (n < tile_cols) {
1535     int i;
1536     for (i = 0; i < num_workers && n < tile_cols; ++i) {
1537       VPxWorker *const worker = &pbi->tile_workers[i];
1538       TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1539       TileInfo *const tile = (TileInfo*)worker->data2;
1540       TileBuffer *const buf = &tile_buffers[0][n];
1541
1542       tile_data->pbi = pbi;
1543       tile_data->xd = pbi->mb;
1544       tile_data->xd.corrupted = 0;
1545       tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1546                              0 : &tile_data->counts;
1547       vp9_zero(tile_data->dqcoeff);
1548       vp9_tile_init(tile, cm, 0, buf->col);
1549       vp9_tile_init(&tile_data->xd.tile, cm, 0, buf->col);
1550       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1551                           &tile_data->bit_reader, pbi->decrypt_cb,
1552                           pbi->decrypt_state);
1553       vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1554
1555       worker->had_error = 0;
1556       if (i == num_workers - 1 || n == tile_cols - 1) {
1557         winterface->execute(worker);
1558       } else {
1559         winterface->launch(worker);
1560       }
1561
1562       if (buf->col == tile_cols - 1) {
1563         final_worker = i;
1564       }
1565
1566       ++n;
1567     }
1568
1569     for (; i > 0; --i) {
1570       VPxWorker *const worker = &pbi->tile_workers[i - 1];
1571       // TODO(jzern): The tile may have specific error data associated with
1572       // its vpx_internal_error_info which could be propagated to the main info
1573       // in cm. Additionally once the threads have been synced and an error is
1574       // detected, there's no point in continuing to decode tiles.
1575       pbi->mb.corrupted |= !winterface->sync(worker);
1576     }
1577     if (final_worker > -1) {
1578       TileWorkerData *const tile_data =
1579           (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1580       bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1581       final_worker = -1;
1582     }
1583
1584     // Accumulate thread frame counts.
1585     if (n >= tile_cols && !cm->frame_parallel_decoding_mode) {
1586       for (i = 0; i < num_workers; ++i) {
1587         TileWorkerData *const tile_data =
1588             (TileWorkerData*)pbi->tile_workers[i].data1;
1589         vp9_accumulate_frame_counts(cm, &tile_data->counts, 1);
1590       }
1591     }
1592   }
1593
1594   return bit_reader_end;
1595 }
1596
1597 static void error_handler(void *data) {
1598   VP9_COMMON *const cm = (VP9_COMMON *)data;
1599   vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1600 }
1601
1602 static void read_bitdepth_colorspace_sampling(
1603     VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1604   if (cm->profile >= PROFILE_2) {
1605     cm->bit_depth = vp9_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1606 #if CONFIG_VP9_HIGHBITDEPTH
1607     cm->use_highbitdepth = 1;
1608 #endif
1609   } else {
1610     cm->bit_depth = VPX_BITS_8;
1611 #if CONFIG_VP9_HIGHBITDEPTH
1612     cm->use_highbitdepth = 0;
1613 #endif
1614   }
1615   cm->color_space = vp9_rb_read_literal(rb, 3);
1616   if (cm->color_space != VPX_CS_SRGB) {
1617     vp9_rb_read_bit(rb);  // [16,235] (including xvycc) vs [0,255] range
1618     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1619       cm->subsampling_x = vp9_rb_read_bit(rb);
1620       cm->subsampling_y = vp9_rb_read_bit(rb);
1621       if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1622         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1623                            "4:2:0 color not supported in profile 1 or 3");
1624       if (vp9_rb_read_bit(rb))
1625         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1626                            "Reserved bit set");
1627     } else {
1628       cm->subsampling_y = cm->subsampling_x = 1;
1629     }
1630   } else {
1631     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1632       // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1633       // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1634       cm->subsampling_y = cm->subsampling_x = 0;
1635       if (vp9_rb_read_bit(rb))
1636         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1637                            "Reserved bit set");
1638     } else {
1639       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1640                          "4:4:4 color not supported in profile 0 or 2");
1641     }
1642   }
1643 }
1644
1645 static size_t read_uncompressed_header(VP9Decoder *pbi,
1646                                        struct vp9_read_bit_buffer *rb) {
1647   VP9_COMMON *const cm = &pbi->common;
1648   BufferPool *const pool = cm->buffer_pool;
1649   RefCntBuffer *const frame_bufs = pool->frame_bufs;
1650   int i, mask, ref_index = 0;
1651   size_t sz;
1652
1653   cm->last_frame_type = cm->frame_type;
1654   cm->last_intra_only = cm->intra_only;
1655
1656   if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1657       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1658                          "Invalid frame marker");
1659
1660   cm->profile = vp9_read_profile(rb);
1661
1662   if (cm->profile >= MAX_PROFILES)
1663     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1664                        "Unsupported bitstream profile");
1665
1666   cm->show_existing_frame = vp9_rb_read_bit(rb);
1667   if (cm->show_existing_frame) {
1668     // Show an existing frame directly.
1669     const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1670     lock_buffer_pool(pool);
1671     if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1672       unlock_buffer_pool(pool);
1673       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1674                          "Buffer %d does not contain a decoded frame",
1675                          frame_to_show);
1676     }
1677
1678     ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1679     unlock_buffer_pool(pool);
1680     pbi->refresh_frame_flags = 0;
1681     cm->lf.filter_level = 0;
1682     cm->show_frame = 1;
1683
1684     if (pbi->frame_parallel_decode) {
1685       for (i = 0; i < REF_FRAMES; ++i)
1686         cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1687     }
1688     return 0;
1689   }
1690
1691   cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1692   cm->show_frame = vp9_rb_read_bit(rb);
1693   cm->error_resilient_mode = vp9_rb_read_bit(rb);
1694
1695   if (cm->frame_type == KEY_FRAME) {
1696     if (!vp9_read_sync_code(rb))
1697       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1698                          "Invalid frame sync code");
1699
1700     read_bitdepth_colorspace_sampling(cm, rb);
1701     pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1702
1703     for (i = 0; i < REFS_PER_FRAME; ++i) {
1704       cm->frame_refs[i].idx = INVALID_IDX;
1705       cm->frame_refs[i].buf = NULL;
1706     }
1707
1708     setup_frame_size(cm, rb);
1709     if (pbi->need_resync) {
1710       memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1711       pbi->need_resync = 0;
1712     }
1713   } else {
1714     cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1715
1716     cm->reset_frame_context = cm->error_resilient_mode ?
1717         0 : vp9_rb_read_literal(rb, 2);
1718
1719     if (cm->intra_only) {
1720       if (!vp9_read_sync_code(rb))
1721         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1722                            "Invalid frame sync code");
1723       if (cm->profile > PROFILE_0) {
1724         read_bitdepth_colorspace_sampling(cm, rb);
1725       } else {
1726         // NOTE: The intra-only frame header does not include the specification
1727         // of either the color format or color sub-sampling in profile 0. VP9
1728         // specifies that the default color format should be YUV 4:2:0 in this
1729         // case (normative).
1730         cm->color_space = VPX_CS_BT_601;
1731         cm->subsampling_y = cm->subsampling_x = 1;
1732         cm->bit_depth = VPX_BITS_8;
1733 #if CONFIG_VP9_HIGHBITDEPTH
1734         cm->use_highbitdepth = 0;
1735 #endif
1736       }
1737
1738       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1739       setup_frame_size(cm, rb);
1740       if (pbi->need_resync) {
1741         memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1742         pbi->need_resync = 0;
1743       }
1744     } else if (pbi->need_resync != 1) {  /* Skip if need resync */
1745       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1746       for (i = 0; i < REFS_PER_FRAME; ++i) {
1747         const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1748         const int idx = cm->ref_frame_map[ref];
1749         RefBuffer *const ref_frame = &cm->frame_refs[i];
1750         ref_frame->idx = idx;
1751         ref_frame->buf = &frame_bufs[idx].buf;
1752         cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1753       }
1754
1755       setup_frame_size_with_refs(cm, rb);
1756
1757       cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1758       cm->interp_filter = read_interp_filter(rb);
1759
1760       for (i = 0; i < REFS_PER_FRAME; ++i) {
1761         RefBuffer *const ref_buf = &cm->frame_refs[i];
1762 #if CONFIG_VP9_HIGHBITDEPTH
1763         vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1764                                           ref_buf->buf->y_crop_width,
1765                                           ref_buf->buf->y_crop_height,
1766                                           cm->width, cm->height,
1767                                           cm->use_highbitdepth);
1768 #else
1769         vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1770                                           ref_buf->buf->y_crop_width,
1771                                           ref_buf->buf->y_crop_height,
1772                                           cm->width, cm->height);
1773 #endif
1774       }
1775     }
1776   }
1777 #if CONFIG_VP9_HIGHBITDEPTH
1778   get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1779 #endif
1780   get_frame_new_buffer(cm)->color_space = cm->color_space;
1781
1782   if (pbi->need_resync) {
1783     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1784                        "Keyframe / intra-only frame required to reset decoder"
1785                        " state");
1786   }
1787
1788   if (!cm->error_resilient_mode) {
1789     cm->refresh_frame_context = vp9_rb_read_bit(rb);
1790     cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
1791   } else {
1792     cm->refresh_frame_context = 0;
1793     cm->frame_parallel_decoding_mode = 1;
1794   }
1795
1796   // This flag will be overridden by the call to vp9_setup_past_independence
1797   // below, forcing the use of context 0 for those frame types.
1798   cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1799
1800   // Generate next_ref_frame_map.
1801   lock_buffer_pool(pool);
1802   for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
1803     if (mask & 1) {
1804       cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
1805       ++frame_bufs[cm->new_fb_idx].ref_count;
1806     } else {
1807       cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1808     }
1809     // Current thread holds the reference frame.
1810     if (cm->ref_frame_map[ref_index] >= 0)
1811       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1812     ++ref_index;
1813   }
1814
1815   for (; ref_index < REF_FRAMES; ++ref_index) {
1816     cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1817     // Current thread holds the reference frame.
1818     if (cm->ref_frame_map[ref_index] >= 0)
1819       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1820   }
1821   unlock_buffer_pool(pool);
1822   pbi->hold_ref_buf = 1;
1823
1824   if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1825     vp9_setup_past_independence(cm);
1826
1827   setup_loopfilter(&cm->lf, rb);
1828   setup_quantization(cm, &pbi->mb, rb);
1829   setup_segmentation(&cm->seg, rb);
1830   setup_segmentation_dequant(cm);
1831
1832   setup_tile_info(cm, rb);
1833   sz = vp9_rb_read_literal(rb, 16);
1834
1835   if (sz == 0)
1836     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1837                        "Invalid header size");
1838
1839   return sz;
1840 }
1841
1842 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
1843                                   size_t partition_size) {
1844   VP9_COMMON *const cm = &pbi->common;
1845   MACROBLOCKD *const xd = &pbi->mb;
1846   FRAME_CONTEXT *const fc = cm->fc;
1847   vp9_reader r;
1848   int k;
1849
1850   if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
1851                       pbi->decrypt_state))
1852     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1853                        "Failed to allocate bool decoder 0");
1854
1855   cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1856   if (cm->tx_mode == TX_MODE_SELECT)
1857     read_tx_mode_probs(&fc->tx_probs, &r);
1858   read_coef_probs(fc, cm->tx_mode, &r);
1859
1860   for (k = 0; k < SKIP_CONTEXTS; ++k)
1861     vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1862
1863   if (!frame_is_intra_only(cm)) {
1864     nmv_context *const nmvc = &fc->nmvc;
1865     int i, j;
1866
1867     read_inter_mode_probs(fc, &r);
1868
1869     if (cm->interp_filter == SWITCHABLE)
1870       read_switchable_interp_probs(fc, &r);
1871
1872     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1873       vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1874
1875     cm->reference_mode = read_frame_reference_mode(cm, &r);
1876     if (cm->reference_mode != SINGLE_REFERENCE)
1877       setup_compound_reference_mode(cm);
1878     read_frame_reference_mode_probs(cm, &r);
1879
1880     for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1881       for (i = 0; i < INTRA_MODES - 1; ++i)
1882         vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1883
1884     for (j = 0; j < PARTITION_CONTEXTS; ++j)
1885       for (i = 0; i < PARTITION_TYPES - 1; ++i)
1886         vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1887
1888     read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
1889   }
1890
1891   return vp9_reader_has_error(&r);
1892 }
1893
1894 #ifdef NDEBUG
1895 #define debug_check_frame_counts(cm) (void)0
1896 #else  // !NDEBUG
1897 // Counts should only be incremented when frame_parallel_decoding_mode and
1898 // error_resilient_mode are disabled.
1899 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
1900   FRAME_COUNTS zero_counts;
1901   vp9_zero(zero_counts);
1902   assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
1903   assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
1904                  sizeof(cm->counts.y_mode)));
1905   assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
1906                  sizeof(cm->counts.uv_mode)));
1907   assert(!memcmp(cm->counts.partition, zero_counts.partition,
1908                  sizeof(cm->counts.partition)));
1909   assert(!memcmp(cm->counts.coef, zero_counts.coef,
1910                  sizeof(cm->counts.coef)));
1911   assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
1912                  sizeof(cm->counts.eob_branch)));
1913   assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
1914                  sizeof(cm->counts.switchable_interp)));
1915   assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
1916                  sizeof(cm->counts.inter_mode)));
1917   assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
1918                  sizeof(cm->counts.intra_inter)));
1919   assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
1920                  sizeof(cm->counts.comp_inter)));
1921   assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
1922                  sizeof(cm->counts.single_ref)));
1923   assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
1924                  sizeof(cm->counts.comp_ref)));
1925   assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
1926   assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
1927   assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
1928 }
1929 #endif  // NDEBUG
1930
1931 static struct vp9_read_bit_buffer *init_read_bit_buffer(
1932     VP9Decoder *pbi,
1933     struct vp9_read_bit_buffer *rb,
1934     const uint8_t *data,
1935     const uint8_t *data_end,
1936     uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
1937   rb->bit_offset = 0;
1938   rb->error_handler = error_handler;
1939   rb->error_handler_data = &pbi->common;
1940   if (pbi->decrypt_cb) {
1941     const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
1942     pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
1943     rb->bit_buffer = clear_data;
1944     rb->bit_buffer_end = clear_data + n;
1945   } else {
1946     rb->bit_buffer = data;
1947     rb->bit_buffer_end = data_end;
1948   }
1949   return rb;
1950 }
1951
1952 //------------------------------------------------------------------------------
1953
1954 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
1955   return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
1956          vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
1957          vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
1958 }
1959
1960 void vp9_read_frame_size(struct vp9_read_bit_buffer *rb,
1961                          int *width, int *height) {
1962   *width = vp9_rb_read_literal(rb, 16) + 1;
1963   *height = vp9_rb_read_literal(rb, 16) + 1;
1964 }
1965
1966 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
1967   int profile = vp9_rb_read_bit(rb);
1968   profile |= vp9_rb_read_bit(rb) << 1;
1969   if (profile > 2)
1970     profile += vp9_rb_read_bit(rb);
1971   return (BITSTREAM_PROFILE) profile;
1972 }
1973
1974 void vp9_decode_frame(VP9Decoder *pbi,
1975                       const uint8_t *data, const uint8_t *data_end,
1976                       const uint8_t **p_data_end) {
1977   VP9_COMMON *const cm = &pbi->common;
1978   MACROBLOCKD *const xd = &pbi->mb;
1979   struct vp9_read_bit_buffer rb;
1980   int context_updated = 0;
1981   uint8_t clear_data[MAX_VP9_HEADER_SIZE];
1982   const size_t first_partition_size = read_uncompressed_header(pbi,
1983       init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
1984   const int tile_rows = 1 << cm->log2_tile_rows;
1985   const int tile_cols = 1 << cm->log2_tile_cols;
1986   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
1987   xd->cur_buf = new_fb;
1988
1989   if (!first_partition_size) {
1990     // showing a frame directly
1991     *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
1992     return;
1993   }
1994
1995   data += vp9_rb_bytes_read(&rb);
1996   if (!read_is_valid(data, first_partition_size, data_end))
1997     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1998                        "Truncated packet or corrupt header length");
1999
2000   cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
2001                            cm->width == cm->last_width &&
2002                            cm->height == cm->last_height &&
2003                            !cm->last_intra_only &&
2004                            cm->last_show_frame &&
2005                            (cm->last_frame_type != KEY_FRAME);
2006
2007   vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2008
2009   *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2010   if (!cm->fc->initialized)
2011     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2012                        "Uninitialized entropy context.");
2013
2014   vp9_zero(cm->counts);
2015
2016   xd->corrupted = 0;
2017   new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2018   if (new_fb->corrupted)
2019     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2020                        "Decode failed. Frame data header is corrupted.");
2021
2022   if (cm->lf.filter_level && !cm->skip_loop_filter) {
2023     vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2024   }
2025
2026   // If encoded in frame parallel mode, frame context is ready after decoding
2027   // the frame header.
2028   if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2029     VPxWorker *const worker = pbi->frame_worker_owner;
2030     FrameWorkerData *const frame_worker_data = worker->data1;
2031     if (cm->refresh_frame_context) {
2032       context_updated = 1;
2033       cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2034     }
2035     vp9_frameworker_lock_stats(worker);
2036     pbi->cur_buf->row = -1;
2037     pbi->cur_buf->col = -1;
2038     frame_worker_data->frame_context_ready = 1;
2039     // Signal the main thread that context is ready.
2040     vp9_frameworker_signal_stats(worker);
2041     vp9_frameworker_unlock_stats(worker);
2042   }
2043
2044   if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2045     // Multi-threaded tile decoder
2046     *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2047     if (!xd->corrupted) {
2048       if (!cm->skip_loop_filter) {
2049         // If multiple threads are used to decode tiles, then we use those
2050         // threads to do parallel loopfiltering.
2051         vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2052                                  cm->lf.filter_level, 0, 0, pbi->tile_workers,
2053                                  pbi->num_tile_workers, &pbi->lf_row_sync);
2054       }
2055     } else {
2056       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2057                          "Decode failed. Frame data is corrupted.");
2058
2059     }
2060   } else {
2061     *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2062   }
2063
2064   if (!xd->corrupted) {
2065     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2066       vp9_adapt_coef_probs(cm);
2067
2068       if (!frame_is_intra_only(cm)) {
2069         vp9_adapt_mode_probs(cm);
2070         vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2071       }
2072     } else {
2073       debug_check_frame_counts(cm);
2074     }
2075   } else {
2076     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2077                        "Decode failed. Frame data is corrupted.");
2078   }
2079
2080   // Non frame parallel update frame context here.
2081   if (cm->refresh_frame_context && !context_updated)
2082     cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2083 }