Merge "Rework scan order fetch logic for decoder"
[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_tile_init(&tile_data->xd.tile, tile_data->cm, tile_row, tile_col);
1328       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1329                           &tile_data->bit_reader, pbi->decrypt_cb,
1330                           pbi->decrypt_state);
1331       vp9_init_macroblockd(cm, &tile_data->xd);
1332     }
1333   }
1334
1335   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1336     TileInfo tile;
1337     vp9_tile_set_row(&tile, cm, tile_row);
1338     for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1339          mi_row += MI_BLOCK_SIZE) {
1340       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1341         const int col = pbi->inv_tile_order ?
1342                         tile_cols - tile_col - 1 : tile_col;
1343         tile_data = pbi->tile_data + tile_cols * tile_row + col;
1344         vp9_tile_set_col(&tile, tile_data->cm, col);
1345         vp9_zero(tile_data->xd.left_context);
1346         vp9_zero(tile_data->xd.left_seg_context);
1347         for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1348              mi_col += MI_BLOCK_SIZE) {
1349           decode_partition(pbi, &tile_data->xd, mi_row, mi_col,
1350                            &tile_data->bit_reader, BLOCK_64X64);
1351         }
1352         pbi->mb.corrupted |= tile_data->xd.corrupted;
1353         if (pbi->mb.corrupted)
1354             vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1355                                "Failed to decode tile data");
1356       }
1357       // Loopfilter one row.
1358       if (cm->lf.filter_level && !cm->skip_loop_filter) {
1359         const int lf_start = mi_row - MI_BLOCK_SIZE;
1360         LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1361
1362         // delay the loopfilter by 1 macroblock row.
1363         if (lf_start < 0) continue;
1364
1365         // decoding has completed: finish up the loop filter in this thread.
1366         if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1367
1368         winterface->sync(&pbi->lf_worker);
1369         lf_data->start = lf_start;
1370         lf_data->stop = mi_row;
1371         if (pbi->max_threads > 1) {
1372           winterface->launch(&pbi->lf_worker);
1373         } else {
1374           winterface->execute(&pbi->lf_worker);
1375         }
1376       }
1377       // After loopfiltering, the last 7 row pixels in each superblock row may
1378       // still be changed by the longest loopfilter of the next superblock
1379       // row.
1380       if (pbi->frame_parallel_decode)
1381         vp9_frameworker_broadcast(pbi->cur_buf,
1382                                   mi_row << MI_BLOCK_SIZE_LOG2);
1383     }
1384   }
1385
1386   // Loopfilter remaining rows in the frame.
1387   if (cm->lf.filter_level && !cm->skip_loop_filter) {
1388     LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1389     winterface->sync(&pbi->lf_worker);
1390     lf_data->start = lf_data->stop;
1391     lf_data->stop = cm->mi_rows;
1392     winterface->execute(&pbi->lf_worker);
1393   }
1394
1395   // Get last tile data.
1396   tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1397
1398   if (pbi->frame_parallel_decode)
1399     vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1400   return vp9_reader_find_end(&tile_data->bit_reader);
1401 }
1402
1403 static int tile_worker_hook(TileWorkerData *const tile_data,
1404                             const TileInfo *const tile) {
1405   int mi_row, mi_col;
1406
1407   if (setjmp(tile_data->error_info.jmp)) {
1408     tile_data->error_info.setjmp = 0;
1409     tile_data->xd.corrupted = 1;
1410     return 0;
1411   }
1412
1413   tile_data->error_info.setjmp = 1;
1414   tile_data->xd.error_info = &tile_data->error_info;
1415
1416   for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1417        mi_row += MI_BLOCK_SIZE) {
1418     vp9_zero(tile_data->xd.left_context);
1419     vp9_zero(tile_data->xd.left_seg_context);
1420     for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1421          mi_col += MI_BLOCK_SIZE) {
1422       decode_partition(tile_data->pbi, &tile_data->xd,
1423                        mi_row, mi_col, &tile_data->bit_reader,
1424                        BLOCK_64X64);
1425     }
1426   }
1427   return !tile_data->xd.corrupted;
1428 }
1429
1430 // sorts in descending order
1431 static int compare_tile_buffers(const void *a, const void *b) {
1432   const TileBuffer *const buf1 = (const TileBuffer*)a;
1433   const TileBuffer *const buf2 = (const TileBuffer*)b;
1434   return (int)(buf2->size - buf1->size);
1435 }
1436
1437 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1438                                       const uint8_t *data,
1439                                       const uint8_t *data_end) {
1440   VP9_COMMON *const cm = &pbi->common;
1441   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1442   const uint8_t *bit_reader_end = NULL;
1443   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1444   const int tile_cols = 1 << cm->log2_tile_cols;
1445   const int tile_rows = 1 << cm->log2_tile_rows;
1446   const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1447   TileBuffer tile_buffers[1][1 << 6];
1448   int n;
1449   int final_worker = -1;
1450
1451   assert(tile_cols <= (1 << 6));
1452   assert(tile_rows == 1);
1453   (void)tile_rows;
1454
1455   // TODO(jzern): See if we can remove the restriction of passing in max
1456   // threads to the decoder.
1457   if (pbi->num_tile_workers == 0) {
1458     const int num_threads = pbi->max_threads & ~1;
1459     int i;
1460     CHECK_MEM_ERROR(cm, pbi->tile_workers,
1461                     vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1462     // Ensure tile data offsets will be properly aligned. This may fail on
1463     // platforms without DECLARE_ALIGNED().
1464     assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1465     CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1466                     vpx_memalign(32, num_threads *
1467                                  sizeof(*pbi->tile_worker_data)));
1468     CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1469                     vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1470     for (i = 0; i < num_threads; ++i) {
1471       VPxWorker *const worker = &pbi->tile_workers[i];
1472       ++pbi->num_tile_workers;
1473
1474       winterface->init(worker);
1475       if (i < num_threads - 1 && !winterface->reset(worker)) {
1476         vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1477                            "Tile decoder thread creation failed");
1478       }
1479     }
1480   }
1481
1482   // Reset tile decoding hook
1483   for (n = 0; n < num_workers; ++n) {
1484     VPxWorker *const worker = &pbi->tile_workers[n];
1485     winterface->sync(worker);
1486     worker->hook = (VPxWorkerHook)tile_worker_hook;
1487     worker->data1 = &pbi->tile_worker_data[n];
1488     worker->data2 = &pbi->tile_worker_info[n];
1489   }
1490
1491   // Note: this memset assumes above_context[0], [1] and [2]
1492   // are allocated as part of the same buffer.
1493   memset(cm->above_context, 0,
1494          sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1495   memset(cm->above_seg_context, 0,
1496          sizeof(*cm->above_seg_context) * aligned_mi_cols);
1497
1498   // Load tile data into tile_buffers
1499   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1500
1501   // Sort the buffers based on size in descending order.
1502   qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1503         compare_tile_buffers);
1504
1505   // Rearrange the tile buffers such that per-tile group the largest, and
1506   // presumably the most difficult, tile will be decoded in the main thread.
1507   // This should help minimize the number of instances where the main thread is
1508   // waiting for a worker to complete.
1509   {
1510     int group_start = 0;
1511     while (group_start < tile_cols) {
1512       const TileBuffer largest = tile_buffers[0][group_start];
1513       const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1514       memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1515               (group_end - group_start) * sizeof(tile_buffers[0][0]));
1516       tile_buffers[0][group_end] = largest;
1517       group_start = group_end + 1;
1518     }
1519   }
1520
1521   // Initialize thread frame counts.
1522   if (!cm->frame_parallel_decoding_mode) {
1523     int i;
1524
1525     for (i = 0; i < num_workers; ++i) {
1526       TileWorkerData *const tile_data =
1527           (TileWorkerData*)pbi->tile_workers[i].data1;
1528       vp9_zero(tile_data->counts);
1529     }
1530   }
1531
1532   n = 0;
1533   while (n < tile_cols) {
1534     int i;
1535     for (i = 0; i < num_workers && n < tile_cols; ++i) {
1536       VPxWorker *const worker = &pbi->tile_workers[i];
1537       TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1538       TileInfo *const tile = (TileInfo*)worker->data2;
1539       TileBuffer *const buf = &tile_buffers[0][n];
1540
1541       tile_data->pbi = pbi;
1542       tile_data->xd = pbi->mb;
1543       tile_data->xd.corrupted = 0;
1544       tile_data->xd.counts = cm->frame_parallel_decoding_mode ?
1545                              0 : &tile_data->counts;
1546       vp9_tile_init(tile, cm, 0, buf->col);
1547       vp9_tile_init(&tile_data->xd.tile, cm, 0, buf->col);
1548       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1549                           &tile_data->bit_reader, pbi->decrypt_cb,
1550                           pbi->decrypt_state);
1551       vp9_init_macroblockd(cm, &tile_data->xd);
1552
1553       worker->had_error = 0;
1554       if (i == num_workers - 1 || n == tile_cols - 1) {
1555         winterface->execute(worker);
1556       } else {
1557         winterface->launch(worker);
1558       }
1559
1560       if (buf->col == tile_cols - 1) {
1561         final_worker = i;
1562       }
1563
1564       ++n;
1565     }
1566
1567     for (; i > 0; --i) {
1568       VPxWorker *const worker = &pbi->tile_workers[i - 1];
1569       // TODO(jzern): The tile may have specific error data associated with
1570       // its vpx_internal_error_info which could be propagated to the main info
1571       // in cm. Additionally once the threads have been synced and an error is
1572       // detected, there's no point in continuing to decode tiles.
1573       pbi->mb.corrupted |= !winterface->sync(worker);
1574     }
1575     if (final_worker > -1) {
1576       TileWorkerData *const tile_data =
1577           (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1578       bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1579       final_worker = -1;
1580     }
1581
1582     // Accumulate thread frame counts.
1583     if (n >= tile_cols && !cm->frame_parallel_decoding_mode) {
1584       for (i = 0; i < num_workers; ++i) {
1585         TileWorkerData *const tile_data =
1586             (TileWorkerData*)pbi->tile_workers[i].data1;
1587         vp9_accumulate_frame_counts(cm, &tile_data->counts, 1);
1588       }
1589     }
1590   }
1591
1592   return bit_reader_end;
1593 }
1594
1595 static void error_handler(void *data) {
1596   VP9_COMMON *const cm = (VP9_COMMON *)data;
1597   vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1598 }
1599
1600 static void read_bitdepth_colorspace_sampling(
1601     VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1602   if (cm->profile >= PROFILE_2) {
1603     cm->bit_depth = vp9_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1604 #if CONFIG_VP9_HIGHBITDEPTH
1605     cm->use_highbitdepth = 1;
1606 #endif
1607   } else {
1608     cm->bit_depth = VPX_BITS_8;
1609 #if CONFIG_VP9_HIGHBITDEPTH
1610     cm->use_highbitdepth = 0;
1611 #endif
1612   }
1613   cm->color_space = vp9_rb_read_literal(rb, 3);
1614   if (cm->color_space != VPX_CS_SRGB) {
1615     vp9_rb_read_bit(rb);  // [16,235] (including xvycc) vs [0,255] range
1616     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1617       cm->subsampling_x = vp9_rb_read_bit(rb);
1618       cm->subsampling_y = vp9_rb_read_bit(rb);
1619       if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1620         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1621                            "4:2:0 color not supported in profile 1 or 3");
1622       if (vp9_rb_read_bit(rb))
1623         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1624                            "Reserved bit set");
1625     } else {
1626       cm->subsampling_y = cm->subsampling_x = 1;
1627     }
1628   } else {
1629     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1630       // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1631       // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1632       cm->subsampling_y = cm->subsampling_x = 0;
1633       if (vp9_rb_read_bit(rb))
1634         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1635                            "Reserved bit set");
1636     } else {
1637       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1638                          "4:4:4 color not supported in profile 0 or 2");
1639     }
1640   }
1641 }
1642
1643 static size_t read_uncompressed_header(VP9Decoder *pbi,
1644                                        struct vp9_read_bit_buffer *rb) {
1645   VP9_COMMON *const cm = &pbi->common;
1646   BufferPool *const pool = cm->buffer_pool;
1647   RefCntBuffer *const frame_bufs = pool->frame_bufs;
1648   int i, mask, ref_index = 0;
1649   size_t sz;
1650
1651   cm->last_frame_type = cm->frame_type;
1652   cm->last_intra_only = cm->intra_only;
1653
1654   if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1655       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1656                          "Invalid frame marker");
1657
1658   cm->profile = vp9_read_profile(rb);
1659
1660   if (cm->profile >= MAX_PROFILES)
1661     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1662                        "Unsupported bitstream profile");
1663
1664   cm->show_existing_frame = vp9_rb_read_bit(rb);
1665   if (cm->show_existing_frame) {
1666     // Show an existing frame directly.
1667     const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1668     lock_buffer_pool(pool);
1669     if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1670       unlock_buffer_pool(pool);
1671       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1672                          "Buffer %d does not contain a decoded frame",
1673                          frame_to_show);
1674     }
1675
1676     ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1677     unlock_buffer_pool(pool);
1678     pbi->refresh_frame_flags = 0;
1679     cm->lf.filter_level = 0;
1680     cm->show_frame = 1;
1681
1682     if (pbi->frame_parallel_decode) {
1683       for (i = 0; i < REF_FRAMES; ++i)
1684         cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1685     }
1686     return 0;
1687   }
1688
1689   cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1690   cm->show_frame = vp9_rb_read_bit(rb);
1691   cm->error_resilient_mode = vp9_rb_read_bit(rb);
1692
1693   if (cm->frame_type == KEY_FRAME) {
1694     if (!vp9_read_sync_code(rb))
1695       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1696                          "Invalid frame sync code");
1697
1698     read_bitdepth_colorspace_sampling(cm, rb);
1699     pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1700
1701     for (i = 0; i < REFS_PER_FRAME; ++i) {
1702       cm->frame_refs[i].idx = INVALID_IDX;
1703       cm->frame_refs[i].buf = NULL;
1704     }
1705
1706     setup_frame_size(cm, rb);
1707     if (pbi->need_resync) {
1708       memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1709       pbi->need_resync = 0;
1710     }
1711   } else {
1712     cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1713
1714     cm->reset_frame_context = cm->error_resilient_mode ?
1715         0 : vp9_rb_read_literal(rb, 2);
1716
1717     if (cm->intra_only) {
1718       if (!vp9_read_sync_code(rb))
1719         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1720                            "Invalid frame sync code");
1721       if (cm->profile > PROFILE_0) {
1722         read_bitdepth_colorspace_sampling(cm, rb);
1723       } else {
1724         // NOTE: The intra-only frame header does not include the specification
1725         // of either the color format or color sub-sampling in profile 0. VP9
1726         // specifies that the default color format should be YUV 4:2:0 in this
1727         // case (normative).
1728         cm->color_space = VPX_CS_BT_601;
1729         cm->subsampling_y = cm->subsampling_x = 1;
1730         cm->bit_depth = VPX_BITS_8;
1731 #if CONFIG_VP9_HIGHBITDEPTH
1732         cm->use_highbitdepth = 0;
1733 #endif
1734       }
1735
1736       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1737       setup_frame_size(cm, rb);
1738       if (pbi->need_resync) {
1739         memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1740         pbi->need_resync = 0;
1741       }
1742     } else if (pbi->need_resync != 1) {  /* Skip if need resync */
1743       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1744       for (i = 0; i < REFS_PER_FRAME; ++i) {
1745         const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1746         const int idx = cm->ref_frame_map[ref];
1747         RefBuffer *const ref_frame = &cm->frame_refs[i];
1748         ref_frame->idx = idx;
1749         ref_frame->buf = &frame_bufs[idx].buf;
1750         cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1751       }
1752
1753       setup_frame_size_with_refs(cm, rb);
1754
1755       cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1756       cm->interp_filter = read_interp_filter(rb);
1757
1758       for (i = 0; i < REFS_PER_FRAME; ++i) {
1759         RefBuffer *const ref_buf = &cm->frame_refs[i];
1760 #if CONFIG_VP9_HIGHBITDEPTH
1761         vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1762                                           ref_buf->buf->y_crop_width,
1763                                           ref_buf->buf->y_crop_height,
1764                                           cm->width, cm->height,
1765                                           cm->use_highbitdepth);
1766 #else
1767         vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1768                                           ref_buf->buf->y_crop_width,
1769                                           ref_buf->buf->y_crop_height,
1770                                           cm->width, cm->height);
1771 #endif
1772       }
1773     }
1774   }
1775 #if CONFIG_VP9_HIGHBITDEPTH
1776   get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1777 #endif
1778   get_frame_new_buffer(cm)->color_space = cm->color_space;
1779
1780   if (pbi->need_resync) {
1781     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1782                        "Keyframe / intra-only frame required to reset decoder"
1783                        " state");
1784   }
1785
1786   if (!cm->error_resilient_mode) {
1787     cm->refresh_frame_context = vp9_rb_read_bit(rb);
1788     cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
1789   } else {
1790     cm->refresh_frame_context = 0;
1791     cm->frame_parallel_decoding_mode = 1;
1792   }
1793
1794   // This flag will be overridden by the call to vp9_setup_past_independence
1795   // below, forcing the use of context 0 for those frame types.
1796   cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1797
1798   // Generate next_ref_frame_map.
1799   lock_buffer_pool(pool);
1800   for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
1801     if (mask & 1) {
1802       cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
1803       ++frame_bufs[cm->new_fb_idx].ref_count;
1804     } else {
1805       cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1806     }
1807     // Current thread holds the reference frame.
1808     if (cm->ref_frame_map[ref_index] >= 0)
1809       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1810     ++ref_index;
1811   }
1812
1813   for (; ref_index < REF_FRAMES; ++ref_index) {
1814     cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1815     // Current thread holds the reference frame.
1816     if (cm->ref_frame_map[ref_index] >= 0)
1817       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1818   }
1819   unlock_buffer_pool(pool);
1820   pbi->hold_ref_buf = 1;
1821
1822   if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1823     vp9_setup_past_independence(cm);
1824
1825   setup_loopfilter(&cm->lf, rb);
1826   setup_quantization(cm, &pbi->mb, rb);
1827   setup_segmentation(&cm->seg, rb);
1828   setup_segmentation_dequant(cm);
1829
1830   setup_tile_info(cm, rb);
1831   sz = vp9_rb_read_literal(rb, 16);
1832
1833   if (sz == 0)
1834     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1835                        "Invalid header size");
1836
1837   return sz;
1838 }
1839
1840 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
1841                                   size_t partition_size) {
1842   VP9_COMMON *const cm = &pbi->common;
1843   MACROBLOCKD *const xd = &pbi->mb;
1844   FRAME_CONTEXT *const fc = cm->fc;
1845   vp9_reader r;
1846   int k;
1847
1848   if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
1849                       pbi->decrypt_state))
1850     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1851                        "Failed to allocate bool decoder 0");
1852
1853   cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1854   if (cm->tx_mode == TX_MODE_SELECT)
1855     read_tx_mode_probs(&fc->tx_probs, &r);
1856   read_coef_probs(fc, cm->tx_mode, &r);
1857
1858   for (k = 0; k < SKIP_CONTEXTS; ++k)
1859     vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1860
1861   if (!frame_is_intra_only(cm)) {
1862     nmv_context *const nmvc = &fc->nmvc;
1863     int i, j;
1864
1865     read_inter_mode_probs(fc, &r);
1866
1867     if (cm->interp_filter == SWITCHABLE)
1868       read_switchable_interp_probs(fc, &r);
1869
1870     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1871       vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1872
1873     cm->reference_mode = read_frame_reference_mode(cm, &r);
1874     if (cm->reference_mode != SINGLE_REFERENCE)
1875       setup_compound_reference_mode(cm);
1876     read_frame_reference_mode_probs(cm, &r);
1877
1878     for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1879       for (i = 0; i < INTRA_MODES - 1; ++i)
1880         vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1881
1882     for (j = 0; j < PARTITION_CONTEXTS; ++j)
1883       for (i = 0; i < PARTITION_TYPES - 1; ++i)
1884         vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1885
1886     read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
1887   }
1888
1889   return vp9_reader_has_error(&r);
1890 }
1891
1892 #ifdef NDEBUG
1893 #define debug_check_frame_counts(cm) (void)0
1894 #else  // !NDEBUG
1895 // Counts should only be incremented when frame_parallel_decoding_mode and
1896 // error_resilient_mode are disabled.
1897 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
1898   FRAME_COUNTS zero_counts;
1899   vp9_zero(zero_counts);
1900   assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
1901   assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
1902                  sizeof(cm->counts.y_mode)));
1903   assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
1904                  sizeof(cm->counts.uv_mode)));
1905   assert(!memcmp(cm->counts.partition, zero_counts.partition,
1906                  sizeof(cm->counts.partition)));
1907   assert(!memcmp(cm->counts.coef, zero_counts.coef,
1908                  sizeof(cm->counts.coef)));
1909   assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
1910                  sizeof(cm->counts.eob_branch)));
1911   assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
1912                  sizeof(cm->counts.switchable_interp)));
1913   assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
1914                  sizeof(cm->counts.inter_mode)));
1915   assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
1916                  sizeof(cm->counts.intra_inter)));
1917   assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
1918                  sizeof(cm->counts.comp_inter)));
1919   assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
1920                  sizeof(cm->counts.single_ref)));
1921   assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
1922                  sizeof(cm->counts.comp_ref)));
1923   assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
1924   assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
1925   assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
1926 }
1927 #endif  // NDEBUG
1928
1929 static struct vp9_read_bit_buffer *init_read_bit_buffer(
1930     VP9Decoder *pbi,
1931     struct vp9_read_bit_buffer *rb,
1932     const uint8_t *data,
1933     const uint8_t *data_end,
1934     uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
1935   rb->bit_offset = 0;
1936   rb->error_handler = error_handler;
1937   rb->error_handler_data = &pbi->common;
1938   if (pbi->decrypt_cb) {
1939     const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
1940     pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
1941     rb->bit_buffer = clear_data;
1942     rb->bit_buffer_end = clear_data + n;
1943   } else {
1944     rb->bit_buffer = data;
1945     rb->bit_buffer_end = data_end;
1946   }
1947   return rb;
1948 }
1949
1950 //------------------------------------------------------------------------------
1951
1952 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
1953   return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
1954          vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
1955          vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
1956 }
1957
1958 void vp9_read_frame_size(struct vp9_read_bit_buffer *rb,
1959                          int *width, int *height) {
1960   *width = vp9_rb_read_literal(rb, 16) + 1;
1961   *height = vp9_rb_read_literal(rb, 16) + 1;
1962 }
1963
1964 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
1965   int profile = vp9_rb_read_bit(rb);
1966   profile |= vp9_rb_read_bit(rb) << 1;
1967   if (profile > 2)
1968     profile += vp9_rb_read_bit(rb);
1969   return (BITSTREAM_PROFILE) profile;
1970 }
1971
1972 void vp9_decode_frame(VP9Decoder *pbi,
1973                       const uint8_t *data, const uint8_t *data_end,
1974                       const uint8_t **p_data_end) {
1975   VP9_COMMON *const cm = &pbi->common;
1976   MACROBLOCKD *const xd = &pbi->mb;
1977   struct vp9_read_bit_buffer rb;
1978   int context_updated = 0;
1979   uint8_t clear_data[MAX_VP9_HEADER_SIZE];
1980   const size_t first_partition_size = read_uncompressed_header(pbi,
1981       init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
1982   const int tile_rows = 1 << cm->log2_tile_rows;
1983   const int tile_cols = 1 << cm->log2_tile_cols;
1984   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
1985   xd->cur_buf = new_fb;
1986
1987   if (!first_partition_size) {
1988     // showing a frame directly
1989     *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
1990     return;
1991   }
1992
1993   data += vp9_rb_bytes_read(&rb);
1994   if (!read_is_valid(data, first_partition_size, data_end))
1995     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1996                        "Truncated packet or corrupt header length");
1997
1998   cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
1999                            cm->width == cm->last_width &&
2000                            cm->height == cm->last_height &&
2001                            !cm->last_intra_only &&
2002                            cm->last_show_frame &&
2003                            (cm->last_frame_type != KEY_FRAME);
2004
2005   vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2006
2007   *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2008   if (!cm->fc->initialized)
2009     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2010                        "Uninitialized entropy context.");
2011
2012   vp9_zero(cm->counts);
2013
2014   xd->corrupted = 0;
2015   new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2016   if (new_fb->corrupted)
2017     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2018                        "Decode failed. Frame data header is corrupted.");
2019
2020   if (cm->lf.filter_level && !cm->skip_loop_filter) {
2021     vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2022   }
2023
2024   // If encoded in frame parallel mode, frame context is ready after decoding
2025   // the frame header.
2026   if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2027     VPxWorker *const worker = pbi->frame_worker_owner;
2028     FrameWorkerData *const frame_worker_data = worker->data1;
2029     if (cm->refresh_frame_context) {
2030       context_updated = 1;
2031       cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2032     }
2033     vp9_frameworker_lock_stats(worker);
2034     pbi->cur_buf->row = -1;
2035     pbi->cur_buf->col = -1;
2036     frame_worker_data->frame_context_ready = 1;
2037     // Signal the main thread that context is ready.
2038     vp9_frameworker_signal_stats(worker);
2039     vp9_frameworker_unlock_stats(worker);
2040   }
2041
2042   if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2043     // Multi-threaded tile decoder
2044     *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2045     if (!xd->corrupted) {
2046       if (!cm->skip_loop_filter) {
2047         // If multiple threads are used to decode tiles, then we use those
2048         // threads to do parallel loopfiltering.
2049         vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane,
2050                                  cm->lf.filter_level, 0, 0, pbi->tile_workers,
2051                                  pbi->num_tile_workers, &pbi->lf_row_sync);
2052       }
2053     } else {
2054       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2055                          "Decode failed. Frame data is corrupted.");
2056
2057     }
2058   } else {
2059     *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2060   }
2061
2062   if (!xd->corrupted) {
2063     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2064       vp9_adapt_coef_probs(cm);
2065
2066       if (!frame_is_intra_only(cm)) {
2067         vp9_adapt_mode_probs(cm);
2068         vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2069       }
2070     } else {
2071       debug_check_frame_counts(cm);
2072     }
2073   } else {
2074     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2075                        "Decode failed. Frame data is corrupted.");
2076   }
2077
2078   // Non frame parallel update frame context here.
2079   if (cm->refresh_frame_context && !context_updated)
2080     cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2081 }