vp9_decodframe.c 32.5 KB
Newer Older
John Koleszar's avatar
John Koleszar committed
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
John Koleszar's avatar
John Koleszar committed
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5 6
 *  that can be found in the LICENSE file in the root of the source
 *  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.
John Koleszar's avatar
John Koleszar committed
9 10
 */

11
#include <assert.h>
John Koleszar's avatar
John Koleszar committed
12

13 14 15 16
#include "./vp9_rtcd.h"
#include "vpx_mem/vpx_mem.h"
#include "vpx_scale/vpx_scale.h"

Dmitry Kovalev's avatar
Dmitry Kovalev committed
17
#include "vp9/common/vp9_alloccommon.h"
Ronald S. Bultje's avatar
Ronald S. Bultje committed
18
#include "vp9/common/vp9_common.h"
Yaowu Xu's avatar
Yaowu Xu committed
19
#include "vp9/common/vp9_entropy.h"
20
#include "vp9/common/vp9_entropymode.h"
Dmitry Kovalev's avatar
Dmitry Kovalev committed
21 22
#include "vp9/common/vp9_extend.h"
#include "vp9/common/vp9_pred_common.h"
23
#include "vp9/common/vp9_quant_common.h"
Dmitry Kovalev's avatar
Dmitry Kovalev committed
24 25
#include "vp9/common/vp9_reconintra.h"
#include "vp9/common/vp9_reconinter.h"
26 27
#include "vp9/common/vp9_seg_common.h"
#include "vp9/common/vp9_tile_common.h"
28 29

#include "vp9/decoder/vp9_dboolhuff.h"
30 31 32
#include "vp9/decoder/vp9_decodframe.h"
#include "vp9/decoder/vp9_detokenize.h"
#include "vp9/decoder/vp9_decodemv.h"
33
#include "vp9/decoder/vp9_dsubexp.h"
Dmitry Kovalev's avatar
Dmitry Kovalev committed
34
#include "vp9/decoder/vp9_idct_blk.h"
35 36
#include "vp9/decoder/vp9_onyxd_int.h"
#include "vp9/decoder/vp9_read_bit_buffer.h"
Dmitry Kovalev's avatar
Dmitry Kovalev committed
37
#include "vp9/decoder/vp9_treereader.h"
38

39 40
static int read_be32(const uint8_t *p) {
  return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
41 42 43
}

// len == 0 is not allowed
44
static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
45 46 47
  return start + len > start && start + len <= end;
}

48 49 50 51 52
static int decode_unsigned_max(struct vp9_read_bit_buffer *rb, int max) {
  const int data = vp9_rb_read_literal(rb, get_unsigned_bits(max));
  return data > max ? max : data;
}

53 54 55 56 57
static TX_MODE read_tx_mode(vp9_reader *r) {
  TX_MODE tx_mode = vp9_read_literal(r, 2);
  if (tx_mode == ALLOW_32X32)
    tx_mode += vp9_read_bit(r);
  return tx_mode;
58 59
}

60
static void read_tx_probs(struct tx_probs *tx_probs, vp9_reader *r) {
61 62 63
  int i, j;

  for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
64
    for (j = 0; j < TX_SIZES - 3; ++j)
65
      if (vp9_read(r, VP9_MODE_UPDATE_PROB))
66
        vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
67 68

  for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
69
    for (j = 0; j < TX_SIZES - 2; ++j)
70
      if (vp9_read(r, VP9_MODE_UPDATE_PROB))
71
        vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
72 73

  for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
74
    for (j = 0; j < TX_SIZES - 1; ++j)
75
      if (vp9_read(r, VP9_MODE_UPDATE_PROB))
76
        vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
John Koleszar's avatar
John Koleszar committed
77 78
}

79
static void init_dequantizer(VP9_COMMON *cm, MACROBLOCKD *xd) {
John Koleszar's avatar
John Koleszar committed
80
  int i;
81
  const int segment_id = xd->mode_info_context->mbmi.segment_id;
82
  xd->q_index = vp9_get_qindex(xd, segment_id, cm->base_qindex);
John Koleszar's avatar
John Koleszar committed
83

84
  xd->plane[0].dequant = cm->y_dequant[xd->q_index];
85
  for (i = 1; i < MAX_MB_PLANE; i++)
86
    xd->plane[i].dequant = cm->uv_dequant[xd->q_index];
John Koleszar's avatar
John Koleszar committed
87 88
}

89 90 91
static void decode_block(int plane, int block, BLOCK_SIZE_TYPE bsize,
                         int ss_txfrm_size, void *arg) {
  MACROBLOCKD* const xd = arg;
92 93 94
  struct macroblockd_plane *pd = &xd->plane[plane];
  int16_t* const qcoeff = BLOCK_OFFSET(pd->qcoeff, block, 16);
  const int stride = pd->dst.stride;
95
  const int eob = pd->eobs[block];
96 97 98 99
  const int raster_block = txfrm_block_to_raster_block(xd, bsize, plane,
                                                       block, ss_txfrm_size);
  uint8_t* const dst = raster_block_offset_uint8(xd, bsize, plane,
                                                 raster_block,
100
                                                 pd->dst.buf, stride);
101

102
  switch (ss_txfrm_size / 2) {
103 104
    case TX_4X4: {
      const TX_TYPE tx_type = get_tx_type_4x4(pd->plane_type, xd, raster_block);
105
      if (tx_type == DCT_DCT)
106
        xd->itxm_add(qcoeff, dst, stride, eob);
107
      else
108
        vp9_iht_add_c(tx_type, qcoeff, dst, stride, eob);
109
      break;
110
    }
111
    case TX_8X8:
112 113
      vp9_iht_add_8x8_c(get_tx_type_8x8(pd->plane_type, xd), qcoeff, dst,
                        stride, eob);
114 115
      break;
    case TX_16X16:
116 117
      vp9_iht_add_16x16_c(get_tx_type_16x16(pd->plane_type, xd), qcoeff, dst,
                          stride, eob);
118 119
      break;
    case TX_32X32:
120
      vp9_idct_add_32x32(qcoeff, dst, stride, eob);
121
      break;
122 123 124
  }
}

125 126 127
static void decode_block_intra(int plane, int block, BLOCK_SIZE_TYPE bsize,
                               int ss_txfrm_size, void *arg) {
  MACROBLOCKD* const xd = arg;
128
  struct macroblockd_plane *pd = &xd->plane[plane];
Dmitry Kovalev's avatar
Dmitry Kovalev committed
129
  MODE_INFO *const mi = xd->mode_info_context;
130

131 132 133 134
  const int raster_block = txfrm_block_to_raster_block(xd, bsize, plane,
                                                       block, ss_txfrm_size);
  uint8_t* const dst = raster_block_offset_uint8(xd, bsize, plane,
                                                 raster_block,
135
                                                 pd->dst.buf, pd->dst.stride);
136
  const TX_SIZE tx_size = (TX_SIZE)(ss_txfrm_size / 2);
137
  int b_mode;
138
  int plane_b_size;
139
  const int tx_ib = raster_block >> tx_size;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
140 141
  const int mode = plane == 0 ? mi->mbmi.mode
                              : mi->mbmi.uv_mode;
142

Dmitry Kovalev's avatar
Dmitry Kovalev committed
143
  if (plane == 0 && mi->mbmi.sb_type < BLOCK_SIZE_SB8X8) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
144
    assert(bsize == BLOCK_SIZE_SB8X8);
145
    b_mode = mi->bmi[raster_block].as_mode;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
146
  } else {
147
    b_mode = mode;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
148
  }
149

150
  if (xd->mb_to_right_edge < 0 || xd->mb_to_bottom_edge < 0)
151 152
    extend_for_intra(xd, plane, block, bsize, ss_txfrm_size);

153 154
  plane_b_size = b_width_log2(bsize) - pd->subsampling_x;
  vp9_predict_intra_block(xd, tx_ib, plane_b_size, tx_size, b_mode,
155
                          dst, pd->dst.stride,
156
                          dst, pd->dst.stride);
157

158
  // Early exit if there are no coefficients
Dmitry Kovalev's avatar
Dmitry Kovalev committed
159
  if (mi->mbmi.mb_skip_coeff)
160 161
    return;

162
  decode_block(plane, block, bsize, ss_txfrm_size, arg);
163 164
}

Dmitry Kovalev's avatar
Dmitry Kovalev committed
165 166
static int decode_tokens(VP9D_COMP *pbi, BLOCK_SIZE_TYPE bsize, vp9_reader *r) {
  MACROBLOCKD *const xd = &pbi->mb;
167

Dmitry Kovalev's avatar
Dmitry Kovalev committed
168
  if (xd->mode_info_context->mbmi.mb_skip_coeff) {
169
    vp9_reset_sb_tokens_context(xd, bsize);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
170
    return -1;
171
  } else {
172
    if (xd->seg.enabled)
173
      init_dequantizer(&pbi->common, xd);
174

Dmitry Kovalev's avatar
Dmitry Kovalev committed
175 176
    // TODO(dkovalev) if (!vp9_reader_has_error(r))
    return vp9_decode_tokens(pbi, r, bsize);
177 178 179
  }
}

180
static void set_offsets(VP9D_COMP *pbi, BLOCK_SIZE_TYPE bsize,
181
                        int mi_row, int mi_col) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
182 183
  VP9_COMMON *const cm = &pbi->common;
  MACROBLOCKD *const xd = &pbi->mb;
184 185
  const int bh = 1 << mi_height_log2(bsize);
  const int bw = 1 << mi_width_log2(bsize);
186
  const int mi_idx = mi_row * cm->mode_info_stride + mi_col;
187
  int i;
188

189
  xd->mode_info_context = cm->mi + mi_idx;
190
  xd->mode_info_context->mbmi.sb_type = bsize;
191 192
  // Special case: if prev_mi is NULL, the previous mode info context
  // cannot be used.
193
  xd->prev_mode_info_context = cm->prev_mi ? cm->prev_mi + mi_idx : NULL;
194

195
  for (i = 0; i < MAX_MB_PLANE; i++) {
196 197 198 199 200
    struct macroblockd_plane *pd = &xd->plane[i];
    pd->above_context = cm->above_context[i] +
                            (mi_col * 2 >> pd->subsampling_x);
    pd->left_context = cm->left_context[i] +
                           (((mi_row * 2) & 15) >> pd->subsampling_y);
201
  }
202 203

  set_partition_seg_context(cm, xd, mi_row, mi_col);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
204

205 206
  // Distance of Mb to the various image edges. These are specified to 8th pel
  // as they are always compared to values that are in 1/8th pel units
207
  set_mi_row_col(cm, xd, mi_row, bh, mi_col, bw);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
208

209
  setup_dst_planes(xd, &cm->yv12_fb[cm->new_fb_idx], mi_row, mi_col);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
210
}
John Koleszar's avatar
John Koleszar committed
211

212
static void set_ref(VP9D_COMP *pbi, int i, int mi_row, int mi_col) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
213 214
  VP9_COMMON *const cm = &pbi->common;
  MACROBLOCKD *const xd = &pbi->mb;
215
  MB_MODE_INFO *const mbmi = &xd->mode_info_context->mbmi;
216
  const int ref = mbmi->ref_frame[i] - 1;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
217

218 219
  const YV12_BUFFER_CONFIG *cfg = &cm->yv12_fb[cm->active_ref_idx[ref]];
  xd->scale_factor[i] = cm->active_ref_scale[ref];
220
  setup_pre_planes(xd, i, cfg, mi_row, mi_col, &xd->scale_factor[i]);
221
  xd->corrupted |= cfg->corrupted;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
222
}
John Koleszar's avatar
John Koleszar committed
223

224
static void decode_modes_b(VP9D_COMP *pbi, int mi_row, int mi_col,
225
                           vp9_reader *r, BLOCK_SIZE_TYPE bsize) {
226
  VP9_COMMON *const cm = &pbi->common;
227
  MACROBLOCKD *const xd = &pbi->mb;
228 229
  const int less8x8 = bsize < BLOCK_SIZE_SB8X8;
  MB_MODE_INFO *mbmi;
230

231
  if (less8x8)
232 233
    if (xd->ab_index > 0)
      return;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
234

235
  set_offsets(pbi, bsize, mi_row, mi_col);
236
  vp9_read_mode_info(pbi, mi_row, mi_col, r);
237

238 239 240 241 242 243
  if (less8x8)
    bsize = BLOCK_SIZE_SB8X8;

  // Has to be called after set_offsets
  mbmi = &xd->mode_info_context->mbmi;

244
  if (!is_inter_block(mbmi)) {
245 246 247
    // Intra reconstruction
    decode_tokens(pbi, bsize, r);
    foreach_transformed_block(xd, bsize, decode_block_intra, xd);
248
  } else {
249 250
    // Inter reconstruction
    int eobtotal;
251 252 253 254 255

    set_ref(pbi, 0, mi_row, mi_col);
    if (mbmi->ref_frame[1] > INTRA_FRAME)
      set_ref(pbi, 1, mi_row, mi_col);

256 257 258 259 260 261 262 263 264
    vp9_setup_interp_filters(xd, mbmi->interp_filter, cm);
    vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
    eobtotal = decode_tokens(pbi, bsize, r);
    if (less8x8) {
      if (eobtotal >= 0)
        foreach_transformed_block(xd, bsize, decode_block, xd);
    } else {
      assert(mbmi->sb_type == bsize);
      if (eobtotal == 0)
265 266
        // skip loopfilter
        vp9_set_pred_flag_mbskip(cm, bsize, mi_row, mi_col, 1);
267 268 269
      else if (eobtotal > 0)
        foreach_transformed_block(xd, bsize, decode_block, xd);
    }
270
  }
271
  xd->corrupted |= vp9_reader_has_error(r);
272 273
}

274
static void decode_modes_sb(VP9D_COMP *pbi, int mi_row, int mi_col,
275
                            vp9_reader* r, BLOCK_SIZE_TYPE bsize) {
276 277
  VP9_COMMON *const pc = &pbi->common;
  MACROBLOCKD *const xd = &pbi->mb;
278
  int bs = (1 << mi_width_log2(bsize)) / 2, n;
279 280 281
  PARTITION_TYPE partition = PARTITION_NONE;
  BLOCK_SIZE_TYPE subsize;

282
  if (mi_row >= pc->mi_rows || mi_col >= pc->mi_cols)
283 284
    return;

285
  if (bsize < BLOCK_SIZE_SB8X8) {
286 287
    if (xd->ab_index != 0)
      return;
288
  } else {
289
    int pl;
290
    const int idx = check_bsize_coverage(pc, mi_row, mi_col, bsize);
291
    set_partition_seg_context(pc, xd, mi_row, mi_col);
292
    pl = partition_plane_context(xd, bsize);
293 294 295 296 297 298 299 300 301 302

    if (idx == 0)
      partition = treed_read(r, vp9_partition_tree,
                             pc->fc.partition_prob[pc->frame_type][pl]);
    else if (idx > 0 &&
        !vp9_read(r, pc->fc.partition_prob[pc->frame_type][pl][idx]))
      partition = (idx == 1) ? PARTITION_HORZ : PARTITION_VERT;
    else
      partition = PARTITION_SPLIT;

303
    pc->counts.partition[pl][partition]++;
304 305
  }

306
  subsize = get_subsize(bsize, partition);
307
  *(get_sb_index(xd, subsize)) = 0;
308

309 310
  switch (partition) {
    case PARTITION_NONE:
311
      decode_modes_b(pbi, mi_row, mi_col, r, subsize);
312 313
      break;
    case PARTITION_HORZ:
314
      decode_modes_b(pbi, mi_row, mi_col, r, subsize);
315
      *(get_sb_index(xd, subsize)) = 1;
316
      if (mi_row + bs < pc->mi_rows)
317
        decode_modes_b(pbi, mi_row + bs, mi_col, r, subsize);
318 319
      break;
    case PARTITION_VERT:
320
      decode_modes_b(pbi, mi_row, mi_col, r, subsize);
321
      *(get_sb_index(xd, subsize)) = 1;
322
      if (mi_col + bs < pc->mi_cols)
323
        decode_modes_b(pbi, mi_row, mi_col + bs, r, subsize);
324 325 326 327
      break;
    case PARTITION_SPLIT:
      for (n = 0; n < 4; n++) {
        int j = n >> 1, i = n & 0x01;
328
        *(get_sb_index(xd, subsize)) = n;
329
        decode_modes_sb(pbi, mi_row + j * bs, mi_col + i * bs, r, subsize);
330 331 332
      }
      break;
    default:
333
      assert(!"Invalid partition type");
334
  }
335

336
  // update partition context
337 338
  if (bsize >= BLOCK_SIZE_SB8X8 &&
      (bsize == BLOCK_SIZE_SB8X8 || partition != PARTITION_SPLIT)) {
339 340 341
    set_partition_seg_context(pc, xd, mi_row, mi_col);
    update_partition_context(xd, subsize, bsize);
  }
342 343
}

344
static void setup_token_decoder(VP9D_COMP *pbi,
345
                                const uint8_t *data, size_t read_size,
346
                                vp9_reader *r) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
347
  VP9_COMMON *pc = &pbi->common;
348
  const uint8_t *data_end = pbi->source + pbi->source_sz;
John Koleszar's avatar
John Koleszar committed
349

Dmitry Kovalev's avatar
Dmitry Kovalev committed
350 351 352
  // Validate the calculated partition length. If the buffer
  // described by the partition can't be fully read, then restrict
  // it to the portion that can be (for EC mode) or throw an error.
353
  if (!read_is_valid(data, read_size, data_end))
John Koleszar's avatar
John Koleszar committed
354
    vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
355
                       "Truncated packet or corrupt tile length");
John Koleszar's avatar
John Koleszar committed
356

357
  if (vp9_reader_init(r, data, read_size))
John Koleszar's avatar
John Koleszar committed
358 359
    vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
                       "Failed to allocate bool decoder %d", 1);
John Koleszar's avatar
John Koleszar committed
360 361
}

362
static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
363
                                   vp9_reader *r) {
364 365 366 367 368 369 370 371 372 373 374
  int i, j, k, l, m;

  if (vp9_read_bit(r))
    for (i = 0; i < BLOCK_TYPES; i++)
      for (j = 0; j < REF_TYPES; j++)
        for (k = 0; k < COEF_BANDS; k++)
          for (l = 0; l < PREV_COEF_CONTEXTS; l++)
            if (k > 0 || l < 3)
              for (m = 0; m < UNCONSTRAINED_NODES; m++)
                if (vp9_read(r, VP9_COEF_UPDATE_PROB))
                  vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
375
}
376

377
static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
378
                            vp9_reader *r) {
379
  read_coef_probs_common(fc->coef_probs[TX_4X4], r);
380

381
  if (tx_mode > ONLY_4X4)
382
    read_coef_probs_common(fc->coef_probs[TX_8X8], r);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
383

384
  if (tx_mode > ALLOW_8X8)
385
    read_coef_probs_common(fc->coef_probs[TX_16X16], r);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
386

387
  if (tx_mode > ALLOW_16X16)
388
    read_coef_probs_common(fc->coef_probs[TX_32X32], r);
389 390
}

391 392
static void setup_segmentation(struct segmentation *seg,
                               struct vp9_read_bit_buffer *rb) {
393 394
  int i, j;

395 396
  seg->update_map = 0;
  seg->update_data = 0;
397

398 399
  seg->enabled = vp9_rb_read_bit(rb);
  if (!seg->enabled)
400 401 402
    return;

  // Segmentation map update
403 404
  seg->update_map = vp9_rb_read_bit(rb);
  if (seg->update_map) {
Paul Wilkins's avatar
Paul Wilkins committed
405
    for (i = 0; i < SEG_TREE_PROBS; i++)
406 407
      seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
                                               : MAX_PROB;
408

409 410
    seg->temporal_update = vp9_rb_read_bit(rb);
    if (seg->temporal_update) {
411
      for (i = 0; i < PREDICTION_PROBS; i++)
412 413
        seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
                                                 : MAX_PROB;
414 415
    } else {
      for (i = 0; i < PREDICTION_PROBS; i++)
416
        seg->pred_probs[i] = MAX_PROB;
417
    }
418
  }
419

420
  // Segmentation data update
421 422 423
  seg->update_data = vp9_rb_read_bit(rb);
  if (seg->update_data) {
    seg->abs_delta = vp9_rb_read_bit(rb);
424

425
    vp9_clearall_segfeatures(seg);
426

Paul Wilkins's avatar
Paul Wilkins committed
427
    for (i = 0; i < MAX_SEGMENTS; i++) {
428 429
      for (j = 0; j < SEG_LVL_MAX; j++) {
        int data = 0;
430
        const int feature_enabled = vp9_rb_read_bit(rb);
431
        if (feature_enabled) {
432
          vp9_enable_segfeature(seg, i, j);
433
          data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
434
          if (vp9_is_segfeature_signed(j))
435
            data = vp9_rb_read_bit(rb) ? -data : data;
436
        }
437
        vp9_set_segdata(seg, i, j, data);
438 439 440 441 442
      }
    }
  }
}

443 444
static void setup_loopfilter(struct loopfilter *lf,
                             struct vp9_read_bit_buffer *rb) {
445

446 447
  lf->filter_level = vp9_rb_read_literal(rb, 6);
  lf->sharpness_level = vp9_rb_read_literal(rb, 3);
448 449 450

  // Read in loop filter deltas applied at the MB level based on mode or ref
  // frame.
451
  lf->mode_ref_delta_update = 0;
452

453 454 455 456
  lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
  if (lf->mode_ref_delta_enabled) {
    lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
    if (lf->mode_ref_delta_update) {
457 458
      int i;

459 460
      for (i = 0; i < MAX_REF_LF_DELTAS; i++)
        if (vp9_rb_read_bit(rb))
461
          lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
462

463 464
      for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
        if (vp9_rb_read_bit(rb))
465
          lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
466 467 468 469
    }
  }
}

470 471
static int read_delta_q(struct vp9_read_bit_buffer *rb, int *delta_q) {
  const int old = *delta_q;
472 473
  if (vp9_rb_read_bit(rb))
    *delta_q = vp9_rb_read_signed_literal(rb, 4);
474 475
  return old != *delta_q;
}
476

477
static void setup_quantization(VP9D_COMP *pbi, struct vp9_read_bit_buffer *rb) {
478
  MACROBLOCKD *const xd = &pbi->mb;
479 480
  VP9_COMMON *const cm = &pbi->common;
  int update = 0;
481

482 483 484 485 486 487
  cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
  update |= read_delta_q(rb, &cm->y_dc_delta_q);
  update |= read_delta_q(rb, &cm->uv_dc_delta_q);
  update |= read_delta_q(rb, &cm->uv_ac_delta_q);
  if (update)
    vp9_init_dequantizer(cm);
488 489 490 491 492

  xd->lossless = cm->base_qindex == 0 &&
                 cm->y_dc_delta_q == 0 &&
                 cm->uv_dc_delta_q == 0 &&
                 cm->uv_ac_delta_q == 0;
493 494 495

  xd->itxm_add = xd->lossless ? vp9_idct_add_lossless_c
                              : vp9_idct_add;
496 497
}

498 499 500 501
static INTERPOLATIONFILTERTYPE read_interp_filter_type(
    struct vp9_read_bit_buffer *rb) {
  return vp9_rb_read_bit(rb) ? SWITCHABLE
                             : vp9_rb_read_literal(rb, 2);
502 503
}

504
static void read_frame_size(struct vp9_read_bit_buffer *rb,
505
                            int *width, int *height) {
506 507
  const int w = vp9_rb_read_literal(rb, 16) + 1;
  const int h = vp9_rb_read_literal(rb, 16) + 1;
508 509
  *width = w;
  *height = h;
510 511
}

512
static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
513 514 515
  cm->display_width = cm->width;
  cm->display_height = cm->height;
  if (vp9_rb_read_bit(rb))
516
    read_frame_size(rb, &cm->display_width, &cm->display_height);
517
}
518

519 520
static void apply_frame_size(VP9D_COMP *pbi, int width, int height) {
  VP9_COMMON *cm = &pbi->common;
521

522
  if (cm->width != width || cm->height != height) {
523
    if (!pbi->initial_width || !pbi->initial_height) {
524 525
      if (vp9_alloc_frame_buffers(cm, width, height))
        vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
526
                           "Failed to allocate frame buffers");
527 528
      pbi->initial_width = width;
      pbi->initial_height = height;
529 530
    } else {
      if (width > pbi->initial_width)
531
        vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
532
                           "Frame width too large");
533

534
      if (height > pbi->initial_height)
535
        vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
536
                           "Frame height too large");
537 538
    }

539 540
    cm->width = width;
    cm->height = height;
541

542
    vp9_update_frame_size(cm);
543
  }
544

545 546
  vp9_realloc_frame_buffer(&cm->yv12_fb[cm->new_fb_idx], cm->width, cm->height,
                           cm->subsampling_x, cm->subsampling_y,
547
                           VP9BORDERINPIXELS);
548 549
}

550 551 552
static void setup_frame_size(VP9D_COMP *pbi,
                             struct vp9_read_bit_buffer *rb) {
  int width, height;
553 554
  read_frame_size(rb, &width, &height);
  setup_display_size(&pbi->common, rb);
555 556 557
  apply_frame_size(pbi, width, height);
}

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
static void setup_frame_size_with_refs(VP9D_COMP *pbi,
                                       struct vp9_read_bit_buffer *rb) {
  VP9_COMMON *const cm = &pbi->common;

  int width, height;
  int found = 0, i;
  for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i) {
    if (vp9_rb_read_bit(rb)) {
      YV12_BUFFER_CONFIG *cfg = &cm->yv12_fb[cm->active_ref_idx[i]];
      width = cfg->y_crop_width;
      height = cfg->y_crop_height;
      found = 1;
      break;
    }
  }

  if (!found)
575
    read_frame_size(rb, &width, &height);
576

577 578 579 580
  if (!width || !height)
    vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
                       "Referenced frame with invalid size");

581
  setup_display_size(cm, rb);
582 583 584
  apply_frame_size(pbi, width, height);
}

585 586
static void decode_tile(VP9D_COMP *pbi, vp9_reader *r) {
  VP9_COMMON *const pc = &pbi->common;
587
  int mi_row, mi_col;
588

589 590 591 592
  if (pbi->do_loopfilter_inline) {
    vp9_loop_filter_frame_init(pc, &pbi->mb, pbi->mb.lf.filter_level);
  }

593 594
  for (mi_row = pc->cur_tile_mi_row_start; mi_row < pc->cur_tile_mi_row_end;
       mi_row += MI_BLOCK_SIZE) {
595
    // For a SB there are 2 left contexts, each pertaining to a MB row within
596
    vpx_memset(&pc->left_context, 0, sizeof(pc->left_context));
597
    vpx_memset(pc->left_seg_context, 0, sizeof(pc->left_seg_context));
598
    for (mi_col = pc->cur_tile_mi_col_start; mi_col < pc->cur_tile_mi_col_end;
599
         mi_col += MI_BLOCK_SIZE) {
600
      decode_modes_sb(pbi, mi_row, mi_col, r, BLOCK_SIZE_SB64X64);
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    }

    if (pbi->do_loopfilter_inline) {
      YV12_BUFFER_CONFIG *const fb =
          &pbi->common.yv12_fb[pbi->common.new_fb_idx];
      // delay the loopfilter by 1 macroblock row.
      const int lf_start = mi_row - MI_BLOCK_SIZE;
      if (lf_start < 0) continue;
      vp9_loop_filter_rows(fb, pc, &pbi->mb, lf_start, mi_row, 0);
    }
  }

  if (pbi->do_loopfilter_inline) {
    YV12_BUFFER_CONFIG *const fb = &pbi->common.yv12_fb[pbi->common.new_fb_idx];
    vp9_loop_filter_rows(fb, pc, &pbi->mb,
                         mi_row - MI_BLOCK_SIZE, pc->mi_rows, 0);
617 618 619
  }
}

620
static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
621 622
  int min_log2_tile_cols, max_log2_tile_cols, max_ones;
  vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
623

Dmitry Kovalev's avatar
Dmitry Kovalev committed
624 625 626 627 628
  // columns
  max_ones = max_log2_tile_cols - min_log2_tile_cols;
  cm->log2_tile_cols = min_log2_tile_cols;
  while (max_ones-- && vp9_rb_read_bit(rb))
    cm->log2_tile_cols++;
629

Dmitry Kovalev's avatar
Dmitry Kovalev committed
630
  // rows
631 632 633 634 635
  cm->log2_tile_rows = vp9_rb_read_bit(rb);
  if (cm->log2_tile_rows)
    cm->log2_tile_rows += vp9_rb_read_bit(rb);
}

636 637 638
static const uint8_t *decode_tiles(VP9D_COMP *pbi, const uint8_t *data) {
  vp9_reader residual_bc;

639 640
  VP9_COMMON *const pc = &pbi->common;

641 642
  const uint8_t *const data_end = pbi->source + pbi->source_sz;
  const int aligned_mi_cols = mi_cols_aligned_to_sb(pc->mi_cols);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
643 644
  const int tile_cols = 1 << pc->log2_tile_cols;
  const int tile_rows = 1 << pc->log2_tile_rows;
645
  int tile_row, tile_col;
646

647 648
  // Note: this memset assumes above_context[0], [1] and [2]
  // are allocated as part of the same buffer.
649 650
  vpx_memset(pc->above_context[0], 0,
             sizeof(ENTROPY_CONTEXT) * 2 * MAX_MB_PLANE * aligned_mi_cols);
651

652 653
  vpx_memset(pc->above_seg_context, 0,
             sizeof(PARTITION_CONTEXT) * aligned_mi_cols);
654 655 656

  if (pbi->oxcf.inv_tile_order) {
    const uint8_t *data_ptr2[4][1 << 6];
657
    vp9_reader bc_bak = {0};
658 659

    // pre-initialize the offsets, we're going to read in inverse order
660
    data_ptr2[0][0] = data;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
661
    for (tile_row = 0; tile_row < tile_rows; tile_row++) {
662
      if (tile_row) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
663 664 665
        const int size = read_be32(data_ptr2[tile_row - 1][tile_cols - 1]);
        data_ptr2[tile_row - 1][tile_cols - 1] += 4;
        data_ptr2[tile_row][0] = data_ptr2[tile_row - 1][tile_cols - 1] + size;
666 667
      }

Dmitry Kovalev's avatar
Dmitry Kovalev committed
668
      for (tile_col = 1; tile_col < tile_cols; tile_col++) {
669
        const int size = read_be32(data_ptr2[tile_row][tile_col - 1]);
670 671 672 673 674 675
        data_ptr2[tile_row][tile_col - 1] += 4;
        data_ptr2[tile_row][tile_col] =
            data_ptr2[tile_row][tile_col - 1] + size;
      }
    }

Dmitry Kovalev's avatar
Dmitry Kovalev committed
676
    for (tile_row = 0; tile_row < tile_rows; tile_row++) {
677
      vp9_get_tile_row_offsets(pc, tile_row);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
678
      for (tile_col = tile_cols - 1; tile_col >= 0; tile_col--) {
679
        vp9_get_tile_col_offsets(pc, tile_col);
680 681
        setup_token_decoder(pbi, data_ptr2[tile_row][tile_col],
                            data_end - data_ptr2[tile_row][tile_col],
682 683
                            &residual_bc);
        decode_tile(pbi, &residual_bc);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
684
        if (tile_row == tile_rows - 1 && tile_col == tile_cols - 1)
685
          bc_bak = residual_bc;
686 687
      }
    }
688
    residual_bc = bc_bak;
689 690 691
  } else {
    int has_more;

Dmitry Kovalev's avatar
Dmitry Kovalev committed
692
    for (tile_row = 0; tile_row < tile_rows; tile_row++) {
693
      vp9_get_tile_row_offsets(pc, tile_row);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
694
      for (tile_col = 0; tile_col < tile_cols; tile_col++) {
695 696
        size_t size;

697 698
        vp9_get_tile_col_offsets(pc, tile_col);

Dmitry Kovalev's avatar
Dmitry Kovalev committed
699
        has_more = tile_col < tile_cols - 1 || tile_row < tile_rows - 1;
700
        if (has_more) {
701
          if (!read_is_valid(data, 4, data_end))
702 703 704
            vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
                         "Truncated packet or corrupt tile length");

705 706
          size = read_be32(data);
          data += 4;
707
        } else {
708
          size = data_end - data;
709
        }
710

711 712 713
        setup_token_decoder(pbi, data, size, &residual_bc);
        decode_tile(pbi, &residual_bc);
        data += size;
714 715 716
      }
    }
  }
717 718

  return vp9_reader_find_end(&residual_bc);
719 720
}

721 722 723 724 725 726 727 728
static void check_sync_code(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
  if (vp9_rb_read_literal(rb, 8) != SYNC_CODE_0 ||
      vp9_rb_read_literal(rb, 8) != SYNC_CODE_1 ||
      vp9_rb_read_literal(rb, 8) != SYNC_CODE_2) {
    vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
                       "Invalid frame sync code");
  }
}
John Koleszar's avatar
John Koleszar committed
729

Frank Galligan's avatar
Frank Galligan committed
730
static void error_handler(void *data, size_t bit_offset) {
731 732 733 734
  VP9_COMMON *const cm = (VP9_COMMON *)data;
  vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
}

735 736 737 738
static void setup_inter_inter(VP9_COMMON *cm) {
  int i;

  cm->allow_comp_inter_inter = 0;
739 740
  for (i = 1; i < ALLOWED_REFS_PER_FRAME; ++i)
    cm->allow_comp_inter_inter |=
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
        cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1];

  if (cm->allow_comp_inter_inter) {
    // which one is always-on in comp inter-inter?
    if (cm->ref_frame_sign_bias[LAST_FRAME] ==
        cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
      cm->comp_fixed_ref = ALTREF_FRAME;
      cm->comp_var_ref[0] = LAST_FRAME;
      cm->comp_var_ref[1] = GOLDEN_FRAME;
    } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
               cm->ref_frame_sign_bias[ALTREF_FRAME]) {
      cm->comp_fixed_ref = GOLDEN_FRAME;
      cm->comp_var_ref[0] = LAST_FRAME;
      cm->comp_var_ref[1] = ALTREF_FRAME;
    } else {
      cm->comp_fixed_ref = LAST_FRAME;
      cm->comp_var_ref[0] = GOLDEN_FRAME;
      cm->comp_var_ref[1] = ALTREF_FRAME;
    }
  }
}

763 764 765 766 767
#define RESERVED \
  if (vp9_rb_read_bit(rb)) \
      vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM, \
                         "Reserved bit must be unset")

768 769
static size_t read_uncompressed_header(VP9D_COMP *pbi,
                                       struct vp9_read_bit_buffer *rb) {
770
  VP9_COMMON *const cm = &pbi->common;
771
  MACROBLOCKD *const xd = &pbi->mb;
772
  int i;
773 774

  cm->last_frame_type = cm->frame_type;
775

776