• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #if CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
27 #include "vpx_util/vpx_debug_util.h"
28 #endif  // CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
29 
30 #include "vp9/common/vp9_alloccommon.h"
31 #include "vp9/common/vp9_common.h"
32 #include "vp9/common/vp9_entropy.h"
33 #include "vp9/common/vp9_entropymode.h"
34 #include "vp9/common/vp9_idct.h"
35 #include "vp9/common/vp9_thread_common.h"
36 #include "vp9/common/vp9_pred_common.h"
37 #include "vp9/common/vp9_quant_common.h"
38 #include "vp9/common/vp9_reconintra.h"
39 #include "vp9/common/vp9_reconinter.h"
40 #include "vp9/common/vp9_seg_common.h"
41 #include "vp9/common/vp9_tile_common.h"
42 
43 #include "vp9/decoder/vp9_decodeframe.h"
44 #include "vp9/decoder/vp9_detokenize.h"
45 #include "vp9/decoder/vp9_decodemv.h"
46 #include "vp9/decoder/vp9_decoder.h"
47 #include "vp9/decoder/vp9_dsubexp.h"
48 #include "vp9/decoder/vp9_job_queue.h"
49 
50 #define MAX_VP9_HEADER_SIZE 80
51 
52 typedef int (*predict_recon_func)(TileWorkerData *twd, MODE_INFO *const mi,
53                                   int plane, int row, int col, TX_SIZE tx_size);
54 
55 typedef void (*intra_recon_func)(TileWorkerData *twd, MODE_INFO *const mi,
56                                  int plane, int row, int col, TX_SIZE tx_size);
57 
read_is_valid(const uint8_t * start,size_t len,const uint8_t * end)58 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
59   return len != 0 && len <= (size_t)(end - start);
60 }
61 
decode_unsigned_max(struct vpx_read_bit_buffer * rb,int max)62 static int decode_unsigned_max(struct vpx_read_bit_buffer *rb, int max) {
63   const int data = vpx_rb_read_literal(rb, get_unsigned_bits(max));
64   return data > max ? max : data;
65 }
66 
read_tx_mode(vpx_reader * r)67 static TX_MODE read_tx_mode(vpx_reader *r) {
68   TX_MODE tx_mode = vpx_read_literal(r, 2);
69   if (tx_mode == ALLOW_32X32) tx_mode += vpx_read_bit(r);
70   return tx_mode;
71 }
72 
read_tx_mode_probs(struct tx_probs * tx_probs,vpx_reader * r)73 static void read_tx_mode_probs(struct tx_probs *tx_probs, vpx_reader *r) {
74   int i, j;
75 
76   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
77     for (j = 0; j < TX_SIZES - 3; ++j)
78       vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
79 
80   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
81     for (j = 0; j < TX_SIZES - 2; ++j)
82       vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
83 
84   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
85     for (j = 0; j < TX_SIZES - 1; ++j)
86       vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
87 }
88 
read_switchable_interp_probs(FRAME_CONTEXT * fc,vpx_reader * r)89 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vpx_reader *r) {
90   int i, j;
91   for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
92     for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
93       vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
94 }
95 
read_inter_mode_probs(FRAME_CONTEXT * fc,vpx_reader * r)96 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vpx_reader *r) {
97   int i, j;
98   for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
99     for (j = 0; j < INTER_MODES - 1; ++j)
100       vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
101 }
102 
read_frame_reference_mode(const VP9_COMMON * cm,vpx_reader * r)103 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
104                                                 vpx_reader *r) {
105   if (vp9_compound_reference_allowed(cm)) {
106     return vpx_read_bit(r)
107                ? (vpx_read_bit(r) ? REFERENCE_MODE_SELECT : COMPOUND_REFERENCE)
108                : SINGLE_REFERENCE;
109   } else {
110     return SINGLE_REFERENCE;
111   }
112 }
113 
read_frame_reference_mode_probs(VP9_COMMON * cm,vpx_reader * r)114 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vpx_reader *r) {
115   FRAME_CONTEXT *const fc = cm->fc;
116   int i;
117 
118   if (cm->reference_mode == REFERENCE_MODE_SELECT)
119     for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
120       vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
121 
122   if (cm->reference_mode != COMPOUND_REFERENCE)
123     for (i = 0; i < REF_CONTEXTS; ++i) {
124       vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
125       vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
126     }
127 
128   if (cm->reference_mode != SINGLE_REFERENCE)
129     for (i = 0; i < REF_CONTEXTS; ++i)
130       vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
131 }
132 
update_mv_probs(vpx_prob * p,int n,vpx_reader * r)133 static void update_mv_probs(vpx_prob *p, int n, vpx_reader *r) {
134   int i;
135   for (i = 0; i < n; ++i)
136     if (vpx_read(r, MV_UPDATE_PROB)) p[i] = (vpx_read_literal(r, 7) << 1) | 1;
137 }
138 
read_mv_probs(nmv_context * ctx,int allow_hp,vpx_reader * r)139 static void read_mv_probs(nmv_context *ctx, int allow_hp, vpx_reader *r) {
140   int i, j;
141 
142   update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
143 
144   for (i = 0; i < 2; ++i) {
145     nmv_component *const comp_ctx = &ctx->comps[i];
146     update_mv_probs(&comp_ctx->sign, 1, r);
147     update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
148     update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
149     update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
150   }
151 
152   for (i = 0; i < 2; ++i) {
153     nmv_component *const comp_ctx = &ctx->comps[i];
154     for (j = 0; j < CLASS0_SIZE; ++j)
155       update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
156     update_mv_probs(comp_ctx->fp, 3, r);
157   }
158 
159   if (allow_hp) {
160     for (i = 0; i < 2; ++i) {
161       nmv_component *const comp_ctx = &ctx->comps[i];
162       update_mv_probs(&comp_ctx->class0_hp, 1, r);
163       update_mv_probs(&comp_ctx->hp, 1, r);
164     }
165   }
166 }
167 
inverse_transform_block_inter(MACROBLOCKD * xd,int plane,const TX_SIZE tx_size,uint8_t * dst,int stride,int eob)168 static void inverse_transform_block_inter(MACROBLOCKD *xd, int plane,
169                                           const TX_SIZE tx_size, uint8_t *dst,
170                                           int stride, int eob) {
171   struct macroblockd_plane *const pd = &xd->plane[plane];
172   tran_low_t *const dqcoeff = pd->dqcoeff;
173   assert(eob > 0);
174 #if CONFIG_VP9_HIGHBITDEPTH
175   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
176     uint16_t *const dst16 = CONVERT_TO_SHORTPTR(dst);
177     if (xd->lossless) {
178       vp9_highbd_iwht4x4_add(dqcoeff, dst16, stride, eob, xd->bd);
179     } else {
180       switch (tx_size) {
181         case TX_4X4:
182           vp9_highbd_idct4x4_add(dqcoeff, dst16, stride, eob, xd->bd);
183           break;
184         case TX_8X8:
185           vp9_highbd_idct8x8_add(dqcoeff, dst16, stride, eob, xd->bd);
186           break;
187         case TX_16X16:
188           vp9_highbd_idct16x16_add(dqcoeff, dst16, stride, eob, xd->bd);
189           break;
190         case TX_32X32:
191           vp9_highbd_idct32x32_add(dqcoeff, dst16, stride, eob, xd->bd);
192           break;
193         default: assert(0 && "Invalid transform size");
194       }
195     }
196   } else {
197     if (xd->lossless) {
198       vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
199     } else {
200       switch (tx_size) {
201         case TX_4X4: vp9_idct4x4_add(dqcoeff, dst, stride, eob); break;
202         case TX_8X8: vp9_idct8x8_add(dqcoeff, dst, stride, eob); break;
203         case TX_16X16: vp9_idct16x16_add(dqcoeff, dst, stride, eob); break;
204         case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
205         default: assert(0 && "Invalid transform size"); return;
206       }
207     }
208   }
209 #else
210   if (xd->lossless) {
211     vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
212   } else {
213     switch (tx_size) {
214       case TX_4X4: vp9_idct4x4_add(dqcoeff, dst, stride, eob); break;
215       case TX_8X8: vp9_idct8x8_add(dqcoeff, dst, stride, eob); break;
216       case TX_16X16: vp9_idct16x16_add(dqcoeff, dst, stride, eob); break;
217       case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
218       default: assert(0 && "Invalid transform size"); return;
219     }
220   }
221 #endif  // CONFIG_VP9_HIGHBITDEPTH
222 
223   if (eob == 1) {
224     dqcoeff[0] = 0;
225   } else {
226     if (tx_size <= TX_16X16 && eob <= 10)
227       memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
228     else if (tx_size == TX_32X32 && eob <= 34)
229       memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
230     else
231       memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
232   }
233 }
234 
inverse_transform_block_intra(MACROBLOCKD * xd,int plane,const TX_TYPE tx_type,const TX_SIZE tx_size,uint8_t * dst,int stride,int eob)235 static void inverse_transform_block_intra(MACROBLOCKD *xd, int plane,
236                                           const TX_TYPE tx_type,
237                                           const TX_SIZE tx_size, uint8_t *dst,
238                                           int stride, int eob) {
239   struct macroblockd_plane *const pd = &xd->plane[plane];
240   tran_low_t *const dqcoeff = pd->dqcoeff;
241   assert(eob > 0);
242 #if CONFIG_VP9_HIGHBITDEPTH
243   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
244     uint16_t *const dst16 = CONVERT_TO_SHORTPTR(dst);
245     if (xd->lossless) {
246       vp9_highbd_iwht4x4_add(dqcoeff, dst16, stride, eob, xd->bd);
247     } else {
248       switch (tx_size) {
249         case TX_4X4:
250           vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst16, stride, eob, xd->bd);
251           break;
252         case TX_8X8:
253           vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst16, stride, eob, xd->bd);
254           break;
255         case TX_16X16:
256           vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst16, stride, eob, xd->bd);
257           break;
258         case TX_32X32:
259           vp9_highbd_idct32x32_add(dqcoeff, dst16, stride, eob, xd->bd);
260           break;
261         default: assert(0 && "Invalid transform size");
262       }
263     }
264   } else {
265     if (xd->lossless) {
266       vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
267     } else {
268       switch (tx_size) {
269         case TX_4X4: vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob); break;
270         case TX_8X8: vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob); break;
271         case TX_16X16:
272           vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
273           break;
274         case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
275         default: assert(0 && "Invalid transform size"); return;
276       }
277     }
278   }
279 #else
280   if (xd->lossless) {
281     vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
282   } else {
283     switch (tx_size) {
284       case TX_4X4: vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob); break;
285       case TX_8X8: vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob); break;
286       case TX_16X16:
287         vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
288         break;
289       case TX_32X32: vp9_idct32x32_add(dqcoeff, dst, stride, eob); break;
290       default: assert(0 && "Invalid transform size"); return;
291     }
292   }
293 #endif  // CONFIG_VP9_HIGHBITDEPTH
294 
295   if (eob == 1) {
296     dqcoeff[0] = 0;
297   } else {
298     if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
299       memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
300     else if (tx_size == TX_32X32 && eob <= 34)
301       memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
302     else
303       memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
304   }
305 }
306 
predict_and_reconstruct_intra_block(TileWorkerData * twd,MODE_INFO * const mi,int plane,int row,int col,TX_SIZE tx_size)307 static void predict_and_reconstruct_intra_block(TileWorkerData *twd,
308                                                 MODE_INFO *const mi, int plane,
309                                                 int row, int col,
310                                                 TX_SIZE tx_size) {
311   MACROBLOCKD *const xd = &twd->xd;
312   struct macroblockd_plane *const pd = &xd->plane[plane];
313   PREDICTION_MODE mode = (plane == 0) ? mi->mode : mi->uv_mode;
314   uint8_t *dst;
315   dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col];
316 
317   if (mi->sb_type < BLOCK_8X8)
318     if (plane == 0) mode = xd->mi[0]->bmi[(row << 1) + col].as_mode;
319 
320   vp9_predict_intra_block(xd, pd->n4_wl, tx_size, mode, dst, pd->dst.stride,
321                           dst, pd->dst.stride, col, row, plane);
322 
323   if (!mi->skip) {
324     const TX_TYPE tx_type =
325         (plane || xd->lossless) ? DCT_DCT : intra_mode_to_tx_type_lookup[mode];
326     const scan_order *sc = (plane || xd->lossless)
327                                ? &vp9_default_scan_orders[tx_size]
328                                : &vp9_scan_orders[tx_size][tx_type];
329     const int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size,
330                                             mi->segment_id);
331     if (eob > 0) {
332       inverse_transform_block_intra(xd, plane, tx_type, tx_size, dst,
333                                     pd->dst.stride, eob);
334     }
335   }
336 }
337 
parse_intra_block_row_mt(TileWorkerData * twd,MODE_INFO * const mi,int plane,int row,int col,TX_SIZE tx_size)338 static void parse_intra_block_row_mt(TileWorkerData *twd, MODE_INFO *const mi,
339                                      int plane, int row, int col,
340                                      TX_SIZE tx_size) {
341   MACROBLOCKD *const xd = &twd->xd;
342   PREDICTION_MODE mode = (plane == 0) ? mi->mode : mi->uv_mode;
343 
344   if (mi->sb_type < BLOCK_8X8)
345     if (plane == 0) mode = xd->mi[0]->bmi[(row << 1) + col].as_mode;
346 
347   if (!mi->skip) {
348     struct macroblockd_plane *const pd = &xd->plane[plane];
349     const TX_TYPE tx_type =
350         (plane || xd->lossless) ? DCT_DCT : intra_mode_to_tx_type_lookup[mode];
351     const scan_order *sc = (plane || xd->lossless)
352                                ? &vp9_default_scan_orders[tx_size]
353                                : &vp9_scan_orders[tx_size][tx_type];
354     *pd->eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size,
355                                        mi->segment_id);
356     /* Keep the alignment to 16 */
357     pd->dqcoeff += (16 << (tx_size << 1));
358     pd->eob++;
359   }
360 }
361 
predict_and_reconstruct_intra_block_row_mt(TileWorkerData * twd,MODE_INFO * const mi,int plane,int row,int col,TX_SIZE tx_size)362 static void predict_and_reconstruct_intra_block_row_mt(TileWorkerData *twd,
363                                                        MODE_INFO *const mi,
364                                                        int plane, int row,
365                                                        int col,
366                                                        TX_SIZE tx_size) {
367   MACROBLOCKD *const xd = &twd->xd;
368   struct macroblockd_plane *const pd = &xd->plane[plane];
369   PREDICTION_MODE mode = (plane == 0) ? mi->mode : mi->uv_mode;
370   uint8_t *dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col];
371 
372   if (mi->sb_type < BLOCK_8X8)
373     if (plane == 0) mode = xd->mi[0]->bmi[(row << 1) + col].as_mode;
374 
375   vp9_predict_intra_block(xd, pd->n4_wl, tx_size, mode, dst, pd->dst.stride,
376                           dst, pd->dst.stride, col, row, plane);
377 
378   if (!mi->skip) {
379     const TX_TYPE tx_type =
380         (plane || xd->lossless) ? DCT_DCT : intra_mode_to_tx_type_lookup[mode];
381     if (*pd->eob > 0) {
382       inverse_transform_block_intra(xd, plane, tx_type, tx_size, dst,
383                                     pd->dst.stride, *pd->eob);
384     }
385     /* Keep the alignment to 16 */
386     pd->dqcoeff += (16 << (tx_size << 1));
387     pd->eob++;
388   }
389 }
390 
reconstruct_inter_block(TileWorkerData * twd,MODE_INFO * const mi,int plane,int row,int col,TX_SIZE tx_size,int mi_row,int mi_col)391 static int reconstruct_inter_block(TileWorkerData *twd, MODE_INFO *const mi,
392                                    int plane, int row, int col, TX_SIZE tx_size,
393                                    int mi_row, int mi_col) {
394   MACROBLOCKD *const xd = &twd->xd;
395   struct macroblockd_plane *const pd = &xd->plane[plane];
396   const scan_order *sc = &vp9_default_scan_orders[tx_size];
397   const int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size,
398                                           mi->segment_id);
399   uint8_t *dst = &pd->dst.buf[4 * row * pd->dst.stride + 4 * col];
400 
401   if (eob > 0) {
402     inverse_transform_block_inter(xd, plane, tx_size, dst, pd->dst.stride, eob);
403   }
404 #if CONFIG_MISMATCH_DEBUG
405   {
406     int pixel_c, pixel_r;
407     int blk_w = 1 << (tx_size + TX_UNIT_SIZE_LOG2);
408     int blk_h = 1 << (tx_size + TX_UNIT_SIZE_LOG2);
409     mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, col, row,
410                     pd->subsampling_x, pd->subsampling_y);
411     mismatch_check_block_tx(dst, pd->dst.stride, plane, pixel_c, pixel_r, blk_w,
412                             blk_h, xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
413   }
414 #else
415   (void)mi_row;
416   (void)mi_col;
417 #endif
418   return eob;
419 }
420 
parse_inter_block_row_mt(TileWorkerData * twd,MODE_INFO * const mi,int plane,int row,int col,TX_SIZE tx_size)421 static int parse_inter_block_row_mt(TileWorkerData *twd, MODE_INFO *const mi,
422                                     int plane, int row, int col,
423                                     TX_SIZE tx_size) {
424   MACROBLOCKD *const xd = &twd->xd;
425   struct macroblockd_plane *const pd = &xd->plane[plane];
426   const scan_order *sc = &vp9_default_scan_orders[tx_size];
427   const int eob = vp9_decode_block_tokens(twd, plane, sc, col, row, tx_size,
428                                           mi->segment_id);
429 
430   *pd->eob = eob;
431   pd->dqcoeff += (16 << (tx_size << 1));
432   pd->eob++;
433 
434   return eob;
435 }
436 
reconstruct_inter_block_row_mt(TileWorkerData * twd,MODE_INFO * const mi,int plane,int row,int col,TX_SIZE tx_size)437 static int reconstruct_inter_block_row_mt(TileWorkerData *twd,
438                                           MODE_INFO *const mi, int plane,
439                                           int row, int col, TX_SIZE tx_size) {
440   MACROBLOCKD *const xd = &twd->xd;
441   struct macroblockd_plane *const pd = &xd->plane[plane];
442   const int eob = *pd->eob;
443 
444   (void)mi;
445   if (eob > 0) {
446     inverse_transform_block_inter(
447         xd, plane, tx_size, &pd->dst.buf[4 * row * pd->dst.stride + 4 * col],
448         pd->dst.stride, eob);
449   }
450   pd->dqcoeff += (16 << (tx_size << 1));
451   pd->eob++;
452 
453   return eob;
454 }
455 
build_mc_border(const uint8_t * src,int src_stride,uint8_t * dst,int dst_stride,int x,int y,int b_w,int b_h,int w,int h)456 static void build_mc_border(const uint8_t *src, int src_stride, uint8_t *dst,
457                             int dst_stride, 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 uint8_t *ref_row = src - x - y * src_stride;
461 
462   if (y >= h)
463     ref_row += (h - 1) * src_stride;
464   else if (y > 0)
465     ref_row += y * src_stride;
466 
467   do {
468     int right = 0, copy;
469     int left = x < 0 ? -x : 0;
470 
471     if (left > b_w) left = b_w;
472 
473     if (x + b_w > w) right = x + b_w - w;
474 
475     if (right > b_w) right = b_w;
476 
477     copy = b_w - left - right;
478 
479     if (left) memset(dst, ref_row[0], left);
480 
481     if (copy) memcpy(dst + left, ref_row + x + left, copy);
482 
483     if (right) memset(dst + left + copy, ref_row[w - 1], right);
484 
485     dst += dst_stride;
486     ++y;
487 
488     if (y > 0 && y < h) ref_row += src_stride;
489   } while (--b_h);
490 }
491 
492 #if CONFIG_VP9_HIGHBITDEPTH
high_build_mc_border(const uint8_t * src8,int src_stride,uint16_t * dst,int dst_stride,int x,int y,int b_w,int b_h,int w,int h)493 static void high_build_mc_border(const uint8_t *src8, int src_stride,
494                                  uint16_t *dst, int dst_stride, int x, int y,
495                                  int b_w, int b_h, int w, int h) {
496   // Get a pointer to the start of the real data for this row.
497   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
498   const uint16_t *ref_row = src - x - y * src_stride;
499 
500   if (y >= h)
501     ref_row += (h - 1) * src_stride;
502   else if (y > 0)
503     ref_row += y * src_stride;
504 
505   do {
506     int right = 0, copy;
507     int left = x < 0 ? -x : 0;
508 
509     if (left > b_w) left = b_w;
510 
511     if (x + b_w > w) right = x + b_w - w;
512 
513     if (right > b_w) right = b_w;
514 
515     copy = b_w - left - right;
516 
517     if (left) vpx_memset16(dst, ref_row[0], left);
518 
519     if (copy) memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
520 
521     if (right) vpx_memset16(dst + left + copy, ref_row[w - 1], right);
522 
523     dst += dst_stride;
524     ++y;
525 
526     if (y > 0 && y < h) ref_row += src_stride;
527   } while (--b_h);
528 }
529 #endif  // CONFIG_VP9_HIGHBITDEPTH
530 
531 #if CONFIG_VP9_HIGHBITDEPTH
extend_and_predict(TileWorkerData * twd,const uint8_t * buf_ptr1,int pre_buf_stride,int x0,int y0,int b_w,int b_h,int frame_width,int frame_height,int border_offset,uint8_t * const dst,int dst_buf_stride,int subpel_x,int subpel_y,const InterpKernel * kernel,const struct scale_factors * sf,MACROBLOCKD * xd,int w,int h,int ref,int xs,int ys)532 static void extend_and_predict(TileWorkerData *twd, const uint8_t *buf_ptr1,
533                                int pre_buf_stride, int x0, int y0, int b_w,
534                                int b_h, int frame_width, int frame_height,
535                                int border_offset, uint8_t *const dst,
536                                int dst_buf_stride, int subpel_x, int subpel_y,
537                                const InterpKernel *kernel,
538                                const struct scale_factors *sf, MACROBLOCKD *xd,
539                                int w, int h, int ref, int xs, int ys) {
540   uint16_t *mc_buf_high = twd->extend_and_predict_buf;
541   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
542     high_build_mc_border(buf_ptr1, pre_buf_stride, mc_buf_high, b_w, x0, y0,
543                          b_w, b_h, frame_width, frame_height);
544     highbd_inter_predictor(mc_buf_high + border_offset, b_w,
545                            CONVERT_TO_SHORTPTR(dst), dst_buf_stride, subpel_x,
546                            subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
547   } else {
548     build_mc_border(buf_ptr1, pre_buf_stride, (uint8_t *)mc_buf_high, b_w, x0,
549                     y0, b_w, b_h, frame_width, frame_height);
550     inter_predictor(((uint8_t *)mc_buf_high) + border_offset, b_w, dst,
551                     dst_buf_stride, subpel_x, subpel_y, sf, w, h, ref, kernel,
552                     xs, ys);
553   }
554 }
555 #else
extend_and_predict(TileWorkerData * twd,const uint8_t * buf_ptr1,int pre_buf_stride,int x0,int y0,int b_w,int b_h,int frame_width,int frame_height,int border_offset,uint8_t * const dst,int dst_buf_stride,int subpel_x,int subpel_y,const InterpKernel * kernel,const struct scale_factors * sf,int w,int h,int ref,int xs,int ys)556 static void extend_and_predict(TileWorkerData *twd, const uint8_t *buf_ptr1,
557                                int pre_buf_stride, int x0, int y0, int b_w,
558                                int b_h, int frame_width, int frame_height,
559                                int border_offset, uint8_t *const dst,
560                                int dst_buf_stride, int subpel_x, int subpel_y,
561                                const InterpKernel *kernel,
562                                const struct scale_factors *sf, int w, int h,
563                                int ref, int xs, int ys) {
564   uint8_t *mc_buf = (uint8_t *)twd->extend_and_predict_buf;
565   const uint8_t *buf_ptr;
566 
567   build_mc_border(buf_ptr1, pre_buf_stride, mc_buf, b_w, x0, y0, b_w, b_h,
568                   frame_width, frame_height);
569   buf_ptr = mc_buf + border_offset;
570 
571   inter_predictor(buf_ptr, b_w, dst, dst_buf_stride, subpel_x, subpel_y, sf, w,
572                   h, ref, kernel, xs, ys);
573 }
574 #endif  // CONFIG_VP9_HIGHBITDEPTH
575 
dec_build_inter_predictors(TileWorkerData * twd,MACROBLOCKD * xd,int plane,int bw,int bh,int x,int y,int w,int h,int mi_x,int mi_y,const InterpKernel * kernel,const struct scale_factors * sf,struct buf_2d * pre_buf,struct buf_2d * dst_buf,const MV * mv,RefCntBuffer * ref_frame_buf,int is_scaled,int ref)576 static void dec_build_inter_predictors(
577     TileWorkerData *twd, MACROBLOCKD *xd, int plane, int bw, int bh, int x,
578     int y, int w, int h, int mi_x, int mi_y, const InterpKernel *kernel,
579     const struct scale_factors *sf, struct buf_2d *pre_buf,
580     struct buf_2d *dst_buf, const MV *mv, RefCntBuffer *ref_frame_buf,
581     int is_scaled, int ref) {
582   struct macroblockd_plane *const pd = &xd->plane[plane];
583   uint8_t *const dst = dst_buf->buf + dst_buf->stride * y + x;
584   MV32 scaled_mv;
585   int xs, ys, x0, y0, x0_16, y0_16, frame_width, frame_height, buf_stride,
586       subpel_x, subpel_y;
587   uint8_t *ref_frame, *buf_ptr;
588 
589   // Get reference frame pointer, width and height.
590   if (plane == 0) {
591     frame_width = ref_frame_buf->buf.y_crop_width;
592     frame_height = ref_frame_buf->buf.y_crop_height;
593     ref_frame = ref_frame_buf->buf.y_buffer;
594   } else {
595     frame_width = ref_frame_buf->buf.uv_crop_width;
596     frame_height = ref_frame_buf->buf.uv_crop_height;
597     ref_frame =
598         plane == 1 ? ref_frame_buf->buf.u_buffer : ref_frame_buf->buf.v_buffer;
599   }
600 
601   if (is_scaled) {
602     const MV mv_q4 = clamp_mv_to_umv_border_sb(
603         xd, mv, bw, bh, pd->subsampling_x, pd->subsampling_y);
604     // Co-ordinate of containing block to pixel precision.
605     int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
606     int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
607 #if 0  // CONFIG_BETTER_HW_COMPATIBILITY
608     assert(xd->mi[0]->sb_type != BLOCK_4X8 &&
609            xd->mi[0]->sb_type != BLOCK_8X4);
610     assert(mv_q4.row == mv->row * (1 << (1 - pd->subsampling_y)) &&
611            mv_q4.col == mv->col * (1 << (1 - pd->subsampling_x)));
612 #endif
613     // Co-ordinate of the block to 1/16th pixel precision.
614     x0_16 = (x_start + x) << SUBPEL_BITS;
615     y0_16 = (y_start + y) << SUBPEL_BITS;
616 
617     // Co-ordinate of current block in reference frame
618     // to 1/16th pixel precision.
619     x0_16 = sf->scale_value_x(x0_16, sf);
620     y0_16 = sf->scale_value_y(y0_16, sf);
621 
622     // Map the top left corner of the block into the reference frame.
623     x0 = sf->scale_value_x(x_start + x, sf);
624     y0 = sf->scale_value_y(y_start + y, sf);
625 
626     // Scale the MV and incorporate the sub-pixel offset of the block
627     // in the reference frame.
628     scaled_mv = vp9_scale_mv(&mv_q4, mi_x + x, mi_y + y, sf);
629     xs = sf->x_step_q4;
630     ys = sf->y_step_q4;
631   } else {
632     // Co-ordinate of containing block to pixel precision.
633     x0 = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x)) + x;
634     y0 = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y)) + y;
635 
636     // Co-ordinate of the block to 1/16th pixel precision.
637     x0_16 = x0 << SUBPEL_BITS;
638     y0_16 = y0 << SUBPEL_BITS;
639 
640     scaled_mv.row = mv->row * (1 << (1 - pd->subsampling_y));
641     scaled_mv.col = mv->col * (1 << (1 - pd->subsampling_x));
642     xs = ys = 16;
643   }
644   subpel_x = scaled_mv.col & SUBPEL_MASK;
645   subpel_y = scaled_mv.row & SUBPEL_MASK;
646 
647   // Calculate the top left corner of the best matching block in the
648   // reference frame.
649   x0 += scaled_mv.col >> SUBPEL_BITS;
650   y0 += scaled_mv.row >> SUBPEL_BITS;
651   x0_16 += scaled_mv.col;
652   y0_16 += scaled_mv.row;
653 
654   // Get reference block pointer.
655   buf_ptr = ref_frame + y0 * pre_buf->stride + x0;
656   buf_stride = pre_buf->stride;
657 
658   // Do border extension if there is motion or the
659   // width/height is not a multiple of 8 pixels.
660   if (is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 0x7) ||
661       (frame_height & 0x7)) {
662     int y1 = ((y0_16 + (h - 1) * ys) >> SUBPEL_BITS) + 1;
663 
664     // Get reference block bottom right horizontal coordinate.
665     int x1 = ((x0_16 + (w - 1) * xs) >> SUBPEL_BITS) + 1;
666     int x_pad = 0, y_pad = 0;
667 
668     if (subpel_x || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
669       x0 -= VP9_INTERP_EXTEND - 1;
670       x1 += VP9_INTERP_EXTEND;
671       x_pad = 1;
672     }
673 
674     if (subpel_y || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
675       y0 -= VP9_INTERP_EXTEND - 1;
676       y1 += VP9_INTERP_EXTEND;
677       y_pad = 1;
678     }
679 
680     // Skip border extension if block is inside the frame.
681     if (x0 < 0 || x0 > frame_width - 1 || x1 < 0 || x1 > frame_width - 1 ||
682         y0 < 0 || y0 > frame_height - 1 || y1 < 0 || y1 > frame_height - 1) {
683       // Extend the border.
684       const uint8_t *const buf_ptr1 = ref_frame + y0 * buf_stride + x0;
685       const int b_w = x1 - x0 + 1;
686       const int b_h = y1 - y0 + 1;
687       const int border_offset = y_pad * 3 * b_w + x_pad * 3;
688 
689       extend_and_predict(twd, buf_ptr1, buf_stride, x0, y0, b_w, b_h,
690                          frame_width, frame_height, border_offset, dst,
691                          dst_buf->stride, subpel_x, subpel_y, kernel, sf,
692 #if CONFIG_VP9_HIGHBITDEPTH
693                          xd,
694 #endif
695                          w, h, ref, xs, ys);
696       return;
697     }
698   }
699 #if CONFIG_VP9_HIGHBITDEPTH
700   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
701     highbd_inter_predictor(CONVERT_TO_SHORTPTR(buf_ptr), buf_stride,
702                            CONVERT_TO_SHORTPTR(dst), dst_buf->stride, subpel_x,
703                            subpel_y, sf, w, h, ref, kernel, xs, ys, xd->bd);
704   } else {
705     inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x,
706                     subpel_y, sf, w, h, ref, kernel, xs, ys);
707   }
708 #else
709   inter_predictor(buf_ptr, buf_stride, dst, dst_buf->stride, subpel_x, subpel_y,
710                   sf, w, h, ref, kernel, xs, ys);
711 #endif  // CONFIG_VP9_HIGHBITDEPTH
712 }
713 
dec_build_inter_predictors_sb(TileWorkerData * twd,VP9Decoder * const pbi,MACROBLOCKD * xd,int mi_row,int mi_col)714 static void dec_build_inter_predictors_sb(TileWorkerData *twd,
715                                           VP9Decoder *const pbi,
716                                           MACROBLOCKD *xd, int mi_row,
717                                           int mi_col) {
718   int plane;
719   const int mi_x = mi_col * MI_SIZE;
720   const int mi_y = mi_row * MI_SIZE;
721   const MODE_INFO *mi = xd->mi[0];
722   const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
723   const BLOCK_SIZE sb_type = mi->sb_type;
724   const int is_compound = has_second_ref(mi);
725   int ref;
726   int is_scaled;
727 
728   for (ref = 0; ref < 1 + is_compound; ++ref) {
729     const MV_REFERENCE_FRAME frame = mi->ref_frame[ref];
730     RefBuffer *ref_buf = &pbi->common.frame_refs[frame - LAST_FRAME];
731     const struct scale_factors *const sf = &ref_buf->sf;
732     const int idx = ref_buf->idx;
733     BufferPool *const pool = pbi->common.buffer_pool;
734     RefCntBuffer *const ref_frame_buf = &pool->frame_bufs[idx];
735 
736     if (!vp9_is_valid_scale(sf))
737       vpx_internal_error(xd->error_info, VPX_CODEC_UNSUP_BITSTREAM,
738                          "Reference frame has invalid dimensions");
739 
740     is_scaled = vp9_is_scaled(sf);
741     vp9_setup_pre_planes(xd, ref, ref_buf->buf, mi_row, mi_col,
742                          is_scaled ? sf : NULL);
743     xd->block_refs[ref] = ref_buf;
744 
745     if (sb_type < BLOCK_8X8) {
746       for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
747         struct macroblockd_plane *const pd = &xd->plane[plane];
748         struct buf_2d *const dst_buf = &pd->dst;
749         const int num_4x4_w = pd->n4_w;
750         const int num_4x4_h = pd->n4_h;
751         const int n4w_x4 = 4 * num_4x4_w;
752         const int n4h_x4 = 4 * num_4x4_h;
753         struct buf_2d *const pre_buf = &pd->pre[ref];
754         int i = 0, x, y;
755         for (y = 0; y < num_4x4_h; ++y) {
756           for (x = 0; x < num_4x4_w; ++x) {
757             const MV mv = average_split_mvs(pd, mi, ref, i++);
758             dec_build_inter_predictors(twd, xd, plane, n4w_x4, n4h_x4, 4 * x,
759                                        4 * y, 4, 4, mi_x, mi_y, kernel, sf,
760                                        pre_buf, dst_buf, &mv, ref_frame_buf,
761                                        is_scaled, ref);
762           }
763         }
764       }
765     } else {
766       const MV mv = mi->mv[ref].as_mv;
767       for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
768         struct macroblockd_plane *const pd = &xd->plane[plane];
769         struct buf_2d *const dst_buf = &pd->dst;
770         const int num_4x4_w = pd->n4_w;
771         const int num_4x4_h = pd->n4_h;
772         const int n4w_x4 = 4 * num_4x4_w;
773         const int n4h_x4 = 4 * num_4x4_h;
774         struct buf_2d *const pre_buf = &pd->pre[ref];
775         dec_build_inter_predictors(twd, xd, plane, n4w_x4, n4h_x4, 0, 0, n4w_x4,
776                                    n4h_x4, mi_x, mi_y, kernel, sf, pre_buf,
777                                    dst_buf, &mv, ref_frame_buf, is_scaled, ref);
778       }
779     }
780   }
781 }
782 
dec_reset_skip_context(MACROBLOCKD * xd)783 static INLINE void dec_reset_skip_context(MACROBLOCKD *xd) {
784   int i;
785   for (i = 0; i < MAX_MB_PLANE; i++) {
786     struct macroblockd_plane *const pd = &xd->plane[i];
787     memset(pd->above_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_w);
788     memset(pd->left_context, 0, sizeof(ENTROPY_CONTEXT) * pd->n4_h);
789   }
790 }
791 
set_plane_n4(MACROBLOCKD * const xd,int bw,int bh,int bwl,int bhl)792 static void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh, int bwl,
793                          int bhl) {
794   int i;
795   for (i = 0; i < MAX_MB_PLANE; i++) {
796     xd->plane[i].n4_w = (bw << 1) >> xd->plane[i].subsampling_x;
797     xd->plane[i].n4_h = (bh << 1) >> xd->plane[i].subsampling_y;
798     xd->plane[i].n4_wl = bwl - xd->plane[i].subsampling_x;
799     xd->plane[i].n4_hl = bhl - xd->plane[i].subsampling_y;
800   }
801 }
802 
set_offsets_recon(VP9_COMMON * const cm,MACROBLOCKD * const xd,int mi_row,int mi_col,int bw,int bh,int bwl,int bhl)803 static MODE_INFO *set_offsets_recon(VP9_COMMON *const cm, MACROBLOCKD *const xd,
804                                     int mi_row, int mi_col, int bw, int bh,
805                                     int bwl, int bhl) {
806   const int offset = mi_row * cm->mi_stride + mi_col;
807   const TileInfo *const tile = &xd->tile;
808   xd->mi = cm->mi_grid_visible + offset;
809 
810   set_plane_n4(xd, bw, bh, bwl, bhl);
811 
812   set_skip_context(xd, mi_row, mi_col);
813 
814   // Distance of Mb to the various image edges. These are specified to 8th pel
815   // as they are always compared to values that are in 1/8th pel units
816   set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
817 
818   vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
819   return xd->mi[0];
820 }
821 
set_offsets(VP9_COMMON * const cm,MACROBLOCKD * const xd,BLOCK_SIZE bsize,int mi_row,int mi_col,int bw,int bh,int x_mis,int y_mis,int bwl,int bhl)822 static MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
823                               BLOCK_SIZE bsize, int mi_row, int mi_col, int bw,
824                               int bh, int x_mis, int y_mis, int bwl, int bhl) {
825   const int offset = mi_row * cm->mi_stride + mi_col;
826   int x, y;
827   const TileInfo *const tile = &xd->tile;
828 
829   xd->mi = cm->mi_grid_visible + offset;
830   xd->mi[0] = &cm->mi[offset];
831   // TODO(slavarnway): Generate sb_type based on bwl and bhl, instead of
832   // passing bsize from decode_partition().
833   xd->mi[0]->sb_type = bsize;
834   for (y = 0; y < y_mis; ++y)
835     for (x = !y; x < x_mis; ++x) {
836       xd->mi[y * cm->mi_stride + x] = xd->mi[0];
837     }
838 
839   set_plane_n4(xd, bw, bh, bwl, bhl);
840 
841   set_skip_context(xd, mi_row, mi_col);
842 
843   // Distance of Mb to the various image edges. These are specified to 8th pel
844   // as they are always compared to values that are in 1/8th pel units
845   set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
846 
847   vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
848   return xd->mi[0];
849 }
850 
predict_recon_inter(MACROBLOCKD * xd,MODE_INFO * mi,TileWorkerData * twd,predict_recon_func func)851 static INLINE int predict_recon_inter(MACROBLOCKD *xd, MODE_INFO *mi,
852                                       TileWorkerData *twd,
853                                       predict_recon_func func) {
854   int eobtotal = 0;
855   int plane;
856   for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
857     const struct macroblockd_plane *const pd = &xd->plane[plane];
858     const TX_SIZE tx_size = plane ? get_uv_tx_size(mi, pd) : mi->tx_size;
859     const int num_4x4_w = pd->n4_w;
860     const int num_4x4_h = pd->n4_h;
861     const int step = (1 << tx_size);
862     int row, col;
863     const int max_blocks_wide =
864         num_4x4_w + (xd->mb_to_right_edge >= 0
865                          ? 0
866                          : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
867     const int max_blocks_high =
868         num_4x4_h + (xd->mb_to_bottom_edge >= 0
869                          ? 0
870                          : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
871 
872     xd->max_blocks_wide = xd->mb_to_right_edge >= 0 ? 0 : max_blocks_wide;
873     xd->max_blocks_high = xd->mb_to_bottom_edge >= 0 ? 0 : max_blocks_high;
874 
875     for (row = 0; row < max_blocks_high; row += step)
876       for (col = 0; col < max_blocks_wide; col += step)
877         eobtotal += func(twd, mi, plane, row, col, tx_size);
878   }
879   return eobtotal;
880 }
881 
predict_recon_intra(MACROBLOCKD * xd,MODE_INFO * mi,TileWorkerData * twd,intra_recon_func func)882 static INLINE void predict_recon_intra(MACROBLOCKD *xd, MODE_INFO *mi,
883                                        TileWorkerData *twd,
884                                        intra_recon_func func) {
885   int plane;
886   for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
887     const struct macroblockd_plane *const pd = &xd->plane[plane];
888     const TX_SIZE tx_size = plane ? get_uv_tx_size(mi, pd) : mi->tx_size;
889     const int num_4x4_w = pd->n4_w;
890     const int num_4x4_h = pd->n4_h;
891     const int step = (1 << tx_size);
892     int row, col;
893     const int max_blocks_wide =
894         num_4x4_w + (xd->mb_to_right_edge >= 0
895                          ? 0
896                          : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
897     const int max_blocks_high =
898         num_4x4_h + (xd->mb_to_bottom_edge >= 0
899                          ? 0
900                          : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
901 
902     xd->max_blocks_wide = xd->mb_to_right_edge >= 0 ? 0 : max_blocks_wide;
903     xd->max_blocks_high = xd->mb_to_bottom_edge >= 0 ? 0 : max_blocks_high;
904 
905     for (row = 0; row < max_blocks_high; row += step)
906       for (col = 0; col < max_blocks_wide; col += step)
907         func(twd, mi, plane, row, col, tx_size);
908   }
909 }
910 
decode_block(TileWorkerData * twd,VP9Decoder * const pbi,int mi_row,int mi_col,BLOCK_SIZE bsize,int bwl,int bhl)911 static void decode_block(TileWorkerData *twd, VP9Decoder *const pbi, int mi_row,
912                          int mi_col, BLOCK_SIZE bsize, int bwl, int bhl) {
913   VP9_COMMON *const cm = &pbi->common;
914   const int less8x8 = bsize < BLOCK_8X8;
915   const int bw = 1 << (bwl - 1);
916   const int bh = 1 << (bhl - 1);
917   const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
918   const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
919   vpx_reader *r = &twd->bit_reader;
920   MACROBLOCKD *const xd = &twd->xd;
921 
922   MODE_INFO *mi = set_offsets(cm, xd, bsize, mi_row, mi_col, bw, bh, x_mis,
923                               y_mis, bwl, bhl);
924 
925   if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
926     const BLOCK_SIZE uv_subsize =
927         ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
928     if (uv_subsize == BLOCK_INVALID)
929       vpx_internal_error(xd->error_info, VPX_CODEC_CORRUPT_FRAME,
930                          "Invalid block size.");
931   }
932 
933   vp9_read_mode_info(twd, pbi, mi_row, mi_col, x_mis, y_mis);
934 
935   if (mi->skip) {
936     dec_reset_skip_context(xd);
937   }
938 
939   if (!is_inter_block(mi)) {
940     int plane;
941     for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
942       const struct macroblockd_plane *const pd = &xd->plane[plane];
943       const TX_SIZE tx_size = plane ? get_uv_tx_size(mi, pd) : mi->tx_size;
944       const int num_4x4_w = pd->n4_w;
945       const int num_4x4_h = pd->n4_h;
946       const int step = (1 << tx_size);
947       int row, col;
948       const int max_blocks_wide =
949           num_4x4_w + (xd->mb_to_right_edge >= 0
950                            ? 0
951                            : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
952       const int max_blocks_high =
953           num_4x4_h + (xd->mb_to_bottom_edge >= 0
954                            ? 0
955                            : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
956 
957       xd->max_blocks_wide = xd->mb_to_right_edge >= 0 ? 0 : max_blocks_wide;
958       xd->max_blocks_high = xd->mb_to_bottom_edge >= 0 ? 0 : max_blocks_high;
959 
960       for (row = 0; row < max_blocks_high; row += step)
961         for (col = 0; col < max_blocks_wide; col += step)
962           predict_and_reconstruct_intra_block(twd, mi, plane, row, col,
963                                               tx_size);
964     }
965   } else {
966     // Prediction
967     dec_build_inter_predictors_sb(twd, pbi, xd, mi_row, mi_col);
968 #if CONFIG_MISMATCH_DEBUG
969     {
970       int plane;
971       for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
972         const struct macroblockd_plane *pd = &xd->plane[plane];
973         int pixel_c, pixel_r;
974         const BLOCK_SIZE plane_bsize =
975             get_plane_block_size(VPXMAX(bsize, BLOCK_8X8), &xd->plane[plane]);
976         const int bw = get_block_width(plane_bsize);
977         const int bh = get_block_height(plane_bsize);
978         mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, 0, 0,
979                         pd->subsampling_x, pd->subsampling_y);
980         mismatch_check_block_pre(pd->dst.buf, pd->dst.stride, plane, pixel_c,
981                                  pixel_r, bw, bh,
982                                  xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
983       }
984     }
985 #endif
986 
987     // Reconstruction
988     if (!mi->skip) {
989       int eobtotal = 0;
990       int plane;
991 
992       for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
993         const struct macroblockd_plane *const pd = &xd->plane[plane];
994         const TX_SIZE tx_size = plane ? get_uv_tx_size(mi, pd) : mi->tx_size;
995         const int num_4x4_w = pd->n4_w;
996         const int num_4x4_h = pd->n4_h;
997         const int step = (1 << tx_size);
998         int row, col;
999         const int max_blocks_wide =
1000             num_4x4_w + (xd->mb_to_right_edge >= 0
1001                              ? 0
1002                              : xd->mb_to_right_edge >> (5 + pd->subsampling_x));
1003         const int max_blocks_high =
1004             num_4x4_h +
1005             (xd->mb_to_bottom_edge >= 0
1006                  ? 0
1007                  : xd->mb_to_bottom_edge >> (5 + pd->subsampling_y));
1008 
1009         xd->max_blocks_wide = xd->mb_to_right_edge >= 0 ? 0 : max_blocks_wide;
1010         xd->max_blocks_high = xd->mb_to_bottom_edge >= 0 ? 0 : max_blocks_high;
1011 
1012         for (row = 0; row < max_blocks_high; row += step)
1013           for (col = 0; col < max_blocks_wide; col += step)
1014             eobtotal += reconstruct_inter_block(twd, mi, plane, row, col,
1015                                                 tx_size, mi_row, mi_col);
1016       }
1017 
1018       if (!less8x8 && eobtotal == 0) mi->skip = 1;  // skip loopfilter
1019     }
1020   }
1021 
1022   xd->corrupted |= vpx_reader_has_error(r);
1023 
1024   if (cm->lf.filter_level) {
1025     vp9_build_mask(cm, mi, mi_row, mi_col, bw, bh);
1026   }
1027 }
1028 
recon_block(TileWorkerData * twd,VP9Decoder * const pbi,int mi_row,int mi_col,BLOCK_SIZE bsize,int bwl,int bhl)1029 static void recon_block(TileWorkerData *twd, VP9Decoder *const pbi, int mi_row,
1030                         int mi_col, BLOCK_SIZE bsize, int bwl, int bhl) {
1031   VP9_COMMON *const cm = &pbi->common;
1032   const int bw = 1 << (bwl - 1);
1033   const int bh = 1 << (bhl - 1);
1034   MACROBLOCKD *const xd = &twd->xd;
1035 
1036   MODE_INFO *mi = set_offsets_recon(cm, xd, mi_row, mi_col, bw, bh, bwl, bhl);
1037 
1038   if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
1039     const BLOCK_SIZE uv_subsize =
1040         ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
1041     if (uv_subsize == BLOCK_INVALID)
1042       vpx_internal_error(xd->error_info, VPX_CODEC_CORRUPT_FRAME,
1043                          "Invalid block size.");
1044   }
1045 
1046   if (!is_inter_block(mi)) {
1047     predict_recon_intra(xd, mi, twd,
1048                         predict_and_reconstruct_intra_block_row_mt);
1049   } else {
1050     // Prediction
1051     dec_build_inter_predictors_sb(twd, pbi, xd, mi_row, mi_col);
1052 
1053     // Reconstruction
1054     if (!mi->skip) {
1055       predict_recon_inter(xd, mi, twd, reconstruct_inter_block_row_mt);
1056     }
1057   }
1058 
1059   vp9_build_mask(cm, mi, mi_row, mi_col, bw, bh);
1060 }
1061 
parse_block(TileWorkerData * twd,VP9Decoder * const pbi,int mi_row,int mi_col,BLOCK_SIZE bsize,int bwl,int bhl)1062 static void parse_block(TileWorkerData *twd, VP9Decoder *const pbi, int mi_row,
1063                         int mi_col, BLOCK_SIZE bsize, int bwl, int bhl) {
1064   VP9_COMMON *const cm = &pbi->common;
1065   const int bw = 1 << (bwl - 1);
1066   const int bh = 1 << (bhl - 1);
1067   const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1068   const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1069   vpx_reader *r = &twd->bit_reader;
1070   MACROBLOCKD *const xd = &twd->xd;
1071 
1072   MODE_INFO *mi = set_offsets(cm, xd, bsize, mi_row, mi_col, bw, bh, x_mis,
1073                               y_mis, bwl, bhl);
1074 
1075   if (bsize >= BLOCK_8X8 && (cm->subsampling_x || cm->subsampling_y)) {
1076     const BLOCK_SIZE uv_subsize =
1077         ss_size_lookup[bsize][cm->subsampling_x][cm->subsampling_y];
1078     if (uv_subsize == BLOCK_INVALID)
1079       vpx_internal_error(xd->error_info, VPX_CODEC_CORRUPT_FRAME,
1080                          "Invalid block size.");
1081   }
1082 
1083   vp9_read_mode_info(twd, pbi, mi_row, mi_col, x_mis, y_mis);
1084 
1085   if (mi->skip) {
1086     dec_reset_skip_context(xd);
1087   }
1088 
1089   if (!is_inter_block(mi)) {
1090     predict_recon_intra(xd, mi, twd, parse_intra_block_row_mt);
1091   } else {
1092     if (!mi->skip) {
1093       tran_low_t *dqcoeff[MAX_MB_PLANE];
1094       int *eob[MAX_MB_PLANE];
1095       int plane;
1096       int eobtotal;
1097       // Based on eobtotal and bsize, this may be mi->skip may be set to true
1098       // In that case dqcoeff and eob need to be backed up and restored as
1099       // recon_block will not increment these pointers for skip cases
1100       for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
1101         const struct macroblockd_plane *const pd = &xd->plane[plane];
1102         dqcoeff[plane] = pd->dqcoeff;
1103         eob[plane] = pd->eob;
1104       }
1105       eobtotal = predict_recon_inter(xd, mi, twd, parse_inter_block_row_mt);
1106 
1107       if (bsize >= BLOCK_8X8 && eobtotal == 0) {
1108         mi->skip = 1;  // skip loopfilter
1109         for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
1110           struct macroblockd_plane *pd = &xd->plane[plane];
1111           pd->dqcoeff = dqcoeff[plane];
1112           pd->eob = eob[plane];
1113         }
1114       }
1115     }
1116   }
1117 
1118   xd->corrupted |= vpx_reader_has_error(r);
1119 }
1120 
dec_partition_plane_context(TileWorkerData * twd,int mi_row,int mi_col,int bsl)1121 static INLINE int dec_partition_plane_context(TileWorkerData *twd, int mi_row,
1122                                               int mi_col, int bsl) {
1123   const PARTITION_CONTEXT *above_ctx = twd->xd.above_seg_context + mi_col;
1124   const PARTITION_CONTEXT *left_ctx =
1125       twd->xd.left_seg_context + (mi_row & MI_MASK);
1126   int above = (*above_ctx >> bsl) & 1, left = (*left_ctx >> bsl) & 1;
1127 
1128   //  assert(bsl >= 0);
1129 
1130   return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
1131 }
1132 
dec_update_partition_context(TileWorkerData * twd,int mi_row,int mi_col,BLOCK_SIZE subsize,int bw)1133 static INLINE void dec_update_partition_context(TileWorkerData *twd, int mi_row,
1134                                                 int mi_col, BLOCK_SIZE subsize,
1135                                                 int bw) {
1136   PARTITION_CONTEXT *const above_ctx = twd->xd.above_seg_context + mi_col;
1137   PARTITION_CONTEXT *const left_ctx =
1138       twd->xd.left_seg_context + (mi_row & MI_MASK);
1139 
1140   // update the partition context at the end notes. set partition bits
1141   // of block sizes larger than the current one to be one, and partition
1142   // bits of smaller block sizes to be zero.
1143   memset(above_ctx, partition_context_lookup[subsize].above, bw);
1144   memset(left_ctx, partition_context_lookup[subsize].left, bw);
1145 }
1146 
read_partition(TileWorkerData * twd,int mi_row,int mi_col,int has_rows,int has_cols,int bsl)1147 static PARTITION_TYPE read_partition(TileWorkerData *twd, int mi_row,
1148                                      int mi_col, int has_rows, int has_cols,
1149                                      int bsl) {
1150   const int ctx = dec_partition_plane_context(twd, mi_row, mi_col, bsl);
1151   const vpx_prob *const probs = twd->xd.partition_probs[ctx];
1152   FRAME_COUNTS *counts = twd->xd.counts;
1153   PARTITION_TYPE p;
1154   vpx_reader *r = &twd->bit_reader;
1155 
1156   if (has_rows && has_cols)
1157     p = (PARTITION_TYPE)vpx_read_tree(r, vp9_partition_tree, probs);
1158   else if (!has_rows && has_cols)
1159     p = vpx_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
1160   else if (has_rows && !has_cols)
1161     p = vpx_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
1162   else
1163     p = PARTITION_SPLIT;
1164 
1165   if (counts) ++counts->partition[ctx][p];
1166 
1167   return p;
1168 }
1169 
1170 // TODO(slavarnway): eliminate bsize and subsize in future commits
decode_partition(TileWorkerData * twd,VP9Decoder * const pbi,int mi_row,int mi_col,BLOCK_SIZE bsize,int n4x4_l2)1171 static void decode_partition(TileWorkerData *twd, VP9Decoder *const pbi,
1172                              int mi_row, int mi_col, BLOCK_SIZE bsize,
1173                              int n4x4_l2) {
1174   VP9_COMMON *const cm = &pbi->common;
1175   const int n8x8_l2 = n4x4_l2 - 1;
1176   const int num_8x8_wh = 1 << n8x8_l2;
1177   const int hbs = num_8x8_wh >> 1;
1178   PARTITION_TYPE partition;
1179   BLOCK_SIZE subsize;
1180   const int has_rows = (mi_row + hbs) < cm->mi_rows;
1181   const int has_cols = (mi_col + hbs) < cm->mi_cols;
1182   MACROBLOCKD *const xd = &twd->xd;
1183 
1184   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1185 
1186   partition = read_partition(twd, mi_row, mi_col, has_rows, has_cols, n8x8_l2);
1187   subsize = subsize_lookup[partition][bsize];  // get_subsize(bsize, partition);
1188   if (!hbs) {
1189     // calculate bmode block dimensions (log 2)
1190     xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
1191     xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
1192     decode_block(twd, pbi, mi_row, mi_col, subsize, 1, 1);
1193   } else {
1194     switch (partition) {
1195       case PARTITION_NONE:
1196         decode_block(twd, pbi, mi_row, mi_col, subsize, n4x4_l2, n4x4_l2);
1197         break;
1198       case PARTITION_HORZ:
1199         decode_block(twd, pbi, mi_row, mi_col, subsize, n4x4_l2, n8x8_l2);
1200         if (has_rows)
1201           decode_block(twd, pbi, mi_row + hbs, mi_col, subsize, n4x4_l2,
1202                        n8x8_l2);
1203         break;
1204       case PARTITION_VERT:
1205         decode_block(twd, pbi, mi_row, mi_col, subsize, n8x8_l2, n4x4_l2);
1206         if (has_cols)
1207           decode_block(twd, pbi, mi_row, mi_col + hbs, subsize, n8x8_l2,
1208                        n4x4_l2);
1209         break;
1210       case PARTITION_SPLIT:
1211         decode_partition(twd, pbi, mi_row, mi_col, subsize, n8x8_l2);
1212         decode_partition(twd, pbi, mi_row, mi_col + hbs, subsize, n8x8_l2);
1213         decode_partition(twd, pbi, mi_row + hbs, mi_col, subsize, n8x8_l2);
1214         decode_partition(twd, pbi, mi_row + hbs, mi_col + hbs, subsize,
1215                          n8x8_l2);
1216         break;
1217       default: assert(0 && "Invalid partition type");
1218     }
1219   }
1220 
1221   // update partition context
1222   if (bsize >= BLOCK_8X8 &&
1223       (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
1224     dec_update_partition_context(twd, mi_row, mi_col, subsize, num_8x8_wh);
1225 }
1226 
process_partition(TileWorkerData * twd,VP9Decoder * const pbi,int mi_row,int mi_col,BLOCK_SIZE bsize,int n4x4_l2,int parse_recon_flag,process_block_fn_t process_block)1227 static void process_partition(TileWorkerData *twd, VP9Decoder *const pbi,
1228                               int mi_row, int mi_col, BLOCK_SIZE bsize,
1229                               int n4x4_l2, int parse_recon_flag,
1230                               process_block_fn_t process_block) {
1231   VP9_COMMON *const cm = &pbi->common;
1232   const int n8x8_l2 = n4x4_l2 - 1;
1233   const int num_8x8_wh = 1 << n8x8_l2;
1234   const int hbs = num_8x8_wh >> 1;
1235   PARTITION_TYPE partition;
1236   BLOCK_SIZE subsize;
1237   const int has_rows = (mi_row + hbs) < cm->mi_rows;
1238   const int has_cols = (mi_col + hbs) < cm->mi_cols;
1239   MACROBLOCKD *const xd = &twd->xd;
1240 
1241   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1242 
1243   if (parse_recon_flag & PARSE) {
1244     *xd->partition =
1245         read_partition(twd, mi_row, mi_col, has_rows, has_cols, n8x8_l2);
1246   }
1247 
1248   partition = *xd->partition;
1249   xd->partition++;
1250 
1251   subsize = get_subsize(bsize, partition);
1252   if (!hbs) {
1253     // calculate bmode block dimensions (log 2)
1254     xd->bmode_blocks_wl = 1 >> !!(partition & PARTITION_VERT);
1255     xd->bmode_blocks_hl = 1 >> !!(partition & PARTITION_HORZ);
1256     process_block(twd, pbi, mi_row, mi_col, subsize, 1, 1);
1257   } else {
1258     switch (partition) {
1259       case PARTITION_NONE:
1260         process_block(twd, pbi, mi_row, mi_col, subsize, n4x4_l2, n4x4_l2);
1261         break;
1262       case PARTITION_HORZ:
1263         process_block(twd, pbi, mi_row, mi_col, subsize, n4x4_l2, n8x8_l2);
1264         if (has_rows)
1265           process_block(twd, pbi, mi_row + hbs, mi_col, subsize, n4x4_l2,
1266                         n8x8_l2);
1267         break;
1268       case PARTITION_VERT:
1269         process_block(twd, pbi, mi_row, mi_col, subsize, n8x8_l2, n4x4_l2);
1270         if (has_cols)
1271           process_block(twd, pbi, mi_row, mi_col + hbs, subsize, n8x8_l2,
1272                         n4x4_l2);
1273         break;
1274       case PARTITION_SPLIT:
1275         process_partition(twd, pbi, mi_row, mi_col, subsize, n8x8_l2,
1276                           parse_recon_flag, process_block);
1277         process_partition(twd, pbi, mi_row, mi_col + hbs, subsize, n8x8_l2,
1278                           parse_recon_flag, process_block);
1279         process_partition(twd, pbi, mi_row + hbs, mi_col, subsize, n8x8_l2,
1280                           parse_recon_flag, process_block);
1281         process_partition(twd, pbi, mi_row + hbs, mi_col + hbs, subsize,
1282                           n8x8_l2, parse_recon_flag, process_block);
1283         break;
1284       default: assert(0 && "Invalid partition type");
1285     }
1286   }
1287 
1288   if (parse_recon_flag & PARSE) {
1289     // update partition context
1290     if ((bsize == BLOCK_8X8 || partition != PARTITION_SPLIT) &&
1291         bsize >= BLOCK_8X8)
1292       dec_update_partition_context(twd, mi_row, mi_col, subsize, num_8x8_wh);
1293   }
1294 }
1295 
setup_token_decoder(const uint8_t * data,const uint8_t * data_end,size_t read_size,struct vpx_internal_error_info * error_info,vpx_reader * r,vpx_decrypt_cb decrypt_cb,void * decrypt_state)1296 static void setup_token_decoder(const uint8_t *data, const uint8_t *data_end,
1297                                 size_t read_size,
1298                                 struct vpx_internal_error_info *error_info,
1299                                 vpx_reader *r, vpx_decrypt_cb decrypt_cb,
1300                                 void *decrypt_state) {
1301   // Validate the calculated partition length. If the buffer
1302   // described by the partition can't be fully read, then restrict
1303   // it to the portion that can be (for EC mode) or throw an error.
1304   if (!read_is_valid(data, read_size, data_end))
1305     vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1306                        "Truncated packet or corrupt tile length");
1307 
1308   if (vpx_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
1309     vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
1310                        "Failed to allocate bool decoder %d", 1);
1311 }
1312 
read_coef_probs_common(vp9_coeff_probs_model * coef_probs,vpx_reader * r)1313 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
1314                                    vpx_reader *r) {
1315   int i, j, k, l, m;
1316 
1317   if (vpx_read_bit(r))
1318     for (i = 0; i < PLANE_TYPES; ++i)
1319       for (j = 0; j < REF_TYPES; ++j)
1320         for (k = 0; k < COEF_BANDS; ++k)
1321           for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1322             for (m = 0; m < UNCONSTRAINED_NODES; ++m)
1323               vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
1324 }
1325 
read_coef_probs(FRAME_CONTEXT * fc,TX_MODE tx_mode,vpx_reader * r)1326 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode, vpx_reader *r) {
1327   const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
1328   TX_SIZE tx_size;
1329   for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1330     read_coef_probs_common(fc->coef_probs[tx_size], r);
1331 }
1332 
setup_segmentation(struct segmentation * seg,struct vpx_read_bit_buffer * rb)1333 static void setup_segmentation(struct segmentation *seg,
1334                                struct vpx_read_bit_buffer *rb) {
1335   int i, j;
1336 
1337   seg->update_map = 0;
1338   seg->update_data = 0;
1339 
1340   seg->enabled = vpx_rb_read_bit(rb);
1341   if (!seg->enabled) return;
1342 
1343   // Segmentation map update
1344   seg->update_map = vpx_rb_read_bit(rb);
1345   if (seg->update_map) {
1346     for (i = 0; i < SEG_TREE_PROBS; i++)
1347       seg->tree_probs[i] =
1348           vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8) : MAX_PROB;
1349 
1350     seg->temporal_update = vpx_rb_read_bit(rb);
1351     if (seg->temporal_update) {
1352       for (i = 0; i < PREDICTION_PROBS; i++)
1353         seg->pred_probs[i] =
1354             vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8) : MAX_PROB;
1355     } else {
1356       for (i = 0; i < PREDICTION_PROBS; i++) seg->pred_probs[i] = MAX_PROB;
1357     }
1358   }
1359 
1360   // Segmentation data update
1361   seg->update_data = vpx_rb_read_bit(rb);
1362   if (seg->update_data) {
1363     seg->abs_delta = vpx_rb_read_bit(rb);
1364 
1365     vp9_clearall_segfeatures(seg);
1366 
1367     for (i = 0; i < MAX_SEGMENTS; i++) {
1368       for (j = 0; j < SEG_LVL_MAX; j++) {
1369         int data = 0;
1370         const int feature_enabled = vpx_rb_read_bit(rb);
1371         if (feature_enabled) {
1372           vp9_enable_segfeature(seg, i, j);
1373           data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1374           if (vp9_is_segfeature_signed(j))
1375             data = vpx_rb_read_bit(rb) ? -data : data;
1376         }
1377         vp9_set_segdata(seg, i, j, data);
1378       }
1379     }
1380   }
1381 }
1382 
setup_loopfilter(struct loopfilter * lf,struct vpx_read_bit_buffer * rb)1383 static void setup_loopfilter(struct loopfilter *lf,
1384                              struct vpx_read_bit_buffer *rb) {
1385   lf->filter_level = vpx_rb_read_literal(rb, 6);
1386   lf->sharpness_level = vpx_rb_read_literal(rb, 3);
1387 
1388   // Read in loop filter deltas applied at the MB level based on mode or ref
1389   // frame.
1390   lf->mode_ref_delta_update = 0;
1391 
1392   lf->mode_ref_delta_enabled = vpx_rb_read_bit(rb);
1393   if (lf->mode_ref_delta_enabled) {
1394     lf->mode_ref_delta_update = vpx_rb_read_bit(rb);
1395     if (lf->mode_ref_delta_update) {
1396       int i;
1397 
1398       for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1399         if (vpx_rb_read_bit(rb))
1400           lf->ref_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1401 
1402       for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1403         if (vpx_rb_read_bit(rb))
1404           lf->mode_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1405     }
1406   }
1407 }
1408 
read_delta_q(struct vpx_read_bit_buffer * rb)1409 static INLINE int read_delta_q(struct vpx_read_bit_buffer *rb) {
1410   return vpx_rb_read_bit(rb) ? vpx_rb_read_signed_literal(rb, 4) : 0;
1411 }
1412 
setup_quantization(VP9_COMMON * const cm,MACROBLOCKD * const xd,struct vpx_read_bit_buffer * rb)1413 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1414                                struct vpx_read_bit_buffer *rb) {
1415   cm->base_qindex = vpx_rb_read_literal(rb, QINDEX_BITS);
1416   cm->y_dc_delta_q = read_delta_q(rb);
1417   cm->uv_dc_delta_q = read_delta_q(rb);
1418   cm->uv_ac_delta_q = read_delta_q(rb);
1419   cm->dequant_bit_depth = cm->bit_depth;
1420   xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
1421                  cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
1422 
1423 #if CONFIG_VP9_HIGHBITDEPTH
1424   xd->bd = (int)cm->bit_depth;
1425 #endif
1426 }
1427 
setup_segmentation_dequant(VP9_COMMON * const cm)1428 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1429   // Build y/uv dequant values based on segmentation.
1430   if (cm->seg.enabled) {
1431     int i;
1432     for (i = 0; i < MAX_SEGMENTS; ++i) {
1433       const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1434       cm->y_dequant[i][0] =
1435           vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1436       cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1437       cm->uv_dequant[i][0] =
1438           vp9_dc_quant(qindex, cm->uv_dc_delta_q, cm->bit_depth);
1439       cm->uv_dequant[i][1] =
1440           vp9_ac_quant(qindex, cm->uv_ac_delta_q, cm->bit_depth);
1441     }
1442   } else {
1443     const int qindex = cm->base_qindex;
1444     // When segmentation is disabled, only the first value is used.  The
1445     // remaining are don't cares.
1446     cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1447     cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1448     cm->uv_dequant[0][0] =
1449         vp9_dc_quant(qindex, cm->uv_dc_delta_q, cm->bit_depth);
1450     cm->uv_dequant[0][1] =
1451         vp9_ac_quant(qindex, cm->uv_ac_delta_q, cm->bit_depth);
1452   }
1453 }
1454 
read_interp_filter(struct vpx_read_bit_buffer * rb)1455 static INTERP_FILTER read_interp_filter(struct vpx_read_bit_buffer *rb) {
1456   const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH, EIGHTTAP,
1457                                               EIGHTTAP_SHARP, BILINEAR };
1458   return vpx_rb_read_bit(rb) ? SWITCHABLE
1459                              : literal_to_filter[vpx_rb_read_literal(rb, 2)];
1460 }
1461 
setup_render_size(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)1462 static void setup_render_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1463   cm->render_width = cm->width;
1464   cm->render_height = cm->height;
1465   if (vpx_rb_read_bit(rb))
1466     vp9_read_frame_size(rb, &cm->render_width, &cm->render_height);
1467 }
1468 
resize_mv_buffer(VP9_COMMON * cm)1469 static void resize_mv_buffer(VP9_COMMON *cm) {
1470   vpx_free(cm->cur_frame->mvs);
1471   cm->cur_frame->mi_rows = cm->mi_rows;
1472   cm->cur_frame->mi_cols = cm->mi_cols;
1473   CHECK_MEM_ERROR(cm, cm->cur_frame->mvs,
1474                   (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1475                                        sizeof(*cm->cur_frame->mvs)));
1476 }
1477 
resize_context_buffers(VP9_COMMON * cm,int width,int height)1478 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1479 #if CONFIG_SIZE_LIMIT
1480   if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1481     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1482                        "Dimensions of %dx%d beyond allowed size of %dx%d.",
1483                        width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1484 #endif
1485   if (cm->width != width || cm->height != height) {
1486     const int new_mi_rows =
1487         ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1488     const int new_mi_cols =
1489         ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1490 
1491     // Allocations in vp9_alloc_context_buffers() depend on individual
1492     // dimensions as well as the overall size.
1493     if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1494       if (vp9_alloc_context_buffers(cm, width, height)) {
1495         // The cm->mi_* values have been cleared and any existing context
1496         // buffers have been freed. Clear cm->width and cm->height to be
1497         // consistent and to force a realloc next time.
1498         cm->width = 0;
1499         cm->height = 0;
1500         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1501                            "Failed to allocate context buffers");
1502       }
1503     } else {
1504       vp9_set_mb_mi(cm, width, height);
1505     }
1506     vp9_init_context_buffers(cm);
1507     cm->width = width;
1508     cm->height = height;
1509   }
1510   if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1511       cm->mi_cols > cm->cur_frame->mi_cols) {
1512     resize_mv_buffer(cm);
1513   }
1514 }
1515 
setup_frame_size(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)1516 static void setup_frame_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1517   int width, height;
1518   BufferPool *const pool = cm->buffer_pool;
1519   vp9_read_frame_size(rb, &width, &height);
1520   resize_context_buffers(cm, width, height);
1521   setup_render_size(cm, rb);
1522 
1523   if (vpx_realloc_frame_buffer(
1524           get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x,
1525           cm->subsampling_y,
1526 #if CONFIG_VP9_HIGHBITDEPTH
1527           cm->use_highbitdepth,
1528 #endif
1529           VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment,
1530           &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1531           pool->cb_priv)) {
1532     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1533                        "Failed to allocate frame buffer");
1534   }
1535 
1536   pool->frame_bufs[cm->new_fb_idx].released = 0;
1537   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1538   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1539   pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1540   pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1541   pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1542   pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1543   pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1544 }
1545 
valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,int ref_xss,int ref_yss,vpx_bit_depth_t this_bit_depth,int this_xss,int this_yss)1546 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1547                                           int ref_xss, int ref_yss,
1548                                           vpx_bit_depth_t this_bit_depth,
1549                                           int this_xss, int this_yss) {
1550   return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1551          ref_yss == this_yss;
1552 }
1553 
setup_frame_size_with_refs(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)1554 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1555                                        struct vpx_read_bit_buffer *rb) {
1556   int width, height;
1557   int found = 0, i;
1558   int has_valid_ref_frame = 0;
1559   BufferPool *const pool = cm->buffer_pool;
1560   for (i = 0; i < REFS_PER_FRAME; ++i) {
1561     if (vpx_rb_read_bit(rb)) {
1562       if (cm->frame_refs[i].idx != INVALID_IDX) {
1563         YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1564         width = buf->y_crop_width;
1565         height = buf->y_crop_height;
1566         found = 1;
1567         break;
1568       } else {
1569         vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1570                            "Failed to decode frame size");
1571       }
1572     }
1573   }
1574 
1575   if (!found) vp9_read_frame_size(rb, &width, &height);
1576 
1577   if (width <= 0 || height <= 0)
1578     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1579                        "Invalid frame size");
1580 
1581   // Check to make sure at least one of frames that this frame references
1582   // has valid dimensions.
1583   for (i = 0; i < REFS_PER_FRAME; ++i) {
1584     RefBuffer *const ref_frame = &cm->frame_refs[i];
1585     has_valid_ref_frame |=
1586         (ref_frame->idx != INVALID_IDX &&
1587          valid_ref_frame_size(ref_frame->buf->y_crop_width,
1588                               ref_frame->buf->y_crop_height, width, height));
1589   }
1590   if (!has_valid_ref_frame)
1591     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1592                        "Referenced frame has invalid size");
1593   for (i = 0; i < REFS_PER_FRAME; ++i) {
1594     RefBuffer *const ref_frame = &cm->frame_refs[i];
1595     if (ref_frame->idx == INVALID_IDX ||
1596         !valid_ref_frame_img_fmt(ref_frame->buf->bit_depth,
1597                                  ref_frame->buf->subsampling_x,
1598                                  ref_frame->buf->subsampling_y, cm->bit_depth,
1599                                  cm->subsampling_x, cm->subsampling_y))
1600       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1601                          "Referenced frame has incompatible color format");
1602   }
1603 
1604   resize_context_buffers(cm, width, height);
1605   setup_render_size(cm, rb);
1606 
1607   if (vpx_realloc_frame_buffer(
1608           get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x,
1609           cm->subsampling_y,
1610 #if CONFIG_VP9_HIGHBITDEPTH
1611           cm->use_highbitdepth,
1612 #endif
1613           VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment,
1614           &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1615           pool->cb_priv)) {
1616     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1617                        "Failed to allocate frame buffer");
1618   }
1619 
1620   pool->frame_bufs[cm->new_fb_idx].released = 0;
1621   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1622   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1623   pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1624   pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1625   pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1626   pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1627   pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1628 }
1629 
setup_tile_info(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)1630 static void setup_tile_info(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1631   int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1632   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1633 
1634   // columns
1635   max_ones = max_log2_tile_cols - min_log2_tile_cols;
1636   cm->log2_tile_cols = min_log2_tile_cols;
1637   while (max_ones-- && vpx_rb_read_bit(rb)) cm->log2_tile_cols++;
1638 
1639   if (cm->log2_tile_cols > 6)
1640     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1641                        "Invalid number of tile columns");
1642 
1643   // rows
1644   cm->log2_tile_rows = vpx_rb_read_bit(rb);
1645   if (cm->log2_tile_rows) cm->log2_tile_rows += vpx_rb_read_bit(rb);
1646 }
1647 
1648 // Reads the next tile returning its size and adjusting '*data' accordingly
1649 // based on 'is_last'.
get_tile_buffer(const uint8_t * const data_end,int is_last,struct vpx_internal_error_info * error_info,const uint8_t ** data,vpx_decrypt_cb decrypt_cb,void * decrypt_state,TileBuffer * buf)1650 static void get_tile_buffer(const uint8_t *const data_end, int is_last,
1651                             struct vpx_internal_error_info *error_info,
1652                             const uint8_t **data, vpx_decrypt_cb decrypt_cb,
1653                             void *decrypt_state, TileBuffer *buf) {
1654   size_t size;
1655 
1656   if (!is_last) {
1657     if (!read_is_valid(*data, 4, data_end))
1658       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1659                          "Truncated packet or corrupt tile length");
1660 
1661     if (decrypt_cb) {
1662       uint8_t be_data[4];
1663       decrypt_cb(decrypt_state, *data, be_data, 4);
1664       size = mem_get_be32(be_data);
1665     } else {
1666       size = mem_get_be32(*data);
1667     }
1668     *data += 4;
1669 
1670     if (size > (size_t)(data_end - *data))
1671       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1672                          "Truncated packet or corrupt tile size");
1673   } else {
1674     size = data_end - *data;
1675   }
1676 
1677   buf->data = *data;
1678   buf->size = size;
1679 
1680   *data += size;
1681 }
1682 
get_tile_buffers(VP9Decoder * pbi,const uint8_t * data,const uint8_t * data_end,int tile_cols,int tile_rows,TileBuffer (* tile_buffers)[1<<6])1683 static void get_tile_buffers(VP9Decoder *pbi, const uint8_t *data,
1684                              const uint8_t *data_end, int tile_cols,
1685                              int tile_rows,
1686                              TileBuffer (*tile_buffers)[1 << 6]) {
1687   int r, c;
1688 
1689   for (r = 0; r < tile_rows; ++r) {
1690     for (c = 0; c < tile_cols; ++c) {
1691       const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1692       TileBuffer *const buf = &tile_buffers[r][c];
1693       buf->col = c;
1694       get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1695                       pbi->decrypt_cb, pbi->decrypt_state, buf);
1696     }
1697   }
1698 }
1699 
map_write(RowMTWorkerData * const row_mt_worker_data,int map_idx,int sync_idx)1700 static void map_write(RowMTWorkerData *const row_mt_worker_data, int map_idx,
1701                       int sync_idx) {
1702 #if CONFIG_MULTITHREAD
1703   pthread_mutex_lock(&row_mt_worker_data->recon_sync_mutex[sync_idx]);
1704   row_mt_worker_data->recon_map[map_idx] = 1;
1705   pthread_cond_signal(&row_mt_worker_data->recon_sync_cond[sync_idx]);
1706   pthread_mutex_unlock(&row_mt_worker_data->recon_sync_mutex[sync_idx]);
1707 #else
1708   (void)row_mt_worker_data;
1709   (void)map_idx;
1710   (void)sync_idx;
1711 #endif  // CONFIG_MULTITHREAD
1712 }
1713 
map_read(RowMTWorkerData * const row_mt_worker_data,int map_idx,int sync_idx)1714 static void map_read(RowMTWorkerData *const row_mt_worker_data, int map_idx,
1715                      int sync_idx) {
1716 #if CONFIG_MULTITHREAD
1717   volatile int8_t *map = row_mt_worker_data->recon_map + map_idx;
1718   pthread_mutex_t *const mutex =
1719       &row_mt_worker_data->recon_sync_mutex[sync_idx];
1720   pthread_mutex_lock(mutex);
1721   while (!(*map)) {
1722     pthread_cond_wait(&row_mt_worker_data->recon_sync_cond[sync_idx], mutex);
1723   }
1724   pthread_mutex_unlock(mutex);
1725 #else
1726   (void)row_mt_worker_data;
1727   (void)map_idx;
1728   (void)sync_idx;
1729 #endif  // CONFIG_MULTITHREAD
1730 }
1731 
lpf_map_write_check(VP9LfSync * lf_sync,int row,int num_tile_cols)1732 static int lpf_map_write_check(VP9LfSync *lf_sync, int row, int num_tile_cols) {
1733   int return_val = 0;
1734 #if CONFIG_MULTITHREAD
1735   int corrupted;
1736   pthread_mutex_lock(lf_sync->lf_mutex);
1737   corrupted = lf_sync->corrupted;
1738   pthread_mutex_unlock(lf_sync->lf_mutex);
1739   if (!corrupted) {
1740     pthread_mutex_lock(&lf_sync->recon_done_mutex[row]);
1741     lf_sync->num_tiles_done[row] += 1;
1742     if (num_tile_cols == lf_sync->num_tiles_done[row]) return_val = 1;
1743     pthread_mutex_unlock(&lf_sync->recon_done_mutex[row]);
1744   }
1745 #else
1746   (void)lf_sync;
1747   (void)row;
1748   (void)num_tile_cols;
1749 #endif
1750   return return_val;
1751 }
1752 
vp9_tile_done(VP9Decoder * pbi)1753 static void vp9_tile_done(VP9Decoder *pbi) {
1754 #if CONFIG_MULTITHREAD
1755   int terminate;
1756   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
1757   const int all_parse_done = 1 << pbi->common.log2_tile_cols;
1758   pthread_mutex_lock(&row_mt_worker_data->recon_done_mutex);
1759   row_mt_worker_data->num_tiles_done++;
1760   terminate = all_parse_done == row_mt_worker_data->num_tiles_done;
1761   pthread_mutex_unlock(&row_mt_worker_data->recon_done_mutex);
1762   if (terminate) {
1763     vp9_jobq_terminate(&row_mt_worker_data->jobq);
1764   }
1765 #else
1766   (void)pbi;
1767 #endif
1768 }
1769 
vp9_jobq_alloc(VP9Decoder * pbi)1770 static void vp9_jobq_alloc(VP9Decoder *pbi) {
1771   VP9_COMMON *const cm = &pbi->common;
1772   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
1773   const int aligned_rows = mi_cols_aligned_to_sb(cm->mi_rows);
1774   const int sb_rows = aligned_rows >> MI_BLOCK_SIZE_LOG2;
1775   const int tile_cols = 1 << cm->log2_tile_cols;
1776   const size_t jobq_size = (tile_cols * sb_rows * 2 + sb_rows) * sizeof(Job);
1777 
1778   if (jobq_size > row_mt_worker_data->jobq_size) {
1779     vpx_free(row_mt_worker_data->jobq_buf);
1780     CHECK_MEM_ERROR(cm, row_mt_worker_data->jobq_buf, vpx_calloc(1, jobq_size));
1781     vp9_jobq_init(&row_mt_worker_data->jobq, row_mt_worker_data->jobq_buf,
1782                   jobq_size);
1783     row_mt_worker_data->jobq_size = jobq_size;
1784   }
1785 }
1786 
recon_tile_row(TileWorkerData * tile_data,VP9Decoder * pbi,int mi_row,int is_last_row,VP9LfSync * lf_sync,int cur_tile_col)1787 static void recon_tile_row(TileWorkerData *tile_data, VP9Decoder *pbi,
1788                            int mi_row, int is_last_row, VP9LfSync *lf_sync,
1789                            int cur_tile_col) {
1790   VP9_COMMON *const cm = &pbi->common;
1791   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
1792   const int tile_cols = 1 << cm->log2_tile_cols;
1793   const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1794   const int sb_cols = aligned_cols >> MI_BLOCK_SIZE_LOG2;
1795   const int cur_sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
1796   int mi_col_start = tile_data->xd.tile.mi_col_start;
1797   int mi_col_end = tile_data->xd.tile.mi_col_end;
1798   int mi_col;
1799 
1800   vp9_zero(tile_data->xd.left_context);
1801   vp9_zero(tile_data->xd.left_seg_context);
1802   for (mi_col = mi_col_start; mi_col < mi_col_end; mi_col += MI_BLOCK_SIZE) {
1803     const int c = mi_col >> MI_BLOCK_SIZE_LOG2;
1804     int plane;
1805     const int sb_num = (cur_sb_row * (aligned_cols >> MI_BLOCK_SIZE_LOG2) + c);
1806 
1807     // Top Dependency
1808     if (cur_sb_row) {
1809       map_read(row_mt_worker_data, ((cur_sb_row - 1) * sb_cols) + c,
1810                ((cur_sb_row - 1) * tile_cols) + cur_tile_col);
1811     }
1812 
1813     for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
1814       tile_data->xd.plane[plane].eob =
1815           row_mt_worker_data->eob[plane] + (sb_num << EOBS_PER_SB_LOG2);
1816       tile_data->xd.plane[plane].dqcoeff =
1817           row_mt_worker_data->dqcoeff[plane] + (sb_num << DQCOEFFS_PER_SB_LOG2);
1818     }
1819     tile_data->xd.partition =
1820         row_mt_worker_data->partition + (sb_num * PARTITIONS_PER_SB);
1821     process_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4, RECON,
1822                       recon_block);
1823     if (cm->lf.filter_level && !cm->skip_loop_filter) {
1824       // Queue LPF_JOB
1825       int is_lpf_job_ready = 0;
1826 
1827       if (mi_col + MI_BLOCK_SIZE >= mi_col_end) {
1828         // Checks if this row has been decoded in all tiles
1829         is_lpf_job_ready = lpf_map_write_check(lf_sync, cur_sb_row, tile_cols);
1830 
1831         if (is_lpf_job_ready) {
1832           Job lpf_job;
1833           lpf_job.job_type = LPF_JOB;
1834           if (cur_sb_row > 0) {
1835             lpf_job.row_num = mi_row - MI_BLOCK_SIZE;
1836             vp9_jobq_queue(&row_mt_worker_data->jobq, &lpf_job,
1837                            sizeof(lpf_job));
1838           }
1839           if (is_last_row) {
1840             lpf_job.row_num = mi_row;
1841             vp9_jobq_queue(&row_mt_worker_data->jobq, &lpf_job,
1842                            sizeof(lpf_job));
1843           }
1844         }
1845       }
1846     }
1847     map_write(row_mt_worker_data, (cur_sb_row * sb_cols) + c,
1848               (cur_sb_row * tile_cols) + cur_tile_col);
1849   }
1850 }
1851 
parse_tile_row(TileWorkerData * tile_data,VP9Decoder * pbi,int mi_row,int cur_tile_col,uint8_t ** data_end)1852 static void parse_tile_row(TileWorkerData *tile_data, VP9Decoder *pbi,
1853                            int mi_row, int cur_tile_col, uint8_t **data_end) {
1854   int mi_col;
1855   VP9_COMMON *const cm = &pbi->common;
1856   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
1857   TileInfo *tile = &tile_data->xd.tile;
1858   TileBuffer *const buf = &pbi->tile_buffers[cur_tile_col];
1859   const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1860 
1861   vp9_zero(tile_data->dqcoeff);
1862   vp9_tile_init(tile, cm, 0, cur_tile_col);
1863 
1864   /* Update reader only at the beginning of each row in a tile */
1865   if (mi_row == 0) {
1866     setup_token_decoder(buf->data, *data_end, buf->size, &tile_data->error_info,
1867                         &tile_data->bit_reader, pbi->decrypt_cb,
1868                         pbi->decrypt_state);
1869   }
1870   vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
1871   tile_data->xd.error_info = &tile_data->error_info;
1872 
1873   vp9_zero(tile_data->xd.left_context);
1874   vp9_zero(tile_data->xd.left_seg_context);
1875   for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1876        mi_col += MI_BLOCK_SIZE) {
1877     const int r = mi_row >> MI_BLOCK_SIZE_LOG2;
1878     const int c = mi_col >> MI_BLOCK_SIZE_LOG2;
1879     int plane;
1880     const int sb_num = (r * (aligned_cols >> MI_BLOCK_SIZE_LOG2) + c);
1881     for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
1882       tile_data->xd.plane[plane].eob =
1883           row_mt_worker_data->eob[plane] + (sb_num << EOBS_PER_SB_LOG2);
1884       tile_data->xd.plane[plane].dqcoeff =
1885           row_mt_worker_data->dqcoeff[plane] + (sb_num << DQCOEFFS_PER_SB_LOG2);
1886     }
1887     tile_data->xd.partition =
1888         row_mt_worker_data->partition + sb_num * PARTITIONS_PER_SB;
1889     process_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4, PARSE,
1890                       parse_block);
1891   }
1892 }
1893 
row_decode_worker_hook(void * arg1,void * arg2)1894 static int row_decode_worker_hook(void *arg1, void *arg2) {
1895   ThreadData *const thread_data = (ThreadData *)arg1;
1896   uint8_t **data_end = (uint8_t **)arg2;
1897   VP9Decoder *const pbi = thread_data->pbi;
1898   VP9_COMMON *const cm = &pbi->common;
1899   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
1900   const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1901   const int aligned_rows = mi_cols_aligned_to_sb(cm->mi_rows);
1902   const int sb_rows = aligned_rows >> MI_BLOCK_SIZE_LOG2;
1903   const int tile_cols = 1 << cm->log2_tile_cols;
1904   Job job;
1905   LFWorkerData *lf_data = thread_data->lf_data;
1906   VP9LfSync *lf_sync = thread_data->lf_sync;
1907   volatile int corrupted = 0;
1908   TileWorkerData *volatile tile_data_recon = NULL;
1909 
1910   while (!vp9_jobq_dequeue(&row_mt_worker_data->jobq, &job, sizeof(job), 1)) {
1911     int mi_col;
1912     const int mi_row = job.row_num;
1913 
1914     if (job.job_type == LPF_JOB) {
1915       lf_data->start = mi_row;
1916       lf_data->stop = lf_data->start + MI_BLOCK_SIZE;
1917 
1918       if (cm->lf.filter_level && !cm->skip_loop_filter &&
1919           mi_row < cm->mi_rows) {
1920         vp9_loopfilter_job(lf_data, lf_sync);
1921       }
1922     } else if (job.job_type == RECON_JOB) {
1923       const int cur_sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
1924       const int is_last_row = sb_rows - 1 == cur_sb_row;
1925       int mi_col_start, mi_col_end;
1926       if (!tile_data_recon)
1927         CHECK_MEM_ERROR(cm, tile_data_recon,
1928                         vpx_memalign(32, sizeof(TileWorkerData)));
1929 
1930       tile_data_recon->xd = pbi->mb;
1931       vp9_tile_init(&tile_data_recon->xd.tile, cm, 0, job.tile_col);
1932       vp9_init_macroblockd(cm, &tile_data_recon->xd, tile_data_recon->dqcoeff);
1933       mi_col_start = tile_data_recon->xd.tile.mi_col_start;
1934       mi_col_end = tile_data_recon->xd.tile.mi_col_end;
1935 
1936       if (setjmp(tile_data_recon->error_info.jmp)) {
1937         const int sb_cols = aligned_cols >> MI_BLOCK_SIZE_LOG2;
1938         tile_data_recon->error_info.setjmp = 0;
1939         corrupted = 1;
1940         for (mi_col = mi_col_start; mi_col < mi_col_end;
1941              mi_col += MI_BLOCK_SIZE) {
1942           const int c = mi_col >> MI_BLOCK_SIZE_LOG2;
1943           map_write(row_mt_worker_data, (cur_sb_row * sb_cols) + c,
1944                     (cur_sb_row * tile_cols) + job.tile_col);
1945         }
1946         if (is_last_row) {
1947           vp9_tile_done(pbi);
1948         }
1949         continue;
1950       }
1951 
1952       tile_data_recon->error_info.setjmp = 1;
1953       tile_data_recon->xd.error_info = &tile_data_recon->error_info;
1954 
1955       recon_tile_row(tile_data_recon, pbi, mi_row, is_last_row, lf_sync,
1956                      job.tile_col);
1957 
1958       if (corrupted)
1959         vpx_internal_error(&tile_data_recon->error_info,
1960                            VPX_CODEC_CORRUPT_FRAME,
1961                            "Failed to decode tile data");
1962 
1963       if (is_last_row) {
1964         vp9_tile_done(pbi);
1965       }
1966     } else if (job.job_type == PARSE_JOB) {
1967       TileWorkerData *const tile_data = &pbi->tile_worker_data[job.tile_col];
1968 
1969       if (setjmp(tile_data->error_info.jmp)) {
1970         tile_data->error_info.setjmp = 0;
1971         corrupted = 1;
1972         vp9_tile_done(pbi);
1973         continue;
1974       }
1975 
1976       tile_data->xd = pbi->mb;
1977       tile_data->xd.counts =
1978           cm->frame_parallel_decoding_mode ? 0 : &tile_data->counts;
1979 
1980       tile_data->error_info.setjmp = 1;
1981 
1982       parse_tile_row(tile_data, pbi, mi_row, job.tile_col, data_end);
1983 
1984       corrupted |= tile_data->xd.corrupted;
1985       if (corrupted)
1986         vpx_internal_error(&tile_data->error_info, VPX_CODEC_CORRUPT_FRAME,
1987                            "Failed to decode tile data");
1988 
1989       /* Queue in the recon_job for this row */
1990       {
1991         Job recon_job;
1992         recon_job.row_num = mi_row;
1993         recon_job.tile_col = job.tile_col;
1994         recon_job.job_type = RECON_JOB;
1995         vp9_jobq_queue(&row_mt_worker_data->jobq, &recon_job,
1996                        sizeof(recon_job));
1997       }
1998 
1999       /* Queue next parse job */
2000       if (mi_row + MI_BLOCK_SIZE < cm->mi_rows) {
2001         Job parse_job;
2002         parse_job.row_num = mi_row + MI_BLOCK_SIZE;
2003         parse_job.tile_col = job.tile_col;
2004         parse_job.job_type = PARSE_JOB;
2005         vp9_jobq_queue(&row_mt_worker_data->jobq, &parse_job,
2006                        sizeof(parse_job));
2007       }
2008     }
2009   }
2010 
2011   vpx_free(tile_data_recon);
2012   return !corrupted;
2013 }
2014 
decode_tiles(VP9Decoder * pbi,const uint8_t * data,const uint8_t * data_end)2015 static const uint8_t *decode_tiles(VP9Decoder *pbi, const uint8_t *data,
2016                                    const uint8_t *data_end) {
2017   VP9_COMMON *const cm = &pbi->common;
2018   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
2019   const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2020   const int tile_cols = 1 << cm->log2_tile_cols;
2021   const int tile_rows = 1 << cm->log2_tile_rows;
2022   TileBuffer tile_buffers[4][1 << 6];
2023   int tile_row, tile_col;
2024   int mi_row, mi_col;
2025   TileWorkerData *tile_data = NULL;
2026 
2027   if (cm->lf.filter_level && !cm->skip_loop_filter &&
2028       pbi->lf_worker.data1 == NULL) {
2029     CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
2030                     vpx_memalign(32, sizeof(LFWorkerData)));
2031     pbi->lf_worker.hook = vp9_loop_filter_worker;
2032     if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
2033       vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
2034                          "Loop filter thread creation failed");
2035     }
2036   }
2037 
2038   if (cm->lf.filter_level && !cm->skip_loop_filter) {
2039     LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
2040     // Be sure to sync as we might be resuming after a failed frame decode.
2041     winterface->sync(&pbi->lf_worker);
2042     vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
2043                                pbi->mb.plane);
2044   }
2045 
2046   assert(tile_rows <= 4);
2047   assert(tile_cols <= (1 << 6));
2048 
2049   // Note: this memset assumes above_context[0], [1] and [2]
2050   // are allocated as part of the same buffer.
2051   memset(cm->above_context, 0,
2052          sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
2053 
2054   memset(cm->above_seg_context, 0,
2055          sizeof(*cm->above_seg_context) * aligned_cols);
2056 
2057   vp9_reset_lfm(cm);
2058 
2059   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
2060 
2061   // Load all tile information into tile_data.
2062   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
2063     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
2064       const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
2065       tile_data = pbi->tile_worker_data + tile_cols * tile_row + tile_col;
2066       tile_data->xd = pbi->mb;
2067       tile_data->xd.corrupted = 0;
2068       tile_data->xd.counts =
2069           cm->frame_parallel_decoding_mode ? NULL : &cm->counts;
2070       vp9_zero(tile_data->dqcoeff);
2071       vp9_tile_init(&tile_data->xd.tile, cm, tile_row, tile_col);
2072       setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
2073                           &tile_data->bit_reader, pbi->decrypt_cb,
2074                           pbi->decrypt_state);
2075       vp9_init_macroblockd(cm, &tile_data->xd, tile_data->dqcoeff);
2076     }
2077   }
2078 
2079   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
2080     TileInfo tile;
2081     vp9_tile_set_row(&tile, cm, tile_row);
2082     for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
2083          mi_row += MI_BLOCK_SIZE) {
2084       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
2085         const int col =
2086             pbi->inv_tile_order ? tile_cols - tile_col - 1 : tile_col;
2087         tile_data = pbi->tile_worker_data + tile_cols * tile_row + col;
2088         vp9_tile_set_col(&tile, cm, col);
2089         vp9_zero(tile_data->xd.left_context);
2090         vp9_zero(tile_data->xd.left_seg_context);
2091         for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
2092              mi_col += MI_BLOCK_SIZE) {
2093           if (pbi->row_mt == 1) {
2094             int plane;
2095             RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
2096             for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
2097               tile_data->xd.plane[plane].eob = row_mt_worker_data->eob[plane];
2098               tile_data->xd.plane[plane].dqcoeff =
2099                   row_mt_worker_data->dqcoeff[plane];
2100             }
2101             tile_data->xd.partition = row_mt_worker_data->partition;
2102             process_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4,
2103                               PARSE, parse_block);
2104 
2105             for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
2106               tile_data->xd.plane[plane].eob = row_mt_worker_data->eob[plane];
2107               tile_data->xd.plane[plane].dqcoeff =
2108                   row_mt_worker_data->dqcoeff[plane];
2109             }
2110             tile_data->xd.partition = row_mt_worker_data->partition;
2111             process_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4,
2112                               RECON, recon_block);
2113           } else {
2114             decode_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4);
2115           }
2116         }
2117         pbi->mb.corrupted |= tile_data->xd.corrupted;
2118         if (pbi->mb.corrupted)
2119           vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2120                              "Failed to decode tile data");
2121       }
2122       // Loopfilter one row.
2123       if (cm->lf.filter_level && !cm->skip_loop_filter) {
2124         const int lf_start = mi_row - MI_BLOCK_SIZE;
2125         LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
2126 
2127         // delay the loopfilter by 1 macroblock row.
2128         if (lf_start < 0) continue;
2129 
2130         // decoding has completed: finish up the loop filter in this thread.
2131         if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
2132 
2133         winterface->sync(&pbi->lf_worker);
2134         lf_data->start = lf_start;
2135         lf_data->stop = mi_row;
2136         if (pbi->max_threads > 1) {
2137           winterface->launch(&pbi->lf_worker);
2138         } else {
2139           winterface->execute(&pbi->lf_worker);
2140         }
2141       }
2142     }
2143   }
2144 
2145   // Loopfilter remaining rows in the frame.
2146   if (cm->lf.filter_level && !cm->skip_loop_filter) {
2147     LFWorkerData *const lf_data = (LFWorkerData *)pbi->lf_worker.data1;
2148     winterface->sync(&pbi->lf_worker);
2149     lf_data->start = lf_data->stop;
2150     lf_data->stop = cm->mi_rows;
2151     winterface->execute(&pbi->lf_worker);
2152   }
2153 
2154   // Get last tile data.
2155   tile_data = pbi->tile_worker_data + tile_cols * tile_rows - 1;
2156 
2157   return vpx_reader_find_end(&tile_data->bit_reader);
2158 }
2159 
set_rows_after_error(VP9LfSync * lf_sync,int start_row,int mi_rows,int num_tiles_left,int total_num_tiles)2160 static void set_rows_after_error(VP9LfSync *lf_sync, int start_row, int mi_rows,
2161                                  int num_tiles_left, int total_num_tiles) {
2162   do {
2163     int mi_row;
2164     const int aligned_rows = mi_cols_aligned_to_sb(mi_rows);
2165     const int sb_rows = (aligned_rows >> MI_BLOCK_SIZE_LOG2);
2166     const int corrupted = 1;
2167     for (mi_row = start_row; mi_row < mi_rows; mi_row += MI_BLOCK_SIZE) {
2168       const int is_last_row = (sb_rows - 1 == mi_row >> MI_BLOCK_SIZE_LOG2);
2169       vp9_set_row(lf_sync, total_num_tiles, mi_row >> MI_BLOCK_SIZE_LOG2,
2170                   is_last_row, corrupted);
2171     }
2172     /* If there are multiple tiles, the second tile should start marking row
2173      * progress from row 0.
2174      */
2175     start_row = 0;
2176   } while (num_tiles_left--);
2177 }
2178 
2179 // On entry 'tile_data->data_end' points to the end of the input frame, on exit
2180 // it is updated to reflect the bitreader position of the final tile column if
2181 // present in the tile buffer group or NULL otherwise.
tile_worker_hook(void * arg1,void * arg2)2182 static int tile_worker_hook(void *arg1, void *arg2) {
2183   TileWorkerData *const tile_data = (TileWorkerData *)arg1;
2184   VP9Decoder *const pbi = (VP9Decoder *)arg2;
2185 
2186   TileInfo *volatile tile = &tile_data->xd.tile;
2187   const int final_col = (1 << pbi->common.log2_tile_cols) - 1;
2188   const uint8_t *volatile bit_reader_end = NULL;
2189   VP9_COMMON *cm = &pbi->common;
2190 
2191   LFWorkerData *lf_data = tile_data->lf_data;
2192   VP9LfSync *lf_sync = tile_data->lf_sync;
2193 
2194   volatile int mi_row = 0;
2195   volatile int n = tile_data->buf_start;
2196   tile_data->error_info.setjmp = 1;
2197 
2198   if (setjmp(tile_data->error_info.jmp)) {
2199     tile_data->error_info.setjmp = 0;
2200     tile_data->xd.corrupted = 1;
2201     tile_data->data_end = NULL;
2202     if (pbi->lpf_mt_opt && cm->lf.filter_level && !cm->skip_loop_filter) {
2203       const int num_tiles_left = tile_data->buf_end - n;
2204       const int mi_row_start = mi_row;
2205       set_rows_after_error(lf_sync, mi_row_start, cm->mi_rows, num_tiles_left,
2206                            1 << cm->log2_tile_cols);
2207     }
2208     return 0;
2209   }
2210 
2211   tile_data->xd.corrupted = 0;
2212 
2213   do {
2214     int mi_col;
2215     const TileBuffer *const buf = pbi->tile_buffers + n;
2216 
2217     /* Initialize to 0 is safe since we do not deal with streams that have
2218      * more than one row of tiles. (So tile->mi_row_start will be 0)
2219      */
2220     assert(cm->log2_tile_rows == 0);
2221     mi_row = 0;
2222     vp9_zero(tile_data->dqcoeff);
2223     vp9_tile_init(tile, &pbi->common, 0, buf->col);
2224     setup_token_decoder(buf->data, tile_data->data_end, buf->size,
2225                         &tile_data->error_info, &tile_data->bit_reader,
2226                         pbi->decrypt_cb, pbi->decrypt_state);
2227     vp9_init_macroblockd(&pbi->common, &tile_data->xd, tile_data->dqcoeff);
2228     // init resets xd.error_info
2229     tile_data->xd.error_info = &tile_data->error_info;
2230 
2231     for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
2232          mi_row += MI_BLOCK_SIZE) {
2233       vp9_zero(tile_data->xd.left_context);
2234       vp9_zero(tile_data->xd.left_seg_context);
2235       for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
2236            mi_col += MI_BLOCK_SIZE) {
2237         decode_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4);
2238       }
2239       if (pbi->lpf_mt_opt && cm->lf.filter_level && !cm->skip_loop_filter) {
2240         const int aligned_rows = mi_cols_aligned_to_sb(cm->mi_rows);
2241         const int sb_rows = (aligned_rows >> MI_BLOCK_SIZE_LOG2);
2242         const int is_last_row = (sb_rows - 1 == mi_row >> MI_BLOCK_SIZE_LOG2);
2243         vp9_set_row(lf_sync, 1 << cm->log2_tile_cols,
2244                     mi_row >> MI_BLOCK_SIZE_LOG2, is_last_row,
2245                     tile_data->xd.corrupted);
2246       }
2247     }
2248 
2249     if (buf->col == final_col) {
2250       bit_reader_end = vpx_reader_find_end(&tile_data->bit_reader);
2251     }
2252   } while (!tile_data->xd.corrupted && ++n <= tile_data->buf_end);
2253 
2254   if (pbi->lpf_mt_opt && n < tile_data->buf_end && cm->lf.filter_level &&
2255       !cm->skip_loop_filter) {
2256     /* This was not incremented in the tile loop, so increment before tiles left
2257      * calculation
2258      */
2259     ++n;
2260     set_rows_after_error(lf_sync, 0, cm->mi_rows, tile_data->buf_end - n,
2261                          1 << cm->log2_tile_cols);
2262   }
2263 
2264   if (pbi->lpf_mt_opt && !tile_data->xd.corrupted && cm->lf.filter_level &&
2265       !cm->skip_loop_filter) {
2266     vp9_loopfilter_rows(lf_data, lf_sync);
2267   }
2268 
2269   tile_data->data_end = bit_reader_end;
2270   return !tile_data->xd.corrupted;
2271 }
2272 
2273 // sorts in descending order
compare_tile_buffers(const void * a,const void * b)2274 static int compare_tile_buffers(const void *a, const void *b) {
2275   const TileBuffer *const buf_a = (const TileBuffer *)a;
2276   const TileBuffer *const buf_b = (const TileBuffer *)b;
2277   return (buf_a->size < buf_b->size) - (buf_a->size > buf_b->size);
2278 }
2279 
init_mt(VP9Decoder * pbi)2280 static INLINE void init_mt(VP9Decoder *pbi) {
2281   int n;
2282   VP9_COMMON *const cm = &pbi->common;
2283   VP9LfSync *lf_row_sync = &pbi->lf_row_sync;
2284   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2285   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
2286 
2287   if (pbi->num_tile_workers == 0) {
2288     const int num_threads = pbi->max_threads;
2289     CHECK_MEM_ERROR(cm, pbi->tile_workers,
2290                     vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
2291     for (n = 0; n < num_threads; ++n) {
2292       VPxWorker *const worker = &pbi->tile_workers[n];
2293       ++pbi->num_tile_workers;
2294 
2295       winterface->init(worker);
2296       if (n < num_threads - 1 && !winterface->reset(worker)) {
2297         vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
2298                            "Tile decoder thread creation failed");
2299       }
2300     }
2301   }
2302 
2303   // Initialize LPF
2304   if ((pbi->lpf_mt_opt || pbi->row_mt) && cm->lf.filter_level &&
2305       !cm->skip_loop_filter) {
2306     vp9_lpf_mt_init(lf_row_sync, cm, cm->lf.filter_level,
2307                     pbi->num_tile_workers);
2308   }
2309 
2310   // Note: this memset assumes above_context[0], [1] and [2]
2311   // are allocated as part of the same buffer.
2312   memset(cm->above_context, 0,
2313          sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
2314 
2315   memset(cm->above_seg_context, 0,
2316          sizeof(*cm->above_seg_context) * aligned_mi_cols);
2317 
2318   vp9_reset_lfm(cm);
2319 }
2320 
decode_tiles_row_wise_mt(VP9Decoder * pbi,const uint8_t * data,const uint8_t * data_end)2321 static const uint8_t *decode_tiles_row_wise_mt(VP9Decoder *pbi,
2322                                                const uint8_t *data,
2323                                                const uint8_t *data_end) {
2324   VP9_COMMON *const cm = &pbi->common;
2325   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
2326   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
2327   const int tile_cols = 1 << cm->log2_tile_cols;
2328   const int tile_rows = 1 << cm->log2_tile_rows;
2329   const int num_workers = pbi->max_threads;
2330   int i, n;
2331   int col;
2332   int corrupted = 0;
2333   const int sb_rows = mi_cols_aligned_to_sb(cm->mi_rows) >> MI_BLOCK_SIZE_LOG2;
2334   const int sb_cols = mi_cols_aligned_to_sb(cm->mi_cols) >> MI_BLOCK_SIZE_LOG2;
2335   VP9LfSync *lf_row_sync = &pbi->lf_row_sync;
2336   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2337 
2338   assert(tile_cols <= (1 << 6));
2339   assert(tile_rows == 1);
2340   (void)tile_rows;
2341 
2342   memset(row_mt_worker_data->recon_map, 0,
2343          sb_rows * sb_cols * sizeof(*row_mt_worker_data->recon_map));
2344 
2345   init_mt(pbi);
2346 
2347   // Reset tile decoding hook
2348   for (n = 0; n < num_workers; ++n) {
2349     VPxWorker *const worker = &pbi->tile_workers[n];
2350     ThreadData *const thread_data = &pbi->row_mt_worker_data->thread_data[n];
2351     winterface->sync(worker);
2352 
2353     if (cm->lf.filter_level && !cm->skip_loop_filter) {
2354       thread_data->lf_sync = lf_row_sync;
2355       thread_data->lf_data = &thread_data->lf_sync->lfdata[n];
2356       vp9_loop_filter_data_reset(thread_data->lf_data, new_fb, cm,
2357                                  pbi->mb.plane);
2358     }
2359 
2360     thread_data->pbi = pbi;
2361 
2362     worker->hook = row_decode_worker_hook;
2363     worker->data1 = thread_data;
2364     worker->data2 = (void *)&row_mt_worker_data->data_end;
2365   }
2366 
2367   for (col = 0; col < tile_cols; ++col) {
2368     TileWorkerData *const tile_data = &pbi->tile_worker_data[col];
2369     tile_data->xd = pbi->mb;
2370     tile_data->xd.counts =
2371         cm->frame_parallel_decoding_mode ? NULL : &tile_data->counts;
2372   }
2373 
2374   /* Reset the jobq to start of the jobq buffer */
2375   vp9_jobq_reset(&row_mt_worker_data->jobq);
2376   row_mt_worker_data->num_tiles_done = 0;
2377   row_mt_worker_data->data_end = NULL;
2378 
2379   // Load tile data into tile_buffers
2380   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows,
2381                    &pbi->tile_buffers);
2382 
2383   // Initialize thread frame counts.
2384   if (!cm->frame_parallel_decoding_mode) {
2385     for (col = 0; col < tile_cols; ++col) {
2386       TileWorkerData *const tile_data = &pbi->tile_worker_data[col];
2387       vp9_zero(tile_data->counts);
2388     }
2389   }
2390 
2391   // queue parse jobs for 0th row of every tile
2392   for (col = 0; col < tile_cols; ++col) {
2393     Job parse_job;
2394     parse_job.row_num = 0;
2395     parse_job.tile_col = col;
2396     parse_job.job_type = PARSE_JOB;
2397     vp9_jobq_queue(&row_mt_worker_data->jobq, &parse_job, sizeof(parse_job));
2398   }
2399 
2400   for (i = 0; i < num_workers; ++i) {
2401     VPxWorker *const worker = &pbi->tile_workers[i];
2402     worker->had_error = 0;
2403     if (i == num_workers - 1) {
2404       winterface->execute(worker);
2405     } else {
2406       winterface->launch(worker);
2407     }
2408   }
2409 
2410   for (; n > 0; --n) {
2411     VPxWorker *const worker = &pbi->tile_workers[n - 1];
2412     // TODO(jzern): The tile may have specific error data associated with
2413     // its vpx_internal_error_info which could be propagated to the main info
2414     // in cm. Additionally once the threads have been synced and an error is
2415     // detected, there's no point in continuing to decode tiles.
2416     corrupted |= !winterface->sync(worker);
2417   }
2418 
2419   pbi->mb.corrupted = corrupted;
2420 
2421   {
2422     /* Set data end */
2423     TileWorkerData *const tile_data = &pbi->tile_worker_data[tile_cols - 1];
2424     row_mt_worker_data->data_end = vpx_reader_find_end(&tile_data->bit_reader);
2425   }
2426 
2427   // Accumulate thread frame counts.
2428   if (!cm->frame_parallel_decoding_mode) {
2429     for (i = 0; i < tile_cols; ++i) {
2430       TileWorkerData *const tile_data = &pbi->tile_worker_data[i];
2431       vp9_accumulate_frame_counts(&cm->counts, &tile_data->counts, 1);
2432     }
2433   }
2434 
2435   return row_mt_worker_data->data_end;
2436 }
2437 
decode_tiles_mt(VP9Decoder * pbi,const uint8_t * data,const uint8_t * data_end)2438 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi, const uint8_t *data,
2439                                       const uint8_t *data_end) {
2440   VP9_COMMON *const cm = &pbi->common;
2441   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
2442   const uint8_t *bit_reader_end = NULL;
2443   VP9LfSync *lf_row_sync = &pbi->lf_row_sync;
2444   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2445   const int tile_cols = 1 << cm->log2_tile_cols;
2446   const int tile_rows = 1 << cm->log2_tile_rows;
2447   const int num_workers = VPXMIN(pbi->max_threads, tile_cols);
2448   int n;
2449 
2450   assert(tile_cols <= (1 << 6));
2451   assert(tile_rows == 1);
2452   (void)tile_rows;
2453 
2454   init_mt(pbi);
2455 
2456   // Reset tile decoding hook
2457   for (n = 0; n < num_workers; ++n) {
2458     VPxWorker *const worker = &pbi->tile_workers[n];
2459     TileWorkerData *const tile_data =
2460         &pbi->tile_worker_data[n + pbi->total_tiles];
2461     winterface->sync(worker);
2462 
2463     if (pbi->lpf_mt_opt && cm->lf.filter_level && !cm->skip_loop_filter) {
2464       tile_data->lf_sync = lf_row_sync;
2465       tile_data->lf_data = &tile_data->lf_sync->lfdata[n];
2466       vp9_loop_filter_data_reset(tile_data->lf_data, new_fb, cm, pbi->mb.plane);
2467       tile_data->lf_data->y_only = 0;
2468     }
2469 
2470     tile_data->xd = pbi->mb;
2471     tile_data->xd.counts =
2472         cm->frame_parallel_decoding_mode ? NULL : &tile_data->counts;
2473     worker->hook = tile_worker_hook;
2474     worker->data1 = tile_data;
2475     worker->data2 = pbi;
2476   }
2477 
2478   // Load tile data into tile_buffers
2479   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows,
2480                    &pbi->tile_buffers);
2481 
2482   // Sort the buffers based on size in descending order.
2483   qsort(pbi->tile_buffers, tile_cols, sizeof(pbi->tile_buffers[0]),
2484         compare_tile_buffers);
2485 
2486   if (num_workers == tile_cols) {
2487     // Rearrange the tile buffers such that the largest, and
2488     // presumably the most difficult, tile will be decoded in the main thread.
2489     // This should help minimize the number of instances where the main thread
2490     // is waiting for a worker to complete.
2491     const TileBuffer largest = pbi->tile_buffers[0];
2492     memmove(pbi->tile_buffers, pbi->tile_buffers + 1,
2493             (tile_cols - 1) * sizeof(pbi->tile_buffers[0]));
2494     pbi->tile_buffers[tile_cols - 1] = largest;
2495   } else {
2496     int start = 0, end = tile_cols - 2;
2497     TileBuffer tmp;
2498 
2499     // Interleave the tiles to distribute the load between threads, assuming a
2500     // larger tile implies it is more difficult to decode.
2501     while (start < end) {
2502       tmp = pbi->tile_buffers[start];
2503       pbi->tile_buffers[start] = pbi->tile_buffers[end];
2504       pbi->tile_buffers[end] = tmp;
2505       start += 2;
2506       end -= 2;
2507     }
2508   }
2509 
2510   // Initialize thread frame counts.
2511   if (!cm->frame_parallel_decoding_mode) {
2512     for (n = 0; n < num_workers; ++n) {
2513       TileWorkerData *const tile_data =
2514           (TileWorkerData *)pbi->tile_workers[n].data1;
2515       vp9_zero(tile_data->counts);
2516     }
2517   }
2518 
2519   {
2520     const int base = tile_cols / num_workers;
2521     const int remain = tile_cols % num_workers;
2522     int buf_start = 0;
2523 
2524     for (n = 0; n < num_workers; ++n) {
2525       const int count = base + (remain + n) / num_workers;
2526       VPxWorker *const worker = &pbi->tile_workers[n];
2527       TileWorkerData *const tile_data = (TileWorkerData *)worker->data1;
2528 
2529       tile_data->buf_start = buf_start;
2530       tile_data->buf_end = buf_start + count - 1;
2531       tile_data->data_end = data_end;
2532       buf_start += count;
2533 
2534       worker->had_error = 0;
2535       if (n == num_workers - 1) {
2536         assert(tile_data->buf_end == tile_cols - 1);
2537         winterface->execute(worker);
2538       } else {
2539         winterface->launch(worker);
2540       }
2541     }
2542 
2543     for (; n > 0; --n) {
2544       VPxWorker *const worker = &pbi->tile_workers[n - 1];
2545       TileWorkerData *const tile_data = (TileWorkerData *)worker->data1;
2546       // TODO(jzern): The tile may have specific error data associated with
2547       // its vpx_internal_error_info which could be propagated to the main info
2548       // in cm. Additionally once the threads have been synced and an error is
2549       // detected, there's no point in continuing to decode tiles.
2550       pbi->mb.corrupted |= !winterface->sync(worker);
2551       if (!bit_reader_end) bit_reader_end = tile_data->data_end;
2552     }
2553   }
2554 
2555   // Accumulate thread frame counts.
2556   if (!cm->frame_parallel_decoding_mode) {
2557     for (n = 0; n < num_workers; ++n) {
2558       TileWorkerData *const tile_data =
2559           (TileWorkerData *)pbi->tile_workers[n].data1;
2560       vp9_accumulate_frame_counts(&cm->counts, &tile_data->counts, 1);
2561     }
2562   }
2563 
2564   assert(bit_reader_end || pbi->mb.corrupted);
2565   return bit_reader_end;
2566 }
2567 
error_handler(void * data)2568 static void error_handler(void *data) {
2569   VP9_COMMON *const cm = (VP9_COMMON *)data;
2570   vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
2571 }
2572 
read_bitdepth_colorspace_sampling(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)2573 static void read_bitdepth_colorspace_sampling(VP9_COMMON *cm,
2574                                               struct vpx_read_bit_buffer *rb) {
2575   if (cm->profile >= PROFILE_2) {
2576     cm->bit_depth = vpx_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
2577 #if CONFIG_VP9_HIGHBITDEPTH
2578     cm->use_highbitdepth = 1;
2579 #endif
2580   } else {
2581     cm->bit_depth = VPX_BITS_8;
2582 #if CONFIG_VP9_HIGHBITDEPTH
2583     cm->use_highbitdepth = 0;
2584 #endif
2585   }
2586   cm->color_space = vpx_rb_read_literal(rb, 3);
2587   if (cm->color_space != VPX_CS_SRGB) {
2588     cm->color_range = (vpx_color_range_t)vpx_rb_read_bit(rb);
2589     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
2590       cm->subsampling_x = vpx_rb_read_bit(rb);
2591       cm->subsampling_y = vpx_rb_read_bit(rb);
2592       if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
2593         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2594                            "4:2:0 color not supported in profile 1 or 3");
2595       if (vpx_rb_read_bit(rb))
2596         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2597                            "Reserved bit set");
2598     } else {
2599       cm->subsampling_y = cm->subsampling_x = 1;
2600     }
2601   } else {
2602     cm->color_range = VPX_CR_FULL_RANGE;
2603     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
2604       // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
2605       // 4:2:2 or 4:4:0 chroma sampling is not allowed.
2606       cm->subsampling_y = cm->subsampling_x = 0;
2607       if (vpx_rb_read_bit(rb))
2608         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2609                            "Reserved bit set");
2610     } else {
2611       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2612                          "4:4:4 color not supported in profile 0 or 2");
2613     }
2614   }
2615 }
2616 
flush_all_fb_on_key(VP9_COMMON * cm)2617 static INLINE void flush_all_fb_on_key(VP9_COMMON *cm) {
2618   if (cm->frame_type == KEY_FRAME && cm->current_video_frame > 0) {
2619     RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
2620     BufferPool *const pool = cm->buffer_pool;
2621     int i;
2622     for (i = 0; i < FRAME_BUFFERS; ++i) {
2623       if (i == cm->new_fb_idx) continue;
2624       frame_bufs[i].ref_count = 0;
2625       if (!frame_bufs[i].released) {
2626         pool->release_fb_cb(pool->cb_priv, &frame_bufs[i].raw_frame_buffer);
2627         frame_bufs[i].released = 1;
2628       }
2629     }
2630   }
2631 }
2632 
read_uncompressed_header(VP9Decoder * pbi,struct vpx_read_bit_buffer * rb)2633 static size_t read_uncompressed_header(VP9Decoder *pbi,
2634                                        struct vpx_read_bit_buffer *rb) {
2635   VP9_COMMON *const cm = &pbi->common;
2636   BufferPool *const pool = cm->buffer_pool;
2637   RefCntBuffer *const frame_bufs = pool->frame_bufs;
2638   int i, mask, ref_index = 0;
2639   size_t sz;
2640 
2641   cm->last_frame_type = cm->frame_type;
2642   cm->last_intra_only = cm->intra_only;
2643 
2644   if (vpx_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
2645     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2646                        "Invalid frame marker");
2647 
2648   cm->profile = vp9_read_profile(rb);
2649 #if CONFIG_VP9_HIGHBITDEPTH
2650   if (cm->profile >= MAX_PROFILES)
2651     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2652                        "Unsupported bitstream profile");
2653 #else
2654   if (cm->profile >= PROFILE_2)
2655     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2656                        "Unsupported bitstream profile");
2657 #endif
2658 
2659   cm->show_existing_frame = vpx_rb_read_bit(rb);
2660   if (cm->show_existing_frame) {
2661     // Show an existing frame directly.
2662     const int frame_to_show = cm->ref_frame_map[vpx_rb_read_literal(rb, 3)];
2663     if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
2664       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2665                          "Buffer %d does not contain a decoded frame",
2666                          frame_to_show);
2667     }
2668 
2669     ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
2670     pbi->refresh_frame_flags = 0;
2671     cm->lf.filter_level = 0;
2672     cm->show_frame = 1;
2673 
2674     return 0;
2675   }
2676 
2677   cm->frame_type = (FRAME_TYPE)vpx_rb_read_bit(rb);
2678   cm->show_frame = vpx_rb_read_bit(rb);
2679   cm->error_resilient_mode = vpx_rb_read_bit(rb);
2680 
2681   if (cm->frame_type == KEY_FRAME) {
2682     if (!vp9_read_sync_code(rb))
2683       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2684                          "Invalid frame sync code");
2685 
2686     read_bitdepth_colorspace_sampling(cm, rb);
2687     pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
2688 
2689     for (i = 0; i < REFS_PER_FRAME; ++i) {
2690       cm->frame_refs[i].idx = INVALID_IDX;
2691       cm->frame_refs[i].buf = NULL;
2692     }
2693 
2694     setup_frame_size(cm, rb);
2695     if (pbi->need_resync) {
2696       memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
2697       flush_all_fb_on_key(cm);
2698       pbi->need_resync = 0;
2699     }
2700   } else {
2701     cm->intra_only = cm->show_frame ? 0 : vpx_rb_read_bit(rb);
2702 
2703     cm->reset_frame_context =
2704         cm->error_resilient_mode ? 0 : vpx_rb_read_literal(rb, 2);
2705 
2706     if (cm->intra_only) {
2707       if (!vp9_read_sync_code(rb))
2708         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2709                            "Invalid frame sync code");
2710       if (cm->profile > PROFILE_0) {
2711         read_bitdepth_colorspace_sampling(cm, rb);
2712       } else {
2713         // NOTE: The intra-only frame header does not include the specification
2714         // of either the color format or color sub-sampling in profile 0. VP9
2715         // specifies that the default color format should be YUV 4:2:0 in this
2716         // case (normative).
2717         cm->color_space = VPX_CS_BT_601;
2718         cm->color_range = VPX_CR_STUDIO_RANGE;
2719         cm->subsampling_y = cm->subsampling_x = 1;
2720         cm->bit_depth = VPX_BITS_8;
2721 #if CONFIG_VP9_HIGHBITDEPTH
2722         cm->use_highbitdepth = 0;
2723 #endif
2724       }
2725 
2726       pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
2727       setup_frame_size(cm, rb);
2728       if (pbi->need_resync) {
2729         memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
2730         pbi->need_resync = 0;
2731       }
2732     } else if (pbi->need_resync != 1) { /* Skip if need resync */
2733       pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
2734       for (i = 0; i < REFS_PER_FRAME; ++i) {
2735         const int ref = vpx_rb_read_literal(rb, REF_FRAMES_LOG2);
2736         const int idx = cm->ref_frame_map[ref];
2737         RefBuffer *const ref_frame = &cm->frame_refs[i];
2738         ref_frame->idx = idx;
2739         ref_frame->buf = &frame_bufs[idx].buf;
2740         cm->ref_frame_sign_bias[LAST_FRAME + i] = vpx_rb_read_bit(rb);
2741       }
2742 
2743       setup_frame_size_with_refs(cm, rb);
2744 
2745       cm->allow_high_precision_mv = vpx_rb_read_bit(rb);
2746       cm->interp_filter = read_interp_filter(rb);
2747 
2748       for (i = 0; i < REFS_PER_FRAME; ++i) {
2749         RefBuffer *const ref_buf = &cm->frame_refs[i];
2750 #if CONFIG_VP9_HIGHBITDEPTH
2751         vp9_setup_scale_factors_for_frame(
2752             &ref_buf->sf, ref_buf->buf->y_crop_width,
2753             ref_buf->buf->y_crop_height, cm->width, cm->height,
2754             cm->use_highbitdepth);
2755 #else
2756         vp9_setup_scale_factors_for_frame(
2757             &ref_buf->sf, ref_buf->buf->y_crop_width,
2758             ref_buf->buf->y_crop_height, cm->width, cm->height);
2759 #endif
2760       }
2761     }
2762   }
2763 #if CONFIG_VP9_HIGHBITDEPTH
2764   get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
2765 #endif
2766   get_frame_new_buffer(cm)->color_space = cm->color_space;
2767   get_frame_new_buffer(cm)->color_range = cm->color_range;
2768   get_frame_new_buffer(cm)->render_width = cm->render_width;
2769   get_frame_new_buffer(cm)->render_height = cm->render_height;
2770 
2771   if (pbi->need_resync) {
2772     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2773                        "Keyframe / intra-only frame required to reset decoder"
2774                        " state");
2775   }
2776 
2777   if (!cm->error_resilient_mode) {
2778     cm->refresh_frame_context = vpx_rb_read_bit(rb);
2779     cm->frame_parallel_decoding_mode = vpx_rb_read_bit(rb);
2780     if (!cm->frame_parallel_decoding_mode) vp9_zero(cm->counts);
2781   } else {
2782     cm->refresh_frame_context = 0;
2783     cm->frame_parallel_decoding_mode = 1;
2784   }
2785 
2786   // This flag will be overridden by the call to vp9_setup_past_independence
2787   // below, forcing the use of context 0 for those frame types.
2788   cm->frame_context_idx = vpx_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
2789 
2790   // Generate next_ref_frame_map.
2791   for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
2792     if (mask & 1) {
2793       cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
2794       ++frame_bufs[cm->new_fb_idx].ref_count;
2795     } else {
2796       cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2797     }
2798     // Current thread holds the reference frame.
2799     if (cm->ref_frame_map[ref_index] >= 0)
2800       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2801     ++ref_index;
2802   }
2803 
2804   for (; ref_index < REF_FRAMES; ++ref_index) {
2805     cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2806     // Current thread holds the reference frame.
2807     if (cm->ref_frame_map[ref_index] >= 0)
2808       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2809   }
2810   pbi->hold_ref_buf = 1;
2811 
2812   if (frame_is_intra_only(cm) || cm->error_resilient_mode)
2813     vp9_setup_past_independence(cm);
2814 
2815   setup_loopfilter(&cm->lf, rb);
2816   setup_quantization(cm, &pbi->mb, rb);
2817   setup_segmentation(&cm->seg, rb);
2818   setup_segmentation_dequant(cm);
2819 
2820   setup_tile_info(cm, rb);
2821   if (pbi->row_mt == 1) {
2822     int num_sbs = 1;
2823     const int aligned_rows = mi_cols_aligned_to_sb(cm->mi_rows);
2824     const int sb_rows = aligned_rows >> MI_BLOCK_SIZE_LOG2;
2825     const int num_jobs = sb_rows << cm->log2_tile_cols;
2826 
2827     if (pbi->row_mt_worker_data == NULL) {
2828       CHECK_MEM_ERROR(cm, pbi->row_mt_worker_data,
2829                       vpx_calloc(1, sizeof(*pbi->row_mt_worker_data)));
2830 #if CONFIG_MULTITHREAD
2831       pthread_mutex_init(&pbi->row_mt_worker_data->recon_done_mutex, NULL);
2832 #endif
2833     }
2834 
2835     if (pbi->max_threads > 1) {
2836       const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2837       const int sb_cols = aligned_cols >> MI_BLOCK_SIZE_LOG2;
2838 
2839       num_sbs = sb_cols * sb_rows;
2840     }
2841 
2842     if (num_sbs > pbi->row_mt_worker_data->num_sbs ||
2843         num_jobs > pbi->row_mt_worker_data->num_jobs) {
2844       vp9_dec_free_row_mt_mem(pbi->row_mt_worker_data);
2845       vp9_dec_alloc_row_mt_mem(pbi->row_mt_worker_data, cm, num_sbs,
2846                                pbi->max_threads, num_jobs);
2847     }
2848     vp9_jobq_alloc(pbi);
2849   }
2850   sz = vpx_rb_read_literal(rb, 16);
2851 
2852   if (sz == 0)
2853     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2854                        "Invalid header size");
2855 
2856   return sz;
2857 }
2858 
read_compressed_header(VP9Decoder * pbi,const uint8_t * data,size_t partition_size)2859 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
2860                                   size_t partition_size) {
2861   VP9_COMMON *const cm = &pbi->common;
2862   MACROBLOCKD *const xd = &pbi->mb;
2863   FRAME_CONTEXT *const fc = cm->fc;
2864   vpx_reader r;
2865   int k;
2866 
2867   if (vpx_reader_init(&r, data, partition_size, pbi->decrypt_cb,
2868                       pbi->decrypt_state))
2869     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2870                        "Failed to allocate bool decoder 0");
2871 
2872   cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
2873   if (cm->tx_mode == TX_MODE_SELECT) read_tx_mode_probs(&fc->tx_probs, &r);
2874   read_coef_probs(fc, cm->tx_mode, &r);
2875 
2876   for (k = 0; k < SKIP_CONTEXTS; ++k)
2877     vp9_diff_update_prob(&r, &fc->skip_probs[k]);
2878 
2879   if (!frame_is_intra_only(cm)) {
2880     nmv_context *const nmvc = &fc->nmvc;
2881     int i, j;
2882 
2883     read_inter_mode_probs(fc, &r);
2884 
2885     if (cm->interp_filter == SWITCHABLE) read_switchable_interp_probs(fc, &r);
2886 
2887     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
2888       vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
2889 
2890     cm->reference_mode = read_frame_reference_mode(cm, &r);
2891     if (cm->reference_mode != SINGLE_REFERENCE)
2892       vp9_setup_compound_reference_mode(cm);
2893     read_frame_reference_mode_probs(cm, &r);
2894 
2895     for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
2896       for (i = 0; i < INTRA_MODES - 1; ++i)
2897         vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
2898 
2899     for (j = 0; j < PARTITION_CONTEXTS; ++j)
2900       for (i = 0; i < PARTITION_TYPES - 1; ++i)
2901         vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
2902 
2903     read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2904   }
2905 
2906   return vpx_reader_has_error(&r);
2907 }
2908 
init_read_bit_buffer(VP9Decoder * pbi,struct vpx_read_bit_buffer * rb,const uint8_t * data,const uint8_t * data_end,uint8_t clear_data[MAX_VP9_HEADER_SIZE])2909 static struct vpx_read_bit_buffer *init_read_bit_buffer(
2910     VP9Decoder *pbi, struct vpx_read_bit_buffer *rb, const uint8_t *data,
2911     const uint8_t *data_end, uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2912   rb->bit_offset = 0;
2913   rb->error_handler = error_handler;
2914   rb->error_handler_data = &pbi->common;
2915   if (pbi->decrypt_cb) {
2916     const int n = (int)VPXMIN(MAX_VP9_HEADER_SIZE, data_end - data);
2917     pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2918     rb->bit_buffer = clear_data;
2919     rb->bit_buffer_end = clear_data + n;
2920   } else {
2921     rb->bit_buffer = data;
2922     rb->bit_buffer_end = data_end;
2923   }
2924   return rb;
2925 }
2926 
2927 //------------------------------------------------------------------------------
2928 
vp9_read_sync_code(struct vpx_read_bit_buffer * const rb)2929 int vp9_read_sync_code(struct vpx_read_bit_buffer *const rb) {
2930   return vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2931          vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2932          vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2933 }
2934 
vp9_read_frame_size(struct vpx_read_bit_buffer * rb,int * width,int * height)2935 void vp9_read_frame_size(struct vpx_read_bit_buffer *rb, int *width,
2936                          int *height) {
2937   *width = vpx_rb_read_literal(rb, 16) + 1;
2938   *height = vpx_rb_read_literal(rb, 16) + 1;
2939 }
2940 
vp9_read_profile(struct vpx_read_bit_buffer * rb)2941 BITSTREAM_PROFILE vp9_read_profile(struct vpx_read_bit_buffer *rb) {
2942   int profile = vpx_rb_read_bit(rb);
2943   profile |= vpx_rb_read_bit(rb) << 1;
2944   if (profile > 2) profile += vpx_rb_read_bit(rb);
2945   return (BITSTREAM_PROFILE)profile;
2946 }
2947 
vp9_decode_frame(VP9Decoder * pbi,const uint8_t * data,const uint8_t * data_end,const uint8_t ** p_data_end)2948 void vp9_decode_frame(VP9Decoder *pbi, const uint8_t *data,
2949                       const uint8_t *data_end, const uint8_t **p_data_end) {
2950   VP9_COMMON *const cm = &pbi->common;
2951   MACROBLOCKD *const xd = &pbi->mb;
2952   struct vpx_read_bit_buffer rb;
2953   int context_updated = 0;
2954   uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2955   const size_t first_partition_size = read_uncompressed_header(
2956       pbi, init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2957   const int tile_rows = 1 << cm->log2_tile_rows;
2958   const int tile_cols = 1 << cm->log2_tile_cols;
2959   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2960 #if CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
2961   bitstream_queue_set_frame_read(cm->current_video_frame * 2 + cm->show_frame);
2962 #endif
2963 #if CONFIG_MISMATCH_DEBUG
2964   mismatch_move_frame_idx_r();
2965 #endif
2966   xd->cur_buf = new_fb;
2967 
2968   if (!first_partition_size) {
2969     // showing a frame directly
2970     *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2971     return;
2972   }
2973 
2974   data += vpx_rb_bytes_read(&rb);
2975   if (!read_is_valid(data, first_partition_size, data_end))
2976     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2977                        "Truncated packet or corrupt header length");
2978 
2979   cm->use_prev_frame_mvs =
2980       !cm->error_resilient_mode && cm->width == cm->last_width &&
2981       cm->height == cm->last_height && !cm->last_intra_only &&
2982       cm->last_show_frame && (cm->last_frame_type != KEY_FRAME);
2983 
2984   vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2985 
2986   *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2987   if (!cm->fc->initialized)
2988     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2989                        "Uninitialized entropy context.");
2990 
2991   xd->corrupted = 0;
2992   new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2993   if (new_fb->corrupted)
2994     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2995                        "Decode failed. Frame data header is corrupted.");
2996 
2997   if (cm->lf.filter_level && !cm->skip_loop_filter) {
2998     vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
2999   }
3000 
3001   if (pbi->tile_worker_data == NULL ||
3002       (tile_cols * tile_rows) != pbi->total_tiles) {
3003     const int num_tile_workers =
3004         tile_cols * tile_rows + ((pbi->max_threads > 1) ? pbi->max_threads : 0);
3005     const size_t twd_size = num_tile_workers * sizeof(*pbi->tile_worker_data);
3006     // Ensure tile data offsets will be properly aligned. This may fail on
3007     // platforms without DECLARE_ALIGNED().
3008     assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
3009     vpx_free(pbi->tile_worker_data);
3010     CHECK_MEM_ERROR(cm, pbi->tile_worker_data, vpx_memalign(32, twd_size));
3011     pbi->total_tiles = tile_rows * tile_cols;
3012   }
3013 
3014   if (pbi->max_threads > 1 && tile_rows == 1 &&
3015       (tile_cols > 1 || pbi->row_mt == 1)) {
3016     if (pbi->row_mt == 1) {
3017       *p_data_end =
3018           decode_tiles_row_wise_mt(pbi, data + first_partition_size, data_end);
3019     } else {
3020       // Multi-threaded tile decoder
3021       *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
3022       if (!pbi->lpf_mt_opt) {
3023         if (!xd->corrupted) {
3024           if (!cm->skip_loop_filter) {
3025             // If multiple threads are used to decode tiles, then we use those
3026             // threads to do parallel loopfiltering.
3027             vp9_loop_filter_frame_mt(
3028                 new_fb, cm, pbi->mb.plane, cm->lf.filter_level, 0, 0,
3029                 pbi->tile_workers, pbi->num_tile_workers, &pbi->lf_row_sync);
3030           }
3031         } else {
3032           vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
3033                              "Decode failed. Frame data is corrupted.");
3034         }
3035       }
3036     }
3037   } else {
3038     *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
3039   }
3040 
3041   if (!xd->corrupted) {
3042     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
3043       vp9_adapt_coef_probs(cm);
3044 
3045       if (!frame_is_intra_only(cm)) {
3046         vp9_adapt_mode_probs(cm);
3047         vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
3048       }
3049     }
3050   } else {
3051     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
3052                        "Decode failed. Frame data is corrupted.");
3053   }
3054 
3055   // Non frame parallel update frame context here.
3056   if (cm->refresh_frame_context && !context_updated)
3057     cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
3058 }
3059