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