debe22d6a21576ee2cec692575b1b6ba6770a259
[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     const int aligned_width = ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2);
631     const int aligned_height = ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2);
632
633     // Change in frame size (assumption: color format does not change).
634     if (cm->width == 0 || cm->height == 0 ||
635         aligned_width > cm->width ||
636         aligned_width * aligned_height > cm->width * cm->height) {
637       if (vp9_alloc_context_buffers(cm, width, height))
638         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
639                            "Failed to allocate context buffers");
640     } else {
641       vp9_set_mb_mi(cm, width, height);
642     }
643     vp9_init_context_buffers(cm);
644     cm->width = width;
645     cm->height = height;
646   }
647 }
648
649 static void setup_frame_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
650   int width, height;
651   vp9_read_frame_size(rb, &width, &height);
652   resize_context_buffers(cm, width, height);
653   setup_display_size(cm, rb);
654
655   if (vp9_realloc_frame_buffer(
656           get_frame_new_buffer(cm), cm->width, cm->height,
657           cm->subsampling_x, cm->subsampling_y, VP9_DEC_BORDER_IN_PIXELS,
658           &cm->frame_bufs[cm->new_fb_idx].raw_frame_buffer, cm->get_fb_cb,
659           cm->cb_priv)) {
660     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
661                        "Failed to allocate frame buffer");
662   }
663 }
664
665 static void setup_frame_size_with_refs(VP9_COMMON *cm,
666                                        struct vp9_read_bit_buffer *rb) {
667   int width, height;
668   int found = 0, i;
669   for (i = 0; i < REFS_PER_FRAME; ++i) {
670     if (vp9_rb_read_bit(rb)) {
671       YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
672       width = buf->y_crop_width;
673       height = buf->y_crop_height;
674       found = 1;
675       break;
676     }
677   }
678
679   if (!found)
680     vp9_read_frame_size(rb, &width, &height);
681
682   // Check that each of the frames that this frame references has valid
683   // dimensions.
684   for (i = 0; i < REFS_PER_FRAME; ++i) {
685     RefBuffer *const ref_frame = &cm->frame_refs[i];
686     if (!valid_ref_frame_size(ref_frame->buf->y_width, ref_frame->buf->y_height,
687                               width, height))
688       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
689                          "Referenced frame has invalid size");
690   }
691
692   resize_context_buffers(cm, width, height);
693   setup_display_size(cm, rb);
694
695   if (vp9_realloc_frame_buffer(
696           get_frame_new_buffer(cm), cm->width, cm->height,
697           cm->subsampling_x, cm->subsampling_y, VP9_DEC_BORDER_IN_PIXELS,
698           &cm->frame_bufs[cm->new_fb_idx].raw_frame_buffer, cm->get_fb_cb,
699           cm->cb_priv)) {
700     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
701                        "Failed to allocate frame buffer");
702   }
703 }
704
705 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
706   int min_log2_tile_cols, max_log2_tile_cols, max_ones;
707   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
708
709   // columns
710   max_ones = max_log2_tile_cols - min_log2_tile_cols;
711   cm->log2_tile_cols = min_log2_tile_cols;
712   while (max_ones-- && vp9_rb_read_bit(rb))
713     cm->log2_tile_cols++;
714
715   if (cm->log2_tile_cols > 6)
716     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
717                        "Invalid number of tile columns");
718
719   // rows
720   cm->log2_tile_rows = vp9_rb_read_bit(rb);
721   if (cm->log2_tile_rows)
722     cm->log2_tile_rows += vp9_rb_read_bit(rb);
723 }
724
725 typedef struct TileBuffer {
726   const uint8_t *data;
727   size_t size;
728   int col;  // only used with multi-threaded decoding
729 } TileBuffer;
730
731 // Reads the next tile returning its size and adjusting '*data' accordingly
732 // based on 'is_last'.
733 static void get_tile_buffer(const uint8_t *const data_end,
734                             int is_last,
735                             struct vpx_internal_error_info *error_info,
736                             const uint8_t **data,
737                             vpx_decrypt_cb decrypt_cb, void *decrypt_state,
738                             TileBuffer *buf) {
739   size_t size;
740
741   if (!is_last) {
742     if (!read_is_valid(*data, 4, data_end))
743       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
744                          "Truncated packet or corrupt tile length");
745
746     if (decrypt_cb) {
747       uint8_t be_data[4];
748       decrypt_cb(decrypt_state, *data, be_data, 4);
749       size = mem_get_be32(be_data);
750     } else {
751       size = mem_get_be32(*data);
752     }
753     *data += 4;
754
755     if (size > (size_t)(data_end - *data))
756       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
757                          "Truncated packet or corrupt tile size");
758   } else {
759     size = data_end - *data;
760   }
761
762   buf->data = *data;
763   buf->size = size;
764
765   *data += size;
766 }
767
768 static void get_tile_buffers(VP9Decoder *pbi,
769                              const uint8_t *data, const uint8_t *data_end,
770                              int tile_cols, int tile_rows,
771                              TileBuffer (*tile_buffers)[1 << 6]) {
772   int r, c;
773
774   for (r = 0; r < tile_rows; ++r) {
775     for (c = 0; c < tile_cols; ++c) {
776       const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
777       TileBuffer *const buf = &tile_buffers[r][c];
778       buf->col = c;
779       get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
780                       pbi->decrypt_cb, pbi->decrypt_state, buf);
781     }
782   }
783 }
784
785 static const uint8_t *decode_tiles(VP9Decoder *pbi,
786                                    const uint8_t *data,
787                                    const uint8_t *data_end) {
788   VP9_COMMON *const cm = &pbi->common;
789   const VP9WorkerInterface *const winterface = vp9_get_worker_interface();
790   const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
791   const int tile_cols = 1 << cm->log2_tile_cols;
792   const int tile_rows = 1 << cm->log2_tile_rows;
793   TileBuffer tile_buffers[4][1 << 6];
794   int tile_row, tile_col;
795   int mi_row, mi_col;
796   TileData *tile_data = NULL;
797
798   if (cm->lf.filter_level && pbi->lf_worker.data1 == NULL) {
799     CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
800                     vpx_memalign(32, sizeof(LFWorkerData)));
801     pbi->lf_worker.hook = (VP9WorkerHook)vp9_loop_filter_worker;
802     if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
803       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
804                          "Loop filter thread creation failed");
805     }
806   }
807
808   if (cm->lf.filter_level) {
809     LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
810     lf_data->frame_buffer = get_frame_new_buffer(cm);
811     lf_data->cm = cm;
812     vp9_copy(lf_data->planes, pbi->mb.plane);
813     lf_data->stop = 0;
814     lf_data->y_only = 0;
815     vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
816   }
817
818   assert(tile_rows <= 4);
819   assert(tile_cols <= (1 << 6));
820
821   // Note: this memset assumes above_context[0], [1] and [2]
822   // are allocated as part of the same buffer.
823   vpx_memset(cm->above_context, 0,
824              sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
825
826   vpx_memset(cm->above_seg_context, 0,
827              sizeof(*cm->above_seg_context) * aligned_cols);
828
829   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
830
831   if (pbi->tile_data == NULL ||
832       (tile_cols * tile_rows) != pbi->total_tiles) {
833     vpx_free(pbi->tile_data);
834     CHECK_MEM_ERROR(
835         cm,
836         pbi->tile_data,
837         vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
838     pbi->total_tiles = tile_rows * tile_cols;
839   }
840
841   // Load all tile information into tile_data.
842   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
843     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
844       TileInfo tile;
845       const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
846       tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
847       tile_data->cm = cm;
848       tile_data->xd = pbi->mb;
849       tile_data->xd.corrupted = 0;
850       vp9_tile_init(&tile, tile_data->cm, tile_row, tile_col);
851       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
852                           &tile_data->bit_reader, pbi->decrypt_cb,
853                           pbi->decrypt_state);
854       init_macroblockd(cm, &tile_data->xd);
855       vp9_zero(tile_data->xd.dqcoeff);
856     }
857   }
858
859   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
860     TileInfo tile;
861     vp9_tile_set_row(&tile, cm, tile_row);
862     for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
863          mi_row += MI_BLOCK_SIZE) {
864       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
865         const int col = pbi->inv_tile_order ?
866                         tile_cols - tile_col - 1 : tile_col;
867         tile_data = pbi->tile_data + tile_cols * tile_row + col;
868         vp9_tile_set_col(&tile, tile_data->cm, col);
869         vp9_zero(tile_data->xd.left_context);
870         vp9_zero(tile_data->xd.left_seg_context);
871         for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
872              mi_col += MI_BLOCK_SIZE) {
873           decode_partition(tile_data->cm, &tile_data->xd, &tile, mi_row, mi_col,
874                            &tile_data->bit_reader, BLOCK_64X64);
875         }
876         pbi->mb.corrupted |= tile_data->xd.corrupted;
877       }
878       // Loopfilter one row.
879       if (cm->lf.filter_level) {
880         const int lf_start = mi_row - MI_BLOCK_SIZE;
881         LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
882
883         // delay the loopfilter by 1 macroblock row.
884         if (lf_start < 0) continue;
885
886         // decoding has completed: finish up the loop filter in this thread.
887         if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
888
889         winterface->sync(&pbi->lf_worker);
890         lf_data->start = lf_start;
891         lf_data->stop = mi_row;
892         if (pbi->max_threads > 1) {
893           winterface->launch(&pbi->lf_worker);
894         } else {
895           winterface->execute(&pbi->lf_worker);
896         }
897       }
898     }
899   }
900
901   // Loopfilter remaining rows in the frame.
902   if (cm->lf.filter_level) {
903     LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
904     winterface->sync(&pbi->lf_worker);
905     lf_data->start = lf_data->stop;
906     lf_data->stop = cm->mi_rows;
907     winterface->execute(&pbi->lf_worker);
908   }
909
910   // Get last tile data.
911   tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
912
913   return vp9_reader_find_end(&tile_data->bit_reader);
914 }
915
916 static int tile_worker_hook(void *arg1, void *arg2) {
917   TileWorkerData *const tile_data = (TileWorkerData*)arg1;
918   const TileInfo *const tile = (TileInfo*)arg2;
919   int mi_row, mi_col;
920
921   for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
922        mi_row += MI_BLOCK_SIZE) {
923     vp9_zero(tile_data->xd.left_context);
924     vp9_zero(tile_data->xd.left_seg_context);
925     for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
926          mi_col += MI_BLOCK_SIZE) {
927       decode_partition(tile_data->cm, &tile_data->xd, tile,
928                        mi_row, mi_col, &tile_data->bit_reader, BLOCK_64X64);
929     }
930   }
931   return !tile_data->xd.corrupted;
932 }
933
934 // sorts in descending order
935 static int compare_tile_buffers(const void *a, const void *b) {
936   const TileBuffer *const buf1 = (const TileBuffer*)a;
937   const TileBuffer *const buf2 = (const TileBuffer*)b;
938   if (buf1->size < buf2->size) {
939     return 1;
940   } else if (buf1->size == buf2->size) {
941     return 0;
942   } else {
943     return -1;
944   }
945 }
946
947 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
948                                       const uint8_t *data,
949                                       const uint8_t *data_end) {
950   VP9_COMMON *const cm = &pbi->common;
951   const VP9WorkerInterface *const winterface = vp9_get_worker_interface();
952   const uint8_t *bit_reader_end = NULL;
953   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
954   const int tile_cols = 1 << cm->log2_tile_cols;
955   const int tile_rows = 1 << cm->log2_tile_rows;
956   const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
957   TileBuffer tile_buffers[1][1 << 6];
958   int n;
959   int final_worker = -1;
960
961   assert(tile_cols <= (1 << 6));
962   assert(tile_rows == 1);
963   (void)tile_rows;
964
965   // TODO(jzern): See if we can remove the restriction of passing in max
966   // threads to the decoder.
967   if (pbi->num_tile_workers == 0) {
968     const int num_threads = pbi->max_threads & ~1;
969     int i;
970     // TODO(jzern): Allocate one less worker, as in the current code we only
971     // use num_threads - 1 workers.
972     CHECK_MEM_ERROR(cm, pbi->tile_workers,
973                     vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
974     for (i = 0; i < num_threads; ++i) {
975       VP9Worker *const worker = &pbi->tile_workers[i];
976       ++pbi->num_tile_workers;
977
978       winterface->init(worker);
979       CHECK_MEM_ERROR(cm, worker->data1,
980                       vpx_memalign(32, sizeof(TileWorkerData)));
981       CHECK_MEM_ERROR(cm, worker->data2, vpx_malloc(sizeof(TileInfo)));
982       if (i < num_threads - 1 && !winterface->reset(worker)) {
983         vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
984                            "Tile decoder thread creation failed");
985       }
986     }
987   }
988
989   // Reset tile decoding hook
990   for (n = 0; n < num_workers; ++n) {
991     pbi->tile_workers[n].hook = (VP9WorkerHook)tile_worker_hook;
992   }
993
994   // Note: this memset assumes above_context[0], [1] and [2]
995   // are allocated as part of the same buffer.
996   vpx_memset(cm->above_context, 0,
997              sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
998   vpx_memset(cm->above_seg_context, 0,
999              sizeof(*cm->above_seg_context) * aligned_mi_cols);
1000
1001   // Load tile data into tile_buffers
1002   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1003
1004   // Sort the buffers based on size in descending order.
1005   qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1006         compare_tile_buffers);
1007
1008   // Rearrange the tile buffers such that per-tile group the largest, and
1009   // presumably the most difficult, tile will be decoded in the main thread.
1010   // This should help minimize the number of instances where the main thread is
1011   // waiting for a worker to complete.
1012   {
1013     int group_start = 0;
1014     while (group_start < tile_cols) {
1015       const TileBuffer largest = tile_buffers[0][group_start];
1016       const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1017       memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1018               (group_end - group_start) * sizeof(tile_buffers[0][0]));
1019       tile_buffers[0][group_end] = largest;
1020       group_start = group_end + 1;
1021     }
1022   }
1023
1024   n = 0;
1025   while (n < tile_cols) {
1026     int i;
1027     for (i = 0; i < num_workers && n < tile_cols; ++i) {
1028       VP9Worker *const worker = &pbi->tile_workers[i];
1029       TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1030       TileInfo *const tile = (TileInfo*)worker->data2;
1031       TileBuffer *const buf = &tile_buffers[0][n];
1032
1033       tile_data->cm = cm;
1034       tile_data->xd = pbi->mb;
1035       tile_data->xd.corrupted = 0;
1036       vp9_tile_init(tile, tile_data->cm, 0, buf->col);
1037       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1038                           &tile_data->bit_reader, pbi->decrypt_cb,
1039                           pbi->decrypt_state);
1040       init_macroblockd(cm, &tile_data->xd);
1041       vp9_zero(tile_data->xd.dqcoeff);
1042
1043       worker->had_error = 0;
1044       if (i == num_workers - 1 || n == tile_cols - 1) {
1045         winterface->execute(worker);
1046       } else {
1047         winterface->launch(worker);
1048       }
1049
1050       if (buf->col == tile_cols - 1) {
1051         final_worker = i;
1052       }
1053
1054       ++n;
1055     }
1056
1057     for (; i > 0; --i) {
1058       VP9Worker *const worker = &pbi->tile_workers[i - 1];
1059       pbi->mb.corrupted |= !winterface->sync(worker);
1060     }
1061     if (final_worker > -1) {
1062       TileWorkerData *const tile_data =
1063           (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1064       bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1065       final_worker = -1;
1066     }
1067   }
1068
1069   return bit_reader_end;
1070 }
1071
1072 static void error_handler(void *data) {
1073   VP9_COMMON *const cm = (VP9_COMMON *)data;
1074   vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1075 }
1076
1077 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
1078   return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
1079          vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
1080          vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
1081 }
1082
1083 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
1084   int profile = vp9_rb_read_bit(rb);
1085   profile |= vp9_rb_read_bit(rb) << 1;
1086   if (profile > 2)
1087     profile += vp9_rb_read_bit(rb);
1088   return (BITSTREAM_PROFILE) profile;
1089 }
1090
1091 static size_t read_uncompressed_header(VP9Decoder *pbi,
1092                                        struct vp9_read_bit_buffer *rb) {
1093   VP9_COMMON *const cm = &pbi->common;
1094   size_t sz;
1095   int i;
1096
1097   cm->last_frame_type = cm->frame_type;
1098
1099   if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1100       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1101                          "Invalid frame marker");
1102
1103   cm->profile = vp9_read_profile(rb);
1104   if (cm->profile >= MAX_PROFILES)
1105     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1106                        "Unsupported bitstream profile");
1107
1108   cm->show_existing_frame = vp9_rb_read_bit(rb);
1109   if (cm->show_existing_frame) {
1110     // Show an existing frame directly.
1111     const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1112
1113     if (frame_to_show < 0 || cm->frame_bufs[frame_to_show].ref_count < 1)
1114       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1115                          "Buffer %d does not contain a decoded frame",
1116                          frame_to_show);
1117
1118     ref_cnt_fb(cm->frame_bufs, &cm->new_fb_idx, frame_to_show);
1119     pbi->refresh_frame_flags = 0;
1120     cm->lf.filter_level = 0;
1121     cm->show_frame = 1;
1122     return 0;
1123   }
1124
1125   cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1126   cm->show_frame = vp9_rb_read_bit(rb);
1127   cm->error_resilient_mode = vp9_rb_read_bit(rb);
1128
1129   if (cm->frame_type == KEY_FRAME) {
1130     if (!vp9_read_sync_code(rb))
1131       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1132                          "Invalid frame sync code");
1133     if (cm->profile > PROFILE_1)
1134       cm->bit_depth = vp9_rb_read_bit(rb) ? BITS_12 : BITS_10;
1135     cm->color_space = (COLOR_SPACE)vp9_rb_read_literal(rb, 3);
1136     if (cm->color_space != SRGB) {
1137       vp9_rb_read_bit(rb);  // [16,235] (including xvycc) vs [0,255] range
1138       if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1139         cm->subsampling_x = vp9_rb_read_bit(rb);
1140         cm->subsampling_y = vp9_rb_read_bit(rb);
1141         if (vp9_rb_read_bit(rb))
1142           vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1143                              "Reserved bit set");
1144       } else {
1145         cm->subsampling_y = cm->subsampling_x = 1;
1146       }
1147     } else {
1148       if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1149         cm->subsampling_y = cm->subsampling_x = 0;
1150         if (vp9_rb_read_bit(rb))
1151           vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1152                              "Reserved bit set");
1153       } else {
1154         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1155                            "4:4:4 color not supported in profile 0");
1156       }
1157     }
1158
1159     pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1160
1161     for (i = 0; i < REFS_PER_FRAME; ++i) {
1162       cm->frame_refs[i].idx = -1;
1163       cm->frame_refs[i].buf = NULL;
1164     }
1165
1166     setup_frame_size(cm, rb);
1167   } else {
1168     cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1169
1170     cm->reset_frame_context = cm->error_resilient_mode ?
1171         0 : vp9_rb_read_literal(rb, 2);
1172
1173     if (cm->intra_only) {
1174       if (!vp9_read_sync_code(rb))
1175         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1176                            "Invalid frame sync code");
1177
1178       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1179
1180       // NOTE: The intra-only frame header does not include the specification of
1181       // either the color format or color sub-sampling. VP9 specifies that the
1182       // default color space should be YUV 4:2:0 in this case (normative).
1183       cm->color_space = BT_601;
1184       cm->subsampling_y = cm->subsampling_x = 1;
1185
1186       setup_frame_size(cm, rb);
1187     } else {
1188       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1189       for (i = 0; i < REFS_PER_FRAME; ++i) {
1190         const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1191         const int idx = cm->ref_frame_map[ref];
1192         RefBuffer *const ref_frame = &cm->frame_refs[i];
1193         ref_frame->idx = idx;
1194         ref_frame->buf = &cm->frame_bufs[idx].buf;
1195         cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1196       }
1197
1198       setup_frame_size_with_refs(cm, rb);
1199
1200       cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1201       cm->interp_filter = read_interp_filter(rb);
1202
1203       for (i = 0; i < REFS_PER_FRAME; ++i) {
1204         RefBuffer *const ref_buf = &cm->frame_refs[i];
1205         vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1206                                           ref_buf->buf->y_crop_width,
1207                                           ref_buf->buf->y_crop_height,
1208                                           cm->width, cm->height);
1209         if (vp9_is_scaled(&ref_buf->sf))
1210           vp9_extend_frame_borders(ref_buf->buf);
1211       }
1212     }
1213   }
1214
1215   if (!cm->error_resilient_mode) {
1216     cm->coding_use_prev_mi = 1;
1217     cm->refresh_frame_context = vp9_rb_read_bit(rb);
1218     cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
1219   } else {
1220     cm->coding_use_prev_mi = 0;
1221     cm->refresh_frame_context = 0;
1222     cm->frame_parallel_decoding_mode = 1;
1223   }
1224
1225   // This flag will be overridden by the call to vp9_setup_past_independence
1226   // below, forcing the use of context 0 for those frame types.
1227   cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1228
1229   if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1230     vp9_setup_past_independence(cm);
1231
1232   setup_loopfilter(&cm->lf, rb);
1233   setup_quantization(cm, &pbi->mb, rb);
1234   setup_segmentation(&cm->seg, rb);
1235
1236   setup_tile_info(cm, rb);
1237   sz = vp9_rb_read_literal(rb, 16);
1238
1239   if (sz == 0)
1240     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1241                        "Invalid header size");
1242
1243   return sz;
1244 }
1245
1246 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
1247                                   size_t partition_size) {
1248   VP9_COMMON *const cm = &pbi->common;
1249   MACROBLOCKD *const xd = &pbi->mb;
1250   FRAME_CONTEXT *const fc = &cm->fc;
1251   vp9_reader r;
1252   int k;
1253
1254   if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
1255                       pbi->decrypt_state))
1256     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1257                        "Failed to allocate bool decoder 0");
1258
1259   cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1260   if (cm->tx_mode == TX_MODE_SELECT)
1261     read_tx_mode_probs(&fc->tx_probs, &r);
1262   read_coef_probs(fc, cm->tx_mode, &r);
1263
1264   for (k = 0; k < SKIP_CONTEXTS; ++k)
1265     vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1266
1267   if (!frame_is_intra_only(cm)) {
1268     nmv_context *const nmvc = &fc->nmvc;
1269     int i, j;
1270
1271     read_inter_mode_probs(fc, &r);
1272
1273     if (cm->interp_filter == SWITCHABLE)
1274       read_switchable_interp_probs(fc, &r);
1275
1276     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1277       vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1278
1279     cm->reference_mode = read_frame_reference_mode(cm, &r);
1280     if (cm->reference_mode != SINGLE_REFERENCE)
1281       setup_compound_reference_mode(cm);
1282     read_frame_reference_mode_probs(cm, &r);
1283
1284     for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1285       for (i = 0; i < INTRA_MODES - 1; ++i)
1286         vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1287
1288     for (j = 0; j < PARTITION_CONTEXTS; ++j)
1289       for (i = 0; i < PARTITION_TYPES - 1; ++i)
1290         vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1291
1292     read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
1293   }
1294
1295   return vp9_reader_has_error(&r);
1296 }
1297
1298 void vp9_init_dequantizer(VP9_COMMON *cm) {
1299   int q;
1300
1301   for (q = 0; q < QINDEX_RANGE; q++) {
1302     cm->y_dequant[q][0] = vp9_dc_quant(q, cm->y_dc_delta_q);
1303     cm->y_dequant[q][1] = vp9_ac_quant(q, 0);
1304
1305     cm->uv_dequant[q][0] = vp9_dc_quant(q, cm->uv_dc_delta_q);
1306     cm->uv_dequant[q][1] = vp9_ac_quant(q, cm->uv_ac_delta_q);
1307   }
1308 }
1309
1310 #ifdef NDEBUG
1311 #define debug_check_frame_counts(cm) (void)0
1312 #else  // !NDEBUG
1313 // Counts should only be incremented when frame_parallel_decoding_mode and
1314 // error_resilient_mode are disabled.
1315 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
1316   FRAME_COUNTS zero_counts;
1317   vp9_zero(zero_counts);
1318   assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
1319   assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
1320                  sizeof(cm->counts.y_mode)));
1321   assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
1322                  sizeof(cm->counts.uv_mode)));
1323   assert(!memcmp(cm->counts.partition, zero_counts.partition,
1324                  sizeof(cm->counts.partition)));
1325   assert(!memcmp(cm->counts.coef, zero_counts.coef,
1326                  sizeof(cm->counts.coef)));
1327   assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
1328                  sizeof(cm->counts.eob_branch)));
1329   assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
1330                  sizeof(cm->counts.switchable_interp)));
1331   assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
1332                  sizeof(cm->counts.inter_mode)));
1333   assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
1334                  sizeof(cm->counts.intra_inter)));
1335   assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
1336                  sizeof(cm->counts.comp_inter)));
1337   assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
1338                  sizeof(cm->counts.single_ref)));
1339   assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
1340                  sizeof(cm->counts.comp_ref)));
1341   assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
1342   assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
1343   assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
1344 }
1345 #endif  // NDEBUG
1346
1347 static struct vp9_read_bit_buffer* init_read_bit_buffer(
1348     VP9Decoder *pbi,
1349     struct vp9_read_bit_buffer *rb,
1350     const uint8_t *data,
1351     const uint8_t *data_end,
1352     uint8_t *clear_data /* buffer size MAX_VP9_HEADER_SIZE */) {
1353   rb->bit_offset = 0;
1354   rb->error_handler = error_handler;
1355   rb->error_handler_data = &pbi->common;
1356   if (pbi->decrypt_cb) {
1357     const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
1358     pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
1359     rb->bit_buffer = clear_data;
1360     rb->bit_buffer_end = clear_data + n;
1361   } else {
1362     rb->bit_buffer = data;
1363     rb->bit_buffer_end = data_end;
1364   }
1365   return rb;
1366 }
1367
1368 void vp9_decode_frame(VP9Decoder *pbi,
1369                       const uint8_t *data, const uint8_t *data_end,
1370                       const uint8_t **p_data_end) {
1371   VP9_COMMON *const cm = &pbi->common;
1372   MACROBLOCKD *const xd = &pbi->mb;
1373   struct vp9_read_bit_buffer rb = { NULL, NULL, 0, NULL, 0};
1374
1375   uint8_t clear_data[MAX_VP9_HEADER_SIZE];
1376   const size_t first_partition_size = read_uncompressed_header(pbi,
1377       init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
1378   const int tile_rows = 1 << cm->log2_tile_rows;
1379   const int tile_cols = 1 << cm->log2_tile_cols;
1380   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
1381   xd->cur_buf = new_fb;
1382
1383   if (!first_partition_size) {
1384     // showing a frame directly
1385     *p_data_end = data + 1;
1386     return;
1387   }
1388
1389   data += vp9_rb_bytes_read(&rb);
1390   if (!read_is_valid(data, first_partition_size, data_end))
1391     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1392                        "Truncated packet or corrupt header length");
1393
1394   init_macroblockd(cm, &pbi->mb);
1395
1396   if (cm->coding_use_prev_mi)
1397     set_prev_mi(cm);
1398   else
1399     cm->prev_mi = NULL;
1400
1401   setup_plane_dequants(cm, xd, cm->base_qindex);
1402   vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
1403
1404   cm->fc = cm->frame_contexts[cm->frame_context_idx];
1405   vp9_zero(cm->counts);
1406   vp9_zero(xd->dqcoeff);
1407
1408   xd->corrupted = 0;
1409   new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
1410
1411   // TODO(jzern): remove frame_parallel_decoding_mode restriction for
1412   // single-frame tile decoding.
1413   if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1 &&
1414       cm->frame_parallel_decoding_mode) {
1415     *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
1416     // If multiple threads are used to decode tiles, then we use those threads
1417     // to do parallel loopfiltering.
1418     vp9_loop_filter_frame_mt(new_fb, pbi, cm, cm->lf.filter_level, 0);
1419   } else {
1420     *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
1421   }
1422
1423   new_fb->corrupted |= xd->corrupted;
1424
1425   if (!new_fb->corrupted) {
1426     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
1427       vp9_adapt_coef_probs(cm);
1428
1429       if (!frame_is_intra_only(cm)) {
1430         vp9_adapt_mode_probs(cm);
1431         vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
1432       }
1433     } else {
1434       debug_check_frame_counts(cm);
1435     }
1436   } else {
1437     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1438                        "Decode failed. Frame data is corrupted.");
1439   }
1440
1441   if (cm->refresh_frame_context)
1442     cm->frame_contexts[cm->frame_context_idx] = cm->fc;
1443 }