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