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