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