]> granicus.if.org Git - libvpx/blob - vp9/decoder/vp9_decodeframe.c
subpel variance neon: add mixed sizes
[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_dsp_rtcd.h"
16 #include "./vpx_scale_rtcd.h"
17
18 #include "vpx_dsp/bitreader_buffer.h"
19 #include "vpx_dsp/bitreader.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_mem/vpx_mem.h"
22 #include "vpx_ports/mem.h"
23 #include "vpx_ports/mem_ops.h"
24 #include "vpx_scale/vpx_scale.h"
25 #include "vpx_util/vpx_thread.h"
26
27 #include "vp9/common/vp9_alloccommon.h"
28 #include "vp9/common/vp9_common.h"
29 #include "vp9/common/vp9_entropy.h"
30 #include "vp9/common/vp9_entropymode.h"
31 #include "vp9/common/vp9_idct.h"
32 #include "vp9/common/vp9_thread_common.h"
33 #include "vp9/common/vp9_pred_common.h"
34 #include "vp9/common/vp9_quant_common.h"
35 #include "vp9/common/vp9_reconintra.h"
36 #include "vp9/common/vp9_reconinter.h"
37 #include "vp9/common/vp9_seg_common.h"
38 #include "vp9/common/vp9_tile_common.h"
39
40 #include "vp9/decoder/vp9_decodeframe.h"
41 #include "vp9/decoder/vp9_detokenize.h"
42 #include "vp9/decoder/vp9_decodemv.h"
43 #include "vp9/decoder/vp9_decoder.h"
44 #include "vp9/decoder/vp9_dsubexp.h"
45
46 #define MAX_VP9_HEADER_SIZE 80
47
48 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
49   int i;
50   for (i = 1; i < REFS_PER_FRAME; ++i)
51     if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1]) return 1;
52
53   return 0;
54 }
55
56 static void setup_compound_reference_mode(VP9_COMMON *cm) {
57   if (cm->ref_frame_sign_bias[LAST_FRAME] ==
58       cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
59     cm->comp_fixed_ref = ALTREF_FRAME;
60     cm->comp_var_ref[0] = LAST_FRAME;
61     cm->comp_var_ref[1] = GOLDEN_FRAME;
62   } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
63              cm->ref_frame_sign_bias[ALTREF_FRAME]) {
64     cm->comp_fixed_ref = GOLDEN_FRAME;
65     cm->comp_var_ref[0] = LAST_FRAME;
66     cm->comp_var_ref[1] = ALTREF_FRAME;
67   } else {
68     cm->comp_fixed_ref = LAST_FRAME;
69     cm->comp_var_ref[0] = GOLDEN_FRAME;
70     cm->comp_var_ref[1] = ALTREF_FRAME;
71   }
72 }
73
74 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
75   return len != 0 && len <= (size_t)(end - start);
76 }
77
78 static int decode_unsigned_max(struct vpx_read_bit_buffer *rb, int max) {
79   const int data = vpx_rb_read_literal(rb, get_unsigned_bits(max));
80   return data > max ? max : data;
81 }
82
83 static TX_MODE read_tx_mode(vpx_reader *r) {
84   TX_MODE tx_mode = vpx_read_literal(r, 2);
85   if (tx_mode == ALLOW_32X32) tx_mode += vpx_read_bit(r);
86   return tx_mode;
87 }
88
89 static void read_tx_mode_probs(struct tx_probs *tx_probs, vpx_reader *r) {
90   int i, j;
91
92   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
93     for (j = 0; j < TX_SIZES - 3; ++j)
94       vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
95
96   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
97     for (j = 0; j < TX_SIZES - 2; ++j)
98       vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
99
100   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
101     for (j = 0; j < TX_SIZES - 1; ++j)
102       vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
103 }
104
105 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vpx_reader *r) {
106   int i, j;
107   for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
108     for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
109       vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
110 }
111
112 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vpx_reader *r) {
113   int i, j;
114   for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
115     for (j = 0; j < INTER_MODES - 1; ++j)
116       vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
117 }
118
119 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
120                                                 vpx_reader *r) {
121   if (is_compound_reference_allowed(cm)) {
122     return vpx_read_bit(r)
123                ? (vpx_read_bit(r) ? REFERENCE_MODE_SELECT : COMPOUND_REFERENCE)
124                : SINGLE_REFERENCE;
125   } else {
126     return SINGLE_REFERENCE;
127   }
128 }
129
130 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vpx_reader *r) {
131   FRAME_CONTEXT *const fc = cm->fc;
132   int i;
133
134   if (cm->reference_mode == REFERENCE_MODE_SELECT)
135     for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
136       vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
137
138   if (cm->reference_mode != COMPOUND_REFERENCE)
139     for (i = 0; i < REF_CONTEXTS; ++i) {
140       vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
141       vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
142     }
143
144   if (cm->reference_mode != SINGLE_REFERENCE)
145     for (i = 0; i < REF_CONTEXTS; ++i)
146       vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
147 }
148
149 static void update_mv_probs(vpx_prob *p, int n, vpx_reader *r) {
150   int i;
151   for (i = 0; i < n; ++i)
152     if (vpx_read(r, MV_UPDATE_PROB)) p[i] = (vpx_read_literal(r, 7) << 1) | 1;
153 }
154
155 static void read_mv_probs(nmv_context *ctx, int allow_hp, vpx_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 inverse_transform_block_inter(MACROBLOCKD *xd, int plane,
185                                           const TX_SIZE tx_size, uint8_t *dst,
186                                           int stride, int eob) {
187   struct macroblockd_plane *const pd = &xd->plane[plane];
188   tran_low_t *const dqcoeff = pd->dqcoeff;
189   assert(eob > 0);
190 #if CONFIG_VP9_HIGHBITDEPTH
191   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
192     if (xd->lossless) {
193       vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
194     } else {
195       switch (tx_size) {
196         case TX_4X4:
197           vp9_highbd_idct4x4_add(dqcoeff, dst, stride, eob, xd->bd);
198           break;
199         case TX_8X8:
200           vp9_highbd_idct8x8_add(dqcoeff, dst, stride, eob, xd->bd);
201           break;
202         case TX_16X16:
203           vp9_highbd_idct16x16_add(dqcoeff, dst, stride, eob, xd->bd);
204           break;
205         case TX_32X32:
206           vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
207           break;
208         default: assert(0 && "Invalid transform size");
209       }
210     }
211   } else {
212     if (xd->lossless) {
213       vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
214     } else {
215       switch (tx_size) {
216         case TX_4X4: vp9_idct4x4_add(dqcoeff, dst, stride, eob); break;
217         case TX_8X8: vp9_idct8x8_add(dqcoeff, dst, stride, eob); break;
218         case TX_16X16: vp9_idct16x16_add(dqcoeff, dst, stride, eob); break;
219         case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
220         default: assert(0 && "Invalid transform size"); return;
221       }
222     }
223   }
224 #else
225   if (xd->lossless) {
226     vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
227   } else {
228     switch (tx_size) {
229       case TX_4X4: vp9_idct4x4_add(dqcoeff, dst, stride, eob); break;
230       case TX_8X8: vp9_idct8x8_add(dqcoeff, dst, stride, eob); break;
231       case TX_16X16: vp9_idct16x16_add(dqcoeff, dst, stride, eob); break;
232       case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
233       default: assert(0 && "Invalid transform size"); return;
234     }
235   }
236 #endif  // CONFIG_VP9_HIGHBITDEPTH
237
238   if (eob == 1) {
239     dqcoeff[0] = 0;
240   } else {
241     if (tx_size <= TX_16X16 && eob <= 10)
242       memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
243     else if (tx_size == TX_32X32 && eob <= 34)
244       memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
245     else
246       memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
247   }
248 }
249
250 static void inverse_transform_block_intra(MACROBLOCKD *xd, int plane,
251                                           const TX_TYPE tx_type,
252                                           const TX_SIZE tx_size, uint8_t *dst,
253                                           int stride, int eob) {
254   struct macroblockd_plane *const pd = &xd->plane[plane];
255   tran_low_t *const dqcoeff = pd->dqcoeff;
256   assert(eob > 0);
257 #if CONFIG_VP9_HIGHBITDEPTH
258   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
259     if (xd->lossless) {
260       vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
261     } else {
262       switch (tx_size) {
263         case TX_4X4:
264           vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
265           break;
266         case TX_8X8:
267           vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
268           break;
269         case TX_16X16:
270           vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
271           break;
272         case TX_32X32:
273           vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
274           break;
275         default: assert(0 && "Invalid transform size");
276       }
277     }
278   } else {
279     if (xd->lossless) {
280       vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
281     } else {
282       switch (tx_size) {
283         case TX_4X4: vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob); break;
284         case TX_8X8: vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob); break;
285         case TX_16X16:
286           vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
287           break;
288         case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
289         default: assert(0 && "Invalid transform size"); return;
290       }
291     }
292   }
293 #else
294   if (xd->lossless) {
295     vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
296   } else {
297     switch (tx_size) {
298       case TX_4X4: vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob); break;
299       case TX_8X8: vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob); break;
300       case TX_16X16:
301         vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
302         break;
303       case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
304       default: assert(0 && "Invalid transform size"); return;
305     }
306   }
307 #endif  // CONFIG_VP9_HIGHBITDEPTH
308
309   if (eob == 1) {
310     dqcoeff[0] = 0;
311   } else {
312     if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
313       memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
314     else if (tx_size == TX_32X32 && eob <= 34)
315       memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
316     else
317       memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
318   }
319 }
320
321 static void predict_and_reconstruct_intra_block(TileWorkerData *twd,
322                                                 MODE_INFO *const mi, int plane,
323                                                 int row, int col,
324                                                 TX_SIZE tx_size) {
325   MACROBLOCKD *const xd = &twd->xd;
326   struct macroblockd_plane *const pd = &xd->plane[plane];
327   PREDICTION_MODE mode = (plane == 0) ? mi->mode : mi->uv_mode;
328   uint8_t *dst;
329   dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col];
330
331   if (mi->sb_type < BLOCK_8X8)
332     if (plane == 0) mode = xd->mi[0]->bmi[(row << 1) + col].as_mode;
333
334   vp9_predict_intra_block(xd, pd->n4_wl, tx_size, mode, dst, pd->dst.stride,
335                           dst, pd->dst.stride, col, row, plane);
336
337   if (!mi->skip) {
338     const TX_TYPE tx_type =
339         (plane || xd->lossless) ? DCT_DCT : intra_mode_to_tx_type_lookup[mode];
340     const scan_order *sc = (plane || xd->lossless)
341                                ? &vp9_default_scan_orders[tx_size]
342                                : &vp9_scan_orders[tx_size][tx_type];
343     const int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size,
344                                             mi->segment_id);
345     if (eob > 0) {
346       inverse_transform_block_intra(xd, plane, tx_type, tx_size, dst,
347                                     pd->dst.stride, eob);
348     }
349   }
350 }
351
352 static int reconstruct_inter_block(TileWorkerData *twd, MODE_INFO *const mi,
353                                    int plane, int row, int col,
354                                    TX_SIZE tx_size) {
355   MACROBLOCKD *const xd = &twd->xd;
356   struct macroblockd_plane *const pd = &xd->plane[plane];
357   const scan_order *sc = &vp9_default_scan_orders[tx_size];
358   const int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size,
359                                           mi->segment_id);
360
361   if (eob > 0) {
362     inverse_transform_block_inter(
363         xd, plane, tx_size, &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
364         pd->dst.stride, eob);
365   }
366   return eob;
367 }
368
369 static void build_mc_border(const uint8_t *src, int src_stride, uint8_t *dst,
370                             int dst_stride, int x, int y, int b_w, int b_h,
371                             int w, int h) {
372   // Get a pointer to the start of the real data for this row.
373   const uint8_t *ref_row = src - x - y * src_stride;
374
375   if (y >= h)
376     ref_row += (h - 1) * src_stride;
377   else if (y > 0)
378     ref_row += y * src_stride;
379
380   do {
381     int right = 0, copy;
382     int left = x < 0 ? -x : 0;
383
384     if (left > b_w) left = b_w;
385
386     if (x + b_w > w) right = x + b_w - w;
387
388     if (right > b_w) right = b_w;
389
390     copy = b_w - left - right;
391
392     if (left) memset(dst, ref_row[0], left);
393
394     if (copy) memcpy(dst + left, ref_row + x + left, copy);
395
396     if (right) memset(dst + left + copy, ref_row[w - 1], right);
397
398     dst += dst_stride;
399     ++y;
400
401     if (y > 0 && y < h) ref_row += src_stride;
402   } while (--b_h);
403 }
404
405 #if CONFIG_VP9_HIGHBITDEPTH
406 static void high_build_mc_border(const uint8_t *src8, int src_stride,
407                                  uint16_t *dst, int dst_stride, int x, int y,
408                                  int b_w, int b_h, int w, int h) {
409   // Get a pointer to the start of the real data for this row.
410   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
411   const uint16_t *ref_row = src - x - y * src_stride;
412
413   if (y >= h)
414     ref_row += (h - 1) * src_stride;
415   else if (y > 0)
416     ref_row += y * src_stride;
417
418   do {
419     int right = 0, copy;
420     int left = x < 0 ? -x : 0;
421
422     if (left > b_w) left = b_w;
423
424     if (x + b_w > w) right = x + b_w - w;
425
426     if (right > b_w) right = b_w;
427
428     copy = b_w - left - right;
429
430     if (left) vpx_memset16(dst, ref_row[0], left);
431
432     if (copy) memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
433
434     if (right) vpx_memset16(dst + left + copy, ref_row[w - 1], right);
435
436     dst += dst_stride;
437     ++y;
438
439     if (y > 0 && y < h) ref_row += src_stride;
440   } while (--b_h);
441 }
442 #endif  // CONFIG_VP9_HIGHBITDEPTH
443
444 #if CONFIG_VP9_HIGHBITDEPTH
445 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
446                                int x0, int y0, int b_w, int b_h,
447                                int frame_width, int frame_height,
448                                int border_offset, uint8_t *const dst,
449                                int dst_buf_stride, int subpel_x, int subpel_y,
450                                const InterpKernel *kernel,
451                                const struct scale_factors *sf, MACROBLOCKD *xd,
452                                int w, int h, int ref, int xs, int ys) {
453   DECLARE_ALIGNED(16, uint16_t, mc_buf_high[80 * 2 * 80 * 2]);
454
455   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
456     high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w, x0, y0,
457                          b_w, b_h, frame_width, frame_height);
458     highbd_inter_predictor(mc_buf_high + border_offset, b_w,
459                            CONVERT_TO_SHORTPTR(dst), dst_buf_stride, subpel_x,
460                            subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
461   } else {
462     build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w, x0,
463                     y0, b_w, b_h, frame_width, frame_height);
464     inter_predictor(((uint8_t *)mc_buf_high) + border_offset, b_w, dst,
465                     dst_buf_stride, subpel_x, subpel_y, sf, w, h, ref, kernel,
466                     xs, ys);
467   }
468 }
469 #else
470 static void extend_and_predict(const uint8_t *buf_ptr1, int pre_buf_stride,
471                                int x0, int y0, int b_w, int b_h,
472                                int frame_width, int frame_height,
473                                int border_offset, uint8_t *const dst,
474                                int dst_buf_stride, int subpel_x, int subpel_y,
475                                const InterpKernel *kernel,
476                                const struct scale_factors *sf, int w, int h,
477                                int ref, int xs, int ys) {
478   DECLARE_ALIGNED(16, uint8_t, mc_buf[80 * 2 * 80 * 2]);
479   const uint8_t *buf_ptr;
480
481   build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w, x0, y0, b_w, b_h,
482                   frame_width, frame_height);
483   buf_ptr = mc_buf + border_offset;
484
485   inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x, subpel_y, sf, w,
486                   h, ref, kernel, xs, ys);
487 }
488 #endif  // CONFIG_VP9_HIGHBITDEPTH
489
490 static void dec_build_inter_predictors(
491     VPxWorker *const worker, MACROBLOCKD *xd, int plane, int bw, int bh, int x,
492     int y, int w, int h, int mi_x, int mi_y, const InterpKernel *kernel,
493     const struct scale_factors *sf, struct buf_2d *pre_buf,
494     struct buf_2d *dst_buf, const MV *mv, RefCntBuffer *ref_frame_buf,
495     int is_scaled, int ref) {
496   struct macroblockd_plane *const pd = &xd->plane[plane];
497   uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
498   MV32 scaled_mv;
499   int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height, buf_stride,
500       subpel_x, subpel_y;
501   uint8_t *ref_frame, *buf_ptr;
502
503   // Get reference frame pointer, width and height.
504   if (plane == 0) {
505     frame_width = ref_frame_buf->buf.y_crop_width;
506     frame_height = ref_frame_buf->buf.y_crop_height;
507     ref_frame = ref_frame_buf->buf.y_buffer;
508   } else {
509     frame_width = ref_frame_buf->buf.uv_crop_width;
510     frame_height = ref_frame_buf->buf.uv_crop_height;
511     ref_frame =
512         plane == 1 ? ref_frame_buf->buf.u_buffer : ref_frame_buf->buf.v_buffer;
513   }
514
515   if (is_scaled) {
516     const MV mv_q4 = clamp_mv_to_umv_border_sb(
517         xd, mv, bw, bh, pd->subsampling_x, pd->subsampling_y);
518     // Co-ordinate of containing block to pixel precision.
519     int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
520     int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
521 #if 0  // CONFIG_BETTER_HW_COMPATIBILITY
522     assert(xd->mi[0]->sb_type != BLOCK_4X8 &&
523            xd->mi[0]->sb_type != BLOCK_8X4);
524     assert(mv_q4.row == mv->row * (1 << (1 - pd->subsampling_y)) &&
525            mv_q4.col == mv->col * (1 << (1 - pd->subsampling_x)));
526 #endif
527     // Co-ordinate of the block to 1/16th pixel precision.
528     x0_16 = (x_start + x) << SUBPEL_BITS;
529     y0_16 = (y_start + y) << SUBPEL_BITS;
530
531     // Co-ordinate of current block in reference frame
532     // to 1/16th pixel precision.
533     x0_16 = sf->scale_value_x(x0_16, sf);
534     y0_16 = sf->scale_value_y(y0_16, sf);
535
536     // Map the top left corner of the block into the reference frame.
537     x0 = sf->scale_value_x(x_start + x, sf);
538     y0 = sf->scale_value_y(y_start + y, sf);
539
540     // Scale the MV and incorporate the sub-pixel offset of the block
541     // in the reference frame.
542     scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
543     xs = sf->x_step_q4;
544     ys = sf->y_step_q4;
545   } else {
546     // Co-ordinate of containing block to pixel precision.
547     x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
548     y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
549
550     // Co-ordinate of the block to 1/16th pixel precision.
551     x0_16 = x0 << SUBPEL_BITS;
552     y0_16 = y0 << SUBPEL_BITS;
553
554     scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
555     scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
556     xs = ys = 16;
557   }
558   subpel_x = scaled_mv.col & SUBPEL_MASK;
559   subpel_y = scaled_mv.row & SUBPEL_MASK;
560
561   // Calculate the top left corner of the best matching block in the
562   // reference frame.
563   x0 += scaled_mv.col >> SUBPEL_BITS;
564   y0 += scaled_mv.row >> SUBPEL_BITS;
565   x0_16 += scaled_mv.col;
566   y0_16 += scaled_mv.row;
567
568   // Get reference block pointer.
569   buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
570   buf_stride = pre_buf->stride;
571
572   // Do border extension if there is motion or the
573   // width/height is not a multiple of 8 pixels.
574   if (is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 0x7) ||
575       (frame_height & 0x7)) {
576     int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
577
578     // Get reference block bottom right horizontal coordinate.
579     int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
580     int x_pad = 0, y_pad = 0;
581
582     if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
583       x0 -= VP9_INTERP_EXTEND - 1;
584       x1 += VP9_INTERP_EXTEND;
585       x_pad = 1;
586     }
587
588     if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
589       y0 -= VP9_INTERP_EXTEND - 1;
590       y1 += VP9_INTERP_EXTEND;
591       y_pad = 1;
592     }
593
594     // Wait until reference block is ready. Pad 7 more pixels as last 7
595     // pixels of each superblock row can be changed by next superblock row.
596     if (worker != NULL)
597       vp9_frameworker_wait(worker, ref_frame_buf, VPXMAX(0, (y1 + 7))
598                                                       << (plane == 0 ? 0 : 1));
599
600     // Skip border extension if block is inside the frame.
601     if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
602         y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
603       // Extend the border.
604       const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
605       const int b_w = x1 - x0 + 1;
606       const int b_h = y1 - y0 + 1;
607       const int border_offset = y_pad * 3 * b_w + x_pad * 3;
608
609       extend_and_predict(buf_ptr1, buf_stride, x0, y0, b_w, b_h, frame_width,
610                          frame_height, border_offset, dst, dst_buf->stride,
611                          subpel_x, subpel_y, kernel, sf,
612 #if CONFIG_VP9_HIGHBITDEPTH
613                          xd,
614 #endif
615                          w, h, ref, xs, ys);
616       return;
617     }
618   } else {
619     // Wait until reference block is ready. Pad 7 more pixels as last 7
620     // pixels of each superblock row can be changed by next superblock row.
621     if (worker != NULL) {
622       const int y1 = (y0_16 + (h - 1) * ys) >> SUBPEL_BITS;
623       vp9_frameworker_wait(worker, ref_frame_buf, VPXMAX(0, (y1 + 7))
624                                                       << (plane == 0 ? 0 : 1));
625     }
626   }
627 #if CONFIG_VP9_HIGHBITDEPTH
628   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
629     highbd_inter_predictor(CONVERT_TO_SHORTPTR(buf_ptr), buf_stride,
630                            CONVERT_TO_SHORTPTR(dst), dst_buf->stride, subpel_x,
631                            subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
632   } else {
633     inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
634                     subpel_y, sf, w, h, ref, kernel, xs, ys);
635   }
636 #else
637   inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x, subpel_y,
638                   sf, w, h, ref, kernel, xs, ys);
639 #endif  // CONFIG_VP9_HIGHBITDEPTH
640 }
641
642 static void dec_build_inter_predictors_sb(VP9Decoder *const pbi,
643                                           MACROBLOCKD *xd, int mi_row,
644                                           int mi_col) {
645   int plane;
646   const int mi_x = mi_col * MI_SIZE;
647   const int mi_y = mi_row * MI_SIZE;
648   const MODE_INFO *mi = xd->mi[0];
649   const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
650   const BLOCK_SIZE sb_type = mi->sb_type;
651   const int is_compound = has_second_ref(mi);
652   int ref;
653   int is_scaled;
654   VPxWorker *const fwo =
655       pbi->frame_parallel_decode ? pbi->frame_worker_owner : NULL;
656
657   for (ref = 0; ref < 1 + is_compound; ++ref) {
658     const MV_REFERENCE_FRAME frame = mi->ref_frame[ref];
659     RefBuffer *ref_buf = &pbi->common.frame_refs[frame - LAST_FRAME];
660     const struct scale_factors *const sf = &ref_buf->sf;
661     const int idx = ref_buf->idx;
662     BufferPool *const pool = pbi->common.buffer_pool;
663     RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
664
665     if (!vp9_is_valid_scale(sf))
666       vpx_internal_error(xd->error_info, VPX_CODEC_UNSUP_BITSTREAM,
667                          "Reference frame has invalid dimensions");
668
669     is_scaled = vp9_is_scaled(sf);
670     vp9_setup_pre_planes(xd, ref, ref_buf->buf, mi_row, mi_col,
671                          is_scaled ? sf : NULL);
672     xd->block_refs[ref] = ref_buf;
673
674     if (sb_type < BLOCK_8X8) {
675       for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
676         struct macroblockd_plane *const pd = &xd->plane[plane];
677         struct buf_2d *const dst_buf = &pd->dst;
678         const int num_4x4_w = pd->n4_w;
679         const int num_4x4_h = pd->n4_h;
680         const int n4w_x4 = 4 * num_4x4_w;
681         const int n4h_x4 = 4 * num_4x4_h;
682         struct buf_2d *const pre_buf = &pd->pre[ref];
683         int i = 0, x, y;
684         for (y = 0; y < num_4x4_h; ++y) {
685           for (x = 0; x < num_4x4_w; ++x) {
686             const MV mv = average_split_mvs(pd, mi, ref, i++);
687             dec_build_inter_predictors(fwo, xd, plane, n4w_x4, n4h_x4, 4 * x,
688                                        4 * y, 4, 4, mi_x, mi_y, kernel, sf,
689                                        pre_buf, dst_buf, &mv, ref_frame_buf,
690                                        is_scaled, ref);
691           }
692         }
693       }
694     } else {
695       const MV mv = mi->mv[ref].as_mv;
696       for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
697         struct macroblockd_plane *const pd = &xd->plane[plane];
698         struct buf_2d *const dst_buf = &pd->dst;
699         const int num_4x4_w = pd->n4_w;
700         const int num_4x4_h = pd->n4_h;
701         const int n4w_x4 = 4 * num_4x4_w;
702         const int n4h_x4 = 4 * num_4x4_h;
703         struct buf_2d *const pre_buf = &pd->pre[ref];
704         dec_build_inter_predictors(fwo, xd, plane, n4w_x4, n4h_x4, 0, 0, n4w_x4,
705                                    n4h_x4, mi_x, mi_y, kernel, sf, pre_buf,
706                                    dst_buf, &mv, ref_frame_buf, is_scaled, ref);
707       }
708     }
709   }
710 }
711
712 static INLINE void dec_reset_skip_context(MACROBLOCKD *xd) {
713   int i;
714   for (i = 0; i < MAX_MB_PLANE; i++) {
715     struct macroblockd_plane *const pd = &xd->plane[i];
716     memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w);
717     memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h);
718   }
719 }
720
721 static void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh, int bwl,
722                          int bhl) {
723   int i;
724   for (i = 0; i < MAX_MB_PLANE; i++) {
725     xd->plane[i].n4_w = (bw << 1) >> xd->plane[i].subsampling_x;
726     xd->plane[i].n4_h = (bh << 1) >> xd->plane[i].subsampling_y;
727     xd->plane[i].n4_wl = bwl - xd->plane[i].subsampling_x;
728     xd->plane[i].n4_hl = bhl - xd->plane[i].subsampling_y;
729   }
730 }
731
732 static MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
733                               BLOCK_SIZE bsize, int mi_row, int mi_col, int bw,
734                               int bh, int x_mis, int y_mis, int bwl, int bhl) {
735   const int offset = mi_row * cm->mi_stride + mi_col;
736   int x, y;
737   const TileInfo *const tile = &xd->tile;
738
739   xd->mi = cm->mi_grid_visible + offset;
740   xd->mi[0] = &cm->mi[offset];
741   // TODO(slavarnway): Generate sb_type based on bwl and bhl, instead of
742   // passing bsize from decode_partition().
743   xd->mi[0]->sb_type = bsize;
744   for (y = 0; y < y_mis; ++y)
745     for (x = !y; x < x_mis; ++x) {
746       xd->mi[y * cm->mi_stride + x] = xd->mi[0];
747     }
748
749   set_plane_n4(xd, bw, bh, bwl, bhl);
750
751   set_skip_context(xd, mi_row, mi_col);
752
753   // Distance of Mb to the various image edges. These are specified to 8th pel
754   // as they are always compared to values that are in 1/8th pel units
755   set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
756
757   vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
758   return xd->mi[0];
759 }
760
761 static void decode_block(TileWorkerData *twd, VP9Decoder *const pbi, int mi_row,
762                          int mi_col, BLOCK_SIZE bsize, int bwl, int bhl) {
763   VP9_COMMON *const cm = &pbi->common;
764   const int less8x8 = bsize < BLOCK_8X8;
765   const int bw = 1 << (bwl - 1);
766   const int bh = 1 << (bhl - 1);
767   const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
768   const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
769   vpx_reader *r = &twd->bit_reader;
770   MACROBLOCKD *const xd = &twd->xd;
771
772   MODE_INFO *mi = set_offsets(cm, xd, bsize, mi_row, mi_col, bw, bh, x_mis,
773                               y_mis, bwl, bhl);
774
775   if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
776     const BLOCK_SIZE uv_subsize =
777         ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
778     if (uv_subsize == BLOCK_INVALID)
779       vpx_internal_error(xd->error_info, VPX_CODEC_CORRUPT_FRAME,
780                          "Invalid block size.");
781   }
782
783   vp9_read_mode_info(twd, pbi, mi_row, mi_col, x_mis, y_mis);
784
785   if (mi->skip) {
786     dec_reset_skip_context(xd);
787   }
788
789   if (!is_inter_block(mi)) {
790     int plane;
791     for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
792       const struct macroblockd_plane *const pd = &xd->plane[plane];
793       const TX_SIZE tx_size = plane ? get_uv_tx_size(mi, pd) : mi->tx_size;
794       const int num_4x4_w = pd->n4_w;
795       const int num_4x4_h = pd->n4_h;
796       const int step = (1 << tx_size);
797       int row, col;
798       const int max_blocks_wide =
799           num_4x4_w + (xd->mb_to_right_edge >= 0
800                            ? 0
801                            : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
802       const int max_blocks_high =
803           num_4x4_h + (xd->mb_to_bottom_edge >= 0
804                            ? 0
805                            : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
806
807       xd->max_blocks_wide = xd->mb_to_right_edge >= 0 ? 0 : max_blocks_wide;
808       xd->max_blocks_high = xd->mb_to_bottom_edge >= 0 ? 0 : max_blocks_high;
809
810       for (row = 0; row < max_blocks_high; row += step)
811         for (col = 0; col < max_blocks_wide; col += step)
812           predict_and_reconstruct_intra_block(twd, mi, plane, row, col,
813                                               tx_size);
814     }
815   } else {
816     // Prediction
817     dec_build_inter_predictors_sb(pbi, xd, mi_row, mi_col);
818
819     // Reconstruction
820     if (!mi->skip) {
821       int eobtotal = 0;
822       int plane;
823
824       for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
825         const struct macroblockd_plane *const pd = &xd->plane[plane];
826         const TX_SIZE tx_size = plane ? get_uv_tx_size(mi, pd) : mi->tx_size;
827         const int num_4x4_w = pd->n4_w;
828         const int num_4x4_h = pd->n4_h;
829         const int step = (1 << tx_size);
830         int row, col;
831         const int max_blocks_wide =
832             num_4x4_w + (xd->mb_to_right_edge >= 0
833                              ? 0
834                              : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
835         const int max_blocks_high =
836             num_4x4_h +
837             (xd->mb_to_bottom_edge >= 0
838                  ? 0
839                  : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
840
841         xd->max_blocks_wide = xd->mb_to_right_edge >= 0 ? 0 : max_blocks_wide;
842         xd->max_blocks_high = xd->mb_to_bottom_edge >= 0 ? 0 : max_blocks_high;
843
844         for (row = 0; row < max_blocks_high; row += step)
845           for (col = 0; col < max_blocks_wide; col += step)
846             eobtotal +=
847                 reconstruct_inter_block(twd, mi, plane, row, col, tx_size);
848       }
849
850       if (!less8x8 && eobtotal == 0) mi->skip = 1;  // skip loopfilter
851     }
852   }
853
854   xd->corrupted |= vpx_reader_has_error(r);
855
856   if (cm->lf.filter_level) {
857     vp9_build_mask(cm, mi, mi_row, mi_col, bw, bh);
858   }
859 }
860
861 static INLINE int dec_partition_plane_context(TileWorkerData *twd, int mi_row,
862                                               int mi_col, int bsl) {
863   const PARTITION_CONTEXT *above_ctx = twd->xd.above_seg_context + mi_col;
864   const PARTITION_CONTEXT *left_ctx =
865       twd->xd.left_seg_context + (mi_row & MI_MASK);
866   int above = (*above_ctx >> bsl) & 1, left = (*left_ctx >> bsl) & 1;
867
868   //  assert(bsl >= 0);
869
870   return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
871 }
872
873 static INLINE void dec_update_partition_context(TileWorkerData *twd, int mi_row,
874                                                 int mi_col, BLOCK_SIZE subsize,
875                                                 int bw) {
876   PARTITION_CONTEXT *const above_ctx = twd->xd.above_seg_context + mi_col;
877   PARTITION_CONTEXT *const left_ctx =
878       twd->xd.left_seg_context + (mi_row & MI_MASK);
879
880   // update the partition context at the end notes. set partition bits
881   // of block sizes larger than the current one to be one, and partition
882   // bits of smaller block sizes to be zero.
883   memset(above_ctx, partition_context_lookup[subsize].above, bw);
884   memset(left_ctx, partition_context_lookup[subsize].left, bw);
885 }
886
887 static PARTITION_TYPE read_partition(TileWorkerData *twd, int mi_row,
888                                      int mi_col, int has_rows, int has_cols,
889                                      int bsl) {
890   const int ctx = dec_partition_plane_context(twd, mi_row, mi_col, bsl);
891   const vpx_prob *const probs = twd->xd.partition_probs[ctx];
892   FRAME_COUNTS *counts = twd->xd.counts;
893   PARTITION_TYPE p;
894   vpx_reader *r = &twd->bit_reader;
895
896   if (has_rows && has_cols)
897     p = (PARTITION_TYPE)vpx_read_tree(r, vp9_partition_tree, probs);
898   else if (!has_rows && has_cols)
899     p = vpx_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
900   else if (has_rows && !has_cols)
901     p = vpx_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
902   else
903     p = PARTITION_SPLIT;
904
905   if (counts) ++counts->partition[ctx][p];
906
907   return p;
908 }
909
910 // TODO(slavarnway): eliminate bsize and subsize in future commits
911 static void decode_partition(TileWorkerData *twd, VP9Decoder *const pbi,
912                              int mi_row, int mi_col, BLOCK_SIZE bsize,
913                              int n4x4_l2) {
914   VP9_COMMON *const cm = &pbi->common;
915   const int n8x8_l2 = n4x4_l2 - 1;
916   const int num_8x8_wh = 1 << n8x8_l2;
917   const int hbs = num_8x8_wh >> 1;
918   PARTITION_TYPE partition;
919   BLOCK_SIZE subsize;
920   const int has_rows = (mi_row + hbs) < cm->mi_rows;
921   const int has_cols = (mi_col + hbs) < cm->mi_cols;
922   MACROBLOCKD *const xd = &twd->xd;
923
924   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
925
926   partition = read_partition(twd, mi_row, mi_col, has_rows, has_cols, n8x8_l2);
927   subsize = subsize_lookup[partition][bsize];  // get_subsize(bsize, partition);
928   if (!hbs) {
929     // calculate bmode block dimensions (log 2)
930     xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
931     xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
932     decode_block(twd, pbi, mi_row, mi_col, subsize, 1, 1);
933   } else {
934     switch (partition) {
935       case PARTITION_NONE:
936         decode_block(twd, pbi, mi_row, mi_col, subsize, n4x4_l2, n4x4_l2);
937         break;
938       case PARTITION_HORZ:
939         decode_block(twd, pbi, mi_row, mi_col, subsize, n4x4_l2, n8x8_l2);
940         if (has_rows)
941           decode_block(twd, pbi, mi_row + hbs, mi_col, subsize, n4x4_l2,
942                        n8x8_l2);
943         break;
944       case PARTITION_VERT:
945         decode_block(twd, pbi, mi_row, mi_col, subsize, n8x8_l2, n4x4_l2);
946         if (has_cols)
947           decode_block(twd, pbi, mi_row, mi_col + hbs, subsize, n8x8_l2,
948                        n4x4_l2);
949         break;
950       case PARTITION_SPLIT:
951         decode_partition(twd, pbi, mi_row, mi_col, subsize, n8x8_l2);
952         decode_partition(twd, pbi, mi_row, mi_col + hbs, subsize, n8x8_l2);
953         decode_partition(twd, pbi, mi_row + hbs, mi_col, subsize, n8x8_l2);
954         decode_partition(twd, pbi, mi_row + hbs, mi_col + hbs, subsize,
955                          n8x8_l2);
956         break;
957       default: assert(0 && "Invalid partition type");
958     }
959   }
960
961   // update partition context
962   if (bsize >= BLOCK_8X8 &&
963       (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
964     dec_update_partition_context(twd, mi_row, mi_col, subsize, num_8x8_wh);
965 }
966
967 static void setup_token_decoder(const uint8_t *data, const uint8_t *data_end,
968                                 size_t read_size,
969                                 struct vpx_internal_error_info *error_info,
970                                 vpx_reader *r, vpx_decrypt_cb decrypt_cb,
971                                 void *decrypt_state) {
972   // Validate the calculated partition length. If the buffer
973   // described by the partition can't be fully read, then restrict
974   // it to the portion that can be (for EC mode) or throw an error.
975   if (!read_is_valid(data, read_size, data_end))
976     vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
977                        "Truncated packet or corrupt tile length");
978
979   if (vpx_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
980     vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
981                        "Failed to allocate bool decoder %d", 1);
982 }
983
984 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
985                                    vpx_reader *r) {
986   int i, j, k, l, m;
987
988   if (vpx_read_bit(r))
989     for (i = 0; i < PLANE_TYPES; ++i)
990       for (j = 0; j < REF_TYPES; ++j)
991         for (k = 0; k < COEF_BANDS; ++k)
992           for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
993             for (m = 0; m < UNCONSTRAINED_NODES; ++m)
994               vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
995 }
996
997 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode, vpx_reader *r) {
998   const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
999   TX_SIZE tx_size;
1000   for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1001     read_coef_probs_common(fc->coef_probs[tx_size], r);
1002 }
1003
1004 static void setup_segmentation(struct segmentation *seg,
1005                                struct vpx_read_bit_buffer *rb) {
1006   int i, j;
1007
1008   seg->update_map = 0;
1009   seg->update_data = 0;
1010
1011   seg->enabled = vpx_rb_read_bit(rb);
1012   if (!seg->enabled) return;
1013
1014   // Segmentation map update
1015   seg->update_map = vpx_rb_read_bit(rb);
1016   if (seg->update_map) {
1017     for (i = 0; i < SEG_TREE_PROBS; i++)
1018       seg->tree_probs[i] =
1019           vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8) : MAX_PROB;
1020
1021     seg->temporal_update = vpx_rb_read_bit(rb);
1022     if (seg->temporal_update) {
1023       for (i = 0; i < PREDICTION_PROBS; i++)
1024         seg->pred_probs[i] =
1025             vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8) : MAX_PROB;
1026     } else {
1027       for (i = 0; i < PREDICTION_PROBS; i++) seg->pred_probs[i] = MAX_PROB;
1028     }
1029   }
1030
1031   // Segmentation data update
1032   seg->update_data = vpx_rb_read_bit(rb);
1033   if (seg->update_data) {
1034     seg->abs_delta = vpx_rb_read_bit(rb);
1035
1036     vp9_clearall_segfeatures(seg);
1037
1038     for (i = 0; i < MAX_SEGMENTS; i++) {
1039       for (j = 0; j < SEG_LVL_MAX; j++) {
1040         int data = 0;
1041         const int feature_enabled = vpx_rb_read_bit(rb);
1042         if (feature_enabled) {
1043           vp9_enable_segfeature(seg, i, j);
1044           data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1045           if (vp9_is_segfeature_signed(j))
1046             data = vpx_rb_read_bit(rb) ? -data : data;
1047         }
1048         vp9_set_segdata(seg, i, j, data);
1049       }
1050     }
1051   }
1052 }
1053
1054 static void setup_loopfilter(struct loopfilter *lf,
1055                              struct vpx_read_bit_buffer *rb) {
1056   lf->filter_level = vpx_rb_read_literal(rb, 6);
1057   lf->sharpness_level = vpx_rb_read_literal(rb, 3);
1058
1059   // Read in loop filter deltas applied at the MB level based on mode or ref
1060   // frame.
1061   lf->mode_ref_delta_update = 0;
1062
1063   lf->mode_ref_delta_enabled = vpx_rb_read_bit(rb);
1064   if (lf->mode_ref_delta_enabled) {
1065     lf->mode_ref_delta_update = vpx_rb_read_bit(rb);
1066     if (lf->mode_ref_delta_update) {
1067       int i;
1068
1069       for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1070         if (vpx_rb_read_bit(rb))
1071           lf->ref_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1072
1073       for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1074         if (vpx_rb_read_bit(rb))
1075           lf->mode_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1076     }
1077   }
1078 }
1079
1080 static INLINE int read_delta_q(struct vpx_read_bit_buffer *rb) {
1081   return vpx_rb_read_bit(rb) ? vpx_rb_read_signed_literal(rb, 4) : 0;
1082 }
1083
1084 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1085                                struct vpx_read_bit_buffer *rb) {
1086   cm->base_qindex = vpx_rb_read_literal(rb, QINDEX_BITS);
1087   cm->y_dc_delta_q = read_delta_q(rb);
1088   cm->uv_dc_delta_q = read_delta_q(rb);
1089   cm->uv_ac_delta_q = read_delta_q(rb);
1090   cm->dequant_bit_depth = cm->bit_depth;
1091   xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
1092                  cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
1093
1094 #if CONFIG_VP9_HIGHBITDEPTH
1095   xd->bd = (int)cm->bit_depth;
1096 #endif
1097 }
1098
1099 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1100   // Build y/uv dequant values based on segmentation.
1101   if (cm->seg.enabled) {
1102     int i;
1103     for (i = 0; i < MAX_SEGMENTS; ++i) {
1104       const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1105       cm->y_dequant[i][0] =
1106           vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1107       cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1108       cm->uv_dequant[i][0] =
1109           vp9_dc_quant(qindex, cm->uv_dc_delta_q, cm->bit_depth);
1110       cm->uv_dequant[i][1] =
1111           vp9_ac_quant(qindex, cm->uv_ac_delta_q, cm->bit_depth);
1112     }
1113   } else {
1114     const int qindex = cm->base_qindex;
1115     // When segmentation is disabled, only the first value is used.  The
1116     // remaining are don't cares.
1117     cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1118     cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1119     cm->uv_dequant[0][0] =
1120         vp9_dc_quant(qindex, cm->uv_dc_delta_q, cm->bit_depth);
1121     cm->uv_dequant[0][1] =
1122         vp9_ac_quant(qindex, cm->uv_ac_delta_q, cm->bit_depth);
1123   }
1124 }
1125
1126 static INTERP_FILTER read_interp_filter(struct vpx_read_bit_buffer *rb) {
1127   const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH, EIGHTTAP,
1128                                               EIGHTTAP_SHARP, BILINEAR };
1129   return vpx_rb_read_bit(rb) ? SWITCHABLE
1130                              : literal_to_filter[vpx_rb_read_literal(rb, 2)];
1131 }
1132
1133 static void setup_render_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1134   cm->render_width = cm->width;
1135   cm->render_height = cm->height;
1136   if (vpx_rb_read_bit(rb))
1137     vp9_read_frame_size(rb, &cm->render_width, &cm->render_height);
1138 }
1139
1140 static void resize_mv_buffer(VP9_COMMON *cm) {
1141   vpx_free(cm->cur_frame->mvs);
1142   cm->cur_frame->mi_rows = cm->mi_rows;
1143   cm->cur_frame->mi_cols = cm->mi_cols;
1144   CHECK_MEM_ERROR(cm, cm->cur_frame->mvs,
1145                   (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1146                                        sizeof(*cm->cur_frame->mvs)));
1147 }
1148
1149 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1150 #if CONFIG_SIZE_LIMIT
1151   if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1152     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1153                        "Dimensions of %dx%d beyond allowed size of %dx%d.",
1154                        width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1155 #endif
1156   if (cm->width != width || cm->height != height) {
1157     const int new_mi_rows =
1158         ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1159     const int new_mi_cols =
1160         ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1161
1162     // Allocations in vp9_alloc_context_buffers() depend on individual
1163     // dimensions as well as the overall size.
1164     if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1165       if (vp9_alloc_context_buffers(cm, width, height))
1166         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1167                            "Failed to allocate context buffers");
1168     } else {
1169       vp9_set_mb_mi(cm, width, height);
1170     }
1171     vp9_init_context_buffers(cm);
1172     cm->width = width;
1173     cm->height = height;
1174   }
1175   if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1176       cm->mi_cols > cm->cur_frame->mi_cols) {
1177     resize_mv_buffer(cm);
1178   }
1179 }
1180
1181 static void setup_frame_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1182   int width, height;
1183   BufferPool *const pool = cm->buffer_pool;
1184   vp9_read_frame_size(rb, &width, &height);
1185   resize_context_buffers(cm, width, height);
1186   setup_render_size(cm, rb);
1187
1188   lock_buffer_pool(pool);
1189   if (vpx_realloc_frame_buffer(
1190           get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x,
1191           cm->subsampling_y,
1192 #if CONFIG_VP9_HIGHBITDEPTH
1193           cm->use_highbitdepth,
1194 #endif
1195           VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment,
1196           &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1197           pool->cb_priv)) {
1198     unlock_buffer_pool(pool);
1199     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1200                        "Failed to allocate frame buffer");
1201   }
1202   unlock_buffer_pool(pool);
1203
1204   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1205   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1206   pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1207   pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1208   pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1209   pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1210   pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1211 }
1212
1213 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1214                                           int ref_xss, int ref_yss,
1215                                           vpx_bit_depth_t this_bit_depth,
1216                                           int this_xss, int this_yss) {
1217   return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1218          ref_yss == this_yss;
1219 }
1220
1221 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1222                                        struct vpx_read_bit_buffer *rb) {
1223   int width, height;
1224   int found = 0, i;
1225   int has_valid_ref_frame = 0;
1226   BufferPool *const pool = cm->buffer_pool;
1227   for (i = 0; i < REFS_PER_FRAME; ++i) {
1228     if (vpx_rb_read_bit(rb)) {
1229       if (cm->frame_refs[i].idx != INVALID_IDX) {
1230         YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1231         width = buf->y_crop_width;
1232         height = buf->y_crop_height;
1233         found = 1;
1234         break;
1235       } else {
1236         vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1237                            "Failed to decode frame size");
1238       }
1239     }
1240   }
1241
1242   if (!found) vp9_read_frame_size(rb, &width, &height);
1243
1244   if (width <= 0 || height <= 0)
1245     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1246                        "Invalid frame size");
1247
1248   // Check to make sure at least one of frames that this frame references
1249   // has valid dimensions.
1250   for (i = 0; i < REFS_PER_FRAME; ++i) {
1251     RefBuffer *const ref_frame = &cm->frame_refs[i];
1252     has_valid_ref_frame |=
1253         (ref_frame->idx != INVALID_IDX &&
1254          valid_ref_frame_size(ref_frame->buf->y_crop_width,
1255                               ref_frame->buf->y_crop_height, width, height));
1256   }
1257   if (!has_valid_ref_frame)
1258     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1259                        "Referenced frame has invalid size");
1260   for (i = 0; i < REFS_PER_FRAME; ++i) {
1261     RefBuffer *const ref_frame = &cm->frame_refs[i];
1262     if (ref_frame->idx == INVALID_IDX ||
1263         !valid_ref_frame_img_fmt(ref_frame->buf->bit_depth,
1264                                  ref_frame->buf->subsampling_x,
1265                                  ref_frame->buf->subsampling_y, cm->bit_depth,
1266                                  cm->subsampling_x, cm->subsampling_y))
1267       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1268                          "Referenced frame has incompatible color format");
1269   }
1270
1271   resize_context_buffers(cm, width, height);
1272   setup_render_size(cm, rb);
1273
1274   lock_buffer_pool(pool);
1275   if (vpx_realloc_frame_buffer(
1276           get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x,
1277           cm->subsampling_y,
1278 #if CONFIG_VP9_HIGHBITDEPTH
1279           cm->use_highbitdepth,
1280 #endif
1281           VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment,
1282           &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1283           pool->cb_priv)) {
1284     unlock_buffer_pool(pool);
1285     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1286                        "Failed to allocate frame buffer");
1287   }
1288   unlock_buffer_pool(pool);
1289
1290   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1291   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1292   pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1293   pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1294   pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1295   pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1296   pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1297 }
1298
1299 static void setup_tile_info(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1300   int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1301   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1302
1303   // columns
1304   max_ones = max_log2_tile_cols - min_log2_tile_cols;
1305   cm->log2_tile_cols = min_log2_tile_cols;
1306   while (max_ones-- && vpx_rb_read_bit(rb)) cm->log2_tile_cols++;
1307
1308   if (cm->log2_tile_cols > 6)
1309     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1310                        "Invalid number of tile columns");
1311
1312   // rows
1313   cm->log2_tile_rows = vpx_rb_read_bit(rb);
1314   if (cm->log2_tile_rows) cm->log2_tile_rows += vpx_rb_read_bit(rb);
1315 }
1316
1317 // Reads the next tile returning its size and adjusting '*data' accordingly
1318 // based on 'is_last'.
1319 static void get_tile_buffer(const uint8_t *const data_end, int is_last,
1320                             struct vpx_internal_error_info *error_info,
1321                             const uint8_t **data, vpx_decrypt_cb decrypt_cb,
1322                             void *decrypt_state, TileBuffer *buf) {
1323   size_t size;
1324
1325   if (!is_last) {
1326     if (!read_is_valid(*data, 4, data_end))
1327       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1328                          "Truncated packet or corrupt tile length");
1329
1330     if (decrypt_cb) {
1331       uint8_t be_data[4];
1332       decrypt_cb(decrypt_state, *data, be_data, 4);
1333       size = mem_get_be32(be_data);
1334     } else {
1335       size = mem_get_be32(*data);
1336     }
1337     *data += 4;
1338
1339     if (size > (size_t)(data_end - *data))
1340       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1341                          "Truncated packet or corrupt tile size");
1342   } else {
1343     size = data_end - *data;
1344   }
1345
1346   buf->data = *data;
1347   buf->size = size;
1348
1349   *data += size;
1350 }
1351
1352 static void get_tile_buffers(VP9Decoder *pbi, const uint8_t *data,
1353                              const uint8_t *data_end, int tile_cols,
1354                              int tile_rows,
1355                              TileBuffer (*tile_buffers)[1 << 6]) {
1356   int r, c;
1357
1358   for (r = 0; r < tile_rows; ++r) {
1359     for (c = 0; c < tile_cols; ++c) {
1360       const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1361       TileBuffer *const buf = &tile_buffers[r][c];
1362       buf->col = c;
1363       get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1364                       pbi->decrypt_cb, pbi->decrypt_state, buf);
1365     }
1366   }
1367 }
1368
1369 static const uint8_t *decode_tiles(VP9Decoder *pbi, const uint8_t *data,
1370                                    const uint8_t *data_end) {
1371   VP9_COMMON *const cm = &pbi->common;
1372   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1373   const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1374   const int tile_cols = 1 << cm->log2_tile_cols;
1375   const int tile_rows = 1 << cm->log2_tile_rows;
1376   TileBuffer tile_buffers[4][1 << 6];
1377   int tile_row, tile_col;
1378   int mi_row, mi_col;
1379   TileWorkerData *tile_data = NULL;
1380
1381   if (cm->lf.filter_level && !cm->skip_loop_filter &&
1382       pbi->lf_worker.data1 == NULL) {
1383     CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
1384                     vpx_memalign(32, sizeof(LFWorkerData)));
1385     pbi->lf_worker.hook = (VPxWorkerHook)vp9_loop_filter_worker;
1386     if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
1387       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1388                          "Loop filter thread creation failed");
1389     }
1390   }
1391
1392   if (cm->lf.filter_level && !cm->skip_loop_filter) {
1393     LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
1394     // Be sure to sync as we might be resuming after a failed frame decode.
1395     winterface->sync(&pbi->lf_worker);
1396     vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
1397                                pbi->mb.plane);
1398   }
1399
1400   assert(tile_rows <= 4);
1401   assert(tile_cols <= (1 << 6));
1402
1403   // Note: this memset assumes above_context[0], [1] and [2]
1404   // are allocated as part of the same buffer.
1405   memset(cm->above_context, 0,
1406          sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
1407
1408   memset(cm->above_seg_context, 0,
1409          sizeof(*cm->above_seg_context) * aligned_cols);
1410
1411   vp9_reset_lfm(cm);
1412
1413   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1414
1415   // Load all tile information into tile_data.
1416   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1417     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1418       const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
1419       tile_data = pbi->tile_worker_data + tile_cols * tile_row + tile_col;
1420       tile_data->xd = pbi->mb;
1421       tile_data->xd.corrupted = 0;
1422       tile_data->xd.counts =
1423           cm->frame_parallel_decoding_mode ? NULL : &cm->counts;
1424       vp9_zero(tile_data->dqcoeff);
1425       vp9_tile_init(&tile_data->xd.tile, cm, tile_row, tile_col);
1426       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1427                           &tile_data->bit_reader, pbi->decrypt_cb,
1428                           pbi->decrypt_state);
1429       vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1430     }
1431   }
1432
1433   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
1434     TileInfo tile;
1435     vp9_tile_set_row(&tile, cm, tile_row);
1436     for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
1437          mi_row += MI_BLOCK_SIZE) {
1438       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
1439         const int col =
1440             pbi->inv_tile_order ? tile_cols - tile_col - 1 : tile_col;
1441         tile_data = pbi->tile_worker_data + tile_cols * tile_row + col;
1442         vp9_tile_set_col(&tile, cm, col);
1443         vp9_zero(tile_data->xd.left_context);
1444         vp9_zero(tile_data->xd.left_seg_context);
1445         for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
1446              mi_col += MI_BLOCK_SIZE) {
1447           decode_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4);
1448         }
1449         pbi->mb.corrupted |= tile_data->xd.corrupted;
1450         if (pbi->mb.corrupted)
1451           vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1452                              "Failed to decode tile data");
1453       }
1454       // Loopfilter one row.
1455       if (cm->lf.filter_level && !cm->skip_loop_filter) {
1456         const int lf_start = mi_row - MI_BLOCK_SIZE;
1457         LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
1458
1459         // delay the loopfilter by 1 macroblock row.
1460         if (lf_start < 0) continue;
1461
1462         // decoding has completed: finish up the loop filter in this thread.
1463         if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
1464
1465         winterface->sync(&pbi->lf_worker);
1466         lf_data->start = lf_start;
1467         lf_data->stop = mi_row;
1468         if (pbi->max_threads > 1) {
1469           winterface->launch(&pbi->lf_worker);
1470         } else {
1471           winterface->execute(&pbi->lf_worker);
1472         }
1473       }
1474       // After loopfiltering, the last 7 row pixels in each superblock row may
1475       // still be changed by the longest loopfilter of the next superblock
1476       // row.
1477       if (pbi->frame_parallel_decode)
1478         vp9_frameworker_broadcast(pbi->cur_buf, mi_row << MI_BLOCK_SIZE_LOG2);
1479     }
1480   }
1481
1482   // Loopfilter remaining rows in the frame.
1483   if (cm->lf.filter_level && !cm->skip_loop_filter) {
1484     LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
1485     winterface->sync(&pbi->lf_worker);
1486     lf_data->start = lf_data->stop;
1487     lf_data->stop = cm->mi_rows;
1488     winterface->execute(&pbi->lf_worker);
1489   }
1490
1491   // Get last tile data.
1492   tile_data = pbi->tile_worker_data + tile_cols * tile_rows - 1;
1493
1494   if (pbi->frame_parallel_decode)
1495     vp9_frameworker_broadcast(pbi->cur_buf, INT_MAX);
1496   return vpx_reader_find_end(&tile_data->bit_reader);
1497 }
1498
1499 // On entry 'tile_data->data_end' points to the end of the input frame, on exit
1500 // it is updated to reflect the bitreader position of the final tile column if
1501 // present in the tile buffer group or NULL otherwise.
1502 static int tile_worker_hook(TileWorkerData *const tile_data,
1503                             VP9Decoder *const pbi) {
1504   TileInfo *volatile tile = &tile_data->xd.tile;
1505   const int final_col = (1 << pbi->common.log2_tile_cols) - 1;
1506   const uint8_t *volatile bit_reader_end = NULL;
1507   volatile int n = tile_data->buf_start;
1508   tile_data->error_info.setjmp = 1;
1509
1510   if (setjmp(tile_data->error_info.jmp)) {
1511     tile_data->error_info.setjmp = 0;
1512     tile_data->xd.corrupted = 1;
1513     tile_data->data_end = NULL;
1514     return 0;
1515   }
1516
1517   tile_data->xd.corrupted = 0;
1518
1519   do {
1520     int mi_row, mi_col;
1521     const TileBuffer *const buf = pbi->tile_buffers + n;
1522     vp9_zero(tile_data->dqcoeff);
1523     vp9_tile_init(tile, &pbi->common, 0, buf->col);
1524     setup_token_decoder(buf->data, tile_data->data_end, buf->size,
1525                         &tile_data->error_info, &tile_data->bit_reader,
1526                         pbi->decrypt_cb, pbi->decrypt_state);
1527     vp9_init_macroblockd(&pbi->common, &tile_data->xd, tile_data->dqcoeff);
1528     // init resets xd.error_info
1529     tile_data->xd.error_info = &tile_data->error_info;
1530
1531     for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1532          mi_row += MI_BLOCK_SIZE) {
1533       vp9_zero(tile_data->xd.left_context);
1534       vp9_zero(tile_data->xd.left_seg_context);
1535       for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1536            mi_col += MI_BLOCK_SIZE) {
1537         decode_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4);
1538       }
1539     }
1540
1541     if (buf->col == final_col) {
1542       bit_reader_end = vpx_reader_find_end(&tile_data->bit_reader);
1543     }
1544   } while (!tile_data->xd.corrupted && ++n <= tile_data->buf_end);
1545
1546   tile_data->data_end = bit_reader_end;
1547   return !tile_data->xd.corrupted;
1548 }
1549
1550 // sorts in descending order
1551 static int compare_tile_buffers(const void *a, const void *b) {
1552   const TileBuffer *const buf1 = (const TileBuffer *)a;
1553   const TileBuffer *const buf2 = (const TileBuffer *)b;
1554   return (int)(buf2->size - buf1->size);
1555 }
1556
1557 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi, const uint8_t *data,
1558                                       const uint8_t *data_end) {
1559   VP9_COMMON *const cm = &pbi->common;
1560   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1561   const uint8_t *bit_reader_end = NULL;
1562   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1563   const int tile_cols = 1 << cm->log2_tile_cols;
1564   const int tile_rows = 1 << cm->log2_tile_rows;
1565   const int num_workers = VPXMIN(pbi->max_threads, tile_cols);
1566   int n;
1567
1568   assert(tile_cols <= (1 << 6));
1569   assert(tile_rows == 1);
1570   (void)tile_rows;
1571
1572   if (pbi->num_tile_workers == 0) {
1573     const int num_threads = pbi->max_threads;
1574     CHECK_MEM_ERROR(cm, pbi->tile_workers,
1575                     vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1576     for (n = 0; n < num_threads; ++n) {
1577       VPxWorker *const worker = &pbi->tile_workers[n];
1578       ++pbi->num_tile_workers;
1579
1580       winterface->init(worker);
1581       if (n < num_threads - 1 && !winterface->reset(worker)) {
1582         vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1583                            "Tile decoder thread creation failed");
1584       }
1585     }
1586   }
1587
1588   // Reset tile decoding hook
1589   for (n = 0; n < num_workers; ++n) {
1590     VPxWorker *const worker = &pbi->tile_workers[n];
1591     TileWorkerData *const tile_data =
1592         &pbi->tile_worker_data[n + pbi->total_tiles];
1593     winterface->sync(worker);
1594     tile_data->xd = pbi->mb;
1595     tile_data->xd.counts =
1596         cm->frame_parallel_decoding_mode ? NULL : &tile_data->counts;
1597     worker->hook = (VPxWorkerHook)tile_worker_hook;
1598     worker->data1 = tile_data;
1599     worker->data2 = pbi;
1600   }
1601
1602   // Note: this memset assumes above_context[0], [1] and [2]
1603   // are allocated as part of the same buffer.
1604   memset(cm->above_context, 0,
1605          sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1606   memset(cm->above_seg_context, 0,
1607          sizeof(*cm->above_seg_context) * aligned_mi_cols);
1608
1609   vp9_reset_lfm(cm);
1610
1611   // Load tile data into tile_buffers
1612   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows,
1613                    &pbi->tile_buffers);
1614
1615   // Sort the buffers based on size in descending order.
1616   qsort(pbi->tile_buffers, tile_cols, sizeof(pbi->tile_buffers[0]),
1617         compare_tile_buffers);
1618
1619   if (num_workers == tile_cols) {
1620     // Rearrange the tile buffers such that the largest, and
1621     // presumably the most difficult, tile will be decoded in the main thread.
1622     // This should help minimize the number of instances where the main thread
1623     // is waiting for a worker to complete.
1624     const TileBuffer largest = pbi->tile_buffers[0];
1625     memmove(pbi->tile_buffers, pbi->tile_buffers + 1,
1626             (tile_cols - 1) * sizeof(pbi->tile_buffers[0]));
1627     pbi->tile_buffers[tile_cols - 1] = largest;
1628   } else {
1629     int start = 0, end = tile_cols - 2;
1630     TileBuffer tmp;
1631
1632     // Interleave the tiles to distribute the load between threads, assuming a
1633     // larger tile implies it is more difficult to decode.
1634     while (start < end) {
1635       tmp = pbi->tile_buffers[start];
1636       pbi->tile_buffers[start] = pbi->tile_buffers[end];
1637       pbi->tile_buffers[end] = tmp;
1638       start += 2;
1639       end -= 2;
1640     }
1641   }
1642
1643   // Initialize thread frame counts.
1644   if (!cm->frame_parallel_decoding_mode) {
1645     for (n = 0; n < num_workers; ++n) {
1646       TileWorkerData *const tile_data =
1647           (TileWorkerData *)pbi->tile_workers[n].data1;
1648       vp9_zero(tile_data->counts);
1649     }
1650   }
1651
1652   {
1653     const int base = tile_cols / num_workers;
1654     const int remain = tile_cols % num_workers;
1655     int buf_start = 0;
1656
1657     for (n = 0; n < num_workers; ++n) {
1658       const int count = base + (remain + n) / num_workers;
1659       VPxWorker *const worker = &pbi->tile_workers[n];
1660       TileWorkerData *const tile_data = (TileWorkerData *)worker->data1;
1661
1662       tile_data->buf_start = buf_start;
1663       tile_data->buf_end = buf_start + count - 1;
1664       tile_data->data_end = data_end;
1665       buf_start += count;
1666
1667       worker->had_error = 0;
1668       if (n == num_workers - 1) {
1669         assert(tile_data->buf_end == tile_cols - 1);
1670         winterface->execute(worker);
1671       } else {
1672         winterface->launch(worker);
1673       }
1674     }
1675
1676     for (; n > 0; --n) {
1677       VPxWorker *const worker = &pbi->tile_workers[n - 1];
1678       TileWorkerData *const tile_data = (TileWorkerData *)worker->data1;
1679       // TODO(jzern): The tile may have specific error data associated with
1680       // its vpx_internal_error_info which could be propagated to the main info
1681       // in cm. Additionally once the threads have been synced and an error is
1682       // detected, there's no point in continuing to decode tiles.
1683       pbi->mb.corrupted |= !winterface->sync(worker);
1684       if (!bit_reader_end) bit_reader_end = tile_data->data_end;
1685     }
1686   }
1687
1688   // Accumulate thread frame counts.
1689   if (!cm->frame_parallel_decoding_mode) {
1690     for (n = 0; n < num_workers; ++n) {
1691       TileWorkerData *const tile_data =
1692           (TileWorkerData *)pbi->tile_workers[n].data1;
1693       vp9_accumulate_frame_counts(&cm->counts, &tile_data->counts, 1);
1694     }
1695   }
1696
1697   assert(bit_reader_end || pbi->mb.corrupted);
1698   return bit_reader_end;
1699 }
1700
1701 static void error_handler(void *data) {
1702   VP9_COMMON *const cm = (VP9_COMMON *)data;
1703   vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1704 }
1705
1706 static void read_bitdepth_colorspace_sampling(VP9_COMMON *cm,
1707                                               struct vpx_read_bit_buffer *rb) {
1708   if (cm->profile >= PROFILE_2) {
1709     cm->bit_depth = vpx_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1710 #if CONFIG_VP9_HIGHBITDEPTH
1711     cm->use_highbitdepth = 1;
1712 #endif
1713   } else {
1714     cm->bit_depth = VPX_BITS_8;
1715 #if CONFIG_VP9_HIGHBITDEPTH
1716     cm->use_highbitdepth = 0;
1717 #endif
1718   }
1719   cm->color_space = vpx_rb_read_literal(rb, 3);
1720   if (cm->color_space != VPX_CS_SRGB) {
1721     cm->color_range = (vpx_color_range_t)vpx_rb_read_bit(rb);
1722     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1723       cm->subsampling_x = vpx_rb_read_bit(rb);
1724       cm->subsampling_y = vpx_rb_read_bit(rb);
1725       if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1726         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1727                            "4:2:0 color not supported in profile 1 or 3");
1728       if (vpx_rb_read_bit(rb))
1729         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1730                            "Reserved bit set");
1731     } else {
1732       cm->subsampling_y = cm->subsampling_x = 1;
1733     }
1734   } else {
1735     cm->color_range = VPX_CR_FULL_RANGE;
1736     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1737       // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1738       // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1739       cm->subsampling_y = cm->subsampling_x = 0;
1740       if (vpx_rb_read_bit(rb))
1741         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1742                            "Reserved bit set");
1743     } else {
1744       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1745                          "4:4:4 color not supported in profile 0 or 2");
1746     }
1747   }
1748 }
1749
1750 static size_t read_uncompressed_header(VP9Decoder *pbi,
1751                                        struct vpx_read_bit_buffer *rb) {
1752   VP9_COMMON *const cm = &pbi->common;
1753   BufferPool *const pool = cm->buffer_pool;
1754   RefCntBuffer *const frame_bufs = pool->frame_bufs;
1755   int i, mask, ref_index = 0;
1756   size_t sz;
1757
1758   cm->last_frame_type = cm->frame_type;
1759   cm->last_intra_only = cm->intra_only;
1760
1761   if (vpx_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1762     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1763                        "Invalid frame marker");
1764
1765   cm->profile = vp9_read_profile(rb);
1766 #if CONFIG_VP9_HIGHBITDEPTH
1767   if (cm->profile >= MAX_PROFILES)
1768     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1769                        "Unsupported bitstream profile");
1770 #else
1771   if (cm->profile >= PROFILE_2)
1772     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1773                        "Unsupported bitstream profile");
1774 #endif
1775
1776   cm->show_existing_frame = vpx_rb_read_bit(rb);
1777   if (cm->show_existing_frame) {
1778     // Show an existing frame directly.
1779     const int frame_to_show = cm->ref_frame_map[vpx_rb_read_literal(rb, 3)];
1780     lock_buffer_pool(pool);
1781     if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
1782       unlock_buffer_pool(pool);
1783       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1784                          "Buffer %d does not contain a decoded frame",
1785                          frame_to_show);
1786     }
1787
1788     ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
1789     unlock_buffer_pool(pool);
1790     pbi->refresh_frame_flags = 0;
1791     cm->lf.filter_level = 0;
1792     cm->show_frame = 1;
1793
1794     if (pbi->frame_parallel_decode) {
1795       for (i = 0; i < REF_FRAMES; ++i)
1796         cm->next_ref_frame_map[i] = cm->ref_frame_map[i];
1797     }
1798     return 0;
1799   }
1800
1801   cm->frame_type = (FRAME_TYPE)vpx_rb_read_bit(rb);
1802   cm->show_frame = vpx_rb_read_bit(rb);
1803   cm->error_resilient_mode = vpx_rb_read_bit(rb);
1804
1805   if (cm->frame_type == KEY_FRAME) {
1806     if (!vp9_read_sync_code(rb))
1807       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1808                          "Invalid frame sync code");
1809
1810     read_bitdepth_colorspace_sampling(cm, rb);
1811     pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1812
1813     for (i = 0; i < REFS_PER_FRAME; ++i) {
1814       cm->frame_refs[i].idx = INVALID_IDX;
1815       cm->frame_refs[i].buf = NULL;
1816     }
1817
1818     setup_frame_size(cm, rb);
1819     if (pbi->need_resync) {
1820       memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1821       pbi->need_resync = 0;
1822     }
1823   } else {
1824     cm->intra_only = cm->show_frame ? 0 : vpx_rb_read_bit(rb);
1825
1826     cm->reset_frame_context =
1827         cm->error_resilient_mode ? 0 : vpx_rb_read_literal(rb, 2);
1828
1829     if (cm->intra_only) {
1830       if (!vp9_read_sync_code(rb))
1831         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1832                            "Invalid frame sync code");
1833       if (cm->profile > PROFILE_0) {
1834         read_bitdepth_colorspace_sampling(cm, rb);
1835       } else {
1836         // NOTE: The intra-only frame header does not include the specification
1837         // of either the color format or color sub-sampling in profile 0. VP9
1838         // specifies that the default color format should be YUV 4:2:0 in this
1839         // case (normative).
1840         cm->color_space = VPX_CS_BT_601;
1841         cm->color_range = VPX_CR_STUDIO_RANGE;
1842         cm->subsampling_y = cm->subsampling_x = 1;
1843         cm->bit_depth = VPX_BITS_8;
1844 #if CONFIG_VP9_HIGHBITDEPTH
1845         cm->use_highbitdepth = 0;
1846 #endif
1847       }
1848
1849       pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
1850       setup_frame_size(cm, rb);
1851       if (pbi->need_resync) {
1852         memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
1853         pbi->need_resync = 0;
1854       }
1855     } else if (pbi->need_resync != 1) { /* Skip if need resync */
1856       pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
1857       for (i = 0; i < REFS_PER_FRAME; ++i) {
1858         const int ref = vpx_rb_read_literal(rb, REF_FRAMES_LOG2);
1859         const int idx = cm->ref_frame_map[ref];
1860         RefBuffer *const ref_frame = &cm->frame_refs[i];
1861         ref_frame->idx = idx;
1862         ref_frame->buf = &frame_bufs[idx].buf;
1863         cm->ref_frame_sign_bias[LAST_FRAME + i] = vpx_rb_read_bit(rb);
1864       }
1865
1866       setup_frame_size_with_refs(cm, rb);
1867
1868       cm->allow_high_precision_mv = vpx_rb_read_bit(rb);
1869       cm->interp_filter = read_interp_filter(rb);
1870
1871       for (i = 0; i < REFS_PER_FRAME; ++i) {
1872         RefBuffer *const ref_buf = &cm->frame_refs[i];
1873 #if CONFIG_VP9_HIGHBITDEPTH
1874         vp9_setup_scale_factors_for_frame(
1875             &ref_buf->sf, ref_buf->buf->y_crop_width,
1876             ref_buf->buf->y_crop_height, cm->width, cm->height,
1877             cm->use_highbitdepth);
1878 #else
1879         vp9_setup_scale_factors_for_frame(
1880             &ref_buf->sf, ref_buf->buf->y_crop_width,
1881             ref_buf->buf->y_crop_height, cm->width, cm->height);
1882 #endif
1883       }
1884     }
1885   }
1886 #if CONFIG_VP9_HIGHBITDEPTH
1887   get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1888 #endif
1889   get_frame_new_buffer(cm)->color_space = cm->color_space;
1890   get_frame_new_buffer(cm)->color_range = cm->color_range;
1891   get_frame_new_buffer(cm)->render_width = cm->render_width;
1892   get_frame_new_buffer(cm)->render_height = cm->render_height;
1893
1894   if (pbi->need_resync) {
1895     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1896                        "Keyframe / intra-only frame required to reset decoder"
1897                        " state");
1898   }
1899
1900   if (!cm->error_resilient_mode) {
1901     cm->refresh_frame_context = vpx_rb_read_bit(rb);
1902     cm->frame_parallel_decoding_mode = vpx_rb_read_bit(rb);
1903     if (!cm->frame_parallel_decoding_mode) vp9_zero(cm->counts);
1904   } else {
1905     cm->refresh_frame_context = 0;
1906     cm->frame_parallel_decoding_mode = 1;
1907   }
1908
1909   // This flag will be overridden by the call to vp9_setup_past_independence
1910   // below, forcing the use of context 0 for those frame types.
1911   cm->frame_context_idx = vpx_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1912
1913   // Generate next_ref_frame_map.
1914   lock_buffer_pool(pool);
1915   for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
1916     if (mask & 1) {
1917       cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
1918       ++frame_bufs[cm->new_fb_idx].ref_count;
1919     } else {
1920       cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1921     }
1922     // Current thread holds the reference frame.
1923     if (cm->ref_frame_map[ref_index] >= 0)
1924       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1925     ++ref_index;
1926   }
1927
1928   for (; ref_index < REF_FRAMES; ++ref_index) {
1929     cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
1930     // Current thread holds the reference frame.
1931     if (cm->ref_frame_map[ref_index] >= 0)
1932       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
1933   }
1934   unlock_buffer_pool(pool);
1935   pbi->hold_ref_buf = 1;
1936
1937   if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1938     vp9_setup_past_independence(cm);
1939
1940   setup_loopfilter(&cm->lf, rb);
1941   setup_quantization(cm, &pbi->mb, rb);
1942   setup_segmentation(&cm->seg, rb);
1943   setup_segmentation_dequant(cm);
1944
1945   setup_tile_info(cm, rb);
1946   sz = vpx_rb_read_literal(rb, 16);
1947
1948   if (sz == 0)
1949     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1950                        "Invalid header size");
1951
1952   return sz;
1953 }
1954
1955 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
1956                                   size_t partition_size) {
1957   VP9_COMMON *const cm = &pbi->common;
1958   MACROBLOCKD *const xd = &pbi->mb;
1959   FRAME_CONTEXT *const fc = cm->fc;
1960   vpx_reader r;
1961   int k;
1962
1963   if (vpx_reader_init(&r, data, partition_size, pbi->decrypt_cb,
1964                       pbi->decrypt_state))
1965     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1966                        "Failed to allocate bool decoder 0");
1967
1968   cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1969   if (cm->tx_mode == TX_MODE_SELECT) read_tx_mode_probs(&fc->tx_probs, &r);
1970   read_coef_probs(fc, cm->tx_mode, &r);
1971
1972   for (k = 0; k < SKIP_CONTEXTS; ++k)
1973     vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1974
1975   if (!frame_is_intra_only(cm)) {
1976     nmv_context *const nmvc = &fc->nmvc;
1977     int i, j;
1978
1979     read_inter_mode_probs(fc, &r);
1980
1981     if (cm->interp_filter == SWITCHABLE) read_switchable_interp_probs(fc, &r);
1982
1983     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1984       vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1985
1986     cm->reference_mode = read_frame_reference_mode(cm, &r);
1987     if (cm->reference_mode != SINGLE_REFERENCE)
1988       setup_compound_reference_mode(cm);
1989     read_frame_reference_mode_probs(cm, &r);
1990
1991     for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1992       for (i = 0; i < INTRA_MODES - 1; ++i)
1993         vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1994
1995     for (j = 0; j < PARTITION_CONTEXTS; ++j)
1996       for (i = 0; i < PARTITION_TYPES - 1; ++i)
1997         vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1998
1999     read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2000   }
2001
2002   return vpx_reader_has_error(&r);
2003 }
2004
2005 static struct vpx_read_bit_buffer *init_read_bit_buffer(
2006     VP9Decoder *pbi, struct vpx_read_bit_buffer *rb, const uint8_t *data,
2007     const uint8_t *data_end, uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2008   rb->bit_offset = 0;
2009   rb->error_handler = error_handler;
2010   rb->error_handler_data = &pbi->common;
2011   if (pbi->decrypt_cb) {
2012     const int n = (int)VPXMIN(MAX_VP9_HEADER_SIZE, data_end - data);
2013     pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2014     rb->bit_buffer = clear_data;
2015     rb->bit_buffer_end = clear_data + n;
2016   } else {
2017     rb->bit_buffer = data;
2018     rb->bit_buffer_end = data_end;
2019   }
2020   return rb;
2021 }
2022
2023 //------------------------------------------------------------------------------
2024
2025 int vp9_read_sync_code(struct vpx_read_bit_buffer *const rb) {
2026   return vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2027          vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2028          vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2029 }
2030
2031 void vp9_read_frame_size(struct vpx_read_bit_buffer *rb, int *width,
2032                          int *height) {
2033   *width = vpx_rb_read_literal(rb, 16) + 1;
2034   *height = vpx_rb_read_literal(rb, 16) + 1;
2035 }
2036
2037 BITSTREAM_PROFILE vp9_read_profile(struct vpx_read_bit_buffer *rb) {
2038   int profile = vpx_rb_read_bit(rb);
2039   profile |= vpx_rb_read_bit(rb) << 1;
2040   if (profile > 2) profile += vpx_rb_read_bit(rb);
2041   return (BITSTREAM_PROFILE)profile;
2042 }
2043
2044 void vp9_decode_frame(VP9Decoder *pbi, const uint8_t *data,
2045                       const uint8_t *data_end, const uint8_t **p_data_end) {
2046   VP9_COMMON *const cm = &pbi->common;
2047   MACROBLOCKD *const xd = &pbi->mb;
2048   struct vpx_read_bit_buffer rb;
2049   int context_updated = 0;
2050   uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2051   const size_t first_partition_size = read_uncompressed_header(
2052       pbi, init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2053   const int tile_rows = 1 << cm->log2_tile_rows;
2054   const int tile_cols = 1 << cm->log2_tile_cols;
2055   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2056   xd->cur_buf = new_fb;
2057
2058   if (!first_partition_size) {
2059     // showing a frame directly
2060     *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2061     return;
2062   }
2063
2064   data += vpx_rb_bytes_read(&rb);
2065   if (!read_is_valid(data, first_partition_size, data_end))
2066     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2067                        "Truncated packet or corrupt header length");
2068
2069   cm->use_prev_frame_mvs =
2070       !cm->error_resilient_mode && cm->width == cm->last_width &&
2071       cm->height == cm->last_height && !cm->last_intra_only &&
2072       cm->last_show_frame && (cm->last_frame_type != KEY_FRAME);
2073
2074   vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2075
2076   *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2077   if (!cm->fc->initialized)
2078     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2079                        "Uninitialized entropy context.");
2080
2081   xd->corrupted = 0;
2082   new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2083   if (new_fb->corrupted)
2084     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2085                        "Decode failed. Frame data header is corrupted.");
2086
2087   if (cm->lf.filter_level && !cm->skip_loop_filter) {
2088     vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2089   }
2090
2091   // If encoded in frame parallel mode, frame context is ready after decoding
2092   // the frame header.
2093   if (pbi->frame_parallel_decode && cm->frame_parallel_decoding_mode) {
2094     VPxWorker *const worker = pbi->frame_worker_owner;
2095     FrameWorkerData *const frame_worker_data = worker->data1;
2096     if (cm->refresh_frame_context) {
2097       context_updated = 1;
2098       cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2099     }
2100     vp9_frameworker_lock_stats(worker);
2101     pbi->cur_buf->row = -1;
2102     pbi->cur_buf->col = -1;
2103     frame_worker_data->frame_context_ready = 1;
2104     // Signal the main thread that context is ready.
2105     vp9_frameworker_signal_stats(worker);
2106     vp9_frameworker_unlock_stats(worker);
2107   }
2108
2109   if (pbi->tile_worker_data == NULL ||
2110       (tile_cols * tile_rows) != pbi->total_tiles) {
2111     const int num_tile_workers =
2112         tile_cols * tile_rows + ((pbi->max_threads > 1) ? pbi->max_threads : 0);
2113     const size_t twd_size = num_tile_workers * sizeof(*pbi->tile_worker_data);
2114     // Ensure tile data offsets will be properly aligned. This may fail on
2115     // platforms without DECLARE_ALIGNED().
2116     assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
2117     vpx_free(pbi->tile_worker_data);
2118     CHECK_MEM_ERROR(cm, pbi->tile_worker_data, vpx_memalign(32, twd_size));
2119     pbi->total_tiles = tile_rows * tile_cols;
2120   }
2121
2122   if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1) {
2123     // Multi-threaded tile decoder
2124     *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
2125     if (!xd->corrupted) {
2126       if (!cm->skip_loop_filter) {
2127         // If multiple threads are used to decode tiles, then we use those
2128         // threads to do parallel loopfiltering.
2129         vp9_loop_filter_frame_mt(new_fb, cm, pbi->mb.plane, cm->lf.filter_level,
2130                                  0, 0, pbi->tile_workers, pbi->num_tile_workers,
2131                                  &pbi->lf_row_sync);
2132       }
2133     } else {
2134       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2135                          "Decode failed. Frame data is corrupted.");
2136     }
2137   } else {
2138     *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
2139   }
2140
2141   if (!xd->corrupted) {
2142     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2143       vp9_adapt_coef_probs(cm);
2144
2145       if (!frame_is_intra_only(cm)) {
2146         vp9_adapt_mode_probs(cm);
2147         vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2148       }
2149     }
2150   } else {
2151     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2152                        "Decode failed. Frame data is corrupted.");
2153   }
2154
2155   // Non frame parallel update frame context here.
2156   if (cm->refresh_frame_context && !context_updated)
2157     cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
2158 }