• 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 ScanOrder *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 ScanOrder *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 ScanOrder *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 ScanOrder *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 described by the
1302   // partition can't be fully read then throw an error.
1303   if (!read_is_valid(data, read_size, data_end))
1304     vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1305                        "Truncated packet or corrupt tile length");
1306 
1307   if (vpx_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
1308     vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
1309                        "Failed to allocate bool decoder %d", 1);
1310 }
1311 
read_coef_probs_common(vp9_coeff_probs_model * coef_probs,vpx_reader * r)1312 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
1313                                    vpx_reader *r) {
1314   int i, j, k, l, m;
1315 
1316   if (vpx_read_bit(r))
1317     for (i = 0; i < PLANE_TYPES; ++i)
1318       for (j = 0; j < REF_TYPES; ++j)
1319         for (k = 0; k < COEF_BANDS; ++k)
1320           for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1321             for (m = 0; m < UNCONSTRAINED_NODES; ++m)
1322               vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
1323 }
1324 
read_coef_probs(FRAME_CONTEXT * fc,TX_MODE tx_mode,vpx_reader * r)1325 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode, vpx_reader *r) {
1326   const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
1327   TX_SIZE tx_size;
1328   for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
1329     read_coef_probs_common(fc->coef_probs[tx_size], r);
1330 }
1331 
setup_segmentation(struct segmentation * seg,struct vpx_read_bit_buffer * rb)1332 static void setup_segmentation(struct segmentation *seg,
1333                                struct vpx_read_bit_buffer *rb) {
1334   int i, j;
1335 
1336   seg->update_map = 0;
1337   seg->update_data = 0;
1338 
1339   seg->enabled = vpx_rb_read_bit(rb);
1340   if (!seg->enabled) return;
1341 
1342   // Segmentation map update
1343   seg->update_map = vpx_rb_read_bit(rb);
1344   if (seg->update_map) {
1345     for (i = 0; i < SEG_TREE_PROBS; i++)
1346       seg->tree_probs[i] =
1347           vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8) : MAX_PROB;
1348 
1349     seg->temporal_update = vpx_rb_read_bit(rb);
1350     if (seg->temporal_update) {
1351       for (i = 0; i < PREDICTION_PROBS; i++)
1352         seg->pred_probs[i] =
1353             vpx_rb_read_bit(rb) ? vpx_rb_read_literal(rb, 8) : MAX_PROB;
1354     } else {
1355       for (i = 0; i < PREDICTION_PROBS; i++) seg->pred_probs[i] = MAX_PROB;
1356     }
1357   }
1358 
1359   // Segmentation data update
1360   seg->update_data = vpx_rb_read_bit(rb);
1361   if (seg->update_data) {
1362     seg->abs_delta = vpx_rb_read_bit(rb);
1363 
1364     vp9_clearall_segfeatures(seg);
1365 
1366     for (i = 0; i < MAX_SEGMENTS; i++) {
1367       for (j = 0; j < SEG_LVL_MAX; j++) {
1368         int data = 0;
1369         const int feature_enabled = vpx_rb_read_bit(rb);
1370         if (feature_enabled) {
1371           vp9_enable_segfeature(seg, i, j);
1372           data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
1373           if (vp9_is_segfeature_signed(j))
1374             data = vpx_rb_read_bit(rb) ? -data : data;
1375         }
1376         vp9_set_segdata(seg, i, j, data);
1377       }
1378     }
1379   }
1380 }
1381 
setup_loopfilter(struct loopfilter * lf,struct vpx_read_bit_buffer * rb)1382 static void setup_loopfilter(struct loopfilter *lf,
1383                              struct vpx_read_bit_buffer *rb) {
1384   lf->filter_level = vpx_rb_read_literal(rb, 6);
1385   lf->sharpness_level = vpx_rb_read_literal(rb, 3);
1386 
1387   // Read in loop filter deltas applied at the MB level based on mode or ref
1388   // frame.
1389   lf->mode_ref_delta_update = 0;
1390 
1391   lf->mode_ref_delta_enabled = vpx_rb_read_bit(rb);
1392   if (lf->mode_ref_delta_enabled) {
1393     lf->mode_ref_delta_update = vpx_rb_read_bit(rb);
1394     if (lf->mode_ref_delta_update) {
1395       int i;
1396 
1397       for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1398         if (vpx_rb_read_bit(rb))
1399           lf->ref_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1400 
1401       for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1402         if (vpx_rb_read_bit(rb))
1403           lf->mode_deltas[i] = vpx_rb_read_signed_literal(rb, 6);
1404     }
1405   }
1406 }
1407 
read_delta_q(struct vpx_read_bit_buffer * rb)1408 static INLINE int read_delta_q(struct vpx_read_bit_buffer *rb) {
1409   return vpx_rb_read_bit(rb) ? vpx_rb_read_signed_literal(rb, 4) : 0;
1410 }
1411 
setup_quantization(VP9_COMMON * const cm,MACROBLOCKD * const xd,struct vpx_read_bit_buffer * rb)1412 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
1413                                struct vpx_read_bit_buffer *rb) {
1414   cm->base_qindex = vpx_rb_read_literal(rb, QINDEX_BITS);
1415   cm->y_dc_delta_q = read_delta_q(rb);
1416   cm->uv_dc_delta_q = read_delta_q(rb);
1417   cm->uv_ac_delta_q = read_delta_q(rb);
1418   cm->dequant_bit_depth = cm->bit_depth;
1419   xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
1420                  cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
1421 
1422 #if CONFIG_VP9_HIGHBITDEPTH
1423   xd->bd = (int)cm->bit_depth;
1424 #endif
1425 }
1426 
setup_segmentation_dequant(VP9_COMMON * const cm)1427 static void setup_segmentation_dequant(VP9_COMMON *const cm) {
1428   // Build y/uv dequant values based on segmentation.
1429   if (cm->seg.enabled) {
1430     int i;
1431     for (i = 0; i < MAX_SEGMENTS; ++i) {
1432       const int qindex = vp9_get_qindex(&cm->seg, i, cm->base_qindex);
1433       cm->y_dequant[i][0] =
1434           vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1435       cm->y_dequant[i][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1436       cm->uv_dequant[i][0] =
1437           vp9_dc_quant(qindex, cm->uv_dc_delta_q, cm->bit_depth);
1438       cm->uv_dequant[i][1] =
1439           vp9_ac_quant(qindex, cm->uv_ac_delta_q, cm->bit_depth);
1440     }
1441   } else {
1442     const int qindex = cm->base_qindex;
1443     // When segmentation is disabled, only the first value is used.  The
1444     // remaining are don't cares.
1445     cm->y_dequant[0][0] = vp9_dc_quant(qindex, cm->y_dc_delta_q, cm->bit_depth);
1446     cm->y_dequant[0][1] = vp9_ac_quant(qindex, 0, cm->bit_depth);
1447     cm->uv_dequant[0][0] =
1448         vp9_dc_quant(qindex, cm->uv_dc_delta_q, cm->bit_depth);
1449     cm->uv_dequant[0][1] =
1450         vp9_ac_quant(qindex, cm->uv_ac_delta_q, cm->bit_depth);
1451   }
1452 }
1453 
read_interp_filter(struct vpx_read_bit_buffer * rb)1454 static INTERP_FILTER read_interp_filter(struct vpx_read_bit_buffer *rb) {
1455   const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH, EIGHTTAP,
1456                                               EIGHTTAP_SHARP, BILINEAR };
1457   return vpx_rb_read_bit(rb) ? SWITCHABLE
1458                              : literal_to_filter[vpx_rb_read_literal(rb, 2)];
1459 }
1460 
setup_render_size(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)1461 static void setup_render_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1462   cm->render_width = cm->width;
1463   cm->render_height = cm->height;
1464   if (vpx_rb_read_bit(rb))
1465     vp9_read_frame_size(rb, &cm->render_width, &cm->render_height);
1466 }
1467 
resize_mv_buffer(VP9_COMMON * cm)1468 static void resize_mv_buffer(VP9_COMMON *cm) {
1469   vpx_free(cm->cur_frame->mvs);
1470   cm->cur_frame->mi_rows = cm->mi_rows;
1471   cm->cur_frame->mi_cols = cm->mi_cols;
1472   CHECK_MEM_ERROR(&cm->error, cm->cur_frame->mvs,
1473                   (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
1474                                        sizeof(*cm->cur_frame->mvs)));
1475 }
1476 
resize_context_buffers(VP9_COMMON * cm,int width,int height)1477 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
1478 #if CONFIG_SIZE_LIMIT
1479   if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1480     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1481                        "Dimensions of %dx%d beyond allowed size of %dx%d.",
1482                        width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1483 #endif
1484   if (cm->width != width || cm->height != height) {
1485     const int new_mi_rows =
1486         ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1487     const int new_mi_cols =
1488         ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1489 
1490     // Allocations in vp9_alloc_context_buffers() depend on individual
1491     // dimensions as well as the overall size.
1492     if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
1493       if (vp9_alloc_context_buffers(cm, width, height)) {
1494         // The cm->mi_* values have been cleared and any existing context
1495         // buffers have been freed. Clear cm->width and cm->height to be
1496         // consistent and to force a realloc next time.
1497         cm->width = 0;
1498         cm->height = 0;
1499         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1500                            "Failed to allocate context buffers");
1501       }
1502     } else {
1503       vp9_set_mb_mi(cm, width, height);
1504     }
1505     vp9_init_context_buffers(cm);
1506     cm->width = width;
1507     cm->height = height;
1508   }
1509   if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
1510       cm->mi_cols > cm->cur_frame->mi_cols) {
1511     resize_mv_buffer(cm);
1512   }
1513 }
1514 
setup_frame_size(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)1515 static void setup_frame_size(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1516   int width, height;
1517   BufferPool *const pool = cm->buffer_pool;
1518   vp9_read_frame_size(rb, &width, &height);
1519   resize_context_buffers(cm, width, height);
1520   setup_render_size(cm, rb);
1521 
1522   if (vpx_realloc_frame_buffer(
1523           get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x,
1524           cm->subsampling_y,
1525 #if CONFIG_VP9_HIGHBITDEPTH
1526           cm->use_highbitdepth,
1527 #endif
1528           VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment,
1529           &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1530           pool->cb_priv)) {
1531     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1532                        "Failed to allocate frame buffer");
1533   }
1534 
1535   pool->frame_bufs[cm->new_fb_idx].released = 0;
1536   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1537   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1538   pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1539   pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1540   pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1541   pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1542   pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1543 }
1544 
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)1545 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
1546                                           int ref_xss, int ref_yss,
1547                                           vpx_bit_depth_t this_bit_depth,
1548                                           int this_xss, int this_yss) {
1549   return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1550          ref_yss == this_yss;
1551 }
1552 
setup_frame_size_with_refs(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)1553 static void setup_frame_size_with_refs(VP9_COMMON *cm,
1554                                        struct vpx_read_bit_buffer *rb) {
1555   int width, height;
1556   int found = 0, i;
1557   int has_valid_ref_frame = 0;
1558   BufferPool *const pool = cm->buffer_pool;
1559   for (i = 0; i < REFS_PER_FRAME; ++i) {
1560     if (vpx_rb_read_bit(rb)) {
1561       if (cm->frame_refs[i].idx != INVALID_IDX) {
1562         YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
1563         width = buf->y_crop_width;
1564         height = buf->y_crop_height;
1565         found = 1;
1566         break;
1567       } else {
1568         vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1569                            "Failed to decode frame size");
1570       }
1571     }
1572   }
1573 
1574   if (!found) vp9_read_frame_size(rb, &width, &height);
1575 
1576   if (width <= 0 || height <= 0)
1577     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1578                        "Invalid frame size");
1579 
1580   // Check to make sure at least one of frames that this frame references
1581   // has valid dimensions.
1582   for (i = 0; i < REFS_PER_FRAME; ++i) {
1583     RefBuffer *const ref_frame = &cm->frame_refs[i];
1584     has_valid_ref_frame |=
1585         (ref_frame->idx != INVALID_IDX &&
1586          valid_ref_frame_size(ref_frame->buf->y_crop_width,
1587                               ref_frame->buf->y_crop_height, width, height));
1588   }
1589   if (!has_valid_ref_frame)
1590     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1591                        "Referenced frame has invalid size");
1592   for (i = 0; i < REFS_PER_FRAME; ++i) {
1593     RefBuffer *const ref_frame = &cm->frame_refs[i];
1594     if (ref_frame->idx == INVALID_IDX ||
1595         !valid_ref_frame_img_fmt(ref_frame->buf->bit_depth,
1596                                  ref_frame->buf->subsampling_x,
1597                                  ref_frame->buf->subsampling_y, cm->bit_depth,
1598                                  cm->subsampling_x, cm->subsampling_y))
1599       vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1600                          "Referenced frame has incompatible color format");
1601   }
1602 
1603   resize_context_buffers(cm, width, height);
1604   setup_render_size(cm, rb);
1605 
1606   if (vpx_realloc_frame_buffer(
1607           get_frame_new_buffer(cm), cm->width, cm->height, cm->subsampling_x,
1608           cm->subsampling_y,
1609 #if CONFIG_VP9_HIGHBITDEPTH
1610           cm->use_highbitdepth,
1611 #endif
1612           VP9_DEC_BORDER_IN_PIXELS, cm->byte_alignment,
1613           &pool->frame_bufs[cm->new_fb_idx].raw_frame_buffer, pool->get_fb_cb,
1614           pool->cb_priv)) {
1615     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1616                        "Failed to allocate frame buffer");
1617   }
1618 
1619   pool->frame_bufs[cm->new_fb_idx].released = 0;
1620   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
1621   pool->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
1622   pool->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
1623   pool->frame_bufs[cm->new_fb_idx].buf.color_space = cm->color_space;
1624   pool->frame_bufs[cm->new_fb_idx].buf.color_range = cm->color_range;
1625   pool->frame_bufs[cm->new_fb_idx].buf.render_width = cm->render_width;
1626   pool->frame_bufs[cm->new_fb_idx].buf.render_height = cm->render_height;
1627 }
1628 
setup_tile_info(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)1629 static void setup_tile_info(VP9_COMMON *cm, struct vpx_read_bit_buffer *rb) {
1630   int min_log2_tile_cols, max_log2_tile_cols, max_ones;
1631   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1632 
1633   // columns
1634   max_ones = max_log2_tile_cols - min_log2_tile_cols;
1635   cm->log2_tile_cols = min_log2_tile_cols;
1636   while (max_ones-- && vpx_rb_read_bit(rb)) cm->log2_tile_cols++;
1637 
1638   if (cm->log2_tile_cols > 6)
1639     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1640                        "Invalid number of tile columns");
1641 
1642   // rows
1643   cm->log2_tile_rows = vpx_rb_read_bit(rb);
1644   if (cm->log2_tile_rows) cm->log2_tile_rows += vpx_rb_read_bit(rb);
1645 }
1646 
1647 // Reads the next tile returning its size and adjusting '*data' accordingly
1648 // 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)1649 static void get_tile_buffer(const uint8_t *const data_end, int is_last,
1650                             struct vpx_internal_error_info *error_info,
1651                             const uint8_t **data, vpx_decrypt_cb decrypt_cb,
1652                             void *decrypt_state, TileBuffer *buf) {
1653   size_t size;
1654 
1655   if (!is_last) {
1656     if (!read_is_valid(*data, 4, data_end))
1657       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1658                          "Truncated packet or corrupt tile length");
1659 
1660     if (decrypt_cb) {
1661       uint8_t be_data[4];
1662       decrypt_cb(decrypt_state, *data, be_data, 4);
1663       size = mem_get_be32(be_data);
1664     } else {
1665       size = mem_get_be32(*data);
1666     }
1667     *data += 4;
1668 
1669     if (size > (size_t)(data_end - *data))
1670       vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
1671                          "Truncated packet or corrupt tile size");
1672   } else {
1673     size = data_end - *data;
1674   }
1675 
1676   buf->data = *data;
1677   buf->size = size;
1678 
1679   *data += size;
1680 }
1681 
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])1682 static void get_tile_buffers(VP9Decoder *pbi, const uint8_t *data,
1683                              const uint8_t *data_end, int tile_cols,
1684                              int tile_rows,
1685                              TileBuffer (*tile_buffers)[1 << 6]) {
1686   int r, c;
1687 
1688   for (r = 0; r < tile_rows; ++r) {
1689     for (c = 0; c < tile_cols; ++c) {
1690       const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
1691       TileBuffer *const buf = &tile_buffers[r][c];
1692       buf->col = c;
1693       get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
1694                       pbi->decrypt_cb, pbi->decrypt_state, buf);
1695     }
1696   }
1697 }
1698 
map_write(RowMTWorkerData * const row_mt_worker_data,int map_idx,int sync_idx)1699 static void map_write(RowMTWorkerData *const row_mt_worker_data, int map_idx,
1700                       int sync_idx) {
1701 #if CONFIG_MULTITHREAD
1702   pthread_mutex_lock(&row_mt_worker_data->recon_sync_mutex[sync_idx]);
1703   row_mt_worker_data->recon_map[map_idx] = 1;
1704   pthread_cond_signal(&row_mt_worker_data->recon_sync_cond[sync_idx]);
1705   pthread_mutex_unlock(&row_mt_worker_data->recon_sync_mutex[sync_idx]);
1706 #else
1707   (void)row_mt_worker_data;
1708   (void)map_idx;
1709   (void)sync_idx;
1710 #endif  // CONFIG_MULTITHREAD
1711 }
1712 
map_read(RowMTWorkerData * const row_mt_worker_data,int map_idx,int sync_idx)1713 static void map_read(RowMTWorkerData *const row_mt_worker_data, int map_idx,
1714                      int sync_idx) {
1715 #if CONFIG_MULTITHREAD
1716   volatile int8_t *map = row_mt_worker_data->recon_map + map_idx;
1717   pthread_mutex_t *const mutex =
1718       &row_mt_worker_data->recon_sync_mutex[sync_idx];
1719   pthread_mutex_lock(mutex);
1720   while (!(*map)) {
1721     pthread_cond_wait(&row_mt_worker_data->recon_sync_cond[sync_idx], mutex);
1722   }
1723   pthread_mutex_unlock(mutex);
1724 #else
1725   (void)row_mt_worker_data;
1726   (void)map_idx;
1727   (void)sync_idx;
1728 #endif  // CONFIG_MULTITHREAD
1729 }
1730 
lpf_map_write_check(VP9LfSync * lf_sync,int row,int num_tile_cols)1731 static int lpf_map_write_check(VP9LfSync *lf_sync, int row, int num_tile_cols) {
1732   int return_val = 0;
1733 #if CONFIG_MULTITHREAD
1734   int corrupted;
1735   pthread_mutex_lock(lf_sync->lf_mutex);
1736   corrupted = lf_sync->corrupted;
1737   pthread_mutex_unlock(lf_sync->lf_mutex);
1738   if (!corrupted) {
1739     pthread_mutex_lock(&lf_sync->recon_done_mutex[row]);
1740     lf_sync->num_tiles_done[row] += 1;
1741     if (num_tile_cols == lf_sync->num_tiles_done[row]) return_val = 1;
1742     pthread_mutex_unlock(&lf_sync->recon_done_mutex[row]);
1743   }
1744 #else
1745   (void)lf_sync;
1746   (void)row;
1747   (void)num_tile_cols;
1748 #endif
1749   return return_val;
1750 }
1751 
vp9_tile_done(VP9Decoder * pbi)1752 static void vp9_tile_done(VP9Decoder *pbi) {
1753 #if CONFIG_MULTITHREAD
1754   int terminate;
1755   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
1756   const int all_parse_done = 1 << pbi->common.log2_tile_cols;
1757   pthread_mutex_lock(&row_mt_worker_data->recon_done_mutex);
1758   row_mt_worker_data->num_tiles_done++;
1759   terminate = all_parse_done == row_mt_worker_data->num_tiles_done;
1760   pthread_mutex_unlock(&row_mt_worker_data->recon_done_mutex);
1761   if (terminate) {
1762     vp9_jobq_terminate(&row_mt_worker_data->jobq);
1763   }
1764 #else
1765   (void)pbi;
1766 #endif
1767 }
1768 
vp9_jobq_alloc(VP9Decoder * pbi)1769 static void vp9_jobq_alloc(VP9Decoder *pbi) {
1770   VP9_COMMON *const cm = &pbi->common;
1771   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
1772   const int aligned_rows = mi_cols_aligned_to_sb(cm->mi_rows);
1773   const int sb_rows = aligned_rows >> MI_BLOCK_SIZE_LOG2;
1774   const int tile_cols = 1 << cm->log2_tile_cols;
1775   const size_t jobq_size = (tile_cols * sb_rows * 2 + sb_rows) * sizeof(Job);
1776 
1777   if (jobq_size > row_mt_worker_data->jobq_size) {
1778     vpx_free(row_mt_worker_data->jobq_buf);
1779     CHECK_MEM_ERROR(&cm->error, row_mt_worker_data->jobq_buf,
1780                     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->error, 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->error, 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   if (setjmp(tile_data->error_info.jmp)) {
2197     tile_data->error_info.setjmp = 0;
2198     tile_data->xd.corrupted = 1;
2199     tile_data->data_end = NULL;
2200     if (pbi->lpf_mt_opt && cm->lf.filter_level && !cm->skip_loop_filter) {
2201       const int num_tiles_left = tile_data->buf_end - n;
2202       const int mi_row_start = mi_row;
2203       set_rows_after_error(lf_sync, mi_row_start, cm->mi_rows, num_tiles_left,
2204                            1 << cm->log2_tile_cols);
2205     }
2206     return 0;
2207   }
2208   tile_data->error_info.setjmp = 1;
2209 
2210   tile_data->xd.corrupted = 0;
2211 
2212   do {
2213     int mi_col;
2214     const TileBuffer *const buf = pbi->tile_buffers + n;
2215 
2216     /* Initialize to 0 is safe since we do not deal with streams that have
2217      * more than one row of tiles. (So tile->mi_row_start will be 0)
2218      */
2219     assert(cm->log2_tile_rows == 0);
2220     mi_row = 0;
2221     vp9_zero(tile_data->dqcoeff);
2222     vp9_tile_init(tile, &pbi->common, 0, buf->col);
2223     setup_token_decoder(buf->data, tile_data->data_end, buf->size,
2224                         &tile_data->error_info, &tile_data->bit_reader,
2225                         pbi->decrypt_cb, pbi->decrypt_state);
2226     vp9_init_macroblockd(&pbi->common, &tile_data->xd, tile_data->dqcoeff);
2227     // init resets xd.error_info
2228     tile_data->xd.error_info = &tile_data->error_info;
2229 
2230     for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
2231          mi_row += MI_BLOCK_SIZE) {
2232       vp9_zero(tile_data->xd.left_context);
2233       vp9_zero(tile_data->xd.left_seg_context);
2234       for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
2235            mi_col += MI_BLOCK_SIZE) {
2236         decode_partition(tile_data, pbi, mi_row, mi_col, BLOCK_64X64, 4);
2237       }
2238       if (pbi->lpf_mt_opt && cm->lf.filter_level && !cm->skip_loop_filter) {
2239         const int aligned_rows = mi_cols_aligned_to_sb(cm->mi_rows);
2240         const int sb_rows = (aligned_rows >> MI_BLOCK_SIZE_LOG2);
2241         const int is_last_row = (sb_rows - 1 == mi_row >> MI_BLOCK_SIZE_LOG2);
2242         vp9_set_row(lf_sync, 1 << cm->log2_tile_cols,
2243                     mi_row >> MI_BLOCK_SIZE_LOG2, is_last_row,
2244                     tile_data->xd.corrupted);
2245       }
2246     }
2247 
2248     if (buf->col == final_col) {
2249       bit_reader_end = vpx_reader_find_end(&tile_data->bit_reader);
2250     }
2251   } while (!tile_data->xd.corrupted && ++n <= tile_data->buf_end);
2252 
2253   if (pbi->lpf_mt_opt && n < tile_data->buf_end && cm->lf.filter_level &&
2254       !cm->skip_loop_filter) {
2255     /* This was not incremented in the tile loop, so increment before tiles left
2256      * calculation
2257      */
2258     ++n;
2259     set_rows_after_error(lf_sync, 0, cm->mi_rows, tile_data->buf_end - n,
2260                          1 << cm->log2_tile_cols);
2261   }
2262 
2263   if (pbi->lpf_mt_opt && !tile_data->xd.corrupted && cm->lf.filter_level &&
2264       !cm->skip_loop_filter) {
2265     vp9_loopfilter_rows(lf_data, lf_sync);
2266   }
2267 
2268   tile_data->data_end = bit_reader_end;
2269   return !tile_data->xd.corrupted;
2270 }
2271 
2272 // sorts in descending order
compare_tile_buffers(const void * a,const void * b)2273 static int compare_tile_buffers(const void *a, const void *b) {
2274   const TileBuffer *const buf_a = (const TileBuffer *)a;
2275   const TileBuffer *const buf_b = (const TileBuffer *)b;
2276   return (buf_a->size < buf_b->size) - (buf_a->size > buf_b->size);
2277 }
2278 
init_mt(VP9Decoder * pbi)2279 static INLINE void init_mt(VP9Decoder *pbi) {
2280   int n;
2281   VP9_COMMON *const cm = &pbi->common;
2282   VP9LfSync *lf_row_sync = &pbi->lf_row_sync;
2283   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2284   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
2285 
2286   if (pbi->num_tile_workers == 0) {
2287     const int num_threads = pbi->max_threads;
2288     CHECK_MEM_ERROR(&cm->error, pbi->tile_workers,
2289                     vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
2290     for (n = 0; n < num_threads; ++n) {
2291       VPxWorker *const worker = &pbi->tile_workers[n];
2292       ++pbi->num_tile_workers;
2293 
2294       winterface->init(worker);
2295       if (n < num_threads - 1 && !winterface->reset(worker)) {
2296         do {
2297           winterface->end(&pbi->tile_workers[pbi->num_tile_workers - 1]);
2298         } while (--pbi->num_tile_workers != 0);
2299         vpx_free(pbi->tile_workers);
2300         pbi->tile_workers = NULL;
2301         vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
2302                            "Tile decoder thread creation failed");
2303       }
2304     }
2305   }
2306 
2307   // Initialize LPF
2308   if ((pbi->lpf_mt_opt || pbi->row_mt) && cm->lf.filter_level &&
2309       !cm->skip_loop_filter) {
2310     vp9_lpf_mt_init(lf_row_sync, cm, cm->lf.filter_level,
2311                     pbi->num_tile_workers);
2312   }
2313 
2314   // Note: this memset assumes above_context[0], [1] and [2]
2315   // are allocated as part of the same buffer.
2316   memset(cm->above_context, 0,
2317          sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
2318 
2319   memset(cm->above_seg_context, 0,
2320          sizeof(*cm->above_seg_context) * aligned_mi_cols);
2321 
2322   vp9_reset_lfm(cm);
2323 }
2324 
decode_tiles_row_wise_mt(VP9Decoder * pbi,const uint8_t * data,const uint8_t * data_end)2325 static const uint8_t *decode_tiles_row_wise_mt(VP9Decoder *pbi,
2326                                                const uint8_t *data,
2327                                                const uint8_t *data_end) {
2328   VP9_COMMON *const cm = &pbi->common;
2329   RowMTWorkerData *const row_mt_worker_data = pbi->row_mt_worker_data;
2330   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
2331   const int tile_cols = 1 << cm->log2_tile_cols;
2332   const int tile_rows = 1 << cm->log2_tile_rows;
2333   const int num_workers = pbi->max_threads;
2334   int i, n;
2335   int col;
2336   int corrupted = 0;
2337   const int sb_rows = mi_cols_aligned_to_sb(cm->mi_rows) >> MI_BLOCK_SIZE_LOG2;
2338   const int sb_cols = mi_cols_aligned_to_sb(cm->mi_cols) >> MI_BLOCK_SIZE_LOG2;
2339   VP9LfSync *lf_row_sync = &pbi->lf_row_sync;
2340   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2341 
2342   assert(tile_cols <= (1 << 6));
2343   assert(tile_rows == 1);
2344   (void)tile_rows;
2345 
2346   memset(row_mt_worker_data->recon_map, 0,
2347          sb_rows * sb_cols * sizeof(*row_mt_worker_data->recon_map));
2348 
2349   init_mt(pbi);
2350 
2351   // Reset tile decoding hook
2352   for (n = 0; n < num_workers; ++n) {
2353     VPxWorker *const worker = &pbi->tile_workers[n];
2354     ThreadData *const thread_data = &pbi->row_mt_worker_data->thread_data[n];
2355     winterface->sync(worker);
2356 
2357     if (cm->lf.filter_level && !cm->skip_loop_filter) {
2358       thread_data->lf_sync = lf_row_sync;
2359       thread_data->lf_data = &thread_data->lf_sync->lfdata[n];
2360       vp9_loop_filter_data_reset(thread_data->lf_data, new_fb, cm,
2361                                  pbi->mb.plane);
2362     }
2363 
2364     thread_data->pbi = pbi;
2365 
2366     worker->hook = row_decode_worker_hook;
2367     worker->data1 = thread_data;
2368     worker->data2 = (void *)&row_mt_worker_data->data_end;
2369   }
2370 
2371   for (col = 0; col < tile_cols; ++col) {
2372     TileWorkerData *const tile_data = &pbi->tile_worker_data[col];
2373     tile_data->xd = pbi->mb;
2374     tile_data->xd.counts =
2375         cm->frame_parallel_decoding_mode ? NULL : &tile_data->counts;
2376   }
2377 
2378   /* Reset the jobq to start of the jobq buffer */
2379   vp9_jobq_reset(&row_mt_worker_data->jobq);
2380   row_mt_worker_data->num_tiles_done = 0;
2381   row_mt_worker_data->data_end = NULL;
2382 
2383   // Load tile data into tile_buffers
2384   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows,
2385                    &pbi->tile_buffers);
2386 
2387   // Initialize thread frame counts.
2388   if (!cm->frame_parallel_decoding_mode) {
2389     for (col = 0; col < tile_cols; ++col) {
2390       TileWorkerData *const tile_data = &pbi->tile_worker_data[col];
2391       vp9_zero(tile_data->counts);
2392     }
2393   }
2394 
2395   // queue parse jobs for 0th row of every tile
2396   for (col = 0; col < tile_cols; ++col) {
2397     Job parse_job;
2398     parse_job.row_num = 0;
2399     parse_job.tile_col = col;
2400     parse_job.job_type = PARSE_JOB;
2401     vp9_jobq_queue(&row_mt_worker_data->jobq, &parse_job, sizeof(parse_job));
2402   }
2403 
2404   for (i = 0; i < num_workers; ++i) {
2405     VPxWorker *const worker = &pbi->tile_workers[i];
2406     worker->had_error = 0;
2407     if (i == num_workers - 1) {
2408       winterface->execute(worker);
2409     } else {
2410       winterface->launch(worker);
2411     }
2412   }
2413 
2414   for (; n > 0; --n) {
2415     VPxWorker *const worker = &pbi->tile_workers[n - 1];
2416     // TODO(jzern): The tile may have specific error data associated with
2417     // its vpx_internal_error_info which could be propagated to the main info
2418     // in cm. Additionally once the threads have been synced and an error is
2419     // detected, there's no point in continuing to decode tiles.
2420     corrupted |= !winterface->sync(worker);
2421   }
2422 
2423   pbi->mb.corrupted = corrupted;
2424 
2425   {
2426     /* Set data end */
2427     TileWorkerData *const tile_data = &pbi->tile_worker_data[tile_cols - 1];
2428     row_mt_worker_data->data_end = vpx_reader_find_end(&tile_data->bit_reader);
2429   }
2430 
2431   // Accumulate thread frame counts.
2432   if (!cm->frame_parallel_decoding_mode) {
2433     for (i = 0; i < tile_cols; ++i) {
2434       TileWorkerData *const tile_data = &pbi->tile_worker_data[i];
2435       vp9_accumulate_frame_counts(&cm->counts, &tile_data->counts, 1);
2436     }
2437   }
2438 
2439   return row_mt_worker_data->data_end;
2440 }
2441 
decode_tiles_mt(VP9Decoder * pbi,const uint8_t * data,const uint8_t * data_end)2442 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi, const uint8_t *data,
2443                                       const uint8_t *data_end) {
2444   VP9_COMMON *const cm = &pbi->common;
2445   const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
2446   const uint8_t *bit_reader_end = NULL;
2447   VP9LfSync *lf_row_sync = &pbi->lf_row_sync;
2448   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2449   const int tile_cols = 1 << cm->log2_tile_cols;
2450   const int tile_rows = 1 << cm->log2_tile_rows;
2451   const int num_workers = VPXMIN(pbi->max_threads, tile_cols);
2452   int n;
2453 
2454   assert(tile_cols <= (1 << 6));
2455   assert(tile_rows == 1);
2456   (void)tile_rows;
2457 
2458   init_mt(pbi);
2459 
2460   // Reset tile decoding hook
2461   for (n = 0; n < num_workers; ++n) {
2462     VPxWorker *const worker = &pbi->tile_workers[n];
2463     TileWorkerData *const tile_data =
2464         &pbi->tile_worker_data[n + pbi->total_tiles];
2465     winterface->sync(worker);
2466 
2467     if (pbi->lpf_mt_opt && cm->lf.filter_level && !cm->skip_loop_filter) {
2468       tile_data->lf_sync = lf_row_sync;
2469       tile_data->lf_data = &tile_data->lf_sync->lfdata[n];
2470       vp9_loop_filter_data_reset(tile_data->lf_data, new_fb, cm, pbi->mb.plane);
2471       tile_data->lf_data->y_only = 0;
2472     }
2473 
2474     tile_data->xd = pbi->mb;
2475     tile_data->xd.counts =
2476         cm->frame_parallel_decoding_mode ? NULL : &tile_data->counts;
2477     worker->hook = tile_worker_hook;
2478     worker->data1 = tile_data;
2479     worker->data2 = pbi;
2480   }
2481 
2482   // Load tile data into tile_buffers
2483   get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows,
2484                    &pbi->tile_buffers);
2485 
2486   // Sort the buffers based on size in descending order.
2487   qsort(pbi->tile_buffers, tile_cols, sizeof(pbi->tile_buffers[0]),
2488         compare_tile_buffers);
2489 
2490   if (num_workers == tile_cols) {
2491     // Rearrange the tile buffers such that the largest, and
2492     // presumably the most difficult, tile will be decoded in the main thread.
2493     // This should help minimize the number of instances where the main thread
2494     // is waiting for a worker to complete.
2495     const TileBuffer largest = pbi->tile_buffers[0];
2496     memmove(pbi->tile_buffers, pbi->tile_buffers + 1,
2497             (tile_cols - 1) * sizeof(pbi->tile_buffers[0]));
2498     pbi->tile_buffers[tile_cols - 1] = largest;
2499   } else {
2500     int start = 0, end = tile_cols - 2;
2501     TileBuffer tmp;
2502 
2503     // Interleave the tiles to distribute the load between threads, assuming a
2504     // larger tile implies it is more difficult to decode.
2505     while (start < end) {
2506       tmp = pbi->tile_buffers[start];
2507       pbi->tile_buffers[start] = pbi->tile_buffers[end];
2508       pbi->tile_buffers[end] = tmp;
2509       start += 2;
2510       end -= 2;
2511     }
2512   }
2513 
2514   // Initialize thread frame counts.
2515   if (!cm->frame_parallel_decoding_mode) {
2516     for (n = 0; n < num_workers; ++n) {
2517       TileWorkerData *const tile_data =
2518           (TileWorkerData *)pbi->tile_workers[n].data1;
2519       vp9_zero(tile_data->counts);
2520     }
2521   }
2522 
2523   {
2524     const int base = tile_cols / num_workers;
2525     const int remain = tile_cols % num_workers;
2526     int buf_start = 0;
2527 
2528     for (n = 0; n < num_workers; ++n) {
2529       const int count = base + (remain + n) / num_workers;
2530       VPxWorker *const worker = &pbi->tile_workers[n];
2531       TileWorkerData *const tile_data = (TileWorkerData *)worker->data1;
2532 
2533       tile_data->buf_start = buf_start;
2534       tile_data->buf_end = buf_start + count - 1;
2535       tile_data->data_end = data_end;
2536       buf_start += count;
2537 
2538       worker->had_error = 0;
2539       if (n == num_workers - 1) {
2540         assert(tile_data->buf_end == tile_cols - 1);
2541         winterface->execute(worker);
2542       } else {
2543         winterface->launch(worker);
2544       }
2545     }
2546 
2547     for (; n > 0; --n) {
2548       VPxWorker *const worker = &pbi->tile_workers[n - 1];
2549       TileWorkerData *const tile_data = (TileWorkerData *)worker->data1;
2550       // TODO(jzern): The tile may have specific error data associated with
2551       // its vpx_internal_error_info which could be propagated to the main info
2552       // in cm. Additionally once the threads have been synced and an error is
2553       // detected, there's no point in continuing to decode tiles.
2554       pbi->mb.corrupted |= !winterface->sync(worker);
2555       if (!bit_reader_end) bit_reader_end = tile_data->data_end;
2556     }
2557   }
2558 
2559   // Accumulate thread frame counts.
2560   if (!cm->frame_parallel_decoding_mode) {
2561     for (n = 0; n < num_workers; ++n) {
2562       TileWorkerData *const tile_data =
2563           (TileWorkerData *)pbi->tile_workers[n].data1;
2564       vp9_accumulate_frame_counts(&cm->counts, &tile_data->counts, 1);
2565     }
2566   }
2567 
2568   assert(bit_reader_end || pbi->mb.corrupted);
2569   return bit_reader_end;
2570 }
2571 
error_handler(void * data)2572 static void error_handler(void *data) {
2573   VP9_COMMON *const cm = (VP9_COMMON *)data;
2574   vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
2575 }
2576 
read_bitdepth_colorspace_sampling(VP9_COMMON * cm,struct vpx_read_bit_buffer * rb)2577 static void read_bitdepth_colorspace_sampling(VP9_COMMON *cm,
2578                                               struct vpx_read_bit_buffer *rb) {
2579   if (cm->profile >= PROFILE_2) {
2580     cm->bit_depth = vpx_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
2581 #if CONFIG_VP9_HIGHBITDEPTH
2582     cm->use_highbitdepth = 1;
2583 #endif
2584   } else {
2585     cm->bit_depth = VPX_BITS_8;
2586 #if CONFIG_VP9_HIGHBITDEPTH
2587     cm->use_highbitdepth = 0;
2588 #endif
2589   }
2590   cm->color_space = vpx_rb_read_literal(rb, 3);
2591   if (cm->color_space != VPX_CS_SRGB) {
2592     cm->color_range = (vpx_color_range_t)vpx_rb_read_bit(rb);
2593     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
2594       cm->subsampling_x = vpx_rb_read_bit(rb);
2595       cm->subsampling_y = vpx_rb_read_bit(rb);
2596       if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
2597         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2598                            "4:2:0 color not supported in profile 1 or 3");
2599       if (vpx_rb_read_bit(rb))
2600         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2601                            "Reserved bit set");
2602     } else {
2603       cm->subsampling_y = cm->subsampling_x = 1;
2604     }
2605   } else {
2606     cm->color_range = VPX_CR_FULL_RANGE;
2607     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
2608       // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
2609       // 4:2:2 or 4:4:0 chroma sampling is not allowed.
2610       cm->subsampling_y = cm->subsampling_x = 0;
2611       if (vpx_rb_read_bit(rb))
2612         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2613                            "Reserved bit set");
2614     } else {
2615       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2616                          "4:4:4 color not supported in profile 0 or 2");
2617     }
2618   }
2619 }
2620 
flush_all_fb_on_key(VP9_COMMON * cm)2621 static INLINE void flush_all_fb_on_key(VP9_COMMON *cm) {
2622   if (cm->frame_type == KEY_FRAME && cm->current_video_frame > 0) {
2623     RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
2624     BufferPool *const pool = cm->buffer_pool;
2625     int i;
2626     for (i = 0; i < FRAME_BUFFERS; ++i) {
2627       if (i == cm->new_fb_idx) continue;
2628       frame_bufs[i].ref_count = 0;
2629       if (!frame_bufs[i].released) {
2630         pool->release_fb_cb(pool->cb_priv, &frame_bufs[i].raw_frame_buffer);
2631         frame_bufs[i].released = 1;
2632       }
2633     }
2634   }
2635 }
2636 
read_uncompressed_header(VP9Decoder * pbi,struct vpx_read_bit_buffer * rb)2637 static size_t read_uncompressed_header(VP9Decoder *pbi,
2638                                        struct vpx_read_bit_buffer *rb) {
2639   VP9_COMMON *const cm = &pbi->common;
2640   BufferPool *const pool = cm->buffer_pool;
2641   RefCntBuffer *const frame_bufs = pool->frame_bufs;
2642   int i, mask, ref_index = 0;
2643   size_t sz;
2644 
2645   cm->last_frame_type = cm->frame_type;
2646   cm->last_intra_only = cm->intra_only;
2647 
2648   if (vpx_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
2649     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2650                        "Invalid frame marker");
2651 
2652   cm->profile = vp9_read_profile(rb);
2653 #if CONFIG_VP9_HIGHBITDEPTH
2654   if (cm->profile >= MAX_PROFILES)
2655     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2656                        "Unsupported bitstream profile");
2657 #else
2658   if (cm->profile >= PROFILE_2)
2659     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2660                        "Unsupported bitstream profile");
2661 #endif
2662 
2663   cm->show_existing_frame = vpx_rb_read_bit(rb);
2664   if (cm->show_existing_frame) {
2665     // Show an existing frame directly.
2666     const int frame_to_show = cm->ref_frame_map[vpx_rb_read_literal(rb, 3)];
2667     if (frame_to_show < 0 || frame_bufs[frame_to_show].ref_count < 1) {
2668       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2669                          "Buffer %d does not contain a decoded frame",
2670                          frame_to_show);
2671     }
2672 
2673     ref_cnt_fb(frame_bufs, &cm->new_fb_idx, frame_to_show);
2674     pbi->refresh_frame_flags = 0;
2675     cm->lf.filter_level = 0;
2676     cm->show_frame = 1;
2677 
2678     return 0;
2679   }
2680 
2681   cm->frame_type = (FRAME_TYPE)vpx_rb_read_bit(rb);
2682   cm->show_frame = vpx_rb_read_bit(rb);
2683   cm->error_resilient_mode = vpx_rb_read_bit(rb);
2684 
2685   if (cm->frame_type == KEY_FRAME) {
2686     if (!vp9_read_sync_code(rb))
2687       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2688                          "Invalid frame sync code");
2689 
2690     read_bitdepth_colorspace_sampling(cm, rb);
2691     pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
2692 
2693     for (i = 0; i < REFS_PER_FRAME; ++i) {
2694       cm->frame_refs[i].idx = INVALID_IDX;
2695       cm->frame_refs[i].buf = NULL;
2696     }
2697 
2698     setup_frame_size(cm, rb);
2699     if (pbi->need_resync) {
2700       memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
2701       flush_all_fb_on_key(cm);
2702       pbi->need_resync = 0;
2703     }
2704   } else {
2705     cm->intra_only = cm->show_frame ? 0 : vpx_rb_read_bit(rb);
2706 
2707     cm->reset_frame_context =
2708         cm->error_resilient_mode ? 0 : vpx_rb_read_literal(rb, 2);
2709 
2710     if (cm->intra_only) {
2711       if (!vp9_read_sync_code(rb))
2712         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
2713                            "Invalid frame sync code");
2714       if (cm->profile > PROFILE_0) {
2715         read_bitdepth_colorspace_sampling(cm, rb);
2716       } else {
2717         // NOTE: The intra-only frame header does not include the specification
2718         // of either the color format or color sub-sampling in profile 0. VP9
2719         // specifies that the default color format should be YUV 4:2:0 in this
2720         // case (normative).
2721         cm->color_space = VPX_CS_BT_601;
2722         cm->color_range = VPX_CR_STUDIO_RANGE;
2723         cm->subsampling_y = cm->subsampling_x = 1;
2724         cm->bit_depth = VPX_BITS_8;
2725 #if CONFIG_VP9_HIGHBITDEPTH
2726         cm->use_highbitdepth = 0;
2727 #endif
2728       }
2729 
2730       pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
2731       setup_frame_size(cm, rb);
2732       if (pbi->need_resync) {
2733         memset(&cm->ref_frame_map, -1, sizeof(cm->ref_frame_map));
2734         pbi->need_resync = 0;
2735       }
2736     } else if (pbi->need_resync != 1) { /* Skip if need resync */
2737       pbi->refresh_frame_flags = vpx_rb_read_literal(rb, REF_FRAMES);
2738       for (i = 0; i < REFS_PER_FRAME; ++i) {
2739         const int ref = vpx_rb_read_literal(rb, REF_FRAMES_LOG2);
2740         const int idx = cm->ref_frame_map[ref];
2741         RefBuffer *const ref_frame = &cm->frame_refs[i];
2742         ref_frame->idx = idx;
2743         ref_frame->buf = &frame_bufs[idx].buf;
2744         cm->ref_frame_sign_bias[LAST_FRAME + i] = vpx_rb_read_bit(rb);
2745       }
2746 
2747       setup_frame_size_with_refs(cm, rb);
2748 
2749       cm->allow_high_precision_mv = vpx_rb_read_bit(rb);
2750       cm->interp_filter = read_interp_filter(rb);
2751 
2752       for (i = 0; i < REFS_PER_FRAME; ++i) {
2753         RefBuffer *const ref_buf = &cm->frame_refs[i];
2754 #if CONFIG_VP9_HIGHBITDEPTH
2755         vp9_setup_scale_factors_for_frame(
2756             &ref_buf->sf, ref_buf->buf->y_crop_width,
2757             ref_buf->buf->y_crop_height, cm->width, cm->height,
2758             cm->use_highbitdepth);
2759 #else
2760         vp9_setup_scale_factors_for_frame(
2761             &ref_buf->sf, ref_buf->buf->y_crop_width,
2762             ref_buf->buf->y_crop_height, cm->width, cm->height);
2763 #endif
2764       }
2765     }
2766   }
2767 #if CONFIG_VP9_HIGHBITDEPTH
2768   get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
2769 #endif
2770   get_frame_new_buffer(cm)->color_space = cm->color_space;
2771   get_frame_new_buffer(cm)->color_range = cm->color_range;
2772   get_frame_new_buffer(cm)->render_width = cm->render_width;
2773   get_frame_new_buffer(cm)->render_height = cm->render_height;
2774 
2775   if (pbi->need_resync) {
2776     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2777                        "Keyframe / intra-only frame required to reset decoder"
2778                        " state");
2779   }
2780 
2781   if (!cm->error_resilient_mode) {
2782     cm->refresh_frame_context = vpx_rb_read_bit(rb);
2783     cm->frame_parallel_decoding_mode = vpx_rb_read_bit(rb);
2784     if (!cm->frame_parallel_decoding_mode) vp9_zero(cm->counts);
2785   } else {
2786     cm->refresh_frame_context = 0;
2787     cm->frame_parallel_decoding_mode = 1;
2788   }
2789 
2790   // This flag will be overridden by the call to vp9_setup_past_independence
2791   // below, forcing the use of context 0 for those frame types.
2792   cm->frame_context_idx = vpx_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
2793 
2794   // Generate next_ref_frame_map.
2795   for (mask = pbi->refresh_frame_flags; mask; mask >>= 1) {
2796     if (mask & 1) {
2797       cm->next_ref_frame_map[ref_index] = cm->new_fb_idx;
2798       ++frame_bufs[cm->new_fb_idx].ref_count;
2799     } else {
2800       cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2801     }
2802     // Current thread holds the reference frame.
2803     if (cm->ref_frame_map[ref_index] >= 0)
2804       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2805     ++ref_index;
2806   }
2807 
2808   for (; ref_index < REF_FRAMES; ++ref_index) {
2809     cm->next_ref_frame_map[ref_index] = cm->ref_frame_map[ref_index];
2810     // Current thread holds the reference frame.
2811     if (cm->ref_frame_map[ref_index] >= 0)
2812       ++frame_bufs[cm->ref_frame_map[ref_index]].ref_count;
2813   }
2814   pbi->hold_ref_buf = 1;
2815 
2816   if (frame_is_intra_only(cm) || cm->error_resilient_mode)
2817     vp9_setup_past_independence(cm);
2818 
2819   setup_loopfilter(&cm->lf, rb);
2820   setup_quantization(cm, &pbi->mb, rb);
2821   setup_segmentation(&cm->seg, rb);
2822   setup_segmentation_dequant(cm);
2823 
2824   setup_tile_info(cm, rb);
2825   if (pbi->row_mt == 1) {
2826     int num_sbs = 1;
2827     const int aligned_rows = mi_cols_aligned_to_sb(cm->mi_rows);
2828     const int sb_rows = aligned_rows >> MI_BLOCK_SIZE_LOG2;
2829     const int num_jobs = sb_rows << cm->log2_tile_cols;
2830 
2831     if (pbi->row_mt_worker_data == NULL) {
2832       CHECK_MEM_ERROR(&cm->error, pbi->row_mt_worker_data,
2833                       vpx_calloc(1, sizeof(*pbi->row_mt_worker_data)));
2834 #if CONFIG_MULTITHREAD
2835       pthread_mutex_init(&pbi->row_mt_worker_data->recon_done_mutex, NULL);
2836 #endif
2837     }
2838 
2839     if (pbi->max_threads > 1) {
2840       const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2841       const int sb_cols = aligned_cols >> MI_BLOCK_SIZE_LOG2;
2842 
2843       num_sbs = sb_cols * sb_rows;
2844     }
2845 
2846     if (num_sbs > pbi->row_mt_worker_data->num_sbs ||
2847         num_jobs > pbi->row_mt_worker_data->num_jobs) {
2848       vp9_dec_free_row_mt_mem(pbi->row_mt_worker_data);
2849       vp9_dec_alloc_row_mt_mem(pbi->row_mt_worker_data, cm, num_sbs,
2850                                pbi->max_threads, num_jobs);
2851     }
2852     vp9_jobq_alloc(pbi);
2853   }
2854   sz = vpx_rb_read_literal(rb, 16);
2855 
2856   if (sz == 0)
2857     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2858                        "Invalid header size");
2859 
2860   return sz;
2861 }
2862 
read_compressed_header(VP9Decoder * pbi,const uint8_t * data,size_t partition_size)2863 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
2864                                   size_t partition_size) {
2865   VP9_COMMON *const cm = &pbi->common;
2866   MACROBLOCKD *const xd = &pbi->mb;
2867   FRAME_CONTEXT *const fc = cm->fc;
2868   vpx_reader r;
2869   int k;
2870 
2871   if (vpx_reader_init(&r, data, partition_size, pbi->decrypt_cb,
2872                       pbi->decrypt_state))
2873     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2874                        "Failed to allocate bool decoder 0");
2875 
2876   cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
2877   if (cm->tx_mode == TX_MODE_SELECT) read_tx_mode_probs(&fc->tx_probs, &r);
2878   read_coef_probs(fc, cm->tx_mode, &r);
2879 
2880   for (k = 0; k < SKIP_CONTEXTS; ++k)
2881     vp9_diff_update_prob(&r, &fc->skip_probs[k]);
2882 
2883   if (!frame_is_intra_only(cm)) {
2884     nmv_context *const nmvc = &fc->nmvc;
2885     int i, j;
2886 
2887     read_inter_mode_probs(fc, &r);
2888 
2889     if (cm->interp_filter == SWITCHABLE) read_switchable_interp_probs(fc, &r);
2890 
2891     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
2892       vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
2893 
2894     cm->reference_mode = read_frame_reference_mode(cm, &r);
2895     if (cm->reference_mode != SINGLE_REFERENCE)
2896       vp9_setup_compound_reference_mode(cm);
2897     read_frame_reference_mode_probs(cm, &r);
2898 
2899     for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
2900       for (i = 0; i < INTRA_MODES - 1; ++i)
2901         vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
2902 
2903     for (j = 0; j < PARTITION_CONTEXTS; ++j)
2904       for (i = 0; i < PARTITION_TYPES - 1; ++i)
2905         vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
2906 
2907     read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
2908   }
2909 
2910   return vpx_reader_has_error(&r);
2911 }
2912 
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])2913 static struct vpx_read_bit_buffer *init_read_bit_buffer(
2914     VP9Decoder *pbi, struct vpx_read_bit_buffer *rb, const uint8_t *data,
2915     const uint8_t *data_end, uint8_t clear_data[MAX_VP9_HEADER_SIZE]) {
2916   rb->bit_offset = 0;
2917   rb->error_handler = error_handler;
2918   rb->error_handler_data = &pbi->common;
2919   if (pbi->decrypt_cb) {
2920     const int n = (int)VPXMIN(MAX_VP9_HEADER_SIZE, data_end - data);
2921     pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
2922     rb->bit_buffer = clear_data;
2923     rb->bit_buffer_end = clear_data + n;
2924   } else {
2925     rb->bit_buffer = data;
2926     rb->bit_buffer_end = data_end;
2927   }
2928   return rb;
2929 }
2930 
2931 //------------------------------------------------------------------------------
2932 
vp9_read_sync_code(struct vpx_read_bit_buffer * const rb)2933 int vp9_read_sync_code(struct vpx_read_bit_buffer *const rb) {
2934   return vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
2935          vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
2936          vpx_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
2937 }
2938 
vp9_read_frame_size(struct vpx_read_bit_buffer * rb,int * width,int * height)2939 void vp9_read_frame_size(struct vpx_read_bit_buffer *rb, int *width,
2940                          int *height) {
2941   *width = vpx_rb_read_literal(rb, 16) + 1;
2942   *height = vpx_rb_read_literal(rb, 16) + 1;
2943 }
2944 
vp9_read_profile(struct vpx_read_bit_buffer * rb)2945 BITSTREAM_PROFILE vp9_read_profile(struct vpx_read_bit_buffer *rb) {
2946   int profile = vpx_rb_read_bit(rb);
2947   profile |= vpx_rb_read_bit(rb) << 1;
2948   if (profile > 2) profile += vpx_rb_read_bit(rb);
2949   return (BITSTREAM_PROFILE)profile;
2950 }
2951 
vp9_decode_frame(VP9Decoder * pbi,const uint8_t * data,const uint8_t * data_end,const uint8_t ** p_data_end)2952 void vp9_decode_frame(VP9Decoder *pbi, const uint8_t *data,
2953                       const uint8_t *data_end, const uint8_t **p_data_end) {
2954   VP9_COMMON *const cm = &pbi->common;
2955   MACROBLOCKD *const xd = &pbi->mb;
2956   struct vpx_read_bit_buffer rb;
2957   int context_updated = 0;
2958   uint8_t clear_data[MAX_VP9_HEADER_SIZE];
2959   const size_t first_partition_size = read_uncompressed_header(
2960       pbi, init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
2961   const int tile_rows = 1 << cm->log2_tile_rows;
2962   const int tile_cols = 1 << cm->log2_tile_cols;
2963   YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
2964 #if CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
2965   bitstream_queue_set_frame_read(cm->current_video_frame * 2 + cm->show_frame);
2966 #endif
2967 #if CONFIG_MISMATCH_DEBUG
2968   mismatch_move_frame_idx_r();
2969 #endif
2970   xd->cur_buf = new_fb;
2971 
2972   if (!first_partition_size) {
2973     // showing a frame directly
2974     *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
2975     return;
2976   }
2977 
2978   data += vpx_rb_bytes_read(&rb);
2979   if (!read_is_valid(data, first_partition_size, data_end))
2980     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2981                        "Truncated packet or corrupt header length");
2982 
2983   cm->use_prev_frame_mvs =
2984       !cm->error_resilient_mode && cm->width == cm->last_width &&
2985       cm->height == cm->last_height && !cm->last_intra_only &&
2986       cm->last_show_frame && (cm->last_frame_type != KEY_FRAME);
2987 
2988   vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
2989 
2990   *cm->fc = cm->frame_contexts[cm->frame_context_idx];
2991   if (!cm->fc->initialized)
2992     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2993                        "Uninitialized entropy context.");
2994 
2995   xd->corrupted = 0;
2996   new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
2997   if (new_fb->corrupted)
2998     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
2999                        "Decode failed. Frame data header is corrupted.");
3000 
3001   if (cm->lf.filter_level && !cm->skip_loop_filter) {
3002     vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
3003   }
3004 
3005   if (pbi->tile_worker_data == NULL ||
3006       (tile_cols * tile_rows) != pbi->total_tiles) {
3007     const int num_tile_workers =
3008         tile_cols * tile_rows + ((pbi->max_threads > 1) ? pbi->max_threads : 0);
3009     const size_t twd_size = num_tile_workers * sizeof(*pbi->tile_worker_data);
3010     // Ensure tile data offsets will be properly aligned. This may fail on
3011     // platforms without DECLARE_ALIGNED().
3012     assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
3013     vpx_free(pbi->tile_worker_data);
3014     CHECK_MEM_ERROR(&cm->error, pbi->tile_worker_data,
3015                     vpx_memalign(32, twd_size));
3016     pbi->total_tiles = tile_rows * tile_cols;
3017   }
3018 
3019   if (pbi->max_threads > 1 && tile_rows == 1 &&
3020       (tile_cols > 1 || pbi->row_mt == 1)) {
3021     if (pbi->row_mt == 1) {
3022       *p_data_end =
3023           decode_tiles_row_wise_mt(pbi, data + first_partition_size, data_end);
3024     } else {
3025       // Multi-threaded tile decoder
3026       *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
3027       if (!pbi->lpf_mt_opt) {
3028         if (!xd->corrupted) {
3029           if (!cm->skip_loop_filter) {
3030             // If multiple threads are used to decode tiles, then we use those
3031             // threads to do parallel loopfiltering.
3032             vp9_loop_filter_frame_mt(
3033                 new_fb, cm, pbi->mb.plane, cm->lf.filter_level, 0, 0,
3034                 pbi->tile_workers, pbi->num_tile_workers, &pbi->lf_row_sync);
3035           }
3036         } else {
3037           vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
3038                              "Decode failed. Frame data is corrupted.");
3039         }
3040       }
3041     }
3042   } else {
3043     *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
3044   }
3045 
3046   if (!xd->corrupted) {
3047     if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
3048       vp9_adapt_coef_probs(cm);
3049 
3050       if (!frame_is_intra_only(cm)) {
3051         vp9_adapt_mode_probs(cm);
3052         vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
3053       }
3054     }
3055   } else {
3056     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
3057                        "Decode failed. Frame data is corrupted.");
3058   }
3059 
3060   // Non frame parallel update frame context here.
3061   if (cm->refresh_frame_context && !context_updated)
3062     cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
3063 }
3064