Merge "vp9_reconinter.h static functions in header converted to global"
[platform/upstream/libvpx.git] / vp9 / decoder / vp9_decodeframe.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <assert.h>
12 #include <stdlib.h>  // qsort()
13
14 #include "./vp9_rtcd.h"
15 #include "./vpx_scale_rtcd.h"
16
17 #include "vpx_mem/vpx_mem.h"
18 #include "vpx_ports/mem_ops.h"
19 #include "vpx_scale/vpx_scale.h"
20
21 #include "vp9/common/vp9_alloccommon.h"
22 #include "vp9/common/vp9_common.h"
23 #include "vp9/common/vp9_entropy.h"
24 #include "vp9/common/vp9_entropymode.h"
25 #include "vp9/common/vp9_idct.h"
26 #include "vp9/common/vp9_pred_common.h"
27 #include "vp9/common/vp9_quant_common.h"
28 #include "vp9/common/vp9_reconintra.h"
29 #include "vp9/common/vp9_reconinter.h"
30 #include "vp9/common/vp9_seg_common.h"
31 #include "vp9/common/vp9_tile_common.h"
32
33 #include "vp9/decoder/vp9_decodeframe.h"
34 #include "vp9/decoder/vp9_detokenize.h"
35 #include "vp9/decoder/vp9_decodemv.h"
36 #include "vp9/decoder/vp9_dsubexp.h"
37 #include "vp9/decoder/vp9_dthread.h"
38 #include "vp9/decoder/vp9_onyxd.h"
39 #include "vp9/decoder/vp9_read_bit_buffer.h"
40 #include "vp9/decoder/vp9_reader.h"
41 #include "vp9/decoder/vp9_thread.h"
42
43 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
44   int i;
45   for (i = 1; i < REFS_PER_FRAME; ++i)
46     if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1])
47       return 1;
48
49   return 0;
50 }
51
52 static void setup_compound_reference_mode(VP9_COMMON *cm) {
53   if (cm->ref_frame_sign_bias[LAST_FRAME] ==
54           cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
55     cm->comp_fixed_ref = ALTREF_FRAME;
56     cm->comp_var_ref[0] = LAST_FRAME;
57     cm->comp_var_ref[1] = GOLDEN_FRAME;
58   } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
59                  cm->ref_frame_sign_bias[ALTREF_FRAME]) {
60     cm->comp_fixed_ref = GOLDEN_FRAME;
61     cm->comp_var_ref[0] = LAST_FRAME;
62     cm->comp_var_ref[1] = ALTREF_FRAME;
63   } else {
64     cm->comp_fixed_ref = LAST_FRAME;
65     cm->comp_var_ref[0] = GOLDEN_FRAME;
66     cm->comp_var_ref[1] = ALTREF_FRAME;
67   }
68 }
69
70 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
71   return len != 0 && len <= (size_t)(end - start);
72 }
73
74 static int decode_unsigned_max(struct vp9_read_bit_buffer *rb, int max) {
75   const int data = vp9_rb_read_literal(rb, get_unsigned_bits(max));
76   return data > max ? max : data;
77 }
78
79 static TX_MODE read_tx_mode(vp9_reader *r) {
80   TX_MODE tx_mode = vp9_read_literal(r, 2);
81   if (tx_mode == ALLOW_32X32)
82     tx_mode += vp9_read_bit(r);
83   return tx_mode;
84 }
85
86 static void read_tx_mode_probs(struct tx_probs *tx_probs, vp9_reader *r) {
87   int i, j;
88
89   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
90     for (j = 0; j < TX_SIZES - 3; ++j)
91       vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
92
93   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
94     for (j = 0; j < TX_SIZES - 2; ++j)
95       vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
96
97   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
98     for (j = 0; j < TX_SIZES - 1; ++j)
99       vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
100 }
101
102 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
103   int i, j;
104   for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
105     for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
106       vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
107 }
108
109 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
110   int i, j;
111   for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
112     for (j = 0; j < INTER_MODES - 1; ++j)
113       vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
114 }
115
116 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
117                                                 vp9_reader *r) {
118   if (is_compound_reference_allowed(cm)) {
119     return vp9_read_bit(r) ? (vp9_read_bit(r) ? REFERENCE_MODE_SELECT
120                                               : COMPOUND_REFERENCE)
121                            : SINGLE_REFERENCE;
122   } else {
123     return SINGLE_REFERENCE;
124   }
125 }
126
127 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vp9_reader *r) {
128   FRAME_CONTEXT *const fc = &cm->fc;
129   int i;
130
131   if (cm->reference_mode == REFERENCE_MODE_SELECT)
132     for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
133       vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
134
135   if (cm->reference_mode != COMPOUND_REFERENCE)
136     for (i = 0; i < REF_CONTEXTS; ++i) {
137       vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
138       vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
139     }
140
141   if (cm->reference_mode != SINGLE_REFERENCE)
142     for (i = 0; i < REF_CONTEXTS; ++i)
143       vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
144 }
145
146 static void update_mv_probs(vp9_prob *p, int n, vp9_reader *r) {
147   int i;
148   for (i = 0; i < n; ++i)
149     if (vp9_read(r, MV_UPDATE_PROB))
150       p[i] = (vp9_read_literal(r, 7) << 1) | 1;
151 }
152
153 static void read_mv_probs(nmv_context *ctx, int allow_hp, vp9_reader *r) {
154   int i, j;
155
156   update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
157
158   for (i = 0; i < 2; ++i) {
159     nmv_component *const comp_ctx = &ctx->comps[i];
160     update_mv_probs(&comp_ctx->sign, 1, r);
161     update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
162     update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
163     update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
164   }
165
166   for (i = 0; i < 2; ++i) {
167     nmv_component *const comp_ctx = &ctx->comps[i];
168     for (j = 0; j < CLASS0_SIZE; ++j)
169       update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
170     update_mv_probs(comp_ctx->fp, 3, r);
171   }
172
173   if (allow_hp) {
174     for (i = 0; i < 2; ++i) {
175       nmv_component *const comp_ctx = &ctx->comps[i];
176       update_mv_probs(&comp_ctx->class0_hp, 1, r);
177       update_mv_probs(&comp_ctx->hp, 1, r);
178     }
179   }
180 }
181
182 static void setup_plane_dequants(VP9_COMMON *cm, MACROBLOCKD *xd, int q_index) {
183   int i;
184   xd->plane[0].dequant = cm->y_dequant[q_index];
185
186   for (i = 1; i < MAX_MB_PLANE; i++)
187     xd->plane[i].dequant = cm->uv_dequant[q_index];
188 }
189
190 // Allocate storage for each tile column.
191 // TODO(jzern): when max_threads <= 1 the same storage could be used for each
192 // tile.
193 static void alloc_tile_storage(VP9D_COMP *pbi, int tile_rows, int tile_cols) {
194   VP9_COMMON *const cm = &pbi->common;
195   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
196   int i, tile_row, tile_col;
197
198   CHECK_MEM_ERROR(cm, pbi->mi_streams,
199                   vpx_realloc(pbi->mi_streams, tile_rows * tile_cols *
200                               sizeof(*pbi->mi_streams)));
201   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
202     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
203       TileInfo tile;
204       vp9_tile_init(&tile, cm, tile_row, tile_col);
205       pbi->mi_streams[tile_row * tile_cols + tile_col] =
206           &cm->mi[tile.mi_row_start * cm->mode_info_stride
207                   + tile.mi_col_start];
208     }
209   }
210
211   // 2 contexts per 'mi unit', so that we have one context per 4x4 txfm
212   // block where mi unit size is 8x8.
213   CHECK_MEM_ERROR(cm, pbi->above_context[0],
214                   vpx_realloc(pbi->above_context[0],
215                               sizeof(*pbi->above_context[0]) * MAX_MB_PLANE *
216                               2 * aligned_mi_cols));
217   for (i = 1; i < MAX_MB_PLANE; ++i) {
218     pbi->above_context[i] = pbi->above_context[0] +
219                             i * sizeof(*pbi->above_context[0]) *
220                             2 * aligned_mi_cols;
221   }
222
223   // This is sized based on the entire frame. Each tile operates within its
224   // column bounds.
225   CHECK_MEM_ERROR(cm, pbi->above_seg_context,
226                   vpx_realloc(pbi->above_seg_context,
227                               sizeof(*pbi->above_seg_context) *
228                               aligned_mi_cols));
229 }
230
231 static void inverse_transform_block(MACROBLOCKD* xd, int plane, int block,
232                                     TX_SIZE tx_size, uint8_t *dst, int stride,
233                                     int eob) {
234   struct macroblockd_plane *const pd = &xd->plane[plane];
235   if (eob > 0) {
236     TX_TYPE tx_type;
237     const int plane_type = pd->plane_type;
238     int16_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
239     switch (tx_size) {
240       case TX_4X4:
241         tx_type = get_tx_type_4x4(plane_type, xd, block);
242         if (tx_type == DCT_DCT)
243           xd->itxm_add(dqcoeff, dst, stride, eob);
244         else
245           vp9_iht4x4_16_add(dqcoeff, dst, stride, tx_type);
246         break;
247       case TX_8X8:
248         tx_type = get_tx_type(plane_type, xd);
249         vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
250         break;
251       case TX_16X16:
252         tx_type = get_tx_type(plane_type, xd);
253         vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
254         break;
255       case TX_32X32:
256         tx_type = DCT_DCT;
257         vp9_idct32x32_add(dqcoeff, dst, stride, eob);
258         break;
259       default:
260         assert(0 && "Invalid transform size");
261     }
262
263     if (eob == 1) {
264       vpx_memset(dqcoeff, 0, 2 * sizeof(dqcoeff[0]));
265     } else {
266       if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
267         vpx_memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
268       else if (tx_size == TX_32X32 && eob <= 34)
269         vpx_memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
270       else
271         vpx_memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
272     }
273   }
274 }
275
276 struct intra_args {
277   VP9_COMMON *cm;
278   MACROBLOCKD *xd;
279   vp9_reader *r;
280 };
281
282 static void predict_and_reconstruct_intra_block(int plane, int block,
283                                                 BLOCK_SIZE plane_bsize,
284                                                 TX_SIZE tx_size, void *arg) {
285   struct intra_args *const args = arg;
286   VP9_COMMON *const cm = args->cm;
287   MACROBLOCKD *const xd = args->xd;
288   struct macroblockd_plane *const pd = &xd->plane[plane];
289   MODE_INFO *const mi = xd->mi_8x8[0];
290   const MB_PREDICTION_MODE mode = (plane == 0) ? get_y_mode(mi, block)
291                                                : mi->mbmi.uv_mode;
292   int x, y;
293   uint8_t *dst;
294   txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x, &y);
295   dst = &pd->dst.buf[4 * y * pd->dst.stride + 4 * x];
296
297   vp9_predict_intra_block(xd, block >> (tx_size << 1),
298                           b_width_log2(plane_bsize), tx_size, mode,
299                           dst, pd->dst.stride, dst, pd->dst.stride,
300                           x, y, plane);
301
302   if (!mi->mbmi.skip) {
303     const int eob = vp9_decode_block_tokens(cm, xd, plane, block,
304                                             plane_bsize, x, y, tx_size,
305                                             args->r);
306     inverse_transform_block(xd, plane, block, tx_size, dst, pd->dst.stride,
307                             eob);
308   }
309 }
310
311 struct inter_args {
312   VP9_COMMON *cm;
313   MACROBLOCKD *xd;
314   vp9_reader *r;
315   int *eobtotal;
316 };
317
318 static void reconstruct_inter_block(int plane, int block,
319                                     BLOCK_SIZE plane_bsize,
320                                     TX_SIZE tx_size, void *arg) {
321   struct inter_args *args = arg;
322   VP9_COMMON *const cm = args->cm;
323   MACROBLOCKD *const xd = args->xd;
324   struct macroblockd_plane *const pd = &xd->plane[plane];
325   int x, y, eob;
326   txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x, &y);
327   eob = vp9_decode_block_tokens(cm, xd, plane, block, plane_bsize, x, y,
328                                 tx_size, args->r);
329   inverse_transform_block(xd, plane, block, tx_size,
330                           &pd->dst.buf[4 * y * pd->dst.stride + 4 * x],
331                           pd->dst.stride, eob);
332   *args->eobtotal += eob;
333 }
334
335 static void set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
336                         const TileInfo *const tile,
337                         BLOCK_SIZE bsize, int mi_row, int mi_col) {
338   const int bw = num_8x8_blocks_wide_lookup[bsize];
339   const int bh = num_8x8_blocks_high_lookup[bsize];
340   const int x_mis = MIN(bw, cm->mi_cols - mi_col);
341   const int y_mis = MIN(bh, cm->mi_rows - mi_row);
342   const int offset = mi_row * cm->mode_info_stride + mi_col;
343   const int tile_offset = tile->mi_row_start * cm->mode_info_stride +
344                           tile->mi_col_start;
345   int x, y;
346
347   xd->mi_8x8 = cm->mi_grid_visible + offset;
348   xd->prev_mi_8x8 = cm->prev_mi_grid_visible + offset;
349
350   xd->last_mi = cm->coding_use_prev_mi && cm->prev_mi ?
351       xd->prev_mi_8x8[0] : NULL;
352
353   xd->mi_8x8[0] = xd->mi_stream + offset - tile_offset;
354   xd->mi_8x8[0]->mbmi.sb_type = bsize;
355   for (y = 0; y < y_mis; ++y)
356     for (x = !y; x < x_mis; ++x)
357       xd->mi_8x8[y * cm->mode_info_stride + x] = xd->mi_8x8[0];
358
359   set_skip_context(xd, xd->above_context, xd->left_context, mi_row, mi_col);
360
361   // Distance of Mb to the various image edges. These are specified to 8th pel
362   // as they are always compared to values that are in 1/8th pel units
363   set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
364
365   vp9_setup_dst_planes(xd, get_frame_new_buffer(cm), mi_row, mi_col);
366 }
367
368 static void set_ref(VP9_COMMON *const cm, MACROBLOCKD *const xd,
369                     int idx, int mi_row, int mi_col) {
370   MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
371   RefBuffer *ref_buffer = &cm->frame_refs[mbmi->ref_frame[idx] - LAST_FRAME];
372   xd->block_refs[idx] = ref_buffer;
373   if (!vp9_is_valid_scale(&ref_buffer->sf))
374     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
375                        "Invalid scale factors");
376   vp9_setup_pre_planes(xd, idx, ref_buffer->buf, mi_row, mi_col,
377                        &ref_buffer->sf);
378   xd->corrupted |= ref_buffer->buf->corrupted;
379 }
380
381 static void decode_modes_b(VP9_COMMON *const cm, MACROBLOCKD *const xd,
382                            const TileInfo *const tile,
383                            int mi_row, int mi_col,
384                            vp9_reader *r, BLOCK_SIZE bsize) {
385   const int less8x8 = bsize < BLOCK_8X8;
386   MB_MODE_INFO *mbmi;
387
388   set_offsets(cm, xd, tile, bsize, mi_row, mi_col);
389   vp9_read_mode_info(cm, xd, tile, mi_row, mi_col, r);
390
391   if (less8x8)
392     bsize = BLOCK_8X8;
393
394   // Has to be called after set_offsets
395   mbmi = &xd->mi_8x8[0]->mbmi;
396
397   if (mbmi->skip) {
398     reset_skip_context(xd, bsize);
399   } else {
400     if (cm->seg.enabled)
401       setup_plane_dequants(cm, xd, vp9_get_qindex(&cm->seg, mbmi->segment_id,
402                                                   cm->base_qindex));
403   }
404
405   if (!is_inter_block(mbmi)) {
406     struct intra_args arg = { cm, xd, r };
407     vp9_foreach_transformed_block(xd, bsize,
408                                   predict_and_reconstruct_intra_block, &arg);
409   } else {
410     // Setup
411     set_ref(cm, xd, 0, mi_row, mi_col);
412     if (has_second_ref(mbmi))
413       set_ref(cm, xd, 1, mi_row, mi_col);
414
415     xd->interp_kernel = vp9_get_interp_kernel(mbmi->interp_filter);
416
417     // Prediction
418     vp9_dec_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
419
420     // Reconstruction
421     if (!mbmi->skip) {
422       int eobtotal = 0;
423       struct inter_args arg = { cm, xd, r, &eobtotal };
424       vp9_foreach_transformed_block(xd, bsize, reconstruct_inter_block, &arg);
425       if (!less8x8 && eobtotal == 0)
426         mbmi->skip = 1;  // skip loopfilter
427     }
428   }
429
430   xd->corrupted |= vp9_reader_has_error(r);
431 }
432
433 static PARTITION_TYPE read_partition(VP9_COMMON *cm, MACROBLOCKD *xd, int hbs,
434                                      int mi_row, int mi_col, BLOCK_SIZE bsize,
435                                      vp9_reader *r) {
436   const int ctx = partition_plane_context(xd->above_seg_context,
437                                           xd->left_seg_context,
438                                           mi_row, mi_col, bsize);
439   const vp9_prob *const probs = get_partition_probs(cm, ctx);
440   const int has_rows = (mi_row + hbs) < cm->mi_rows;
441   const int has_cols = (mi_col + hbs) < cm->mi_cols;
442   PARTITION_TYPE p;
443
444   if (has_rows && has_cols)
445     p = vp9_read_tree(r, vp9_partition_tree, probs);
446   else if (!has_rows && has_cols)
447     p = vp9_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
448   else if (has_rows && !has_cols)
449     p = vp9_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
450   else
451     p = PARTITION_SPLIT;
452
453   if (!cm->frame_parallel_decoding_mode)
454     ++cm->counts.partition[ctx][p];
455
456   return p;
457 }
458
459 static void decode_modes_sb(VP9_COMMON *const cm, MACROBLOCKD *const xd,
460                             const TileInfo *const tile,
461                             int mi_row, int mi_col,
462                             vp9_reader* r, BLOCK_SIZE bsize) {
463   const int hbs = num_8x8_blocks_wide_lookup[bsize] / 2;
464   PARTITION_TYPE partition;
465   BLOCK_SIZE subsize;
466
467   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
468     return;
469
470   partition = read_partition(cm, xd, hbs, mi_row, mi_col, bsize, r);
471   subsize = get_subsize(bsize, partition);
472   if (subsize < BLOCK_8X8) {
473     decode_modes_b(cm, xd, tile, mi_row, mi_col, r, subsize);
474   } else {
475     switch (partition) {
476       case PARTITION_NONE:
477         decode_modes_b(cm, xd, tile, mi_row, mi_col, r, subsize);
478         break;
479       case PARTITION_HORZ:
480         decode_modes_b(cm, xd, tile, mi_row, mi_col, r, subsize);
481         if (mi_row + hbs < cm->mi_rows)
482           decode_modes_b(cm, xd, tile, mi_row + hbs, mi_col, r, subsize);
483         break;
484       case PARTITION_VERT:
485         decode_modes_b(cm, xd, tile, mi_row, mi_col, r, subsize);
486         if (mi_col + hbs < cm->mi_cols)
487           decode_modes_b(cm, xd, tile, mi_row, mi_col + hbs, r, subsize);
488         break;
489       case PARTITION_SPLIT:
490         decode_modes_sb(cm, xd, tile, mi_row, mi_col, r, subsize);
491         decode_modes_sb(cm, xd, tile, mi_row, mi_col + hbs, r, subsize);
492         decode_modes_sb(cm, xd, tile, mi_row + hbs, mi_col, r, subsize);
493         decode_modes_sb(cm, xd, tile, mi_row + hbs, mi_col + hbs, r, subsize);
494         break;
495       default:
496         assert(0 && "Invalid partition type");
497     }
498   }
499
500   // update partition context
501   if (bsize >= BLOCK_8X8 &&
502       (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
503     update_partition_context(xd->above_seg_context, xd->left_seg_context,
504                              mi_row, mi_col, subsize, bsize);
505 }
506
507 static void setup_token_decoder(const uint8_t *data,
508                                 const uint8_t *data_end,
509                                 size_t read_size,
510                                 struct vpx_internal_error_info *error_info,
511                                 vp9_reader *r) {
512   // Validate the calculated partition length. If the buffer
513   // described by the partition can't be fully read, then restrict
514   // it to the portion that can be (for EC mode) or throw an error.
515   if (!read_is_valid(data, read_size, data_end))
516     vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
517                        "Truncated packet or corrupt tile length");
518
519   if (vp9_reader_init(r, data, read_size))
520     vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
521                        "Failed to allocate bool decoder %d", 1);
522 }
523
524 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
525                                    vp9_reader *r) {
526   int i, j, k, l, m;
527
528   if (vp9_read_bit(r))
529     for (i = 0; i < PLANE_TYPES; ++i)
530       for (j = 0; j < REF_TYPES; ++j)
531         for (k = 0; k < COEF_BANDS; ++k)
532           for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
533             for (m = 0; m < UNCONSTRAINED_NODES; ++m)
534               vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
535 }
536
537 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
538                             vp9_reader *r) {
539     const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
540     TX_SIZE tx_size;
541     for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
542       read_coef_probs_common(fc->coef_probs[tx_size], r);
543 }
544
545 static void setup_segmentation(struct segmentation *seg,
546                                struct vp9_read_bit_buffer *rb) {
547   int i, j;
548
549   seg->update_map = 0;
550   seg->update_data = 0;
551
552   seg->enabled = vp9_rb_read_bit(rb);
553   if (!seg->enabled)
554     return;
555
556   // Segmentation map update
557   seg->update_map = vp9_rb_read_bit(rb);
558   if (seg->update_map) {
559     for (i = 0; i < SEG_TREE_PROBS; i++)
560       seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
561                                                : MAX_PROB;
562
563     seg->temporal_update = vp9_rb_read_bit(rb);
564     if (seg->temporal_update) {
565       for (i = 0; i < PREDICTION_PROBS; i++)
566         seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
567                                                  : MAX_PROB;
568     } else {
569       for (i = 0; i < PREDICTION_PROBS; i++)
570         seg->pred_probs[i] = MAX_PROB;
571     }
572   }
573
574   // Segmentation data update
575   seg->update_data = vp9_rb_read_bit(rb);
576   if (seg->update_data) {
577     seg->abs_delta = vp9_rb_read_bit(rb);
578
579     vp9_clearall_segfeatures(seg);
580
581     for (i = 0; i < MAX_SEGMENTS; i++) {
582       for (j = 0; j < SEG_LVL_MAX; j++) {
583         int data = 0;
584         const int feature_enabled = vp9_rb_read_bit(rb);
585         if (feature_enabled) {
586           vp9_enable_segfeature(seg, i, j);
587           data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
588           if (vp9_is_segfeature_signed(j))
589             data = vp9_rb_read_bit(rb) ? -data : data;
590         }
591         vp9_set_segdata(seg, i, j, data);
592       }
593     }
594   }
595 }
596
597 static void setup_loopfilter(struct loopfilter *lf,
598                              struct vp9_read_bit_buffer *rb) {
599   lf->filter_level = vp9_rb_read_literal(rb, 6);
600   lf->sharpness_level = vp9_rb_read_literal(rb, 3);
601
602   // Read in loop filter deltas applied at the MB level based on mode or ref
603   // frame.
604   lf->mode_ref_delta_update = 0;
605
606   lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
607   if (lf->mode_ref_delta_enabled) {
608     lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
609     if (lf->mode_ref_delta_update) {
610       int i;
611
612       for (i = 0; i < MAX_REF_LF_DELTAS; i++)
613         if (vp9_rb_read_bit(rb))
614           lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
615
616       for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
617         if (vp9_rb_read_bit(rb))
618           lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
619     }
620   }
621 }
622
623 static int read_delta_q(struct vp9_read_bit_buffer *rb, int *delta_q) {
624   const int old = *delta_q;
625   *delta_q = vp9_rb_read_bit(rb) ? vp9_rb_read_signed_literal(rb, 4) : 0;
626   return old != *delta_q;
627 }
628
629 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
630                                struct vp9_read_bit_buffer *rb) {
631   int update = 0;
632
633   cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
634   update |= read_delta_q(rb, &cm->y_dc_delta_q);
635   update |= read_delta_q(rb, &cm->uv_dc_delta_q);
636   update |= read_delta_q(rb, &cm->uv_ac_delta_q);
637   if (update)
638     vp9_init_dequantizer(cm);
639
640   xd->lossless = cm->base_qindex == 0 &&
641                  cm->y_dc_delta_q == 0 &&
642                  cm->uv_dc_delta_q == 0 &&
643                  cm->uv_ac_delta_q == 0;
644
645   xd->itxm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
646 }
647
648 static INTERP_FILTER read_interp_filter(struct vp9_read_bit_buffer *rb) {
649   const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
650                                               EIGHTTAP,
651                                               EIGHTTAP_SHARP,
652                                               BILINEAR };
653   return vp9_rb_read_bit(rb) ? SWITCHABLE
654                              : literal_to_filter[vp9_rb_read_literal(rb, 2)];
655 }
656
657 static void read_frame_size(struct vp9_read_bit_buffer *rb,
658                             int *width, int *height) {
659   const int w = vp9_rb_read_literal(rb, 16) + 1;
660   const int h = vp9_rb_read_literal(rb, 16) + 1;
661   *width = w;
662   *height = h;
663 }
664
665 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
666   cm->display_width = cm->width;
667   cm->display_height = cm->height;
668   if (vp9_rb_read_bit(rb))
669     read_frame_size(rb, &cm->display_width, &cm->display_height);
670 }
671
672 static void apply_frame_size(VP9D_COMP *pbi, int width, int height) {
673   VP9_COMMON *cm = &pbi->common;
674
675   if (cm->width != width || cm->height != height) {
676     // Change in frame size.
677     // TODO(agrange) Don't test width/height, check overall size.
678     if (width > cm->width || height > cm->height) {
679       // Rescale frame buffers only if they're not big enough already.
680       if (vp9_resize_frame_buffers(cm, width, height))
681         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
682                            "Failed to allocate frame buffers");
683     }
684
685     cm->width = width;
686     cm->height = height;
687
688     vp9_update_frame_size(cm);
689   }
690
691   if (vp9_realloc_frame_buffer(
692           get_frame_new_buffer(cm), cm->width, cm->height,
693           cm->subsampling_x, cm->subsampling_y, VP9_DEC_BORDER_IN_PIXELS,
694           &cm->frame_bufs[cm->new_fb_idx].raw_frame_buffer, cm->get_fb_cb,
695           cm->cb_priv)) {
696     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
697                        "Failed to allocate frame buffer");
698   }
699 }
700
701 static void setup_frame_size(VP9D_COMP *pbi,
702                              struct vp9_read_bit_buffer *rb) {
703   int width, height;
704   read_frame_size(rb, &width, &height);
705   apply_frame_size(pbi, width, height);
706   setup_display_size(&pbi->common, rb);
707 }
708
709 static void setup_frame_size_with_refs(VP9D_COMP *pbi,
710                                        struct vp9_read_bit_buffer *rb) {
711   VP9_COMMON *const cm = &pbi->common;
712
713   int width, height;
714   int found = 0, i;
715   for (i = 0; i < REFS_PER_FRAME; ++i) {
716     if (vp9_rb_read_bit(rb)) {
717       YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
718       width = buf->y_crop_width;
719       height = buf->y_crop_height;
720       found = 1;
721       break;
722     }
723   }
724
725   if (!found)
726     read_frame_size(rb, &width, &height);
727
728   if (width <= 0 || height <= 0)
729     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
730                        "Referenced frame with invalid size");
731
732   apply_frame_size(pbi, width, height);
733   setup_display_size(cm, rb);
734 }
735
736 static void setup_tile_context(VP9D_COMP *const pbi, MACROBLOCKD *const xd,
737                                int tile_row, int tile_col) {
738   int i;
739   const int tile_cols = 1 << pbi->common.log2_tile_cols;
740   xd->mi_stream = pbi->mi_streams[tile_row * tile_cols + tile_col];
741
742   for (i = 0; i < MAX_MB_PLANE; ++i) {
743     xd->above_context[i] = pbi->above_context[i];
744   }
745   // see note in alloc_tile_storage().
746   xd->above_seg_context = pbi->above_seg_context;
747 }
748
749 static void decode_tile(VP9D_COMP *pbi, const TileInfo *const tile,
750                         vp9_reader *r) {
751   const int num_threads = pbi->oxcf.max_threads;
752   VP9_COMMON *const cm = &pbi->common;
753   int mi_row, mi_col;
754   MACROBLOCKD *xd = &pbi->mb;
755
756   if (pbi->do_loopfilter_inline) {
757     LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
758     lf_data->frame_buffer = get_frame_new_buffer(cm);
759     lf_data->cm = cm;
760     lf_data->xd = pbi->mb;
761     lf_data->stop = 0;
762     lf_data->y_only = 0;
763     vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
764   }
765
766   for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
767        mi_row += MI_BLOCK_SIZE) {
768     // For a SB there are 2 left contexts, each pertaining to a MB row within
769     vp9_zero(xd->left_context);
770     vp9_zero(xd->left_seg_context);
771     for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
772          mi_col += MI_BLOCK_SIZE) {
773       decode_modes_sb(cm, xd, tile, mi_row, mi_col, r, BLOCK_64X64);
774     }
775
776     if (pbi->do_loopfilter_inline) {
777       const int lf_start = mi_row - MI_BLOCK_SIZE;
778       LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
779
780       // delay the loopfilter by 1 macroblock row.
781       if (lf_start < 0) continue;
782
783       // decoding has completed: finish up the loop filter in this thread.
784       if (mi_row + MI_BLOCK_SIZE >= tile->mi_row_end) continue;
785
786       vp9_worker_sync(&pbi->lf_worker);
787       lf_data->start = lf_start;
788       lf_data->stop = mi_row;
789       if (num_threads > 1) {
790         vp9_worker_launch(&pbi->lf_worker);
791       } else {
792         vp9_worker_execute(&pbi->lf_worker);
793       }
794     }
795   }
796
797   if (pbi->do_loopfilter_inline) {
798     LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
799
800     vp9_worker_sync(&pbi->lf_worker);
801     lf_data->start = lf_data->stop;
802     lf_data->stop = cm->mi_rows;
803     vp9_worker_execute(&pbi->lf_worker);
804   }
805 }
806
807 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
808   int min_log2_tile_cols, max_log2_tile_cols, max_ones;
809   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
810
811   // columns
812   max_ones = max_log2_tile_cols - min_log2_tile_cols;
813   cm->log2_tile_cols = min_log2_tile_cols;
814   while (max_ones-- && vp9_rb_read_bit(rb))
815     cm->log2_tile_cols++;
816
817   // rows
818   cm->log2_tile_rows = vp9_rb_read_bit(rb);
819   if (cm->log2_tile_rows)
820     cm->log2_tile_rows += vp9_rb_read_bit(rb);
821 }
822
823 // Reads the next tile returning its size and adjusting '*data' accordingly
824 // based on 'is_last'.
825 static size_t get_tile(const uint8_t *const data_end,
826                        int is_last,
827                        struct vpx_internal_error_info *error_info,
828                        const uint8_t **data) {
829   size_t size;
830
831   if (!is_last) {
832     if (!read_is_valid(*data, 4, data_end))
833       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
834                          "Truncated packet or corrupt tile length");
835
836     size = mem_get_be32(*data);
837     *data += 4;
838
839     if (size > (size_t)(data_end - *data))
840       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
841                          "Truncated packet or corrupt tile size");
842   } else {
843     size = data_end - *data;
844   }
845   return size;
846 }
847
848 typedef struct TileBuffer {
849   const uint8_t *data;
850   size_t size;
851   int col;  // only used with multi-threaded decoding
852 } TileBuffer;
853
854 static const uint8_t *decode_tiles(VP9D_COMP *pbi, const uint8_t *data) {
855   VP9_COMMON *const cm = &pbi->common;
856   MACROBLOCKD *const xd = &pbi->mb;
857   const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
858   const int tile_cols = 1 << cm->log2_tile_cols;
859   const int tile_rows = 1 << cm->log2_tile_rows;
860   TileBuffer tile_buffers[4][1 << 6];
861   int tile_row, tile_col;
862   const uint8_t *const data_end = pbi->source + pbi->source_sz;
863   const uint8_t *end = NULL;
864   vp9_reader r;
865
866   assert(tile_rows <= 4);
867   assert(tile_cols <= (1 << 6));
868
869   // Note: this memset assumes above_context[0], [1] and [2]
870   // are allocated as part of the same buffer.
871   vpx_memset(pbi->above_context[0], 0,
872              sizeof(*pbi->above_context[0]) * MAX_MB_PLANE * 2 * aligned_cols);
873
874   vpx_memset(pbi->above_seg_context, 0,
875              sizeof(*pbi->above_seg_context) * aligned_cols);
876
877   // Load tile data into tile_buffers
878   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
879     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
880       const int last_tile = tile_row == tile_rows - 1 &&
881                             tile_col == tile_cols - 1;
882       const size_t size = get_tile(data_end, last_tile, &cm->error, &data);
883       TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
884       buf->data = data;
885       buf->size = size;
886       data += size;
887     }
888   }
889
890   // Decode tiles using data from tile_buffers
891   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
892     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
893       const int col = pbi->oxcf.inv_tile_order ? tile_cols - tile_col - 1
894                                                : tile_col;
895       const int last_tile = tile_row == tile_rows - 1 &&
896                                  col == tile_cols - 1;
897       const TileBuffer *const buf = &tile_buffers[tile_row][col];
898       TileInfo tile;
899
900       vp9_tile_init(&tile, cm, tile_row, col);
901       setup_token_decoder(buf->data, data_end, buf->size, &cm->error, &r);
902       setup_tile_context(pbi, xd, tile_row, col);
903       decode_tile(pbi, &tile, &r);
904
905       if (last_tile)
906         end = vp9_reader_find_end(&r);
907     }
908   }
909
910   return end;
911 }
912
913 static void setup_tile_macroblockd(TileWorkerData *const tile_data) {
914   MACROBLOCKD *xd = &tile_data->xd;
915   struct macroblockd_plane *const pd = xd->plane;
916   int i;
917
918   for (i = 0; i < MAX_MB_PLANE; ++i) {
919     pd[i].dqcoeff = tile_data->dqcoeff[i];
920     vpx_memset(xd->plane[i].dqcoeff, 0, 64 * 64 * sizeof(int16_t));
921   }
922 }
923
924 static int tile_worker_hook(void *arg1, void *arg2) {
925   TileWorkerData *const tile_data = (TileWorkerData*)arg1;
926   const TileInfo *const tile = (TileInfo*)arg2;
927   int mi_row, mi_col;
928
929   for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
930        mi_row += MI_BLOCK_SIZE) {
931     vp9_zero(tile_data->xd.left_context);
932     vp9_zero(tile_data->xd.left_seg_context);
933     for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
934          mi_col += MI_BLOCK_SIZE) {
935       decode_modes_sb(tile_data->cm, &tile_data->xd, tile,
936                       mi_row, mi_col, &tile_data->bit_reader, BLOCK_64X64);
937     }
938   }
939   return !tile_data->xd.corrupted;
940 }
941
942 // sorts in descending order
943 static int compare_tile_buffers(const void *a, const void *b) {
944   const TileBuffer *const buf1 = (const TileBuffer*)a;
945   const TileBuffer *const buf2 = (const TileBuffer*)b;
946   if (buf1->size < buf2->size) {
947     return 1;
948   } else if (buf1->size == buf2->size) {
949     return 0;
950   } else {
951     return -1;
952   }
953 }
954
955 static const uint8_t *decode_tiles_mt(VP9D_COMP *pbi, const uint8_t *data) {
956   VP9_COMMON *const cm = &pbi->common;
957   const uint8_t *bit_reader_end = NULL;
958   const uint8_t *const data_end = pbi->source + pbi->source_sz;
959   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
960   const int tile_cols = 1 << cm->log2_tile_cols;
961   const int tile_rows = 1 << cm->log2_tile_rows;
962   const int num_workers = MIN(pbi->oxcf.max_threads & ~1, tile_cols);
963   TileBuffer tile_buffers[1 << 6];
964   int n;
965   int final_worker = -1;
966
967   assert(tile_cols <= (1 << 6));
968   assert(tile_rows == 1);
969   (void)tile_rows;
970
971   if (num_workers > pbi->num_tile_workers) {
972     int i;
973     CHECK_MEM_ERROR(cm, pbi->tile_workers,
974                     vpx_realloc(pbi->tile_workers,
975                                 num_workers * sizeof(*pbi->tile_workers)));
976     for (i = pbi->num_tile_workers; i < num_workers; ++i) {
977       VP9Worker *const worker = &pbi->tile_workers[i];
978       ++pbi->num_tile_workers;
979
980       vp9_worker_init(worker);
981       CHECK_MEM_ERROR(cm, worker->data1,
982                       vpx_memalign(32, sizeof(TileWorkerData)));
983       CHECK_MEM_ERROR(cm, worker->data2, vpx_malloc(sizeof(TileInfo)));
984       if (i < num_workers - 1 && !vp9_worker_reset(worker)) {
985         vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
986                            "Tile decoder thread creation failed");
987       }
988     }
989   }
990
991   // Reset tile decoding hook
992   for (n = 0; n < pbi->num_tile_workers; ++n) {
993     pbi->tile_workers[n].hook = (VP9WorkerHook)tile_worker_hook;
994   }
995
996   // Note: this memset assumes above_context[0], [1] and [2]
997   // are allocated as part of the same buffer.
998   vpx_memset(pbi->above_context[0], 0,
999              sizeof(*pbi->above_context[0]) * MAX_MB_PLANE *
1000              2 * aligned_mi_cols);
1001   vpx_memset(pbi->above_seg_context, 0,
1002              sizeof(*pbi->above_seg_context) * aligned_mi_cols);
1003
1004   // Load tile data into tile_buffers
1005   for (n = 0; n < tile_cols; ++n) {
1006     const size_t size =
1007         get_tile(data_end, n == tile_cols - 1, &cm->error, &data);
1008     TileBuffer *const buf = &tile_buffers[n];
1009     buf->data = data;
1010     buf->size = size;
1011     buf->col = n;
1012     data += size;
1013   }
1014
1015   // Sort the buffers based on size in descending order.
1016   qsort(tile_buffers, tile_cols, sizeof(tile_buffers[0]), compare_tile_buffers);
1017
1018   // Rearrange the tile buffers such that per-tile group the largest, and
1019   // presumably the most difficult, tile will be decoded in the main thread.
1020   // This should help minimize the number of instances where the main thread is
1021   // waiting for a worker to complete.
1022   {
1023     int group_start = 0;
1024     while (group_start < tile_cols) {
1025       const TileBuffer largest = tile_buffers[group_start];
1026       const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1027       memmove(tile_buffers + group_start, tile_buffers + group_start + 1,
1028               (group_end - group_start) * sizeof(tile_buffers[0]));
1029       tile_buffers[group_end] = largest;
1030       group_start = group_end + 1;
1031     }
1032   }
1033
1034   n = 0;
1035   while (n < tile_cols) {
1036     int i;
1037     for (i = 0; i < num_workers && n < tile_cols; ++i) {
1038       VP9Worker *const worker = &pbi->tile_workers[i];
1039       TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1040       TileInfo *const tile = (TileInfo*)worker->data2;
1041       TileBuffer *const buf = &tile_buffers[n];
1042
1043       tile_data->cm = cm;
1044       tile_data->xd = pbi->mb;
1045       tile_data->xd.corrupted = 0;
1046       vp9_tile_init(tile, tile_data->cm, 0, buf->col);
1047
1048       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1049                           &tile_data->bit_reader);
1050       setup_tile_context(pbi, &tile_data->xd, 0, buf->col);
1051       setup_tile_macroblockd(tile_data);
1052
1053       worker->had_error = 0;
1054       if (i == num_workers - 1 || n == tile_cols - 1) {
1055         vp9_worker_execute(worker);
1056       } else {
1057         vp9_worker_launch(worker);
1058       }
1059
1060       if (buf->col == tile_cols - 1) {
1061         final_worker = i;
1062       }
1063
1064       ++n;
1065     }
1066
1067     for (; i > 0; --i) {
1068       VP9Worker *const worker = &pbi->tile_workers[i - 1];
1069       pbi->mb.corrupted |= !vp9_worker_sync(worker);
1070     }
1071     if (final_worker > -1) {
1072       TileWorkerData *const tile_data =
1073           (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1074       bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1075       final_worker = -1;
1076     }
1077   }
1078
1079   return bit_reader_end;
1080 }
1081
1082 static void check_sync_code(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1083   if (vp9_rb_read_literal(rb, 8) != VP9_SYNC_CODE_0 ||
1084       vp9_rb_read_literal(rb, 8) != VP9_SYNC_CODE_1 ||
1085       vp9_rb_read_literal(rb, 8) != VP9_SYNC_CODE_2) {
1086     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1087                        "Invalid frame sync code");
1088   }
1089 }
1090
1091 static void error_handler(void *data) {
1092   VP9_COMMON *const cm = (VP9_COMMON *)data;
1093   vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1094 }
1095
1096 #define RESERVED \
1097   if (vp9_rb_read_bit(rb)) \
1098       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM, \
1099                          "Reserved bit must be unset")
1100
1101 static size_t read_uncompressed_header(VP9D_COMP *pbi,
1102                                        struct vp9_read_bit_buffer *rb) {
1103   VP9_COMMON *const cm = &pbi->common;
1104   size_t sz;
1105   int i;
1106
1107   cm->last_frame_type = cm->frame_type;
1108
1109   if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1110       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1111                          "Invalid frame marker");
1112
1113   cm->version = vp9_rb_read_bit(rb);
1114   RESERVED;
1115
1116   cm->show_existing_frame = vp9_rb_read_bit(rb);
1117   if (cm->show_existing_frame) {
1118     // Show an existing frame directly.
1119     const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1120
1121     if (cm->frame_bufs[frame_to_show].ref_count < 1)
1122       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1123                          "Buffer %d does not contain a decoded frame",
1124                          frame_to_show);
1125
1126     ref_cnt_fb(cm->frame_bufs, &cm->new_fb_idx, frame_to_show);
1127     pbi->refresh_frame_flags = 0;
1128     cm->lf.filter_level = 0;
1129     cm->show_frame = 1;
1130     return 0;
1131   }
1132
1133   cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1134   cm->show_frame = vp9_rb_read_bit(rb);
1135   cm->error_resilient_mode = vp9_rb_read_bit(rb);
1136
1137   if (cm->frame_type == KEY_FRAME) {
1138     check_sync_code(cm, rb);
1139
1140     cm->color_space = vp9_rb_read_literal(rb, 3);  // colorspace
1141     if (cm->color_space != SRGB) {
1142       vp9_rb_read_bit(rb);  // [16,235] (including xvycc) vs [0,255] range
1143       if (cm->version == 1) {
1144         cm->subsampling_x = vp9_rb_read_bit(rb);
1145         cm->subsampling_y = vp9_rb_read_bit(rb);
1146         vp9_rb_read_bit(rb);  // has extra plane
1147       } else {
1148         cm->subsampling_y = cm->subsampling_x = 1;
1149       }
1150     } else {
1151       if (cm->version == 1) {
1152         cm->subsampling_y = cm->subsampling_x = 0;
1153         vp9_rb_read_bit(rb);  // has extra plane
1154       } else {
1155         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1156                            "RGB not supported in profile 0");
1157       }
1158     }
1159
1160     pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1161
1162     for (i = 0; i < REFS_PER_FRAME; ++i) {
1163       cm->frame_refs[i].idx = cm->new_fb_idx;
1164       cm->frame_refs[i].buf = get_frame_new_buffer(cm);
1165     }
1166
1167     setup_frame_size(pbi, rb);
1168   } else {
1169     cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1170
1171     cm->reset_frame_context = cm->error_resilient_mode ?
1172         0 : vp9_rb_read_literal(rb, 2);
1173
1174     if (cm->intra_only) {
1175       check_sync_code(cm, rb);
1176
1177       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1178       setup_frame_size(pbi, rb);
1179     } else {
1180       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1181
1182       for (i = 0; i < REFS_PER_FRAME; ++i) {
1183         const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1184         const int idx = cm->ref_frame_map[ref];
1185         cm->frame_refs[i].idx = idx;
1186         cm->frame_refs[i].buf = &cm->frame_bufs[idx].buf;
1187         cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1188       }
1189
1190       setup_frame_size_with_refs(pbi, rb);
1191
1192       cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1193       cm->interp_filter = read_interp_filter(rb);
1194
1195       for (i = 0; i < REFS_PER_FRAME; ++i) {
1196         RefBuffer *const ref_buf = &cm->frame_refs[i];
1197         vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1198                                           ref_buf->buf->y_crop_width,
1199                                           ref_buf->buf->y_crop_height,
1200                                           cm->width, cm->height);
1201         if (vp9_is_scaled(&ref_buf->sf))
1202           vp9_extend_frame_borders(ref_buf->buf);
1203       }
1204     }
1205   }
1206
1207   if (!cm->error_resilient_mode) {
1208     cm->coding_use_prev_mi = 1;
1209     cm->refresh_frame_context = vp9_rb_read_bit(rb);
1210     cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
1211   } else {
1212     cm->coding_use_prev_mi = 0;
1213     cm->refresh_frame_context = 0;
1214     cm->frame_parallel_decoding_mode = 1;
1215   }
1216
1217   // This flag will be overridden by the call to vp9_setup_past_independence
1218   // below, forcing the use of context 0 for those frame types.
1219   cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1220
1221   if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1222     vp9_setup_past_independence(cm);
1223
1224   setup_loopfilter(&cm->lf, rb);
1225   setup_quantization(cm, &pbi->mb, rb);
1226   setup_segmentation(&cm->seg, rb);
1227
1228   setup_tile_info(cm, rb);
1229   sz = vp9_rb_read_literal(rb, 16);
1230
1231   if (sz == 0)
1232     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1233                        "Invalid header size");
1234
1235   return sz;
1236 }
1237
1238 static int read_compressed_header(VP9D_COMP *pbi, const uint8_t *data,
1239                                   size_t partition_size) {
1240   VP9_COMMON *const cm = &pbi->common;
1241   MACROBLOCKD *const xd = &pbi->mb;
1242   FRAME_CONTEXT *const fc = &cm->fc;
1243   vp9_reader r;
1244   int k;
1245
1246   if (vp9_reader_init(&r, data, partition_size))
1247     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1248                        "Failed to allocate bool decoder 0");
1249
1250   cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1251   if (cm->tx_mode == TX_MODE_SELECT)
1252     read_tx_mode_probs(&fc->tx_probs, &r);
1253   read_coef_probs(fc, cm->tx_mode, &r);
1254
1255   for (k = 0; k < SKIP_CONTEXTS; ++k)
1256     vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1257
1258   if (!frame_is_intra_only(cm)) {
1259     nmv_context *const nmvc = &fc->nmvc;
1260     int i, j;
1261
1262     read_inter_mode_probs(fc, &r);
1263
1264     if (cm->interp_filter == SWITCHABLE)
1265       read_switchable_interp_probs(fc, &r);
1266
1267     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1268       vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1269
1270     cm->reference_mode = read_frame_reference_mode(cm, &r);
1271     if (cm->reference_mode != SINGLE_REFERENCE)
1272       setup_compound_reference_mode(cm);
1273     read_frame_reference_mode_probs(cm, &r);
1274
1275     for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1276       for (i = 0; i < INTRA_MODES - 1; ++i)
1277         vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1278
1279     for (j = 0; j < PARTITION_CONTEXTS; ++j)
1280       for (i = 0; i < PARTITION_TYPES - 1; ++i)
1281         vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1282
1283     read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
1284   }
1285
1286   return vp9_reader_has_error(&r);
1287 }
1288
1289 void vp9_init_dequantizer(VP9_COMMON *cm) {
1290   int q;
1291
1292   for (q = 0; q < QINDEX_RANGE; q++) {
1293     cm->y_dequant[q][0] = vp9_dc_quant(q, cm->y_dc_delta_q);
1294     cm->y_dequant[q][1] = vp9_ac_quant(q, 0);
1295
1296     cm->uv_dequant[q][0] = vp9_dc_quant(q, cm->uv_dc_delta_q);
1297     cm->uv_dequant[q][1] = vp9_ac_quant(q, cm->uv_ac_delta_q);
1298   }
1299 }
1300
1301 #ifdef NDEBUG
1302 #define debug_check_frame_counts(cm) (void)0
1303 #else  // !NDEBUG
1304 // Counts should only be incremented when frame_parallel_decoding_mode and
1305 // error_resilient_mode are disabled.
1306 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
1307   FRAME_COUNTS zero_counts;
1308   vp9_zero(zero_counts);
1309   assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
1310   assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
1311                  sizeof(cm->counts.y_mode)));
1312   assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
1313                  sizeof(cm->counts.uv_mode)));
1314   assert(!memcmp(cm->counts.partition, zero_counts.partition,
1315                  sizeof(cm->counts.partition)));
1316   assert(!memcmp(cm->counts.coef, zero_counts.coef,
1317                  sizeof(cm->counts.coef)));
1318   assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
1319                  sizeof(cm->counts.eob_branch)));
1320   assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
1321                  sizeof(cm->counts.switchable_interp)));
1322   assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
1323                  sizeof(cm->counts.inter_mode)));
1324   assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
1325                  sizeof(cm->counts.intra_inter)));
1326   assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
1327                  sizeof(cm->counts.comp_inter)));
1328   assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
1329                  sizeof(cm->counts.single_ref)));
1330   assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
1331                  sizeof(cm->counts.comp_ref)));
1332   assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
1333   assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
1334   assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
1335 }
1336 #endif  // NDEBUG
1337
1338 int vp9_decode_frame(VP9D_COMP *pbi, const uint8_t **p_data_end) {
1339   int i;
1340   VP9_COMMON *const cm = &pbi->common;
1341   MACROBLOCKD *const xd = &pbi->mb;
1342
1343   const uint8_t *data = pbi->source;
1344   const uint8_t *const data_end = pbi->source + pbi->source_sz;
1345
1346   struct vp9_read_bit_buffer rb = { data, data_end, 0, cm, error_handler };
1347   const size_t first_partition_size = read_uncompressed_header(pbi, &rb);
1348   const int keyframe = cm->frame_type == KEY_FRAME;
1349   const int tile_rows = 1 << cm->log2_tile_rows;
1350   const int tile_cols = 1 << cm->log2_tile_cols;
1351   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
1352   xd->cur_buf = new_fb;
1353
1354   if (!first_partition_size) {
1355       // showing a frame directly
1356       *p_data_end = data + 1;
1357       return 0;
1358   }
1359
1360   if (!pbi->decoded_key_frame && !keyframe)
1361     return -1;
1362
1363   data += vp9_rb_bytes_read(&rb);
1364   if (!read_is_valid(data, first_partition_size, data_end))
1365     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1366                        "Truncated packet or corrupt header length");
1367
1368   pbi->do_loopfilter_inline =
1369       (cm->log2_tile_rows | cm->log2_tile_cols) == 0 && cm->lf.filter_level;
1370   if (pbi->do_loopfilter_inline && pbi->lf_worker.data1 == NULL) {
1371     CHECK_MEM_ERROR(cm, pbi->lf_worker.data1, vpx_malloc(sizeof(LFWorkerData)));
1372     pbi->lf_worker.hook = (VP9WorkerHook)vp9_loop_filter_worker;
1373     if (pbi->oxcf.max_threads > 1 && !vp9_worker_reset(&pbi->lf_worker)) {
1374       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1375                          "Loop filter thread creation failed");
1376     }
1377   }
1378
1379   alloc_tile_storage(pbi, tile_rows, tile_cols);
1380
1381   xd->mode_info_stride = cm->mode_info_stride;
1382   if (cm->coding_use_prev_mi)
1383     set_prev_mi(cm);
1384   else
1385     cm->prev_mi = NULL;
1386
1387   setup_plane_dequants(cm, xd, cm->base_qindex);
1388   vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
1389
1390   cm->fc = cm->frame_contexts[cm->frame_context_idx];
1391   vp9_zero(cm->counts);
1392   for (i = 0; i < MAX_MB_PLANE; ++i)
1393     vpx_memset(xd->plane[i].dqcoeff, 0, 64 * 64 * sizeof(int16_t));
1394
1395   xd->corrupted = 0;
1396   new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
1397
1398   // TODO(jzern): remove frame_parallel_decoding_mode restriction for
1399   // single-frame tile decoding.
1400   if (pbi->oxcf.max_threads > 1 && tile_rows == 1 && tile_cols > 1 &&
1401       cm->frame_parallel_decoding_mode) {
1402     *p_data_end = decode_tiles_mt(pbi, data + first_partition_size);
1403   } else {
1404     *p_data_end = decode_tiles(pbi, data + first_partition_size);
1405   }
1406
1407   new_fb->corrupted |= xd->corrupted;
1408
1409   if (!pbi->decoded_key_frame) {
1410     if (keyframe && !new_fb->corrupted)
1411       pbi->decoded_key_frame = 1;
1412     else
1413       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1414                          "A stream must start with a complete key frame");
1415   }
1416
1417   if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
1418     vp9_adapt_coef_probs(cm);
1419
1420     if (!frame_is_intra_only(cm)) {
1421       vp9_adapt_mode_probs(cm);
1422       vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
1423     }
1424   } else {
1425     debug_check_frame_counts(cm);
1426   }
1427
1428   if (cm->refresh_frame_context)
1429     cm->frame_contexts[cm->frame_context_idx] = cm->fc;
1430
1431   return 0;
1432 }