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