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