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