• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include <assert.h>
13 #include <stddef.h>
14 
15 #include "config/aom_config.h"
16 #include "config/aom_dsp_rtcd.h"
17 #include "config/aom_scale_rtcd.h"
18 #include "config/av1_rtcd.h"
19 
20 #include "aom/aom_codec.h"
21 #include "aom_dsp/aom_dsp_common.h"
22 #include "aom_dsp/binary_codes_reader.h"
23 #include "aom_dsp/bitreader.h"
24 #include "aom_dsp/bitreader_buffer.h"
25 #include "aom_mem/aom_mem.h"
26 #include "aom_ports/aom_timer.h"
27 #include "aom_ports/mem.h"
28 #include "aom_ports/mem_ops.h"
29 #include "aom_scale/aom_scale.h"
30 #include "aom_util/aom_thread.h"
31 
32 #if CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
33 #include "aom_util/debug_util.h"
34 #endif  // CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
35 
36 #include "av1/common/alloccommon.h"
37 #include "av1/common/cdef.h"
38 #include "av1/common/cfl.h"
39 #if CONFIG_INSPECTION
40 #include "av1/decoder/inspection.h"
41 #endif
42 #include "av1/common/common.h"
43 #include "av1/common/entropy.h"
44 #include "av1/common/entropymode.h"
45 #include "av1/common/entropymv.h"
46 #include "av1/common/frame_buffers.h"
47 #include "av1/common/idct.h"
48 #include "av1/common/mvref_common.h"
49 #include "av1/common/pred_common.h"
50 #include "av1/common/quant_common.h"
51 #include "av1/common/reconinter.h"
52 #include "av1/common/reconintra.h"
53 #include "av1/common/resize.h"
54 #include "av1/common/seg_common.h"
55 #include "av1/common/thread_common.h"
56 #include "av1/common/tile_common.h"
57 #include "av1/common/warped_motion.h"
58 #include "av1/common/obmc.h"
59 #include "av1/decoder/decodeframe.h"
60 #include "av1/decoder/decodemv.h"
61 #include "av1/decoder/decoder.h"
62 #include "av1/decoder/decodetxb.h"
63 #include "av1/decoder/detokenize.h"
64 
65 #define ACCT_STR __func__
66 
67 #define AOM_MIN_THREADS_PER_TILE 1
68 #define AOM_MAX_THREADS_PER_TILE 2
69 
70 // This is needed by ext_tile related unit tests.
71 #define EXT_TILE_DEBUG 1
72 #define MC_TEMP_BUF_PELS                       \
73   (((MAX_SB_SIZE)*2 + (AOM_INTERP_EXTEND)*2) * \
74    ((MAX_SB_SIZE)*2 + (AOM_INTERP_EXTEND)*2))
75 
76 // Checks that the remaining bits start with a 1 and ends with 0s.
77 // It consumes an additional byte, if already byte aligned before the check.
av1_check_trailing_bits(AV1Decoder * pbi,struct aom_read_bit_buffer * rb)78 int av1_check_trailing_bits(AV1Decoder *pbi, struct aom_read_bit_buffer *rb) {
79   // bit_offset is set to 0 (mod 8) when the reader is already byte aligned
80   int bits_before_alignment = 8 - rb->bit_offset % 8;
81   int trailing = aom_rb_read_literal(rb, bits_before_alignment);
82   if (trailing != (1 << (bits_before_alignment - 1))) {
83     pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
84     return -1;
85   }
86   return 0;
87 }
88 
89 // Use only_chroma = 1 to only set the chroma planes
set_planes_to_neutral_grey(const SequenceHeader * const seq_params,const YV12_BUFFER_CONFIG * const buf,int only_chroma)90 static AOM_INLINE void set_planes_to_neutral_grey(
91     const SequenceHeader *const seq_params, const YV12_BUFFER_CONFIG *const buf,
92     int only_chroma) {
93   if (seq_params->use_highbitdepth) {
94     const int val = 1 << (seq_params->bit_depth - 1);
95     for (int plane = only_chroma; plane < MAX_MB_PLANE; plane++) {
96       const int is_uv = plane > 0;
97       uint16_t *const base = CONVERT_TO_SHORTPTR(buf->buffers[plane]);
98       // Set the first row to neutral grey. Then copy the first row to all
99       // subsequent rows.
100       if (buf->crop_heights[is_uv] > 0) {
101         aom_memset16(base, val, buf->crop_widths[is_uv]);
102         for (int row_idx = 1; row_idx < buf->crop_heights[is_uv]; row_idx++) {
103           memcpy(&base[row_idx * buf->strides[is_uv]], base,
104                  sizeof(*base) * buf->crop_widths[is_uv]);
105         }
106       }
107     }
108   } else {
109     for (int plane = only_chroma; plane < MAX_MB_PLANE; plane++) {
110       const int is_uv = plane > 0;
111       for (int row_idx = 0; row_idx < buf->crop_heights[is_uv]; row_idx++) {
112         memset(&buf->buffers[plane][row_idx * buf->uv_stride], 1 << 7,
113                buf->crop_widths[is_uv]);
114       }
115     }
116   }
117 }
118 
119 #if !CONFIG_REALTIME_ONLY
120 static AOM_INLINE void loop_restoration_read_sb_coeffs(
121     const AV1_COMMON *const cm, MACROBLOCKD *xd, aom_reader *const r, int plane,
122     int runit_idx);
123 #endif
124 
read_is_valid(const uint8_t * start,size_t len,const uint8_t * end)125 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
126   return len != 0 && len <= (size_t)(end - start);
127 }
128 
read_tx_mode(struct aom_read_bit_buffer * rb,int coded_lossless)129 static TX_MODE read_tx_mode(struct aom_read_bit_buffer *rb,
130                             int coded_lossless) {
131   if (coded_lossless) return ONLY_4X4;
132   return aom_rb_read_bit(rb) ? TX_MODE_SELECT : TX_MODE_LARGEST;
133 }
134 
read_frame_reference_mode(const AV1_COMMON * cm,struct aom_read_bit_buffer * rb)135 static REFERENCE_MODE read_frame_reference_mode(
136     const AV1_COMMON *cm, struct aom_read_bit_buffer *rb) {
137   if (frame_is_intra_only(cm)) {
138     return SINGLE_REFERENCE;
139   } else {
140     return aom_rb_read_bit(rb) ? REFERENCE_MODE_SELECT : SINGLE_REFERENCE;
141   }
142 }
143 
inverse_transform_block(DecoderCodingBlock * dcb,int plane,const TX_TYPE tx_type,const TX_SIZE tx_size,uint8_t * dst,int stride,int reduced_tx_set)144 static AOM_INLINE void inverse_transform_block(DecoderCodingBlock *dcb,
145                                                int plane, const TX_TYPE tx_type,
146                                                const TX_SIZE tx_size,
147                                                uint8_t *dst, int stride,
148                                                int reduced_tx_set) {
149   tran_low_t *const dqcoeff = dcb->dqcoeff_block[plane] + dcb->cb_offset[plane];
150   eob_info *eob_data = dcb->eob_data[plane] + dcb->txb_offset[plane];
151   uint16_t scan_line = eob_data->max_scan_line;
152   uint16_t eob = eob_data->eob;
153   av1_inverse_transform_block(&dcb->xd, dqcoeff, plane, tx_type, tx_size, dst,
154                               stride, eob, reduced_tx_set);
155   memset(dqcoeff, 0, (scan_line + 1) * sizeof(dqcoeff[0]));
156 }
157 
read_coeffs_tx_intra_block(const AV1_COMMON * const cm,DecoderCodingBlock * dcb,aom_reader * const r,const int plane,const int row,const int col,const TX_SIZE tx_size)158 static AOM_INLINE void read_coeffs_tx_intra_block(
159     const AV1_COMMON *const cm, DecoderCodingBlock *dcb, aom_reader *const r,
160     const int plane, const int row, const int col, const TX_SIZE tx_size) {
161   MB_MODE_INFO *mbmi = dcb->xd.mi[0];
162   if (!mbmi->skip_txfm) {
163 #if TXCOEFF_TIMER
164     struct aom_usec_timer timer;
165     aom_usec_timer_start(&timer);
166 #endif
167     av1_read_coeffs_txb_facade(cm, dcb, r, plane, row, col, tx_size);
168 #if TXCOEFF_TIMER
169     aom_usec_timer_mark(&timer);
170     const int64_t elapsed_time = aom_usec_timer_elapsed(&timer);
171     cm->txcoeff_timer += elapsed_time;
172     ++cm->txb_count;
173 #endif
174   }
175 }
176 
decode_block_void(const AV1_COMMON * const cm,DecoderCodingBlock * dcb,aom_reader * const r,const int plane,const int row,const int col,const TX_SIZE tx_size)177 static AOM_INLINE void decode_block_void(const AV1_COMMON *const cm,
178                                          DecoderCodingBlock *dcb,
179                                          aom_reader *const r, const int plane,
180                                          const int row, const int col,
181                                          const TX_SIZE tx_size) {
182   (void)cm;
183   (void)dcb;
184   (void)r;
185   (void)plane;
186   (void)row;
187   (void)col;
188   (void)tx_size;
189 }
190 
predict_inter_block_void(AV1_COMMON * const cm,DecoderCodingBlock * dcb,BLOCK_SIZE bsize)191 static AOM_INLINE void predict_inter_block_void(AV1_COMMON *const cm,
192                                                 DecoderCodingBlock *dcb,
193                                                 BLOCK_SIZE bsize) {
194   (void)cm;
195   (void)dcb;
196   (void)bsize;
197 }
198 
cfl_store_inter_block_void(AV1_COMMON * const cm,MACROBLOCKD * const xd)199 static AOM_INLINE void cfl_store_inter_block_void(AV1_COMMON *const cm,
200                                                   MACROBLOCKD *const xd) {
201   (void)cm;
202   (void)xd;
203 }
204 
predict_and_reconstruct_intra_block(const AV1_COMMON * const cm,DecoderCodingBlock * dcb,aom_reader * const r,const int plane,const int row,const int col,const TX_SIZE tx_size)205 static AOM_INLINE void predict_and_reconstruct_intra_block(
206     const AV1_COMMON *const cm, DecoderCodingBlock *dcb, aom_reader *const r,
207     const int plane, const int row, const int col, const TX_SIZE tx_size) {
208   (void)r;
209   MACROBLOCKD *const xd = &dcb->xd;
210   MB_MODE_INFO *mbmi = xd->mi[0];
211   PLANE_TYPE plane_type = get_plane_type(plane);
212 
213   av1_predict_intra_block_facade(cm, xd, plane, col, row, tx_size);
214 
215   if (!mbmi->skip_txfm) {
216     eob_info *eob_data = dcb->eob_data[plane] + dcb->txb_offset[plane];
217     if (eob_data->eob) {
218       const bool reduced_tx_set_used = cm->features.reduced_tx_set_used;
219       // tx_type was read out in av1_read_coeffs_txb.
220       const TX_TYPE tx_type = av1_get_tx_type(xd, plane_type, row, col, tx_size,
221                                               reduced_tx_set_used);
222       struct macroblockd_plane *const pd = &xd->plane[plane];
223       uint8_t *dst = &pd->dst.buf[(row * pd->dst.stride + col) << MI_SIZE_LOG2];
224       inverse_transform_block(dcb, plane, tx_type, tx_size, dst, pd->dst.stride,
225                               reduced_tx_set_used);
226     }
227   }
228   if (plane == AOM_PLANE_Y && store_cfl_required(cm, xd)) {
229     cfl_store_tx(xd, row, col, tx_size, mbmi->bsize);
230   }
231 }
232 
inverse_transform_inter_block(const AV1_COMMON * const cm,DecoderCodingBlock * dcb,aom_reader * const r,const int plane,const int blk_row,const int blk_col,const TX_SIZE tx_size)233 static AOM_INLINE void inverse_transform_inter_block(
234     const AV1_COMMON *const cm, DecoderCodingBlock *dcb, aom_reader *const r,
235     const int plane, const int blk_row, const int blk_col,
236     const TX_SIZE tx_size) {
237   (void)r;
238   MACROBLOCKD *const xd = &dcb->xd;
239   PLANE_TYPE plane_type = get_plane_type(plane);
240   const struct macroblockd_plane *const pd = &xd->plane[plane];
241   const bool reduced_tx_set_used = cm->features.reduced_tx_set_used;
242   // tx_type was read out in av1_read_coeffs_txb.
243   const TX_TYPE tx_type = av1_get_tx_type(xd, plane_type, blk_row, blk_col,
244                                           tx_size, reduced_tx_set_used);
245 
246   uint8_t *dst =
247       &pd->dst.buf[(blk_row * pd->dst.stride + blk_col) << MI_SIZE_LOG2];
248   inverse_transform_block(dcb, plane, tx_type, tx_size, dst, pd->dst.stride,
249                           reduced_tx_set_used);
250 #if CONFIG_MISMATCH_DEBUG
251   int pixel_c, pixel_r;
252   BLOCK_SIZE bsize = txsize_to_bsize[tx_size];
253   int blk_w = block_size_wide[bsize];
254   int blk_h = block_size_high[bsize];
255   const int mi_row = -xd->mb_to_top_edge >> (3 + MI_SIZE_LOG2);
256   const int mi_col = -xd->mb_to_left_edge >> (3 + MI_SIZE_LOG2);
257   mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, blk_col, blk_row,
258                   pd->subsampling_x, pd->subsampling_y);
259   mismatch_check_block_tx(dst, pd->dst.stride, cm->current_frame.order_hint,
260                           plane, pixel_c, pixel_r, blk_w, blk_h,
261                           xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
262 #endif
263 }
264 
set_cb_buffer_offsets(DecoderCodingBlock * dcb,TX_SIZE tx_size,int plane)265 static AOM_INLINE void set_cb_buffer_offsets(DecoderCodingBlock *dcb,
266                                              TX_SIZE tx_size, int plane) {
267   dcb->cb_offset[plane] += tx_size_wide[tx_size] * tx_size_high[tx_size];
268   dcb->txb_offset[plane] =
269       dcb->cb_offset[plane] / (TX_SIZE_W_MIN * TX_SIZE_H_MIN);
270 }
271 
decode_reconstruct_tx(AV1_COMMON * cm,ThreadData * const td,aom_reader * r,MB_MODE_INFO * const mbmi,int plane,BLOCK_SIZE plane_bsize,int blk_row,int blk_col,int block,TX_SIZE tx_size,int * eob_total)272 static AOM_INLINE void decode_reconstruct_tx(
273     AV1_COMMON *cm, ThreadData *const td, aom_reader *r,
274     MB_MODE_INFO *const mbmi, int plane, BLOCK_SIZE plane_bsize, int blk_row,
275     int blk_col, int block, TX_SIZE tx_size, int *eob_total) {
276   DecoderCodingBlock *const dcb = &td->dcb;
277   MACROBLOCKD *const xd = &dcb->xd;
278   const struct macroblockd_plane *const pd = &xd->plane[plane];
279   const TX_SIZE plane_tx_size =
280       plane ? av1_get_max_uv_txsize(mbmi->bsize, pd->subsampling_x,
281                                     pd->subsampling_y)
282             : mbmi->inter_tx_size[av1_get_txb_size_index(plane_bsize, blk_row,
283                                                          blk_col)];
284   // Scale to match transform block unit.
285   const int max_blocks_high = max_block_high(xd, plane_bsize, plane);
286   const int max_blocks_wide = max_block_wide(xd, plane_bsize, plane);
287 
288   if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
289 
290   if (tx_size == plane_tx_size || plane) {
291     td->read_coeffs_tx_inter_block_visit(cm, dcb, r, plane, blk_row, blk_col,
292                                          tx_size);
293 
294     td->inverse_tx_inter_block_visit(cm, dcb, r, plane, blk_row, blk_col,
295                                      tx_size);
296     eob_info *eob_data = dcb->eob_data[plane] + dcb->txb_offset[plane];
297     *eob_total += eob_data->eob;
298     set_cb_buffer_offsets(dcb, tx_size, plane);
299   } else {
300     const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
301     assert(IMPLIES(tx_size <= TX_4X4, sub_txs == tx_size));
302     assert(IMPLIES(tx_size > TX_4X4, sub_txs < tx_size));
303     const int bsw = tx_size_wide_unit[sub_txs];
304     const int bsh = tx_size_high_unit[sub_txs];
305     const int sub_step = bsw * bsh;
306     const int row_end =
307         AOMMIN(tx_size_high_unit[tx_size], max_blocks_high - blk_row);
308     const int col_end =
309         AOMMIN(tx_size_wide_unit[tx_size], max_blocks_wide - blk_col);
310 
311     assert(bsw > 0 && bsh > 0);
312 
313     for (int row = 0; row < row_end; row += bsh) {
314       const int offsetr = blk_row + row;
315       for (int col = 0; col < col_end; col += bsw) {
316         const int offsetc = blk_col + col;
317 
318         decode_reconstruct_tx(cm, td, r, mbmi, plane, plane_bsize, offsetr,
319                               offsetc, block, sub_txs, eob_total);
320         block += sub_step;
321       }
322     }
323   }
324 }
325 
set_offsets(AV1_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)326 static AOM_INLINE void set_offsets(AV1_COMMON *const cm, MACROBLOCKD *const xd,
327                                    BLOCK_SIZE bsize, int mi_row, int mi_col,
328                                    int bw, int bh, int x_mis, int y_mis) {
329   const int num_planes = av1_num_planes(cm);
330   const CommonModeInfoParams *const mi_params = &cm->mi_params;
331   const TileInfo *const tile = &xd->tile;
332 
333   set_mi_offsets(mi_params, xd, mi_row, mi_col);
334   xd->mi[0]->bsize = bsize;
335 #if CONFIG_RD_DEBUG
336   xd->mi[0]->mi_row = mi_row;
337   xd->mi[0]->mi_col = mi_col;
338 #endif
339 
340   assert(x_mis && y_mis);
341   for (int x = 1; x < x_mis; ++x) xd->mi[x] = xd->mi[0];
342   int idx = mi_params->mi_stride;
343   for (int y = 1; y < y_mis; ++y) {
344     memcpy(&xd->mi[idx], &xd->mi[0], x_mis * sizeof(xd->mi[0]));
345     idx += mi_params->mi_stride;
346   }
347 
348   set_plane_n4(xd, bw, bh, num_planes);
349   set_entropy_context(xd, mi_row, mi_col, num_planes);
350 
351   // Distance of Mb to the various image edges. These are specified to 8th pel
352   // as they are always compared to values that are in 1/8th pel units
353   set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, mi_params->mi_rows,
354                  mi_params->mi_cols);
355 
356   av1_setup_dst_planes(xd->plane, bsize, &cm->cur_frame->buf, mi_row, mi_col, 0,
357                        num_planes);
358 }
359 
decode_mbmi_block(AV1Decoder * const pbi,DecoderCodingBlock * dcb,int mi_row,int mi_col,aom_reader * r,PARTITION_TYPE partition,BLOCK_SIZE bsize)360 static AOM_INLINE void decode_mbmi_block(AV1Decoder *const pbi,
361                                          DecoderCodingBlock *dcb, int mi_row,
362                                          int mi_col, aom_reader *r,
363                                          PARTITION_TYPE partition,
364                                          BLOCK_SIZE bsize) {
365   AV1_COMMON *const cm = &pbi->common;
366   const SequenceHeader *const seq_params = cm->seq_params;
367   const int bw = mi_size_wide[bsize];
368   const int bh = mi_size_high[bsize];
369   const int x_mis = AOMMIN(bw, cm->mi_params.mi_cols - mi_col);
370   const int y_mis = AOMMIN(bh, cm->mi_params.mi_rows - mi_row);
371   MACROBLOCKD *const xd = &dcb->xd;
372 
373 #if CONFIG_ACCOUNTING
374   aom_accounting_set_context(&pbi->accounting, mi_col, mi_row);
375 #endif
376   set_offsets(cm, xd, bsize, mi_row, mi_col, bw, bh, x_mis, y_mis);
377   xd->mi[0]->partition = partition;
378   av1_read_mode_info(pbi, dcb, r, x_mis, y_mis);
379   if (bsize >= BLOCK_8X8 &&
380       (seq_params->subsampling_x || seq_params->subsampling_y)) {
381     const BLOCK_SIZE uv_subsize =
382         ss_size_lookup[bsize][seq_params->subsampling_x]
383                       [seq_params->subsampling_y];
384     if (uv_subsize == BLOCK_INVALID)
385       aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
386                          "Invalid block size.");
387   }
388 }
389 
390 typedef struct PadBlock {
391   int x0;
392   int x1;
393   int y0;
394   int y1;
395 } PadBlock;
396 
397 #if CONFIG_AV1_HIGHBITDEPTH
highbd_build_mc_border(const uint8_t * src8,int src_stride,uint8_t * dst8,int dst_stride,int x,int y,int b_w,int b_h,int w,int h)398 static AOM_INLINE void highbd_build_mc_border(const uint8_t *src8,
399                                               int src_stride, uint8_t *dst8,
400                                               int dst_stride, int x, int y,
401                                               int b_w, int b_h, int w, int h) {
402   // Get a pointer to the start of the real data for this row.
403   const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
404   uint16_t *dst = CONVERT_TO_SHORTPTR(dst8);
405   const uint16_t *ref_row = src - x - y * src_stride;
406 
407   if (y >= h)
408     ref_row += (h - 1) * src_stride;
409   else if (y > 0)
410     ref_row += y * src_stride;
411 
412   do {
413     int right = 0, copy;
414     int left = x < 0 ? -x : 0;
415 
416     if (left > b_w) left = b_w;
417 
418     if (x + b_w > w) right = x + b_w - w;
419 
420     if (right > b_w) right = b_w;
421 
422     copy = b_w - left - right;
423 
424     if (left) aom_memset16(dst, ref_row[0], left);
425 
426     if (copy) memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
427 
428     if (right) aom_memset16(dst + left + copy, ref_row[w - 1], right);
429 
430     dst += dst_stride;
431     ++y;
432 
433     if (y > 0 && y < h) ref_row += src_stride;
434   } while (--b_h);
435 }
436 #endif  // CONFIG_AV1_HIGHBITDEPTH
437 
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)438 static AOM_INLINE void build_mc_border(const uint8_t *src, int src_stride,
439                                        uint8_t *dst, int dst_stride, int x,
440                                        int y, int b_w, int b_h, int w, int h) {
441   // Get a pointer to the start of the real data for this row.
442   const uint8_t *ref_row = src - x - y * src_stride;
443 
444   if (y >= h)
445     ref_row += (h - 1) * src_stride;
446   else if (y > 0)
447     ref_row += y * src_stride;
448 
449   do {
450     int right = 0, copy;
451     int left = x < 0 ? -x : 0;
452 
453     if (left > b_w) left = b_w;
454 
455     if (x + b_w > w) right = x + b_w - w;
456 
457     if (right > b_w) right = b_w;
458 
459     copy = b_w - left - right;
460 
461     if (left) memset(dst, ref_row[0], left);
462 
463     if (copy) memcpy(dst + left, ref_row + x + left, copy);
464 
465     if (right) memset(dst + left + copy, ref_row[w - 1], right);
466 
467     dst += dst_stride;
468     ++y;
469 
470     if (y > 0 && y < h) ref_row += src_stride;
471   } while (--b_h);
472 }
473 
update_extend_mc_border_params(const struct scale_factors * const sf,struct buf_2d * const pre_buf,MV32 scaled_mv,PadBlock * block,int subpel_x_mv,int subpel_y_mv,int do_warp,int is_intrabc,int * x_pad,int * y_pad)474 static INLINE int update_extend_mc_border_params(
475     const struct scale_factors *const sf, struct buf_2d *const pre_buf,
476     MV32 scaled_mv, PadBlock *block, int subpel_x_mv, int subpel_y_mv,
477     int do_warp, int is_intrabc, int *x_pad, int *y_pad) {
478   const int is_scaled = av1_is_scaled(sf);
479   // Get reference width and height.
480   int frame_width = pre_buf->width;
481   int frame_height = pre_buf->height;
482 
483   // Do border extension if there is motion or
484   // width/height is not a multiple of 8 pixels.
485   if ((!is_intrabc) && (!do_warp) &&
486       (is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 0x7) ||
487        (frame_height & 0x7))) {
488     if (subpel_x_mv || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
489       block->x0 -= AOM_INTERP_EXTEND - 1;
490       block->x1 += AOM_INTERP_EXTEND;
491       *x_pad = 1;
492     }
493 
494     if (subpel_y_mv || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
495       block->y0 -= AOM_INTERP_EXTEND - 1;
496       block->y1 += AOM_INTERP_EXTEND;
497       *y_pad = 1;
498     }
499 
500     // Skip border extension if block is inside the frame.
501     if (block->x0 < 0 || block->x1 > frame_width - 1 || block->y0 < 0 ||
502         block->y1 > frame_height - 1) {
503       return 1;
504     }
505   }
506   return 0;
507 }
508 
extend_mc_border(const struct scale_factors * const sf,struct buf_2d * const pre_buf,MV32 scaled_mv,PadBlock block,int subpel_x_mv,int subpel_y_mv,int do_warp,int is_intrabc,int highbd,uint8_t * mc_buf,uint8_t ** pre,int * src_stride)509 static INLINE void extend_mc_border(const struct scale_factors *const sf,
510                                     struct buf_2d *const pre_buf,
511                                     MV32 scaled_mv, PadBlock block,
512                                     int subpel_x_mv, int subpel_y_mv,
513                                     int do_warp, int is_intrabc, int highbd,
514                                     uint8_t *mc_buf, uint8_t **pre,
515                                     int *src_stride) {
516   int x_pad = 0, y_pad = 0;
517   if (update_extend_mc_border_params(sf, pre_buf, scaled_mv, &block,
518                                      subpel_x_mv, subpel_y_mv, do_warp,
519                                      is_intrabc, &x_pad, &y_pad)) {
520     // Get reference block pointer.
521     const uint8_t *const buf_ptr =
522         pre_buf->buf0 + block.y0 * pre_buf->stride + block.x0;
523     int buf_stride = pre_buf->stride;
524     const int b_w = block.x1 - block.x0;
525     const int b_h = block.y1 - block.y0;
526 
527 #if CONFIG_AV1_HIGHBITDEPTH
528     // Extend the border.
529     if (highbd) {
530       highbd_build_mc_border(buf_ptr, buf_stride, mc_buf, b_w, block.x0,
531                              block.y0, b_w, b_h, pre_buf->width,
532                              pre_buf->height);
533     } else {
534       build_mc_border(buf_ptr, buf_stride, mc_buf, b_w, block.x0, block.y0, b_w,
535                       b_h, pre_buf->width, pre_buf->height);
536     }
537 #else
538     (void)highbd;
539     build_mc_border(buf_ptr, buf_stride, mc_buf, b_w, block.x0, block.y0, b_w,
540                     b_h, pre_buf->width, pre_buf->height);
541 #endif
542     *src_stride = b_w;
543     *pre = mc_buf + y_pad * (AOM_INTERP_EXTEND - 1) * b_w +
544            x_pad * (AOM_INTERP_EXTEND - 1);
545   }
546 }
547 
dec_calc_subpel_params(const MV * const src_mv,InterPredParams * const inter_pred_params,const MACROBLOCKD * const xd,int mi_x,int mi_y,uint8_t ** pre,SubpelParams * subpel_params,int * src_stride,PadBlock * block,MV32 * scaled_mv,int * subpel_x_mv,int * subpel_y_mv)548 static void dec_calc_subpel_params(const MV *const src_mv,
549                                    InterPredParams *const inter_pred_params,
550                                    const MACROBLOCKD *const xd, int mi_x,
551                                    int mi_y, uint8_t **pre,
552                                    SubpelParams *subpel_params, int *src_stride,
553                                    PadBlock *block, MV32 *scaled_mv,
554                                    int *subpel_x_mv, int *subpel_y_mv) {
555   const struct scale_factors *sf = inter_pred_params->scale_factors;
556   struct buf_2d *pre_buf = &inter_pred_params->ref_frame_buf;
557   const int bw = inter_pred_params->block_width;
558   const int bh = inter_pred_params->block_height;
559   const int is_scaled = av1_is_scaled(sf);
560   if (is_scaled) {
561     int ssx = inter_pred_params->subsampling_x;
562     int ssy = inter_pred_params->subsampling_y;
563     int orig_pos_y = inter_pred_params->pix_row << SUBPEL_BITS;
564     orig_pos_y += src_mv->row * (1 << (1 - ssy));
565     int orig_pos_x = inter_pred_params->pix_col << SUBPEL_BITS;
566     orig_pos_x += src_mv->col * (1 << (1 - ssx));
567     int pos_y = sf->scale_value_y(orig_pos_y, sf);
568     int pos_x = sf->scale_value_x(orig_pos_x, sf);
569     pos_x += SCALE_EXTRA_OFF;
570     pos_y += SCALE_EXTRA_OFF;
571 
572     const int top = -AOM_LEFT_TOP_MARGIN_SCALED(ssy);
573     const int left = -AOM_LEFT_TOP_MARGIN_SCALED(ssx);
574     const int bottom = (pre_buf->height + AOM_INTERP_EXTEND)
575                        << SCALE_SUBPEL_BITS;
576     const int right = (pre_buf->width + AOM_INTERP_EXTEND) << SCALE_SUBPEL_BITS;
577     pos_y = clamp(pos_y, top, bottom);
578     pos_x = clamp(pos_x, left, right);
579 
580     subpel_params->subpel_x = pos_x & SCALE_SUBPEL_MASK;
581     subpel_params->subpel_y = pos_y & SCALE_SUBPEL_MASK;
582     subpel_params->xs = sf->x_step_q4;
583     subpel_params->ys = sf->y_step_q4;
584 
585     // Get reference block top left coordinate.
586     block->x0 = pos_x >> SCALE_SUBPEL_BITS;
587     block->y0 = pos_y >> SCALE_SUBPEL_BITS;
588 
589     // Get reference block bottom right coordinate.
590     block->x1 =
591         ((pos_x + (bw - 1) * subpel_params->xs) >> SCALE_SUBPEL_BITS) + 1;
592     block->y1 =
593         ((pos_y + (bh - 1) * subpel_params->ys) >> SCALE_SUBPEL_BITS) + 1;
594 
595     MV temp_mv;
596     temp_mv = clamp_mv_to_umv_border_sb(xd, src_mv, bw, bh,
597                                         inter_pred_params->subsampling_x,
598                                         inter_pred_params->subsampling_y);
599     *scaled_mv = av1_scale_mv(&temp_mv, mi_x, mi_y, sf);
600     scaled_mv->row += SCALE_EXTRA_OFF;
601     scaled_mv->col += SCALE_EXTRA_OFF;
602 
603     *subpel_x_mv = scaled_mv->col & SCALE_SUBPEL_MASK;
604     *subpel_y_mv = scaled_mv->row & SCALE_SUBPEL_MASK;
605   } else {
606     // Get block position in current frame.
607     int pos_x = inter_pred_params->pix_col << SUBPEL_BITS;
608     int pos_y = inter_pred_params->pix_row << SUBPEL_BITS;
609 
610     const MV mv_q4 = clamp_mv_to_umv_border_sb(
611         xd, src_mv, bw, bh, inter_pred_params->subsampling_x,
612         inter_pred_params->subsampling_y);
613     subpel_params->xs = subpel_params->ys = SCALE_SUBPEL_SHIFTS;
614     subpel_params->subpel_x = (mv_q4.col & SUBPEL_MASK) << SCALE_EXTRA_BITS;
615     subpel_params->subpel_y = (mv_q4.row & SUBPEL_MASK) << SCALE_EXTRA_BITS;
616 
617     // Get reference block top left coordinate.
618     pos_x += mv_q4.col;
619     pos_y += mv_q4.row;
620     block->x0 = pos_x >> SUBPEL_BITS;
621     block->y0 = pos_y >> SUBPEL_BITS;
622 
623     // Get reference block bottom right coordinate.
624     block->x1 = (pos_x >> SUBPEL_BITS) + (bw - 1) + 1;
625     block->y1 = (pos_y >> SUBPEL_BITS) + (bh - 1) + 1;
626 
627     scaled_mv->row = mv_q4.row;
628     scaled_mv->col = mv_q4.col;
629     *subpel_x_mv = scaled_mv->col & SUBPEL_MASK;
630     *subpel_y_mv = scaled_mv->row & SUBPEL_MASK;
631   }
632   *pre = pre_buf->buf0 + block->y0 * pre_buf->stride + block->x0;
633   *src_stride = pre_buf->stride;
634 }
635 
dec_calc_subpel_params_and_extend(const MV * const src_mv,InterPredParams * const inter_pred_params,MACROBLOCKD * const xd,int mi_x,int mi_y,int ref,uint8_t ** mc_buf,uint8_t ** pre,SubpelParams * subpel_params,int * src_stride)636 static void dec_calc_subpel_params_and_extend(
637     const MV *const src_mv, InterPredParams *const inter_pred_params,
638     MACROBLOCKD *const xd, int mi_x, int mi_y, int ref, uint8_t **mc_buf,
639     uint8_t **pre, SubpelParams *subpel_params, int *src_stride) {
640   PadBlock block;
641   MV32 scaled_mv;
642   int subpel_x_mv, subpel_y_mv;
643   dec_calc_subpel_params(src_mv, inter_pred_params, xd, mi_x, mi_y, pre,
644                          subpel_params, src_stride, &block, &scaled_mv,
645                          &subpel_x_mv, &subpel_y_mv);
646   extend_mc_border(
647       inter_pred_params->scale_factors, &inter_pred_params->ref_frame_buf,
648       scaled_mv, block, subpel_x_mv, subpel_y_mv,
649       inter_pred_params->mode == WARP_PRED, inter_pred_params->is_intrabc,
650       inter_pred_params->use_hbd_buf, mc_buf[ref], pre, src_stride);
651 }
652 
dec_build_inter_predictors(const AV1_COMMON * cm,DecoderCodingBlock * dcb,int plane,const MB_MODE_INFO * mi,int build_for_obmc,int bw,int bh,int mi_x,int mi_y)653 static void dec_build_inter_predictors(const AV1_COMMON *cm,
654                                        DecoderCodingBlock *dcb, int plane,
655                                        const MB_MODE_INFO *mi,
656                                        int build_for_obmc, int bw, int bh,
657                                        int mi_x, int mi_y) {
658   av1_build_inter_predictors(cm, &dcb->xd, plane, mi, build_for_obmc, bw, bh,
659                              mi_x, mi_y, dcb->mc_buf,
660                              dec_calc_subpel_params_and_extend);
661 }
662 
dec_build_inter_predictor(const AV1_COMMON * cm,DecoderCodingBlock * dcb,int mi_row,int mi_col,BLOCK_SIZE bsize)663 static AOM_INLINE void dec_build_inter_predictor(const AV1_COMMON *cm,
664                                                  DecoderCodingBlock *dcb,
665                                                  int mi_row, int mi_col,
666                                                  BLOCK_SIZE bsize) {
667   MACROBLOCKD *const xd = &dcb->xd;
668   const int num_planes = av1_num_planes(cm);
669   for (int plane = 0; plane < num_planes; ++plane) {
670     if (plane && !xd->is_chroma_ref) break;
671     const int mi_x = mi_col * MI_SIZE;
672     const int mi_y = mi_row * MI_SIZE;
673     dec_build_inter_predictors(cm, dcb, plane, xd->mi[0], 0,
674                                xd->plane[plane].width, xd->plane[plane].height,
675                                mi_x, mi_y);
676     if (is_interintra_pred(xd->mi[0])) {
677       BUFFER_SET ctx = { { xd->plane[0].dst.buf, xd->plane[1].dst.buf,
678                            xd->plane[2].dst.buf },
679                          { xd->plane[0].dst.stride, xd->plane[1].dst.stride,
680                            xd->plane[2].dst.stride } };
681       av1_build_interintra_predictor(cm, xd, xd->plane[plane].dst.buf,
682                                      xd->plane[plane].dst.stride, &ctx, plane,
683                                      bsize);
684     }
685   }
686 }
687 
dec_build_prediction_by_above_pred(MACROBLOCKD * const xd,int rel_mi_row,int rel_mi_col,uint8_t op_mi_size,int dir,MB_MODE_INFO * above_mbmi,void * fun_ctxt,const int num_planes)688 static INLINE void dec_build_prediction_by_above_pred(
689     MACROBLOCKD *const xd, int rel_mi_row, int rel_mi_col, uint8_t op_mi_size,
690     int dir, MB_MODE_INFO *above_mbmi, void *fun_ctxt, const int num_planes) {
691   struct build_prediction_ctxt *ctxt = (struct build_prediction_ctxt *)fun_ctxt;
692   const int above_mi_col = xd->mi_col + rel_mi_col;
693   int mi_x, mi_y;
694   MB_MODE_INFO backup_mbmi = *above_mbmi;
695 
696   (void)rel_mi_row;
697   (void)dir;
698 
699   av1_setup_build_prediction_by_above_pred(xd, rel_mi_col, op_mi_size,
700                                            &backup_mbmi, ctxt, num_planes);
701   mi_x = above_mi_col << MI_SIZE_LOG2;
702   mi_y = xd->mi_row << MI_SIZE_LOG2;
703 
704   const BLOCK_SIZE bsize = xd->mi[0]->bsize;
705 
706   for (int j = 0; j < num_planes; ++j) {
707     const struct macroblockd_plane *pd = &xd->plane[j];
708     int bw = (op_mi_size * MI_SIZE) >> pd->subsampling_x;
709     int bh = clamp(block_size_high[bsize] >> (pd->subsampling_y + 1), 4,
710                    block_size_high[BLOCK_64X64] >> (pd->subsampling_y + 1));
711 
712     if (av1_skip_u4x4_pred_in_obmc(bsize, pd, 0)) continue;
713     dec_build_inter_predictors(ctxt->cm, (DecoderCodingBlock *)ctxt->dcb, j,
714                                &backup_mbmi, 1, bw, bh, mi_x, mi_y);
715   }
716 }
717 
dec_build_prediction_by_above_preds(const AV1_COMMON * cm,DecoderCodingBlock * dcb,uint8_t * tmp_buf[MAX_MB_PLANE],int tmp_width[MAX_MB_PLANE],int tmp_height[MAX_MB_PLANE],int tmp_stride[MAX_MB_PLANE])718 static AOM_INLINE void dec_build_prediction_by_above_preds(
719     const AV1_COMMON *cm, DecoderCodingBlock *dcb,
720     uint8_t *tmp_buf[MAX_MB_PLANE], int tmp_width[MAX_MB_PLANE],
721     int tmp_height[MAX_MB_PLANE], int tmp_stride[MAX_MB_PLANE]) {
722   MACROBLOCKD *const xd = &dcb->xd;
723   if (!xd->up_available) return;
724 
725   // Adjust mb_to_bottom_edge to have the correct value for the OBMC
726   // prediction block. This is half the height of the original block,
727   // except for 128-wide blocks, where we only use a height of 32.
728   const int this_height = xd->height * MI_SIZE;
729   const int pred_height = AOMMIN(this_height / 2, 32);
730   xd->mb_to_bottom_edge += GET_MV_SUBPEL(this_height - pred_height);
731   struct build_prediction_ctxt ctxt = {
732     cm, tmp_buf, tmp_width, tmp_height, tmp_stride, xd->mb_to_right_edge, dcb
733   };
734   const BLOCK_SIZE bsize = xd->mi[0]->bsize;
735   foreach_overlappable_nb_above(cm, xd,
736                                 max_neighbor_obmc[mi_size_wide_log2[bsize]],
737                                 dec_build_prediction_by_above_pred, &ctxt);
738 
739   xd->mb_to_left_edge = -GET_MV_SUBPEL(xd->mi_col * MI_SIZE);
740   xd->mb_to_right_edge = ctxt.mb_to_far_edge;
741   xd->mb_to_bottom_edge -= GET_MV_SUBPEL(this_height - pred_height);
742 }
743 
dec_build_prediction_by_left_pred(MACROBLOCKD * const xd,int rel_mi_row,int rel_mi_col,uint8_t op_mi_size,int dir,MB_MODE_INFO * left_mbmi,void * fun_ctxt,const int num_planes)744 static INLINE void dec_build_prediction_by_left_pred(
745     MACROBLOCKD *const xd, int rel_mi_row, int rel_mi_col, uint8_t op_mi_size,
746     int dir, MB_MODE_INFO *left_mbmi, void *fun_ctxt, const int num_planes) {
747   struct build_prediction_ctxt *ctxt = (struct build_prediction_ctxt *)fun_ctxt;
748   const int left_mi_row = xd->mi_row + rel_mi_row;
749   int mi_x, mi_y;
750   MB_MODE_INFO backup_mbmi = *left_mbmi;
751 
752   (void)rel_mi_col;
753   (void)dir;
754 
755   av1_setup_build_prediction_by_left_pred(xd, rel_mi_row, op_mi_size,
756                                           &backup_mbmi, ctxt, num_planes);
757   mi_x = xd->mi_col << MI_SIZE_LOG2;
758   mi_y = left_mi_row << MI_SIZE_LOG2;
759   const BLOCK_SIZE bsize = xd->mi[0]->bsize;
760 
761   for (int j = 0; j < num_planes; ++j) {
762     const struct macroblockd_plane *pd = &xd->plane[j];
763     int bw = clamp(block_size_wide[bsize] >> (pd->subsampling_x + 1), 4,
764                    block_size_wide[BLOCK_64X64] >> (pd->subsampling_x + 1));
765     int bh = (op_mi_size << MI_SIZE_LOG2) >> pd->subsampling_y;
766 
767     if (av1_skip_u4x4_pred_in_obmc(bsize, pd, 1)) continue;
768     dec_build_inter_predictors(ctxt->cm, (DecoderCodingBlock *)ctxt->dcb, j,
769                                &backup_mbmi, 1, bw, bh, mi_x, mi_y);
770   }
771 }
772 
dec_build_prediction_by_left_preds(const AV1_COMMON * cm,DecoderCodingBlock * dcb,uint8_t * tmp_buf[MAX_MB_PLANE],int tmp_width[MAX_MB_PLANE],int tmp_height[MAX_MB_PLANE],int tmp_stride[MAX_MB_PLANE])773 static AOM_INLINE void dec_build_prediction_by_left_preds(
774     const AV1_COMMON *cm, DecoderCodingBlock *dcb,
775     uint8_t *tmp_buf[MAX_MB_PLANE], int tmp_width[MAX_MB_PLANE],
776     int tmp_height[MAX_MB_PLANE], int tmp_stride[MAX_MB_PLANE]) {
777   MACROBLOCKD *const xd = &dcb->xd;
778   if (!xd->left_available) return;
779 
780   // Adjust mb_to_right_edge to have the correct value for the OBMC
781   // prediction block. This is half the width of the original block,
782   // except for 128-wide blocks, where we only use a width of 32.
783   const int this_width = xd->width * MI_SIZE;
784   const int pred_width = AOMMIN(this_width / 2, 32);
785   xd->mb_to_right_edge += GET_MV_SUBPEL(this_width - pred_width);
786 
787   struct build_prediction_ctxt ctxt = {
788     cm, tmp_buf, tmp_width, tmp_height, tmp_stride, xd->mb_to_bottom_edge, dcb
789   };
790   const BLOCK_SIZE bsize = xd->mi[0]->bsize;
791   foreach_overlappable_nb_left(cm, xd,
792                                max_neighbor_obmc[mi_size_high_log2[bsize]],
793                                dec_build_prediction_by_left_pred, &ctxt);
794 
795   xd->mb_to_top_edge = -GET_MV_SUBPEL(xd->mi_row * MI_SIZE);
796   xd->mb_to_right_edge -= GET_MV_SUBPEL(this_width - pred_width);
797   xd->mb_to_bottom_edge = ctxt.mb_to_far_edge;
798 }
799 
dec_build_obmc_inter_predictors_sb(const AV1_COMMON * cm,DecoderCodingBlock * dcb)800 static AOM_INLINE void dec_build_obmc_inter_predictors_sb(
801     const AV1_COMMON *cm, DecoderCodingBlock *dcb) {
802   const int num_planes = av1_num_planes(cm);
803   uint8_t *dst_buf1[MAX_MB_PLANE], *dst_buf2[MAX_MB_PLANE];
804   int dst_stride1[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
805   int dst_stride2[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
806   int dst_width1[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
807   int dst_width2[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
808   int dst_height1[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
809   int dst_height2[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
810 
811   MACROBLOCKD *const xd = &dcb->xd;
812   av1_setup_obmc_dst_bufs(xd, dst_buf1, dst_buf2);
813 
814   dec_build_prediction_by_above_preds(cm, dcb, dst_buf1, dst_width1,
815                                       dst_height1, dst_stride1);
816   dec_build_prediction_by_left_preds(cm, dcb, dst_buf2, dst_width2, dst_height2,
817                                      dst_stride2);
818   const int mi_row = xd->mi_row;
819   const int mi_col = xd->mi_col;
820   av1_setup_dst_planes(xd->plane, xd->mi[0]->bsize, &cm->cur_frame->buf, mi_row,
821                        mi_col, 0, num_planes);
822   av1_build_obmc_inter_prediction(cm, xd, dst_buf1, dst_stride1, dst_buf2,
823                                   dst_stride2);
824 }
825 
cfl_store_inter_block(AV1_COMMON * const cm,MACROBLOCKD * const xd)826 static AOM_INLINE void cfl_store_inter_block(AV1_COMMON *const cm,
827                                              MACROBLOCKD *const xd) {
828   MB_MODE_INFO *mbmi = xd->mi[0];
829   if (store_cfl_required(cm, xd)) {
830     cfl_store_block(xd, mbmi->bsize, mbmi->tx_size);
831   }
832 }
833 
predict_inter_block(AV1_COMMON * const cm,DecoderCodingBlock * dcb,BLOCK_SIZE bsize)834 static AOM_INLINE void predict_inter_block(AV1_COMMON *const cm,
835                                            DecoderCodingBlock *dcb,
836                                            BLOCK_SIZE bsize) {
837   MACROBLOCKD *const xd = &dcb->xd;
838   MB_MODE_INFO *mbmi = xd->mi[0];
839   const int num_planes = av1_num_planes(cm);
840   const int mi_row = xd->mi_row;
841   const int mi_col = xd->mi_col;
842   for (int ref = 0; ref < 1 + has_second_ref(mbmi); ++ref) {
843     const MV_REFERENCE_FRAME frame = mbmi->ref_frame[ref];
844     if (frame < LAST_FRAME) {
845       assert(is_intrabc_block(mbmi));
846       assert(frame == INTRA_FRAME);
847       assert(ref == 0);
848     } else {
849       const RefCntBuffer *ref_buf = get_ref_frame_buf(cm, frame);
850       const struct scale_factors *ref_scale_factors =
851           get_ref_scale_factors_const(cm, frame);
852 
853       xd->block_ref_scale_factors[ref] = ref_scale_factors;
854       av1_setup_pre_planes(xd, ref, &ref_buf->buf, mi_row, mi_col,
855                            ref_scale_factors, num_planes);
856     }
857   }
858 
859   dec_build_inter_predictor(cm, dcb, mi_row, mi_col, bsize);
860   if (mbmi->motion_mode == OBMC_CAUSAL) {
861     dec_build_obmc_inter_predictors_sb(cm, dcb);
862   }
863 #if CONFIG_MISMATCH_DEBUG
864   for (int plane = 0; plane < num_planes; ++plane) {
865     const struct macroblockd_plane *pd = &xd->plane[plane];
866     int pixel_c, pixel_r;
867     mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, 0, 0, pd->subsampling_x,
868                     pd->subsampling_y);
869     if (!is_chroma_reference(mi_row, mi_col, bsize, pd->subsampling_x,
870                              pd->subsampling_y))
871       continue;
872     mismatch_check_block_pre(pd->dst.buf, pd->dst.stride,
873                              cm->current_frame.order_hint, plane, pixel_c,
874                              pixel_r, pd->width, pd->height,
875                              xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
876   }
877 #endif
878 }
879 
set_color_index_map_offset(MACROBLOCKD * const xd,int plane,aom_reader * r)880 static AOM_INLINE void set_color_index_map_offset(MACROBLOCKD *const xd,
881                                                   int plane, aom_reader *r) {
882   (void)r;
883   Av1ColorMapParam params;
884   const MB_MODE_INFO *const mbmi = xd->mi[0];
885   av1_get_block_dimensions(mbmi->bsize, plane, xd, &params.plane_width,
886                            &params.plane_height, NULL, NULL);
887   xd->color_index_map_offset[plane] += params.plane_width * params.plane_height;
888 }
889 
decode_token_recon_block(AV1Decoder * const pbi,ThreadData * const td,aom_reader * r,BLOCK_SIZE bsize)890 static AOM_INLINE void decode_token_recon_block(AV1Decoder *const pbi,
891                                                 ThreadData *const td,
892                                                 aom_reader *r,
893                                                 BLOCK_SIZE bsize) {
894   AV1_COMMON *const cm = &pbi->common;
895   DecoderCodingBlock *const dcb = &td->dcb;
896   MACROBLOCKD *const xd = &dcb->xd;
897   const int num_planes = av1_num_planes(cm);
898   MB_MODE_INFO *mbmi = xd->mi[0];
899 
900   if (!is_inter_block(mbmi)) {
901     int row, col;
902     assert(bsize == get_plane_block_size(bsize, xd->plane[0].subsampling_x,
903                                          xd->plane[0].subsampling_y));
904     const int max_blocks_wide = max_block_wide(xd, bsize, 0);
905     const int max_blocks_high = max_block_high(xd, bsize, 0);
906     const BLOCK_SIZE max_unit_bsize = BLOCK_64X64;
907     int mu_blocks_wide = mi_size_wide[max_unit_bsize];
908     int mu_blocks_high = mi_size_high[max_unit_bsize];
909     mu_blocks_wide = AOMMIN(max_blocks_wide, mu_blocks_wide);
910     mu_blocks_high = AOMMIN(max_blocks_high, mu_blocks_high);
911 
912     for (row = 0; row < max_blocks_high; row += mu_blocks_high) {
913       for (col = 0; col < max_blocks_wide; col += mu_blocks_wide) {
914         for (int plane = 0; plane < num_planes; ++plane) {
915           if (plane && !xd->is_chroma_ref) break;
916           const struct macroblockd_plane *const pd = &xd->plane[plane];
917           const TX_SIZE tx_size = av1_get_tx_size(plane, xd);
918 #if CONFIG_REALTIME_ONLY
919           // Realtime only build doesn't support 4x rectangular txfm sizes.
920           if (tx_size >= TX_4X16) {
921             aom_internal_error(xd->error_info, AOM_CODEC_UNSUP_FEATURE,
922                                "Realtime only build doesn't support 4x "
923                                "rectangular txfm sizes");
924           }
925 #endif
926           const int stepr = tx_size_high_unit[tx_size];
927           const int stepc = tx_size_wide_unit[tx_size];
928 
929           const int unit_height = ROUND_POWER_OF_TWO(
930               AOMMIN(mu_blocks_high + row, max_blocks_high), pd->subsampling_y);
931           const int unit_width = ROUND_POWER_OF_TWO(
932               AOMMIN(mu_blocks_wide + col, max_blocks_wide), pd->subsampling_x);
933 
934           for (int blk_row = row >> pd->subsampling_y; blk_row < unit_height;
935                blk_row += stepr) {
936             for (int blk_col = col >> pd->subsampling_x; blk_col < unit_width;
937                  blk_col += stepc) {
938               td->read_coeffs_tx_intra_block_visit(cm, dcb, r, plane, blk_row,
939                                                    blk_col, tx_size);
940               td->predict_and_recon_intra_block_visit(
941                   cm, dcb, r, plane, blk_row, blk_col, tx_size);
942               set_cb_buffer_offsets(dcb, tx_size, plane);
943             }
944           }
945         }
946       }
947     }
948   } else {
949     td->predict_inter_block_visit(cm, dcb, bsize);
950     // Reconstruction
951     if (!mbmi->skip_txfm) {
952       int eobtotal = 0;
953 
954       const int max_blocks_wide = max_block_wide(xd, bsize, 0);
955       const int max_blocks_high = max_block_high(xd, bsize, 0);
956       int row, col;
957 
958       const BLOCK_SIZE max_unit_bsize = BLOCK_64X64;
959       assert(max_unit_bsize ==
960              get_plane_block_size(BLOCK_64X64, xd->plane[0].subsampling_x,
961                                   xd->plane[0].subsampling_y));
962       int mu_blocks_wide = mi_size_wide[max_unit_bsize];
963       int mu_blocks_high = mi_size_high[max_unit_bsize];
964 
965       mu_blocks_wide = AOMMIN(max_blocks_wide, mu_blocks_wide);
966       mu_blocks_high = AOMMIN(max_blocks_high, mu_blocks_high);
967 
968       for (row = 0; row < max_blocks_high; row += mu_blocks_high) {
969         for (col = 0; col < max_blocks_wide; col += mu_blocks_wide) {
970           for (int plane = 0; plane < num_planes; ++plane) {
971             if (plane && !xd->is_chroma_ref) break;
972             const struct macroblockd_plane *const pd = &xd->plane[plane];
973             const int ss_x = pd->subsampling_x;
974             const int ss_y = pd->subsampling_y;
975             const BLOCK_SIZE plane_bsize =
976                 get_plane_block_size(bsize, ss_x, ss_y);
977             const TX_SIZE max_tx_size =
978                 get_vartx_max_txsize(xd, plane_bsize, plane);
979             const int bh_var_tx = tx_size_high_unit[max_tx_size];
980             const int bw_var_tx = tx_size_wide_unit[max_tx_size];
981             int block = 0;
982             int step =
983                 tx_size_wide_unit[max_tx_size] * tx_size_high_unit[max_tx_size];
984             int blk_row, blk_col;
985             const int unit_height = ROUND_POWER_OF_TWO(
986                 AOMMIN(mu_blocks_high + row, max_blocks_high), ss_y);
987             const int unit_width = ROUND_POWER_OF_TWO(
988                 AOMMIN(mu_blocks_wide + col, max_blocks_wide), ss_x);
989 
990             for (blk_row = row >> ss_y; blk_row < unit_height;
991                  blk_row += bh_var_tx) {
992               for (blk_col = col >> ss_x; blk_col < unit_width;
993                    blk_col += bw_var_tx) {
994                 decode_reconstruct_tx(cm, td, r, mbmi, plane, plane_bsize,
995                                       blk_row, blk_col, block, max_tx_size,
996                                       &eobtotal);
997                 block += step;
998               }
999             }
1000           }
1001         }
1002       }
1003     }
1004     td->cfl_store_inter_block_visit(cm, xd);
1005   }
1006 
1007   av1_visit_palette(pbi, xd, r, set_color_index_map_offset);
1008 }
1009 
set_inter_tx_size(MB_MODE_INFO * mbmi,int stride_log2,int tx_w_log2,int tx_h_log2,int min_txs,int split_size,int txs,int blk_row,int blk_col)1010 static AOM_INLINE void set_inter_tx_size(MB_MODE_INFO *mbmi, int stride_log2,
1011                                          int tx_w_log2, int tx_h_log2,
1012                                          int min_txs, int split_size, int txs,
1013                                          int blk_row, int blk_col) {
1014   for (int idy = 0; idy < tx_size_high_unit[split_size];
1015        idy += tx_size_high_unit[min_txs]) {
1016     for (int idx = 0; idx < tx_size_wide_unit[split_size];
1017          idx += tx_size_wide_unit[min_txs]) {
1018       const int index = (((blk_row + idy) >> tx_h_log2) << stride_log2) +
1019                         ((blk_col + idx) >> tx_w_log2);
1020       mbmi->inter_tx_size[index] = txs;
1021     }
1022   }
1023 }
1024 
read_tx_size_vartx(MACROBLOCKD * xd,MB_MODE_INFO * mbmi,TX_SIZE tx_size,int depth,int blk_row,int blk_col,aom_reader * r)1025 static AOM_INLINE void read_tx_size_vartx(MACROBLOCKD *xd, MB_MODE_INFO *mbmi,
1026                                           TX_SIZE tx_size, int depth,
1027                                           int blk_row, int blk_col,
1028                                           aom_reader *r) {
1029   FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
1030   int is_split = 0;
1031   const BLOCK_SIZE bsize = mbmi->bsize;
1032   const int max_blocks_high = max_block_high(xd, bsize, 0);
1033   const int max_blocks_wide = max_block_wide(xd, bsize, 0);
1034   if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
1035   assert(tx_size > TX_4X4);
1036   TX_SIZE txs = max_txsize_rect_lookup[bsize];
1037   for (int level = 0; level < MAX_VARTX_DEPTH - 1; ++level)
1038     txs = sub_tx_size_map[txs];
1039   const int tx_w_log2 = tx_size_wide_log2[txs] - MI_SIZE_LOG2;
1040   const int tx_h_log2 = tx_size_high_log2[txs] - MI_SIZE_LOG2;
1041   const int bw_log2 = mi_size_wide_log2[bsize];
1042   const int stride_log2 = bw_log2 - tx_w_log2;
1043 
1044   if (depth == MAX_VARTX_DEPTH) {
1045     set_inter_tx_size(mbmi, stride_log2, tx_w_log2, tx_h_log2, txs, tx_size,
1046                       tx_size, blk_row, blk_col);
1047     mbmi->tx_size = tx_size;
1048     txfm_partition_update(xd->above_txfm_context + blk_col,
1049                           xd->left_txfm_context + blk_row, tx_size, tx_size);
1050     return;
1051   }
1052 
1053   const int ctx = txfm_partition_context(xd->above_txfm_context + blk_col,
1054                                          xd->left_txfm_context + blk_row,
1055                                          mbmi->bsize, tx_size);
1056   is_split = aom_read_symbol(r, ec_ctx->txfm_partition_cdf[ctx], 2, ACCT_STR);
1057 
1058   if (is_split) {
1059     const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
1060     const int bsw = tx_size_wide_unit[sub_txs];
1061     const int bsh = tx_size_high_unit[sub_txs];
1062 
1063     if (sub_txs == TX_4X4) {
1064       set_inter_tx_size(mbmi, stride_log2, tx_w_log2, tx_h_log2, txs, tx_size,
1065                         sub_txs, blk_row, blk_col);
1066       mbmi->tx_size = sub_txs;
1067       txfm_partition_update(xd->above_txfm_context + blk_col,
1068                             xd->left_txfm_context + blk_row, sub_txs, tx_size);
1069       return;
1070     }
1071 
1072     assert(bsw > 0 && bsh > 0);
1073     for (int row = 0; row < tx_size_high_unit[tx_size]; row += bsh) {
1074       for (int col = 0; col < tx_size_wide_unit[tx_size]; col += bsw) {
1075         int offsetr = blk_row + row;
1076         int offsetc = blk_col + col;
1077         read_tx_size_vartx(xd, mbmi, sub_txs, depth + 1, offsetr, offsetc, r);
1078       }
1079     }
1080   } else {
1081     set_inter_tx_size(mbmi, stride_log2, tx_w_log2, tx_h_log2, txs, tx_size,
1082                       tx_size, blk_row, blk_col);
1083     mbmi->tx_size = tx_size;
1084     txfm_partition_update(xd->above_txfm_context + blk_col,
1085                           xd->left_txfm_context + blk_row, tx_size, tx_size);
1086   }
1087 }
1088 
read_selected_tx_size(const MACROBLOCKD * const xd,aom_reader * r)1089 static TX_SIZE read_selected_tx_size(const MACROBLOCKD *const xd,
1090                                      aom_reader *r) {
1091   // TODO(debargha): Clean up the logic here. This function should only
1092   // be called for intra.
1093   const BLOCK_SIZE bsize = xd->mi[0]->bsize;
1094   const int32_t tx_size_cat = bsize_to_tx_size_cat(bsize);
1095   const int max_depths = bsize_to_max_depth(bsize);
1096   const int ctx = get_tx_size_context(xd);
1097   FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
1098   const int depth = aom_read_symbol(r, ec_ctx->tx_size_cdf[tx_size_cat][ctx],
1099                                     max_depths + 1, ACCT_STR);
1100   assert(depth >= 0 && depth <= max_depths);
1101   const TX_SIZE tx_size = depth_to_tx_size(depth, bsize);
1102   return tx_size;
1103 }
1104 
read_tx_size(const MACROBLOCKD * const xd,TX_MODE tx_mode,int is_inter,int allow_select_inter,aom_reader * r)1105 static TX_SIZE read_tx_size(const MACROBLOCKD *const xd, TX_MODE tx_mode,
1106                             int is_inter, int allow_select_inter,
1107                             aom_reader *r) {
1108   const BLOCK_SIZE bsize = xd->mi[0]->bsize;
1109   if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;
1110 
1111   if (block_signals_txsize(bsize)) {
1112     if ((!is_inter || allow_select_inter) && tx_mode == TX_MODE_SELECT) {
1113       const TX_SIZE coded_tx_size = read_selected_tx_size(xd, r);
1114       return coded_tx_size;
1115     } else {
1116       return tx_size_from_tx_mode(bsize, tx_mode);
1117     }
1118   } else {
1119     assert(IMPLIES(tx_mode == ONLY_4X4, bsize == BLOCK_4X4));
1120     return max_txsize_rect_lookup[bsize];
1121   }
1122 }
1123 
parse_decode_block(AV1Decoder * const pbi,ThreadData * const td,int mi_row,int mi_col,aom_reader * r,PARTITION_TYPE partition,BLOCK_SIZE bsize)1124 static AOM_INLINE void parse_decode_block(AV1Decoder *const pbi,
1125                                           ThreadData *const td, int mi_row,
1126                                           int mi_col, aom_reader *r,
1127                                           PARTITION_TYPE partition,
1128                                           BLOCK_SIZE bsize) {
1129   DecoderCodingBlock *const dcb = &td->dcb;
1130   MACROBLOCKD *const xd = &dcb->xd;
1131   decode_mbmi_block(pbi, dcb, mi_row, mi_col, r, partition, bsize);
1132 
1133   av1_visit_palette(pbi, xd, r, av1_decode_palette_tokens);
1134 
1135   AV1_COMMON *cm = &pbi->common;
1136   const int num_planes = av1_num_planes(cm);
1137   MB_MODE_INFO *mbmi = xd->mi[0];
1138   int inter_block_tx = is_inter_block(mbmi) || is_intrabc_block(mbmi);
1139   if (cm->features.tx_mode == TX_MODE_SELECT && block_signals_txsize(bsize) &&
1140       !mbmi->skip_txfm && inter_block_tx && !xd->lossless[mbmi->segment_id]) {
1141     const TX_SIZE max_tx_size = max_txsize_rect_lookup[bsize];
1142     const int bh = tx_size_high_unit[max_tx_size];
1143     const int bw = tx_size_wide_unit[max_tx_size];
1144     const int width = mi_size_wide[bsize];
1145     const int height = mi_size_high[bsize];
1146 
1147     for (int idy = 0; idy < height; idy += bh)
1148       for (int idx = 0; idx < width; idx += bw)
1149         read_tx_size_vartx(xd, mbmi, max_tx_size, 0, idy, idx, r);
1150   } else {
1151     mbmi->tx_size = read_tx_size(xd, cm->features.tx_mode, inter_block_tx,
1152                                  !mbmi->skip_txfm, r);
1153     if (inter_block_tx)
1154       memset(mbmi->inter_tx_size, mbmi->tx_size, sizeof(mbmi->inter_tx_size));
1155     set_txfm_ctxs(mbmi->tx_size, xd->width, xd->height,
1156                   mbmi->skip_txfm && is_inter_block(mbmi), xd);
1157   }
1158 
1159   if (cm->delta_q_info.delta_q_present_flag) {
1160     for (int i = 0; i < MAX_SEGMENTS; i++) {
1161       const int current_qindex =
1162           av1_get_qindex(&cm->seg, i, xd->current_base_qindex);
1163       const CommonQuantParams *const quant_params = &cm->quant_params;
1164       for (int j = 0; j < num_planes; ++j) {
1165         const int dc_delta_q = j == 0 ? quant_params->y_dc_delta_q
1166                                       : (j == 1 ? quant_params->u_dc_delta_q
1167                                                 : quant_params->v_dc_delta_q);
1168         const int ac_delta_q = j == 0 ? 0
1169                                       : (j == 1 ? quant_params->u_ac_delta_q
1170                                                 : quant_params->v_ac_delta_q);
1171         xd->plane[j].seg_dequant_QTX[i][0] = av1_dc_quant_QTX(
1172             current_qindex, dc_delta_q, cm->seq_params->bit_depth);
1173         xd->plane[j].seg_dequant_QTX[i][1] = av1_ac_quant_QTX(
1174             current_qindex, ac_delta_q, cm->seq_params->bit_depth);
1175       }
1176     }
1177   }
1178   if (mbmi->skip_txfm) av1_reset_entropy_context(xd, bsize, num_planes);
1179 
1180   decode_token_recon_block(pbi, td, r, bsize);
1181 }
1182 
set_offsets_for_pred_and_recon(AV1Decoder * const pbi,ThreadData * const td,int mi_row,int mi_col,BLOCK_SIZE bsize)1183 static AOM_INLINE void set_offsets_for_pred_and_recon(AV1Decoder *const pbi,
1184                                                       ThreadData *const td,
1185                                                       int mi_row, int mi_col,
1186                                                       BLOCK_SIZE bsize) {
1187   AV1_COMMON *const cm = &pbi->common;
1188   const CommonModeInfoParams *const mi_params = &cm->mi_params;
1189   DecoderCodingBlock *const dcb = &td->dcb;
1190   MACROBLOCKD *const xd = &dcb->xd;
1191   const int bw = mi_size_wide[bsize];
1192   const int bh = mi_size_high[bsize];
1193   const int num_planes = av1_num_planes(cm);
1194 
1195   const int offset = mi_row * mi_params->mi_stride + mi_col;
1196   const TileInfo *const tile = &xd->tile;
1197 
1198   xd->mi = mi_params->mi_grid_base + offset;
1199   xd->tx_type_map =
1200       &mi_params->tx_type_map[mi_row * mi_params->mi_stride + mi_col];
1201   xd->tx_type_map_stride = mi_params->mi_stride;
1202 
1203   set_plane_n4(xd, bw, bh, num_planes);
1204 
1205   // Distance of Mb to the various image edges. These are specified to 8th pel
1206   // as they are always compared to values that are in 1/8th pel units
1207   set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, mi_params->mi_rows,
1208                  mi_params->mi_cols);
1209 
1210   av1_setup_dst_planes(xd->plane, bsize, &cm->cur_frame->buf, mi_row, mi_col, 0,
1211                        num_planes);
1212 }
1213 
decode_block(AV1Decoder * const pbi,ThreadData * const td,int mi_row,int mi_col,aom_reader * r,PARTITION_TYPE partition,BLOCK_SIZE bsize)1214 static AOM_INLINE void decode_block(AV1Decoder *const pbi, ThreadData *const td,
1215                                     int mi_row, int mi_col, aom_reader *r,
1216                                     PARTITION_TYPE partition,
1217                                     BLOCK_SIZE bsize) {
1218   (void)partition;
1219   set_offsets_for_pred_and_recon(pbi, td, mi_row, mi_col, bsize);
1220   decode_token_recon_block(pbi, td, r, bsize);
1221 }
1222 
read_partition(MACROBLOCKD * xd,int mi_row,int mi_col,aom_reader * r,int has_rows,int has_cols,BLOCK_SIZE bsize)1223 static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
1224                                      aom_reader *r, int has_rows, int has_cols,
1225                                      BLOCK_SIZE bsize) {
1226   const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
1227   FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
1228 
1229   if (!has_rows && !has_cols) return PARTITION_SPLIT;
1230 
1231   assert(ctx >= 0);
1232   aom_cdf_prob *partition_cdf = ec_ctx->partition_cdf[ctx];
1233   if (has_rows && has_cols) {
1234     return (PARTITION_TYPE)aom_read_symbol(
1235         r, partition_cdf, partition_cdf_length(bsize), ACCT_STR);
1236   } else if (!has_rows && has_cols) {
1237     assert(bsize > BLOCK_8X8);
1238     aom_cdf_prob cdf[2];
1239     partition_gather_vert_alike(cdf, partition_cdf, bsize);
1240     assert(cdf[1] == AOM_ICDF(CDF_PROB_TOP));
1241     return aom_read_cdf(r, cdf, 2, ACCT_STR) ? PARTITION_SPLIT : PARTITION_HORZ;
1242   } else {
1243     assert(has_rows && !has_cols);
1244     assert(bsize > BLOCK_8X8);
1245     aom_cdf_prob cdf[2];
1246     partition_gather_horz_alike(cdf, partition_cdf, bsize);
1247     assert(cdf[1] == AOM_ICDF(CDF_PROB_TOP));
1248     return aom_read_cdf(r, cdf, 2, ACCT_STR) ? PARTITION_SPLIT : PARTITION_VERT;
1249   }
1250 }
1251 
1252 // TODO(slavarnway): eliminate bsize and subsize in future commits
decode_partition(AV1Decoder * const pbi,ThreadData * const td,int mi_row,int mi_col,aom_reader * reader,BLOCK_SIZE bsize,int parse_decode_flag)1253 static AOM_INLINE void decode_partition(AV1Decoder *const pbi,
1254                                         ThreadData *const td, int mi_row,
1255                                         int mi_col, aom_reader *reader,
1256                                         BLOCK_SIZE bsize,
1257                                         int parse_decode_flag) {
1258   assert(bsize < BLOCK_SIZES_ALL);
1259   AV1_COMMON *const cm = &pbi->common;
1260   DecoderCodingBlock *const dcb = &td->dcb;
1261   MACROBLOCKD *const xd = &dcb->xd;
1262   const int bw = mi_size_wide[bsize];
1263   const int hbs = bw >> 1;
1264   PARTITION_TYPE partition;
1265   BLOCK_SIZE subsize;
1266   const int quarter_step = bw / 4;
1267   BLOCK_SIZE bsize2 = get_partition_subsize(bsize, PARTITION_SPLIT);
1268   const int has_rows = (mi_row + hbs) < cm->mi_params.mi_rows;
1269   const int has_cols = (mi_col + hbs) < cm->mi_params.mi_cols;
1270 
1271   if (mi_row >= cm->mi_params.mi_rows || mi_col >= cm->mi_params.mi_cols)
1272     return;
1273 
1274   // parse_decode_flag takes the following values :
1275   // 01 - do parse only
1276   // 10 - do decode only
1277   // 11 - do parse and decode
1278   static const block_visitor_fn_t block_visit[4] = { NULL, parse_decode_block,
1279                                                      decode_block,
1280                                                      parse_decode_block };
1281 
1282   if (parse_decode_flag & 1) {
1283     const int num_planes = av1_num_planes(cm);
1284     for (int plane = 0; plane < num_planes; ++plane) {
1285 #if CONFIG_REALTIME_ONLY
1286       assert(cm->rst_info[plane].frame_restoration_type == RESTORE_NONE);
1287 #else
1288       int rcol0, rcol1, rrow0, rrow1;
1289       if (av1_loop_restoration_corners_in_sb(cm, plane, mi_row, mi_col, bsize,
1290                                              &rcol0, &rcol1, &rrow0, &rrow1)) {
1291         const int rstride = cm->rst_info[plane].horz_units_per_tile;
1292         for (int rrow = rrow0; rrow < rrow1; ++rrow) {
1293           for (int rcol = rcol0; rcol < rcol1; ++rcol) {
1294             const int runit_idx = rcol + rrow * rstride;
1295             loop_restoration_read_sb_coeffs(cm, xd, reader, plane, runit_idx);
1296           }
1297         }
1298       }
1299 #endif
1300     }
1301 
1302     partition = (bsize < BLOCK_8X8) ? PARTITION_NONE
1303                                     : read_partition(xd, mi_row, mi_col, reader,
1304                                                      has_rows, has_cols, bsize);
1305   } else {
1306     partition = get_partition(cm, mi_row, mi_col, bsize);
1307   }
1308   subsize = get_partition_subsize(bsize, partition);
1309   if (subsize == BLOCK_INVALID) {
1310     aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
1311                        "Partition is invalid for block size %dx%d",
1312                        block_size_wide[bsize], block_size_high[bsize]);
1313   }
1314   // Check the bitstream is conformant: if there is subsampling on the
1315   // chroma planes, subsize must subsample to a valid block size.
1316   const struct macroblockd_plane *const pd_u = &xd->plane[1];
1317   if (get_plane_block_size(subsize, pd_u->subsampling_x, pd_u->subsampling_y) ==
1318       BLOCK_INVALID) {
1319     aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
1320                        "Block size %dx%d invalid with this subsampling mode",
1321                        block_size_wide[subsize], block_size_high[subsize]);
1322   }
1323 
1324 #define DEC_BLOCK_STX_ARG
1325 #define DEC_BLOCK_EPT_ARG partition,
1326 #define DEC_BLOCK(db_r, db_c, db_subsize)                                  \
1327   block_visit[parse_decode_flag](pbi, td, DEC_BLOCK_STX_ARG(db_r), (db_c), \
1328                                  reader, DEC_BLOCK_EPT_ARG(db_subsize))
1329 #define DEC_PARTITION(db_r, db_c, db_subsize)                        \
1330   decode_partition(pbi, td, DEC_BLOCK_STX_ARG(db_r), (db_c), reader, \
1331                    (db_subsize), parse_decode_flag)
1332 
1333   switch (partition) {
1334     case PARTITION_NONE: DEC_BLOCK(mi_row, mi_col, subsize); break;
1335     case PARTITION_HORZ:
1336       DEC_BLOCK(mi_row, mi_col, subsize);
1337       if (has_rows) DEC_BLOCK(mi_row + hbs, mi_col, subsize);
1338       break;
1339     case PARTITION_VERT:
1340       DEC_BLOCK(mi_row, mi_col, subsize);
1341       if (has_cols) DEC_BLOCK(mi_row, mi_col + hbs, subsize);
1342       break;
1343     case PARTITION_SPLIT:
1344       DEC_PARTITION(mi_row, mi_col, subsize);
1345       DEC_PARTITION(mi_row, mi_col + hbs, subsize);
1346       DEC_PARTITION(mi_row + hbs, mi_col, subsize);
1347       DEC_PARTITION(mi_row + hbs, mi_col + hbs, subsize);
1348       break;
1349     case PARTITION_HORZ_A:
1350       DEC_BLOCK(mi_row, mi_col, bsize2);
1351       DEC_BLOCK(mi_row, mi_col + hbs, bsize2);
1352       DEC_BLOCK(mi_row + hbs, mi_col, subsize);
1353       break;
1354     case PARTITION_HORZ_B:
1355       DEC_BLOCK(mi_row, mi_col, subsize);
1356       DEC_BLOCK(mi_row + hbs, mi_col, bsize2);
1357       DEC_BLOCK(mi_row + hbs, mi_col + hbs, bsize2);
1358       break;
1359     case PARTITION_VERT_A:
1360       DEC_BLOCK(mi_row, mi_col, bsize2);
1361       DEC_BLOCK(mi_row + hbs, mi_col, bsize2);
1362       DEC_BLOCK(mi_row, mi_col + hbs, subsize);
1363       break;
1364     case PARTITION_VERT_B:
1365       DEC_BLOCK(mi_row, mi_col, subsize);
1366       DEC_BLOCK(mi_row, mi_col + hbs, bsize2);
1367       DEC_BLOCK(mi_row + hbs, mi_col + hbs, bsize2);
1368       break;
1369     case PARTITION_HORZ_4:
1370       for (int i = 0; i < 4; ++i) {
1371         int this_mi_row = mi_row + i * quarter_step;
1372         if (i > 0 && this_mi_row >= cm->mi_params.mi_rows) break;
1373         DEC_BLOCK(this_mi_row, mi_col, subsize);
1374       }
1375       break;
1376     case PARTITION_VERT_4:
1377       for (int i = 0; i < 4; ++i) {
1378         int this_mi_col = mi_col + i * quarter_step;
1379         if (i > 0 && this_mi_col >= cm->mi_params.mi_cols) break;
1380         DEC_BLOCK(mi_row, this_mi_col, subsize);
1381       }
1382       break;
1383     default: assert(0 && "Invalid partition type");
1384   }
1385 
1386 #undef DEC_PARTITION
1387 #undef DEC_BLOCK
1388 #undef DEC_BLOCK_EPT_ARG
1389 #undef DEC_BLOCK_STX_ARG
1390 
1391   if (parse_decode_flag & 1)
1392     update_ext_partition_context(xd, mi_row, mi_col, subsize, bsize, partition);
1393 }
1394 
setup_bool_decoder(const uint8_t * data,const uint8_t * data_end,const size_t read_size,struct aom_internal_error_info * error_info,aom_reader * r,uint8_t allow_update_cdf)1395 static AOM_INLINE void setup_bool_decoder(
1396     const uint8_t *data, const uint8_t *data_end, const size_t read_size,
1397     struct aom_internal_error_info *error_info, aom_reader *r,
1398     uint8_t allow_update_cdf) {
1399   // Validate the calculated partition length. If the buffer
1400   // described by the partition can't be fully read, then restrict
1401   // it to the portion that can be (for EC mode) or throw an error.
1402   if (!read_is_valid(data, read_size, data_end))
1403     aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
1404                        "Truncated packet or corrupt tile length");
1405 
1406   if (aom_reader_init(r, data, read_size))
1407     aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
1408                        "Failed to allocate bool decoder %d", 1);
1409 
1410   r->allow_update_cdf = allow_update_cdf;
1411 }
1412 
setup_segmentation(AV1_COMMON * const cm,struct aom_read_bit_buffer * rb)1413 static AOM_INLINE void setup_segmentation(AV1_COMMON *const cm,
1414                                           struct aom_read_bit_buffer *rb) {
1415   struct segmentation *const seg = &cm->seg;
1416 
1417   seg->update_map = 0;
1418   seg->update_data = 0;
1419   seg->temporal_update = 0;
1420 
1421   seg->enabled = aom_rb_read_bit(rb);
1422   if (!seg->enabled) {
1423     if (cm->cur_frame->seg_map) {
1424       memset(cm->cur_frame->seg_map, 0,
1425              (cm->cur_frame->mi_rows * cm->cur_frame->mi_cols));
1426     }
1427 
1428     memset(seg, 0, sizeof(*seg));
1429     segfeatures_copy(&cm->cur_frame->seg, seg);
1430     return;
1431   }
1432   if (cm->seg.enabled && cm->prev_frame &&
1433       (cm->mi_params.mi_rows == cm->prev_frame->mi_rows) &&
1434       (cm->mi_params.mi_cols == cm->prev_frame->mi_cols)) {
1435     cm->last_frame_seg_map = cm->prev_frame->seg_map;
1436   } else {
1437     cm->last_frame_seg_map = NULL;
1438   }
1439   // Read update flags
1440   if (cm->features.primary_ref_frame == PRIMARY_REF_NONE) {
1441     // These frames can't use previous frames, so must signal map + features
1442     seg->update_map = 1;
1443     seg->temporal_update = 0;
1444     seg->update_data = 1;
1445   } else {
1446     seg->update_map = aom_rb_read_bit(rb);
1447     if (seg->update_map) {
1448       seg->temporal_update = aom_rb_read_bit(rb);
1449     } else {
1450       seg->temporal_update = 0;
1451     }
1452     seg->update_data = aom_rb_read_bit(rb);
1453   }
1454 
1455   // Segmentation data update
1456   if (seg->update_data) {
1457     av1_clearall_segfeatures(seg);
1458 
1459     for (int i = 0; i < MAX_SEGMENTS; i++) {
1460       for (int j = 0; j < SEG_LVL_MAX; j++) {
1461         int data = 0;
1462         const int feature_enabled = aom_rb_read_bit(rb);
1463         if (feature_enabled) {
1464           av1_enable_segfeature(seg, i, j);
1465 
1466           const int data_max = av1_seg_feature_data_max(j);
1467           const int data_min = -data_max;
1468           const int ubits = get_unsigned_bits(data_max);
1469 
1470           if (av1_is_segfeature_signed(j)) {
1471             data = aom_rb_read_inv_signed_literal(rb, ubits);
1472           } else {
1473             data = aom_rb_read_literal(rb, ubits);
1474           }
1475 
1476           data = clamp(data, data_min, data_max);
1477         }
1478         av1_set_segdata(seg, i, j, data);
1479       }
1480     }
1481     av1_calculate_segdata(seg);
1482   } else if (cm->prev_frame) {
1483     segfeatures_copy(seg, &cm->prev_frame->seg);
1484   }
1485   segfeatures_copy(&cm->cur_frame->seg, seg);
1486 }
1487 
decode_restoration_mode(AV1_COMMON * cm,struct aom_read_bit_buffer * rb)1488 static AOM_INLINE void decode_restoration_mode(AV1_COMMON *cm,
1489                                                struct aom_read_bit_buffer *rb) {
1490   assert(!cm->features.all_lossless);
1491   const int num_planes = av1_num_planes(cm);
1492   if (cm->features.allow_intrabc) return;
1493   int all_none = 1, chroma_none = 1;
1494   for (int p = 0; p < num_planes; ++p) {
1495     RestorationInfo *rsi = &cm->rst_info[p];
1496     if (aom_rb_read_bit(rb)) {
1497       rsi->frame_restoration_type =
1498           aom_rb_read_bit(rb) ? RESTORE_SGRPROJ : RESTORE_WIENER;
1499     } else {
1500       rsi->frame_restoration_type =
1501           aom_rb_read_bit(rb) ? RESTORE_SWITCHABLE : RESTORE_NONE;
1502     }
1503     if (rsi->frame_restoration_type != RESTORE_NONE) {
1504       all_none = 0;
1505       chroma_none &= p == 0;
1506     }
1507   }
1508   if (!all_none) {
1509 #if CONFIG_REALTIME_ONLY
1510     aom_internal_error(cm->error, AOM_CODEC_UNSUP_FEATURE,
1511                        "Realtime only build doesn't support loop restoration");
1512 #endif
1513     assert(cm->seq_params->sb_size == BLOCK_64X64 ||
1514            cm->seq_params->sb_size == BLOCK_128X128);
1515     const int sb_size = cm->seq_params->sb_size == BLOCK_128X128 ? 128 : 64;
1516 
1517     for (int p = 0; p < num_planes; ++p)
1518       cm->rst_info[p].restoration_unit_size = sb_size;
1519 
1520     RestorationInfo *rsi = &cm->rst_info[0];
1521 
1522     if (sb_size == 64) {
1523       rsi->restoration_unit_size <<= aom_rb_read_bit(rb);
1524     }
1525     if (rsi->restoration_unit_size > 64) {
1526       rsi->restoration_unit_size <<= aom_rb_read_bit(rb);
1527     }
1528   } else {
1529     const int size = RESTORATION_UNITSIZE_MAX;
1530     for (int p = 0; p < num_planes; ++p)
1531       cm->rst_info[p].restoration_unit_size = size;
1532   }
1533 
1534   if (num_planes > 1) {
1535     int s =
1536         AOMMIN(cm->seq_params->subsampling_x, cm->seq_params->subsampling_y);
1537     if (s && !chroma_none) {
1538       cm->rst_info[1].restoration_unit_size =
1539           cm->rst_info[0].restoration_unit_size >> (aom_rb_read_bit(rb) * s);
1540     } else {
1541       cm->rst_info[1].restoration_unit_size =
1542           cm->rst_info[0].restoration_unit_size;
1543     }
1544     cm->rst_info[2].restoration_unit_size =
1545         cm->rst_info[1].restoration_unit_size;
1546   }
1547 }
1548 
1549 #if !CONFIG_REALTIME_ONLY
read_wiener_filter(int wiener_win,WienerInfo * wiener_info,WienerInfo * ref_wiener_info,aom_reader * rb)1550 static AOM_INLINE void read_wiener_filter(int wiener_win,
1551                                           WienerInfo *wiener_info,
1552                                           WienerInfo *ref_wiener_info,
1553                                           aom_reader *rb) {
1554   memset(wiener_info->vfilter, 0, sizeof(wiener_info->vfilter));
1555   memset(wiener_info->hfilter, 0, sizeof(wiener_info->hfilter));
1556 
1557   if (wiener_win == WIENER_WIN)
1558     wiener_info->vfilter[0] = wiener_info->vfilter[WIENER_WIN - 1] =
1559         aom_read_primitive_refsubexpfin(
1560             rb, WIENER_FILT_TAP0_MAXV - WIENER_FILT_TAP0_MINV + 1,
1561             WIENER_FILT_TAP0_SUBEXP_K,
1562             ref_wiener_info->vfilter[0] - WIENER_FILT_TAP0_MINV, ACCT_STR) +
1563         WIENER_FILT_TAP0_MINV;
1564   else
1565     wiener_info->vfilter[0] = wiener_info->vfilter[WIENER_WIN - 1] = 0;
1566   wiener_info->vfilter[1] = wiener_info->vfilter[WIENER_WIN - 2] =
1567       aom_read_primitive_refsubexpfin(
1568           rb, WIENER_FILT_TAP1_MAXV - WIENER_FILT_TAP1_MINV + 1,
1569           WIENER_FILT_TAP1_SUBEXP_K,
1570           ref_wiener_info->vfilter[1] - WIENER_FILT_TAP1_MINV, ACCT_STR) +
1571       WIENER_FILT_TAP1_MINV;
1572   wiener_info->vfilter[2] = wiener_info->vfilter[WIENER_WIN - 3] =
1573       aom_read_primitive_refsubexpfin(
1574           rb, WIENER_FILT_TAP2_MAXV - WIENER_FILT_TAP2_MINV + 1,
1575           WIENER_FILT_TAP2_SUBEXP_K,
1576           ref_wiener_info->vfilter[2] - WIENER_FILT_TAP2_MINV, ACCT_STR) +
1577       WIENER_FILT_TAP2_MINV;
1578   // The central element has an implicit +WIENER_FILT_STEP
1579   wiener_info->vfilter[WIENER_HALFWIN] =
1580       -2 * (wiener_info->vfilter[0] + wiener_info->vfilter[1] +
1581             wiener_info->vfilter[2]);
1582 
1583   if (wiener_win == WIENER_WIN)
1584     wiener_info->hfilter[0] = wiener_info->hfilter[WIENER_WIN - 1] =
1585         aom_read_primitive_refsubexpfin(
1586             rb, WIENER_FILT_TAP0_MAXV - WIENER_FILT_TAP0_MINV + 1,
1587             WIENER_FILT_TAP0_SUBEXP_K,
1588             ref_wiener_info->hfilter[0] - WIENER_FILT_TAP0_MINV, ACCT_STR) +
1589         WIENER_FILT_TAP0_MINV;
1590   else
1591     wiener_info->hfilter[0] = wiener_info->hfilter[WIENER_WIN - 1] = 0;
1592   wiener_info->hfilter[1] = wiener_info->hfilter[WIENER_WIN - 2] =
1593       aom_read_primitive_refsubexpfin(
1594           rb, WIENER_FILT_TAP1_MAXV - WIENER_FILT_TAP1_MINV + 1,
1595           WIENER_FILT_TAP1_SUBEXP_K,
1596           ref_wiener_info->hfilter[1] - WIENER_FILT_TAP1_MINV, ACCT_STR) +
1597       WIENER_FILT_TAP1_MINV;
1598   wiener_info->hfilter[2] = wiener_info->hfilter[WIENER_WIN - 3] =
1599       aom_read_primitive_refsubexpfin(
1600           rb, WIENER_FILT_TAP2_MAXV - WIENER_FILT_TAP2_MINV + 1,
1601           WIENER_FILT_TAP2_SUBEXP_K,
1602           ref_wiener_info->hfilter[2] - WIENER_FILT_TAP2_MINV, ACCT_STR) +
1603       WIENER_FILT_TAP2_MINV;
1604   // The central element has an implicit +WIENER_FILT_STEP
1605   wiener_info->hfilter[WIENER_HALFWIN] =
1606       -2 * (wiener_info->hfilter[0] + wiener_info->hfilter[1] +
1607             wiener_info->hfilter[2]);
1608   memcpy(ref_wiener_info, wiener_info, sizeof(*wiener_info));
1609 }
1610 
read_sgrproj_filter(SgrprojInfo * sgrproj_info,SgrprojInfo * ref_sgrproj_info,aom_reader * rb)1611 static AOM_INLINE void read_sgrproj_filter(SgrprojInfo *sgrproj_info,
1612                                            SgrprojInfo *ref_sgrproj_info,
1613                                            aom_reader *rb) {
1614   sgrproj_info->ep = aom_read_literal(rb, SGRPROJ_PARAMS_BITS, ACCT_STR);
1615   const sgr_params_type *params = &av1_sgr_params[sgrproj_info->ep];
1616 
1617   if (params->r[0] == 0) {
1618     sgrproj_info->xqd[0] = 0;
1619     sgrproj_info->xqd[1] =
1620         aom_read_primitive_refsubexpfin(
1621             rb, SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1, SGRPROJ_PRJ_SUBEXP_K,
1622             ref_sgrproj_info->xqd[1] - SGRPROJ_PRJ_MIN1, ACCT_STR) +
1623         SGRPROJ_PRJ_MIN1;
1624   } else if (params->r[1] == 0) {
1625     sgrproj_info->xqd[0] =
1626         aom_read_primitive_refsubexpfin(
1627             rb, SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1, SGRPROJ_PRJ_SUBEXP_K,
1628             ref_sgrproj_info->xqd[0] - SGRPROJ_PRJ_MIN0, ACCT_STR) +
1629         SGRPROJ_PRJ_MIN0;
1630     sgrproj_info->xqd[1] = clamp((1 << SGRPROJ_PRJ_BITS) - sgrproj_info->xqd[0],
1631                                  SGRPROJ_PRJ_MIN1, SGRPROJ_PRJ_MAX1);
1632   } else {
1633     sgrproj_info->xqd[0] =
1634         aom_read_primitive_refsubexpfin(
1635             rb, SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1, SGRPROJ_PRJ_SUBEXP_K,
1636             ref_sgrproj_info->xqd[0] - SGRPROJ_PRJ_MIN0, ACCT_STR) +
1637         SGRPROJ_PRJ_MIN0;
1638     sgrproj_info->xqd[1] =
1639         aom_read_primitive_refsubexpfin(
1640             rb, SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1, SGRPROJ_PRJ_SUBEXP_K,
1641             ref_sgrproj_info->xqd[1] - SGRPROJ_PRJ_MIN1, ACCT_STR) +
1642         SGRPROJ_PRJ_MIN1;
1643   }
1644 
1645   memcpy(ref_sgrproj_info, sgrproj_info, sizeof(*sgrproj_info));
1646 }
1647 
loop_restoration_read_sb_coeffs(const AV1_COMMON * const cm,MACROBLOCKD * xd,aom_reader * const r,int plane,int runit_idx)1648 static AOM_INLINE void loop_restoration_read_sb_coeffs(
1649     const AV1_COMMON *const cm, MACROBLOCKD *xd, aom_reader *const r, int plane,
1650     int runit_idx) {
1651   const RestorationInfo *rsi = &cm->rst_info[plane];
1652   RestorationUnitInfo *rui = &rsi->unit_info[runit_idx];
1653   assert(rsi->frame_restoration_type != RESTORE_NONE);
1654 
1655   assert(!cm->features.all_lossless);
1656 
1657   const int wiener_win = (plane > 0) ? WIENER_WIN_CHROMA : WIENER_WIN;
1658   WienerInfo *wiener_info = xd->wiener_info + plane;
1659   SgrprojInfo *sgrproj_info = xd->sgrproj_info + plane;
1660 
1661   if (rsi->frame_restoration_type == RESTORE_SWITCHABLE) {
1662     rui->restoration_type =
1663         aom_read_symbol(r, xd->tile_ctx->switchable_restore_cdf,
1664                         RESTORE_SWITCHABLE_TYPES, ACCT_STR);
1665     switch (rui->restoration_type) {
1666       case RESTORE_WIENER:
1667         read_wiener_filter(wiener_win, &rui->wiener_info, wiener_info, r);
1668         break;
1669       case RESTORE_SGRPROJ:
1670         read_sgrproj_filter(&rui->sgrproj_info, sgrproj_info, r);
1671         break;
1672       default: assert(rui->restoration_type == RESTORE_NONE); break;
1673     }
1674   } else if (rsi->frame_restoration_type == RESTORE_WIENER) {
1675     if (aom_read_symbol(r, xd->tile_ctx->wiener_restore_cdf, 2, ACCT_STR)) {
1676       rui->restoration_type = RESTORE_WIENER;
1677       read_wiener_filter(wiener_win, &rui->wiener_info, wiener_info, r);
1678     } else {
1679       rui->restoration_type = RESTORE_NONE;
1680     }
1681   } else if (rsi->frame_restoration_type == RESTORE_SGRPROJ) {
1682     if (aom_read_symbol(r, xd->tile_ctx->sgrproj_restore_cdf, 2, ACCT_STR)) {
1683       rui->restoration_type = RESTORE_SGRPROJ;
1684       read_sgrproj_filter(&rui->sgrproj_info, sgrproj_info, r);
1685     } else {
1686       rui->restoration_type = RESTORE_NONE;
1687     }
1688   }
1689 }
1690 #endif  // !CONFIG_REALTIME_ONLY
1691 
setup_loopfilter(AV1_COMMON * cm,struct aom_read_bit_buffer * rb)1692 static AOM_INLINE void setup_loopfilter(AV1_COMMON *cm,
1693                                         struct aom_read_bit_buffer *rb) {
1694   const int num_planes = av1_num_planes(cm);
1695   struct loopfilter *lf = &cm->lf;
1696 
1697   if (cm->features.allow_intrabc || cm->features.coded_lossless) {
1698     // write default deltas to frame buffer
1699     av1_set_default_ref_deltas(cm->cur_frame->ref_deltas);
1700     av1_set_default_mode_deltas(cm->cur_frame->mode_deltas);
1701     return;
1702   }
1703   assert(!cm->features.coded_lossless);
1704   if (cm->prev_frame) {
1705     // write deltas to frame buffer
1706     memcpy(lf->ref_deltas, cm->prev_frame->ref_deltas, REF_FRAMES);
1707     memcpy(lf->mode_deltas, cm->prev_frame->mode_deltas, MAX_MODE_LF_DELTAS);
1708   } else {
1709     av1_set_default_ref_deltas(lf->ref_deltas);
1710     av1_set_default_mode_deltas(lf->mode_deltas);
1711   }
1712   lf->filter_level[0] = aom_rb_read_literal(rb, 6);
1713   lf->filter_level[1] = aom_rb_read_literal(rb, 6);
1714   if (num_planes > 1) {
1715     if (lf->filter_level[0] || lf->filter_level[1]) {
1716       lf->filter_level_u = aom_rb_read_literal(rb, 6);
1717       lf->filter_level_v = aom_rb_read_literal(rb, 6);
1718     }
1719   }
1720   lf->sharpness_level = aom_rb_read_literal(rb, 3);
1721 
1722   // Read in loop filter deltas applied at the MB level based on mode or ref
1723   // frame.
1724   lf->mode_ref_delta_update = 0;
1725 
1726   lf->mode_ref_delta_enabled = aom_rb_read_bit(rb);
1727   if (lf->mode_ref_delta_enabled) {
1728     lf->mode_ref_delta_update = aom_rb_read_bit(rb);
1729     if (lf->mode_ref_delta_update) {
1730       for (int i = 0; i < REF_FRAMES; i++)
1731         if (aom_rb_read_bit(rb))
1732           lf->ref_deltas[i] = aom_rb_read_inv_signed_literal(rb, 6);
1733 
1734       for (int i = 0; i < MAX_MODE_LF_DELTAS; i++)
1735         if (aom_rb_read_bit(rb))
1736           lf->mode_deltas[i] = aom_rb_read_inv_signed_literal(rb, 6);
1737     }
1738   }
1739 
1740   // write deltas to frame buffer
1741   memcpy(cm->cur_frame->ref_deltas, lf->ref_deltas, REF_FRAMES);
1742   memcpy(cm->cur_frame->mode_deltas, lf->mode_deltas, MAX_MODE_LF_DELTAS);
1743 }
1744 
setup_cdef(AV1_COMMON * cm,struct aom_read_bit_buffer * rb)1745 static AOM_INLINE void setup_cdef(AV1_COMMON *cm,
1746                                   struct aom_read_bit_buffer *rb) {
1747   const int num_planes = av1_num_planes(cm);
1748   CdefInfo *const cdef_info = &cm->cdef_info;
1749 
1750   if (cm->features.allow_intrabc) return;
1751   cdef_info->cdef_damping = aom_rb_read_literal(rb, 2) + 3;
1752   cdef_info->cdef_bits = aom_rb_read_literal(rb, 2);
1753   cdef_info->nb_cdef_strengths = 1 << cdef_info->cdef_bits;
1754   for (int i = 0; i < cdef_info->nb_cdef_strengths; i++) {
1755     cdef_info->cdef_strengths[i] = aom_rb_read_literal(rb, CDEF_STRENGTH_BITS);
1756     cdef_info->cdef_uv_strengths[i] =
1757         num_planes > 1 ? aom_rb_read_literal(rb, CDEF_STRENGTH_BITS) : 0;
1758   }
1759 }
1760 
read_delta_q(struct aom_read_bit_buffer * rb)1761 static INLINE int read_delta_q(struct aom_read_bit_buffer *rb) {
1762   return aom_rb_read_bit(rb) ? aom_rb_read_inv_signed_literal(rb, 6) : 0;
1763 }
1764 
setup_quantization(CommonQuantParams * quant_params,int num_planes,bool separate_uv_delta_q,struct aom_read_bit_buffer * rb)1765 static AOM_INLINE void setup_quantization(CommonQuantParams *quant_params,
1766                                           int num_planes,
1767                                           bool separate_uv_delta_q,
1768                                           struct aom_read_bit_buffer *rb) {
1769   quant_params->base_qindex = aom_rb_read_literal(rb, QINDEX_BITS);
1770   quant_params->y_dc_delta_q = read_delta_q(rb);
1771   if (num_planes > 1) {
1772     int diff_uv_delta = 0;
1773     if (separate_uv_delta_q) diff_uv_delta = aom_rb_read_bit(rb);
1774     quant_params->u_dc_delta_q = read_delta_q(rb);
1775     quant_params->u_ac_delta_q = read_delta_q(rb);
1776     if (diff_uv_delta) {
1777       quant_params->v_dc_delta_q = read_delta_q(rb);
1778       quant_params->v_ac_delta_q = read_delta_q(rb);
1779     } else {
1780       quant_params->v_dc_delta_q = quant_params->u_dc_delta_q;
1781       quant_params->v_ac_delta_q = quant_params->u_ac_delta_q;
1782     }
1783   } else {
1784     quant_params->u_dc_delta_q = 0;
1785     quant_params->u_ac_delta_q = 0;
1786     quant_params->v_dc_delta_q = 0;
1787     quant_params->v_ac_delta_q = 0;
1788   }
1789   quant_params->using_qmatrix = aom_rb_read_bit(rb);
1790   if (quant_params->using_qmatrix) {
1791     quant_params->qmatrix_level_y = aom_rb_read_literal(rb, QM_LEVEL_BITS);
1792     quant_params->qmatrix_level_u = aom_rb_read_literal(rb, QM_LEVEL_BITS);
1793     if (!separate_uv_delta_q)
1794       quant_params->qmatrix_level_v = quant_params->qmatrix_level_u;
1795     else
1796       quant_params->qmatrix_level_v = aom_rb_read_literal(rb, QM_LEVEL_BITS);
1797   } else {
1798     quant_params->qmatrix_level_y = 0;
1799     quant_params->qmatrix_level_u = 0;
1800     quant_params->qmatrix_level_v = 0;
1801   }
1802 }
1803 
1804 // Build y/uv dequant values based on segmentation.
setup_segmentation_dequant(AV1_COMMON * const cm,MACROBLOCKD * const xd)1805 static AOM_INLINE void setup_segmentation_dequant(AV1_COMMON *const cm,
1806                                                   MACROBLOCKD *const xd) {
1807   const int bit_depth = cm->seq_params->bit_depth;
1808   // When segmentation is disabled, only the first value is used.  The
1809   // remaining are don't cares.
1810   const int max_segments = cm->seg.enabled ? MAX_SEGMENTS : 1;
1811   CommonQuantParams *const quant_params = &cm->quant_params;
1812   for (int i = 0; i < max_segments; ++i) {
1813     const int qindex = xd->qindex[i];
1814     quant_params->y_dequant_QTX[i][0] =
1815         av1_dc_quant_QTX(qindex, quant_params->y_dc_delta_q, bit_depth);
1816     quant_params->y_dequant_QTX[i][1] = av1_ac_quant_QTX(qindex, 0, bit_depth);
1817     quant_params->u_dequant_QTX[i][0] =
1818         av1_dc_quant_QTX(qindex, quant_params->u_dc_delta_q, bit_depth);
1819     quant_params->u_dequant_QTX[i][1] =
1820         av1_ac_quant_QTX(qindex, quant_params->u_ac_delta_q, bit_depth);
1821     quant_params->v_dequant_QTX[i][0] =
1822         av1_dc_quant_QTX(qindex, quant_params->v_dc_delta_q, bit_depth);
1823     quant_params->v_dequant_QTX[i][1] =
1824         av1_ac_quant_QTX(qindex, quant_params->v_ac_delta_q, bit_depth);
1825     const int use_qmatrix = av1_use_qmatrix(quant_params, xd, i);
1826     // NB: depends on base index so there is only 1 set per frame
1827     // No quant weighting when lossless or signalled not using QM
1828     const int qmlevel_y =
1829         use_qmatrix ? quant_params->qmatrix_level_y : NUM_QM_LEVELS - 1;
1830     for (int j = 0; j < TX_SIZES_ALL; ++j) {
1831       quant_params->y_iqmatrix[i][j] =
1832           av1_iqmatrix(quant_params, qmlevel_y, AOM_PLANE_Y, j);
1833     }
1834     const int qmlevel_u =
1835         use_qmatrix ? quant_params->qmatrix_level_u : NUM_QM_LEVELS - 1;
1836     for (int j = 0; j < TX_SIZES_ALL; ++j) {
1837       quant_params->u_iqmatrix[i][j] =
1838           av1_iqmatrix(quant_params, qmlevel_u, AOM_PLANE_U, j);
1839     }
1840     const int qmlevel_v =
1841         use_qmatrix ? quant_params->qmatrix_level_v : NUM_QM_LEVELS - 1;
1842     for (int j = 0; j < TX_SIZES_ALL; ++j) {
1843       quant_params->v_iqmatrix[i][j] =
1844           av1_iqmatrix(quant_params, qmlevel_v, AOM_PLANE_V, j);
1845     }
1846   }
1847 }
1848 
read_frame_interp_filter(struct aom_read_bit_buffer * rb)1849 static InterpFilter read_frame_interp_filter(struct aom_read_bit_buffer *rb) {
1850   return aom_rb_read_bit(rb) ? SWITCHABLE
1851                              : aom_rb_read_literal(rb, LOG_SWITCHABLE_FILTERS);
1852 }
1853 
setup_render_size(AV1_COMMON * cm,struct aom_read_bit_buffer * rb)1854 static AOM_INLINE void setup_render_size(AV1_COMMON *cm,
1855                                          struct aom_read_bit_buffer *rb) {
1856   cm->render_width = cm->superres_upscaled_width;
1857   cm->render_height = cm->superres_upscaled_height;
1858   if (aom_rb_read_bit(rb))
1859     av1_read_frame_size(rb, 16, 16, &cm->render_width, &cm->render_height);
1860 }
1861 
1862 // TODO(afergs): make "struct aom_read_bit_buffer *const rb"?
setup_superres(AV1_COMMON * const cm,struct aom_read_bit_buffer * rb,int * width,int * height)1863 static AOM_INLINE void setup_superres(AV1_COMMON *const cm,
1864                                       struct aom_read_bit_buffer *rb,
1865                                       int *width, int *height) {
1866   cm->superres_upscaled_width = *width;
1867   cm->superres_upscaled_height = *height;
1868 
1869   const SequenceHeader *const seq_params = cm->seq_params;
1870   if (!seq_params->enable_superres) return;
1871 
1872   if (aom_rb_read_bit(rb)) {
1873     cm->superres_scale_denominator =
1874         (uint8_t)aom_rb_read_literal(rb, SUPERRES_SCALE_BITS);
1875     cm->superres_scale_denominator += SUPERRES_SCALE_DENOMINATOR_MIN;
1876     // Don't edit cm->width or cm->height directly, or the buffers won't get
1877     // resized correctly
1878     av1_calculate_scaled_superres_size(width, height,
1879                                        cm->superres_scale_denominator);
1880   } else {
1881     // 1:1 scaling - ie. no scaling, scale not provided
1882     cm->superres_scale_denominator = SCALE_NUMERATOR;
1883   }
1884 }
1885 
resize_context_buffers(AV1_COMMON * cm,int width,int height)1886 static AOM_INLINE void resize_context_buffers(AV1_COMMON *cm, int width,
1887                                               int height) {
1888 #if CONFIG_SIZE_LIMIT
1889   if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
1890     aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
1891                        "Dimensions of %dx%d beyond allowed size of %dx%d.",
1892                        width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
1893 #endif
1894   if (cm->width != width || cm->height != height) {
1895     const int new_mi_rows =
1896         ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1897     const int new_mi_cols =
1898         ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
1899 
1900     // Allocations in av1_alloc_context_buffers() depend on individual
1901     // dimensions as well as the overall size.
1902     if (new_mi_cols > cm->mi_params.mi_cols ||
1903         new_mi_rows > cm->mi_params.mi_rows) {
1904       if (av1_alloc_context_buffers(cm, width, height)) {
1905         // The cm->mi_* values have been cleared and any existing context
1906         // buffers have been freed. Clear cm->width and cm->height to be
1907         // consistent and to force a realloc next time.
1908         cm->width = 0;
1909         cm->height = 0;
1910         aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
1911                            "Failed to allocate context buffers");
1912       }
1913     } else {
1914       cm->mi_params.set_mb_mi(&cm->mi_params, width, height);
1915     }
1916     av1_init_mi_buffers(&cm->mi_params);
1917     cm->width = width;
1918     cm->height = height;
1919   }
1920 
1921   ensure_mv_buffer(cm->cur_frame, cm);
1922   cm->cur_frame->width = cm->width;
1923   cm->cur_frame->height = cm->height;
1924 }
1925 
setup_buffer_pool(AV1_COMMON * cm)1926 static AOM_INLINE void setup_buffer_pool(AV1_COMMON *cm) {
1927   BufferPool *const pool = cm->buffer_pool;
1928   const SequenceHeader *const seq_params = cm->seq_params;
1929 
1930   lock_buffer_pool(pool);
1931   if (aom_realloc_frame_buffer(
1932           &cm->cur_frame->buf, cm->width, cm->height, seq_params->subsampling_x,
1933           seq_params->subsampling_y, seq_params->use_highbitdepth,
1934           AOM_DEC_BORDER_IN_PIXELS, cm->features.byte_alignment,
1935           &cm->cur_frame->raw_frame_buffer, pool->get_fb_cb, pool->cb_priv,
1936           0)) {
1937     unlock_buffer_pool(pool);
1938     aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
1939                        "Failed to allocate frame buffer");
1940   }
1941   unlock_buffer_pool(pool);
1942 
1943   cm->cur_frame->buf.bit_depth = (unsigned int)seq_params->bit_depth;
1944   cm->cur_frame->buf.color_primaries = seq_params->color_primaries;
1945   cm->cur_frame->buf.transfer_characteristics =
1946       seq_params->transfer_characteristics;
1947   cm->cur_frame->buf.matrix_coefficients = seq_params->matrix_coefficients;
1948   cm->cur_frame->buf.monochrome = seq_params->monochrome;
1949   cm->cur_frame->buf.chroma_sample_position =
1950       seq_params->chroma_sample_position;
1951   cm->cur_frame->buf.color_range = seq_params->color_range;
1952   cm->cur_frame->buf.render_width = cm->render_width;
1953   cm->cur_frame->buf.render_height = cm->render_height;
1954 }
1955 
setup_frame_size(AV1_COMMON * cm,int frame_size_override_flag,struct aom_read_bit_buffer * rb)1956 static AOM_INLINE void setup_frame_size(AV1_COMMON *cm,
1957                                         int frame_size_override_flag,
1958                                         struct aom_read_bit_buffer *rb) {
1959   const SequenceHeader *const seq_params = cm->seq_params;
1960   int width, height;
1961 
1962   if (frame_size_override_flag) {
1963     int num_bits_width = seq_params->num_bits_width;
1964     int num_bits_height = seq_params->num_bits_height;
1965     av1_read_frame_size(rb, num_bits_width, num_bits_height, &width, &height);
1966     if (width > seq_params->max_frame_width ||
1967         height > seq_params->max_frame_height) {
1968       aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
1969                          "Frame dimensions are larger than the maximum values");
1970     }
1971   } else {
1972     width = seq_params->max_frame_width;
1973     height = seq_params->max_frame_height;
1974   }
1975 
1976   setup_superres(cm, rb, &width, &height);
1977   resize_context_buffers(cm, width, height);
1978   setup_render_size(cm, rb);
1979   setup_buffer_pool(cm);
1980 }
1981 
setup_sb_size(SequenceHeader * seq_params,struct aom_read_bit_buffer * rb)1982 static AOM_INLINE void setup_sb_size(SequenceHeader *seq_params,
1983                                      struct aom_read_bit_buffer *rb) {
1984   set_sb_size(seq_params, aom_rb_read_bit(rb) ? BLOCK_128X128 : BLOCK_64X64);
1985 }
1986 
valid_ref_frame_img_fmt(aom_bit_depth_t ref_bit_depth,int ref_xss,int ref_yss,aom_bit_depth_t this_bit_depth,int this_xss,int this_yss)1987 static INLINE int valid_ref_frame_img_fmt(aom_bit_depth_t ref_bit_depth,
1988                                           int ref_xss, int ref_yss,
1989                                           aom_bit_depth_t this_bit_depth,
1990                                           int this_xss, int this_yss) {
1991   return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
1992          ref_yss == this_yss;
1993 }
1994 
setup_frame_size_with_refs(AV1_COMMON * cm,struct aom_read_bit_buffer * rb)1995 static AOM_INLINE void setup_frame_size_with_refs(
1996     AV1_COMMON *cm, struct aom_read_bit_buffer *rb) {
1997   int width, height;
1998   int found = 0;
1999   int has_valid_ref_frame = 0;
2000   for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2001     if (aom_rb_read_bit(rb)) {
2002       const RefCntBuffer *const ref_buf = get_ref_frame_buf(cm, i);
2003       // This will never be NULL in a normal stream, as streams are required to
2004       // have a shown keyframe before any inter frames, which would refresh all
2005       // the reference buffers. However, it might be null if we're starting in
2006       // the middle of a stream, and static analysis will error if we don't do
2007       // a null check here.
2008       if (ref_buf == NULL) {
2009         aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
2010                            "Invalid condition: invalid reference buffer");
2011       } else {
2012         const YV12_BUFFER_CONFIG *const buf = &ref_buf->buf;
2013         width = buf->y_crop_width;
2014         height = buf->y_crop_height;
2015         cm->render_width = buf->render_width;
2016         cm->render_height = buf->render_height;
2017         setup_superres(cm, rb, &width, &height);
2018         resize_context_buffers(cm, width, height);
2019         found = 1;
2020         break;
2021       }
2022     }
2023   }
2024 
2025   const SequenceHeader *const seq_params = cm->seq_params;
2026   if (!found) {
2027     int num_bits_width = seq_params->num_bits_width;
2028     int num_bits_height = seq_params->num_bits_height;
2029 
2030     av1_read_frame_size(rb, num_bits_width, num_bits_height, &width, &height);
2031     setup_superres(cm, rb, &width, &height);
2032     resize_context_buffers(cm, width, height);
2033     setup_render_size(cm, rb);
2034   }
2035 
2036   if (width <= 0 || height <= 0)
2037     aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
2038                        "Invalid frame size");
2039 
2040   // Check to make sure at least one of frames that this frame references
2041   // has valid dimensions.
2042   for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2043     const RefCntBuffer *const ref_frame = get_ref_frame_buf(cm, i);
2044     has_valid_ref_frame |=
2045         valid_ref_frame_size(ref_frame->buf.y_crop_width,
2046                              ref_frame->buf.y_crop_height, width, height);
2047   }
2048   if (!has_valid_ref_frame)
2049     aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
2050                        "Referenced frame has invalid size");
2051   for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2052     const RefCntBuffer *const ref_frame = get_ref_frame_buf(cm, i);
2053     if (!valid_ref_frame_img_fmt(
2054             ref_frame->buf.bit_depth, ref_frame->buf.subsampling_x,
2055             ref_frame->buf.subsampling_y, seq_params->bit_depth,
2056             seq_params->subsampling_x, seq_params->subsampling_y))
2057       aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
2058                          "Referenced frame has incompatible color format");
2059   }
2060   setup_buffer_pool(cm);
2061 }
2062 
2063 // Same function as av1_read_uniform but reading from uncompresses header wb
rb_read_uniform(struct aom_read_bit_buffer * const rb,int n)2064 static int rb_read_uniform(struct aom_read_bit_buffer *const rb, int n) {
2065   const int l = get_unsigned_bits(n);
2066   const int m = (1 << l) - n;
2067   const int v = aom_rb_read_literal(rb, l - 1);
2068   assert(l != 0);
2069   if (v < m)
2070     return v;
2071   else
2072     return (v << 1) - m + aom_rb_read_bit(rb);
2073 }
2074 
read_tile_info_max_tile(AV1_COMMON * const cm,struct aom_read_bit_buffer * const rb)2075 static AOM_INLINE void read_tile_info_max_tile(
2076     AV1_COMMON *const cm, struct aom_read_bit_buffer *const rb) {
2077   const SequenceHeader *const seq_params = cm->seq_params;
2078   CommonTileParams *const tiles = &cm->tiles;
2079   int width_mi =
2080       ALIGN_POWER_OF_TWO(cm->mi_params.mi_cols, seq_params->mib_size_log2);
2081   int height_mi =
2082       ALIGN_POWER_OF_TWO(cm->mi_params.mi_rows, seq_params->mib_size_log2);
2083   int width_sb = width_mi >> seq_params->mib_size_log2;
2084   int height_sb = height_mi >> seq_params->mib_size_log2;
2085 
2086   av1_get_tile_limits(cm);
2087   tiles->uniform_spacing = aom_rb_read_bit(rb);
2088 
2089   // Read tile columns
2090   if (tiles->uniform_spacing) {
2091     tiles->log2_cols = tiles->min_log2_cols;
2092     while (tiles->log2_cols < tiles->max_log2_cols) {
2093       if (!aom_rb_read_bit(rb)) {
2094         break;
2095       }
2096       tiles->log2_cols++;
2097     }
2098   } else {
2099     int i;
2100     int start_sb;
2101     for (i = 0, start_sb = 0; width_sb > 0 && i < MAX_TILE_COLS; i++) {
2102       const int size_sb =
2103           1 + rb_read_uniform(rb, AOMMIN(width_sb, tiles->max_width_sb));
2104       tiles->col_start_sb[i] = start_sb;
2105       start_sb += size_sb;
2106       width_sb -= size_sb;
2107     }
2108     tiles->cols = i;
2109     tiles->col_start_sb[i] = start_sb + width_sb;
2110   }
2111   av1_calculate_tile_cols(seq_params, cm->mi_params.mi_rows,
2112                           cm->mi_params.mi_cols, tiles);
2113 
2114   // Read tile rows
2115   if (tiles->uniform_spacing) {
2116     tiles->log2_rows = tiles->min_log2_rows;
2117     while (tiles->log2_rows < tiles->max_log2_rows) {
2118       if (!aom_rb_read_bit(rb)) {
2119         break;
2120       }
2121       tiles->log2_rows++;
2122     }
2123   } else {
2124     int i;
2125     int start_sb;
2126     for (i = 0, start_sb = 0; height_sb > 0 && i < MAX_TILE_ROWS; i++) {
2127       const int size_sb =
2128           1 + rb_read_uniform(rb, AOMMIN(height_sb, tiles->max_height_sb));
2129       tiles->row_start_sb[i] = start_sb;
2130       start_sb += size_sb;
2131       height_sb -= size_sb;
2132     }
2133     tiles->rows = i;
2134     tiles->row_start_sb[i] = start_sb + height_sb;
2135   }
2136   av1_calculate_tile_rows(seq_params, cm->mi_params.mi_rows, tiles);
2137 }
2138 
av1_set_single_tile_decoding_mode(AV1_COMMON * const cm)2139 void av1_set_single_tile_decoding_mode(AV1_COMMON *const cm) {
2140   cm->tiles.single_tile_decoding = 0;
2141   if (cm->tiles.large_scale) {
2142     struct loopfilter *lf = &cm->lf;
2143     RestorationInfo *const rst_info = cm->rst_info;
2144     const CdefInfo *const cdef_info = &cm->cdef_info;
2145 
2146     // Figure out single_tile_decoding by loopfilter_level.
2147     const int no_loopfilter = !(lf->filter_level[0] || lf->filter_level[1]);
2148     const int no_cdef = cdef_info->cdef_bits == 0 &&
2149                         cdef_info->cdef_strengths[0] == 0 &&
2150                         cdef_info->cdef_uv_strengths[0] == 0;
2151     const int no_restoration =
2152         rst_info[0].frame_restoration_type == RESTORE_NONE &&
2153         rst_info[1].frame_restoration_type == RESTORE_NONE &&
2154         rst_info[2].frame_restoration_type == RESTORE_NONE;
2155     assert(IMPLIES(cm->features.coded_lossless, no_loopfilter && no_cdef));
2156     assert(IMPLIES(cm->features.all_lossless, no_restoration));
2157     cm->tiles.single_tile_decoding = no_loopfilter && no_cdef && no_restoration;
2158   }
2159 }
2160 
read_tile_info(AV1Decoder * const pbi,struct aom_read_bit_buffer * const rb)2161 static AOM_INLINE void read_tile_info(AV1Decoder *const pbi,
2162                                       struct aom_read_bit_buffer *const rb) {
2163   AV1_COMMON *const cm = &pbi->common;
2164 
2165   read_tile_info_max_tile(cm, rb);
2166 
2167   pbi->context_update_tile_id = 0;
2168   if (cm->tiles.rows * cm->tiles.cols > 1) {
2169     // tile to use for cdf update
2170     pbi->context_update_tile_id =
2171         aom_rb_read_literal(rb, cm->tiles.log2_rows + cm->tiles.log2_cols);
2172     if (pbi->context_update_tile_id >= cm->tiles.rows * cm->tiles.cols) {
2173       aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
2174                          "Invalid context_update_tile_id");
2175     }
2176     // tile size magnitude
2177     pbi->tile_size_bytes = aom_rb_read_literal(rb, 2) + 1;
2178   }
2179 }
2180 
2181 #if EXT_TILE_DEBUG
read_ext_tile_info(AV1Decoder * const pbi,struct aom_read_bit_buffer * const rb)2182 static AOM_INLINE void read_ext_tile_info(
2183     AV1Decoder *const pbi, struct aom_read_bit_buffer *const rb) {
2184   AV1_COMMON *const cm = &pbi->common;
2185 
2186   // This information is stored as a separate byte.
2187   int mod = rb->bit_offset % CHAR_BIT;
2188   if (mod > 0) aom_rb_read_literal(rb, CHAR_BIT - mod);
2189   assert(rb->bit_offset % CHAR_BIT == 0);
2190 
2191   if (cm->tiles.cols * cm->tiles.rows > 1) {
2192     // Read the number of bytes used to store tile size
2193     pbi->tile_col_size_bytes = aom_rb_read_literal(rb, 2) + 1;
2194     pbi->tile_size_bytes = aom_rb_read_literal(rb, 2) + 1;
2195   }
2196 }
2197 #endif  // EXT_TILE_DEBUG
2198 
mem_get_varsize(const uint8_t * src,int sz)2199 static size_t mem_get_varsize(const uint8_t *src, int sz) {
2200   switch (sz) {
2201     case 1: return src[0];
2202     case 2: return mem_get_le16(src);
2203     case 3: return mem_get_le24(src);
2204     case 4: return mem_get_le32(src);
2205     default: assert(0 && "Invalid size"); return -1;
2206   }
2207 }
2208 
2209 #if EXT_TILE_DEBUG
2210 // Reads the next tile returning its size and adjusting '*data' accordingly
2211 // based on 'is_last'. On return, '*data' is updated to point to the end of the
2212 // raw tile buffer in the bit stream.
get_ls_tile_buffer(const uint8_t * const data_end,struct aom_internal_error_info * error_info,const uint8_t ** data,TileBufferDec (* const tile_buffers)[MAX_TILE_COLS],int tile_size_bytes,int col,int row,int tile_copy_mode)2213 static AOM_INLINE void get_ls_tile_buffer(
2214     const uint8_t *const data_end, struct aom_internal_error_info *error_info,
2215     const uint8_t **data, TileBufferDec (*const tile_buffers)[MAX_TILE_COLS],
2216     int tile_size_bytes, int col, int row, int tile_copy_mode) {
2217   size_t size;
2218 
2219   size_t copy_size = 0;
2220   const uint8_t *copy_data = NULL;
2221 
2222   if (!read_is_valid(*data, tile_size_bytes, data_end))
2223     aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
2224                        "Truncated packet or corrupt tile length");
2225   size = mem_get_varsize(*data, tile_size_bytes);
2226 
2227   // If tile_copy_mode = 1, then the top bit of the tile header indicates copy
2228   // mode.
2229   if (tile_copy_mode && (size >> (tile_size_bytes * 8 - 1)) == 1) {
2230     // The remaining bits in the top byte signal the row offset
2231     int offset = (size >> (tile_size_bytes - 1) * 8) & 0x7f;
2232 
2233     // Currently, only use tiles in same column as reference tiles.
2234     copy_data = tile_buffers[row - offset][col].data;
2235     copy_size = tile_buffers[row - offset][col].size;
2236     size = 0;
2237   } else {
2238     size += AV1_MIN_TILE_SIZE_BYTES;
2239   }
2240 
2241   *data += tile_size_bytes;
2242 
2243   if (size > (size_t)(data_end - *data))
2244     aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
2245                        "Truncated packet or corrupt tile size");
2246 
2247   if (size > 0) {
2248     tile_buffers[row][col].data = *data;
2249     tile_buffers[row][col].size = size;
2250   } else {
2251     tile_buffers[row][col].data = copy_data;
2252     tile_buffers[row][col].size = copy_size;
2253   }
2254 
2255   *data += size;
2256 }
2257 
2258 // Returns the end of the last tile buffer
2259 // (tile_buffers[cm->tiles.rows - 1][cm->tiles.cols - 1]).
get_ls_tile_buffers(AV1Decoder * pbi,const uint8_t * data,const uint8_t * data_end,TileBufferDec (* const tile_buffers)[MAX_TILE_COLS])2260 static const uint8_t *get_ls_tile_buffers(
2261     AV1Decoder *pbi, const uint8_t *data, const uint8_t *data_end,
2262     TileBufferDec (*const tile_buffers)[MAX_TILE_COLS]) {
2263   AV1_COMMON *const cm = &pbi->common;
2264   const int tile_cols = cm->tiles.cols;
2265   const int tile_rows = cm->tiles.rows;
2266   const int have_tiles = tile_cols * tile_rows > 1;
2267   const uint8_t *raw_data_end;  // The end of the last tile buffer
2268 
2269   if (!have_tiles) {
2270     const size_t tile_size = data_end - data;
2271     tile_buffers[0][0].data = data;
2272     tile_buffers[0][0].size = tile_size;
2273     raw_data_end = NULL;
2274   } else {
2275     // We locate only the tile buffers that are required, which are the ones
2276     // specified by pbi->dec_tile_col and pbi->dec_tile_row. Also, we always
2277     // need the last (bottom right) tile buffer, as we need to know where the
2278     // end of the compressed frame buffer is for proper superframe decoding.
2279 
2280     const uint8_t *tile_col_data_end[MAX_TILE_COLS] = { NULL };
2281     const uint8_t *const data_start = data;
2282 
2283     const int dec_tile_row = AOMMIN(pbi->dec_tile_row, tile_rows);
2284     const int single_row = pbi->dec_tile_row >= 0;
2285     const int tile_rows_start = single_row ? dec_tile_row : 0;
2286     const int tile_rows_end = single_row ? tile_rows_start + 1 : tile_rows;
2287     const int dec_tile_col = AOMMIN(pbi->dec_tile_col, tile_cols);
2288     const int single_col = pbi->dec_tile_col >= 0;
2289     const int tile_cols_start = single_col ? dec_tile_col : 0;
2290     const int tile_cols_end = single_col ? tile_cols_start + 1 : tile_cols;
2291 
2292     const int tile_col_size_bytes = pbi->tile_col_size_bytes;
2293     const int tile_size_bytes = pbi->tile_size_bytes;
2294     int tile_width, tile_height;
2295     av1_get_uniform_tile_size(cm, &tile_width, &tile_height);
2296     const int tile_copy_mode =
2297         ((AOMMAX(tile_width, tile_height) << MI_SIZE_LOG2) <= 256) ? 1 : 0;
2298     // Read tile column sizes for all columns (we need the last tile buffer)
2299     for (int c = 0; c < tile_cols; ++c) {
2300       const int is_last = c == tile_cols - 1;
2301       size_t tile_col_size;
2302 
2303       if (!is_last) {
2304         tile_col_size = mem_get_varsize(data, tile_col_size_bytes);
2305         data += tile_col_size_bytes;
2306         tile_col_data_end[c] = data + tile_col_size;
2307       } else {
2308         tile_col_size = data_end - data;
2309         tile_col_data_end[c] = data_end;
2310       }
2311       data += tile_col_size;
2312     }
2313 
2314     data = data_start;
2315 
2316     // Read the required tile sizes.
2317     for (int c = tile_cols_start; c < tile_cols_end; ++c) {
2318       const int is_last = c == tile_cols - 1;
2319 
2320       if (c > 0) data = tile_col_data_end[c - 1];
2321 
2322       if (!is_last) data += tile_col_size_bytes;
2323 
2324       // Get the whole of the last column, otherwise stop at the required tile.
2325       for (int r = 0; r < (is_last ? tile_rows : tile_rows_end); ++r) {
2326         get_ls_tile_buffer(tile_col_data_end[c], &pbi->error, &data,
2327                            tile_buffers, tile_size_bytes, c, r, tile_copy_mode);
2328       }
2329     }
2330 
2331     // If we have not read the last column, then read it to get the last tile.
2332     if (tile_cols_end != tile_cols) {
2333       const int c = tile_cols - 1;
2334 
2335       data = tile_col_data_end[c - 1];
2336 
2337       for (int r = 0; r < tile_rows; ++r) {
2338         get_ls_tile_buffer(tile_col_data_end[c], &pbi->error, &data,
2339                            tile_buffers, tile_size_bytes, c, r, tile_copy_mode);
2340       }
2341     }
2342     raw_data_end = data;
2343   }
2344   return raw_data_end;
2345 }
2346 #endif  // EXT_TILE_DEBUG
2347 
get_ls_single_tile_buffer(AV1Decoder * pbi,const uint8_t * data,TileBufferDec (* const tile_buffers)[MAX_TILE_COLS])2348 static const uint8_t *get_ls_single_tile_buffer(
2349     AV1Decoder *pbi, const uint8_t *data,
2350     TileBufferDec (*const tile_buffers)[MAX_TILE_COLS]) {
2351   assert(pbi->dec_tile_row >= 0 && pbi->dec_tile_col >= 0);
2352   tile_buffers[pbi->dec_tile_row][pbi->dec_tile_col].data = data;
2353   tile_buffers[pbi->dec_tile_row][pbi->dec_tile_col].size =
2354       (size_t)pbi->coded_tile_data_size;
2355   return data + pbi->coded_tile_data_size;
2356 }
2357 
2358 // Reads the next tile returning its size and adjusting '*data' accordingly
2359 // based on 'is_last'.
get_tile_buffer(const uint8_t * const data_end,const int tile_size_bytes,int is_last,struct aom_internal_error_info * error_info,const uint8_t ** data,TileBufferDec * const buf)2360 static AOM_INLINE void get_tile_buffer(
2361     const uint8_t *const data_end, const int tile_size_bytes, int is_last,
2362     struct aom_internal_error_info *error_info, const uint8_t **data,
2363     TileBufferDec *const buf) {
2364   size_t size;
2365 
2366   if (!is_last) {
2367     if (!read_is_valid(*data, tile_size_bytes, data_end))
2368       aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
2369                          "Not enough data to read tile size");
2370 
2371     size = mem_get_varsize(*data, tile_size_bytes) + AV1_MIN_TILE_SIZE_BYTES;
2372     *data += tile_size_bytes;
2373 
2374     if (size > (size_t)(data_end - *data))
2375       aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
2376                          "Truncated packet or corrupt tile size");
2377   } else {
2378     size = data_end - *data;
2379   }
2380 
2381   buf->data = *data;
2382   buf->size = size;
2383 
2384   *data += size;
2385 }
2386 
get_tile_buffers(AV1Decoder * pbi,const uint8_t * data,const uint8_t * data_end,TileBufferDec (* const tile_buffers)[MAX_TILE_COLS],int start_tile,int end_tile)2387 static AOM_INLINE void get_tile_buffers(
2388     AV1Decoder *pbi, const uint8_t *data, const uint8_t *data_end,
2389     TileBufferDec (*const tile_buffers)[MAX_TILE_COLS], int start_tile,
2390     int end_tile) {
2391   AV1_COMMON *const cm = &pbi->common;
2392   const int tile_cols = cm->tiles.cols;
2393   const int tile_rows = cm->tiles.rows;
2394   int tc = 0;
2395 
2396   for (int r = 0; r < tile_rows; ++r) {
2397     for (int c = 0; c < tile_cols; ++c, ++tc) {
2398       TileBufferDec *const buf = &tile_buffers[r][c];
2399 
2400       const int is_last = (tc == end_tile);
2401       const size_t hdr_offset = 0;
2402 
2403       if (tc < start_tile || tc > end_tile) continue;
2404 
2405       if (data + hdr_offset >= data_end)
2406         aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
2407                            "Data ended before all tiles were read.");
2408       data += hdr_offset;
2409       get_tile_buffer(data_end, pbi->tile_size_bytes, is_last, &pbi->error,
2410                       &data, buf);
2411     }
2412   }
2413 }
2414 
set_cb_buffer(AV1Decoder * pbi,DecoderCodingBlock * dcb,CB_BUFFER * cb_buffer_base,const int num_planes,int mi_row,int mi_col)2415 static AOM_INLINE void set_cb_buffer(AV1Decoder *pbi, DecoderCodingBlock *dcb,
2416                                      CB_BUFFER *cb_buffer_base,
2417                                      const int num_planes, int mi_row,
2418                                      int mi_col) {
2419   AV1_COMMON *const cm = &pbi->common;
2420   int mib_size_log2 = cm->seq_params->mib_size_log2;
2421   int stride = (cm->mi_params.mi_cols >> mib_size_log2) + 1;
2422   int offset = (mi_row >> mib_size_log2) * stride + (mi_col >> mib_size_log2);
2423   CB_BUFFER *cb_buffer = cb_buffer_base + offset;
2424 
2425   for (int plane = 0; plane < num_planes; ++plane) {
2426     dcb->dqcoeff_block[plane] = cb_buffer->dqcoeff[plane];
2427     dcb->eob_data[plane] = cb_buffer->eob_data[plane];
2428     dcb->cb_offset[plane] = 0;
2429     dcb->txb_offset[plane] = 0;
2430   }
2431   MACROBLOCKD *const xd = &dcb->xd;
2432   xd->plane[0].color_index_map = cb_buffer->color_index_map[0];
2433   xd->plane[1].color_index_map = cb_buffer->color_index_map[1];
2434   xd->color_index_map_offset[0] = 0;
2435   xd->color_index_map_offset[1] = 0;
2436 }
2437 
decoder_alloc_tile_data(AV1Decoder * pbi,const int n_tiles)2438 static AOM_INLINE void decoder_alloc_tile_data(AV1Decoder *pbi,
2439                                                const int n_tiles) {
2440   AV1_COMMON *const cm = &pbi->common;
2441   aom_free(pbi->tile_data);
2442   CHECK_MEM_ERROR(cm, pbi->tile_data,
2443                   aom_memalign(32, n_tiles * sizeof(*pbi->tile_data)));
2444   pbi->allocated_tiles = n_tiles;
2445   for (int i = 0; i < n_tiles; i++) {
2446     TileDataDec *const tile_data = pbi->tile_data + i;
2447     av1_zero(tile_data->dec_row_mt_sync);
2448   }
2449   pbi->allocated_row_mt_sync_rows = 0;
2450 }
2451 
2452 // Set up nsync by width.
get_sync_range(int width)2453 static INLINE int get_sync_range(int width) {
2454 // nsync numbers are picked by testing.
2455 #if 0
2456   if (width < 640)
2457     return 1;
2458   else if (width <= 1280)
2459     return 2;
2460   else if (width <= 4096)
2461     return 4;
2462   else
2463     return 8;
2464 #else
2465   (void)width;
2466 #endif
2467   return 1;
2468 }
2469 
2470 // Allocate memory for decoder row synchronization
dec_row_mt_alloc(AV1DecRowMTSync * dec_row_mt_sync,AV1_COMMON * cm,int rows)2471 static AOM_INLINE void dec_row_mt_alloc(AV1DecRowMTSync *dec_row_mt_sync,
2472                                         AV1_COMMON *cm, int rows) {
2473   dec_row_mt_sync->allocated_sb_rows = rows;
2474 #if CONFIG_MULTITHREAD
2475   {
2476     int i;
2477 
2478     CHECK_MEM_ERROR(cm, dec_row_mt_sync->mutex_,
2479                     aom_malloc(sizeof(*(dec_row_mt_sync->mutex_)) * rows));
2480     if (dec_row_mt_sync->mutex_) {
2481       for (i = 0; i < rows; ++i) {
2482         pthread_mutex_init(&dec_row_mt_sync->mutex_[i], NULL);
2483       }
2484     }
2485 
2486     CHECK_MEM_ERROR(cm, dec_row_mt_sync->cond_,
2487                     aom_malloc(sizeof(*(dec_row_mt_sync->cond_)) * rows));
2488     if (dec_row_mt_sync->cond_) {
2489       for (i = 0; i < rows; ++i) {
2490         pthread_cond_init(&dec_row_mt_sync->cond_[i], NULL);
2491       }
2492     }
2493   }
2494 #endif  // CONFIG_MULTITHREAD
2495 
2496   CHECK_MEM_ERROR(cm, dec_row_mt_sync->cur_sb_col,
2497                   aom_malloc(sizeof(*(dec_row_mt_sync->cur_sb_col)) * rows));
2498 
2499   // Set up nsync.
2500   dec_row_mt_sync->sync_range = get_sync_range(cm->width);
2501 }
2502 
2503 // Deallocate decoder row synchronization related mutex and data
av1_dec_row_mt_dealloc(AV1DecRowMTSync * dec_row_mt_sync)2504 void av1_dec_row_mt_dealloc(AV1DecRowMTSync *dec_row_mt_sync) {
2505   if (dec_row_mt_sync != NULL) {
2506 #if CONFIG_MULTITHREAD
2507     int i;
2508     if (dec_row_mt_sync->mutex_ != NULL) {
2509       for (i = 0; i < dec_row_mt_sync->allocated_sb_rows; ++i) {
2510         pthread_mutex_destroy(&dec_row_mt_sync->mutex_[i]);
2511       }
2512       aom_free(dec_row_mt_sync->mutex_);
2513     }
2514     if (dec_row_mt_sync->cond_ != NULL) {
2515       for (i = 0; i < dec_row_mt_sync->allocated_sb_rows; ++i) {
2516         pthread_cond_destroy(&dec_row_mt_sync->cond_[i]);
2517       }
2518       aom_free(dec_row_mt_sync->cond_);
2519     }
2520 #endif  // CONFIG_MULTITHREAD
2521     aom_free(dec_row_mt_sync->cur_sb_col);
2522 
2523     // clear the structure as the source of this call may be a resize in which
2524     // case this call will be followed by an _alloc() which may fail.
2525     av1_zero(*dec_row_mt_sync);
2526   }
2527 }
2528 
sync_read(AV1DecRowMTSync * const dec_row_mt_sync,int r,int c)2529 static INLINE void sync_read(AV1DecRowMTSync *const dec_row_mt_sync, int r,
2530                              int c) {
2531 #if CONFIG_MULTITHREAD
2532   const int nsync = dec_row_mt_sync->sync_range;
2533 
2534   if (r && !(c & (nsync - 1))) {
2535     pthread_mutex_t *const mutex = &dec_row_mt_sync->mutex_[r - 1];
2536     pthread_mutex_lock(mutex);
2537 
2538     while (c > dec_row_mt_sync->cur_sb_col[r - 1] - nsync) {
2539       pthread_cond_wait(&dec_row_mt_sync->cond_[r - 1], mutex);
2540     }
2541     pthread_mutex_unlock(mutex);
2542   }
2543 #else
2544   (void)dec_row_mt_sync;
2545   (void)r;
2546   (void)c;
2547 #endif  // CONFIG_MULTITHREAD
2548 }
2549 
sync_write(AV1DecRowMTSync * const dec_row_mt_sync,int r,int c,const int sb_cols)2550 static INLINE void sync_write(AV1DecRowMTSync *const dec_row_mt_sync, int r,
2551                               int c, const int sb_cols) {
2552 #if CONFIG_MULTITHREAD
2553   const int nsync = dec_row_mt_sync->sync_range;
2554   int cur;
2555   int sig = 1;
2556 
2557   if (c < sb_cols - 1) {
2558     cur = c;
2559     if (c % nsync) sig = 0;
2560   } else {
2561     cur = sb_cols + nsync;
2562   }
2563 
2564   if (sig) {
2565     pthread_mutex_lock(&dec_row_mt_sync->mutex_[r]);
2566 
2567     dec_row_mt_sync->cur_sb_col[r] = cur;
2568 
2569     pthread_cond_signal(&dec_row_mt_sync->cond_[r]);
2570     pthread_mutex_unlock(&dec_row_mt_sync->mutex_[r]);
2571   }
2572 #else
2573   (void)dec_row_mt_sync;
2574   (void)r;
2575   (void)c;
2576   (void)sb_cols;
2577 #endif  // CONFIG_MULTITHREAD
2578 }
2579 
decode_tile_sb_row(AV1Decoder * pbi,ThreadData * const td,TileInfo tile_info,const int mi_row)2580 static AOM_INLINE void decode_tile_sb_row(AV1Decoder *pbi, ThreadData *const td,
2581                                           TileInfo tile_info,
2582                                           const int mi_row) {
2583   AV1_COMMON *const cm = &pbi->common;
2584   const int num_planes = av1_num_planes(cm);
2585   TileDataDec *const tile_data =
2586       pbi->tile_data + tile_info.tile_row * cm->tiles.cols + tile_info.tile_col;
2587   const int sb_cols_in_tile = av1_get_sb_cols_in_tile(cm, tile_info);
2588   const int sb_row_in_tile =
2589       (mi_row - tile_info.mi_row_start) >> cm->seq_params->mib_size_log2;
2590   int sb_col_in_tile = 0;
2591 
2592   for (int mi_col = tile_info.mi_col_start; mi_col < tile_info.mi_col_end;
2593        mi_col += cm->seq_params->mib_size, sb_col_in_tile++) {
2594     set_cb_buffer(pbi, &td->dcb, pbi->cb_buffer_base, num_planes, mi_row,
2595                   mi_col);
2596 
2597     sync_read(&tile_data->dec_row_mt_sync, sb_row_in_tile, sb_col_in_tile);
2598 
2599     // Decoding of the super-block
2600     decode_partition(pbi, td, mi_row, mi_col, td->bit_reader,
2601                      cm->seq_params->sb_size, 0x2);
2602 
2603     sync_write(&tile_data->dec_row_mt_sync, sb_row_in_tile, sb_col_in_tile,
2604                sb_cols_in_tile);
2605   }
2606 }
2607 
check_trailing_bits_after_symbol_coder(aom_reader * r)2608 static int check_trailing_bits_after_symbol_coder(aom_reader *r) {
2609   if (aom_reader_has_overflowed(r)) return -1;
2610 
2611   uint32_t nb_bits = aom_reader_tell(r);
2612   uint32_t nb_bytes = (nb_bits + 7) >> 3;
2613   const uint8_t *p = aom_reader_find_begin(r) + nb_bytes;
2614 
2615   // aom_reader_tell() returns 1 for a newly initialized decoder, and the
2616   // return value only increases as values are decoded. So nb_bits > 0, and
2617   // thus p > p_begin. Therefore accessing p[-1] is safe.
2618   uint8_t last_byte = p[-1];
2619   uint8_t pattern = 128 >> ((nb_bits - 1) & 7);
2620   if ((last_byte & (2 * pattern - 1)) != pattern) return -1;
2621 
2622   // Make sure that all padding bytes are zero as required by the spec.
2623   const uint8_t *p_end = aom_reader_find_end(r);
2624   while (p < p_end) {
2625     if (*p != 0) return -1;
2626     p++;
2627   }
2628   return 0;
2629 }
2630 
set_decode_func_pointers(ThreadData * td,int parse_decode_flag)2631 static AOM_INLINE void set_decode_func_pointers(ThreadData *td,
2632                                                 int parse_decode_flag) {
2633   td->read_coeffs_tx_intra_block_visit = decode_block_void;
2634   td->predict_and_recon_intra_block_visit = decode_block_void;
2635   td->read_coeffs_tx_inter_block_visit = decode_block_void;
2636   td->inverse_tx_inter_block_visit = decode_block_void;
2637   td->predict_inter_block_visit = predict_inter_block_void;
2638   td->cfl_store_inter_block_visit = cfl_store_inter_block_void;
2639 
2640   if (parse_decode_flag & 0x1) {
2641     td->read_coeffs_tx_intra_block_visit = read_coeffs_tx_intra_block;
2642     td->read_coeffs_tx_inter_block_visit = av1_read_coeffs_txb_facade;
2643   }
2644   if (parse_decode_flag & 0x2) {
2645     td->predict_and_recon_intra_block_visit =
2646         predict_and_reconstruct_intra_block;
2647     td->inverse_tx_inter_block_visit = inverse_transform_inter_block;
2648     td->predict_inter_block_visit = predict_inter_block;
2649     td->cfl_store_inter_block_visit = cfl_store_inter_block;
2650   }
2651 }
2652 
decode_tile(AV1Decoder * pbi,ThreadData * const td,int tile_row,int tile_col)2653 static AOM_INLINE void decode_tile(AV1Decoder *pbi, ThreadData *const td,
2654                                    int tile_row, int tile_col) {
2655   TileInfo tile_info;
2656 
2657   AV1_COMMON *const cm = &pbi->common;
2658   const int num_planes = av1_num_planes(cm);
2659 
2660   av1_tile_set_row(&tile_info, cm, tile_row);
2661   av1_tile_set_col(&tile_info, cm, tile_col);
2662   DecoderCodingBlock *const dcb = &td->dcb;
2663   MACROBLOCKD *const xd = &dcb->xd;
2664 
2665   av1_zero_above_context(cm, xd, tile_info.mi_col_start, tile_info.mi_col_end,
2666                          tile_row);
2667   av1_reset_loop_filter_delta(xd, num_planes);
2668   av1_reset_loop_restoration(xd, num_planes);
2669 
2670   for (int mi_row = tile_info.mi_row_start; mi_row < tile_info.mi_row_end;
2671        mi_row += cm->seq_params->mib_size) {
2672     av1_zero_left_context(xd);
2673 
2674     for (int mi_col = tile_info.mi_col_start; mi_col < tile_info.mi_col_end;
2675          mi_col += cm->seq_params->mib_size) {
2676       set_cb_buffer(pbi, dcb, &td->cb_buffer_base, num_planes, 0, 0);
2677 
2678       // Bit-stream parsing and decoding of the superblock
2679       decode_partition(pbi, td, mi_row, mi_col, td->bit_reader,
2680                        cm->seq_params->sb_size, 0x3);
2681 
2682       if (aom_reader_has_overflowed(td->bit_reader)) {
2683         aom_merge_corrupted_flag(&dcb->corrupted, 1);
2684         return;
2685       }
2686     }
2687   }
2688 
2689   int corrupted =
2690       (check_trailing_bits_after_symbol_coder(td->bit_reader)) ? 1 : 0;
2691   aom_merge_corrupted_flag(&dcb->corrupted, corrupted);
2692 }
2693 
decode_tiles(AV1Decoder * pbi,const uint8_t * data,const uint8_t * data_end,int start_tile,int end_tile)2694 static const uint8_t *decode_tiles(AV1Decoder *pbi, const uint8_t *data,
2695                                    const uint8_t *data_end, int start_tile,
2696                                    int end_tile) {
2697   AV1_COMMON *const cm = &pbi->common;
2698   ThreadData *const td = &pbi->td;
2699   CommonTileParams *const tiles = &cm->tiles;
2700   const int tile_cols = tiles->cols;
2701   const int tile_rows = tiles->rows;
2702   const int n_tiles = tile_cols * tile_rows;
2703   TileBufferDec(*const tile_buffers)[MAX_TILE_COLS] = pbi->tile_buffers;
2704   const int dec_tile_row = AOMMIN(pbi->dec_tile_row, tile_rows);
2705   const int single_row = pbi->dec_tile_row >= 0;
2706   const int dec_tile_col = AOMMIN(pbi->dec_tile_col, tile_cols);
2707   const int single_col = pbi->dec_tile_col >= 0;
2708   int tile_rows_start;
2709   int tile_rows_end;
2710   int tile_cols_start;
2711   int tile_cols_end;
2712   int inv_col_order;
2713   int inv_row_order;
2714   int tile_row, tile_col;
2715   uint8_t allow_update_cdf;
2716   const uint8_t *raw_data_end = NULL;
2717 
2718   if (tiles->large_scale) {
2719     tile_rows_start = single_row ? dec_tile_row : 0;
2720     tile_rows_end = single_row ? dec_tile_row + 1 : tile_rows;
2721     tile_cols_start = single_col ? dec_tile_col : 0;
2722     tile_cols_end = single_col ? tile_cols_start + 1 : tile_cols;
2723     inv_col_order = pbi->inv_tile_order && !single_col;
2724     inv_row_order = pbi->inv_tile_order && !single_row;
2725     allow_update_cdf = 0;
2726   } else {
2727     tile_rows_start = 0;
2728     tile_rows_end = tile_rows;
2729     tile_cols_start = 0;
2730     tile_cols_end = tile_cols;
2731     inv_col_order = pbi->inv_tile_order;
2732     inv_row_order = pbi->inv_tile_order;
2733     allow_update_cdf = 1;
2734   }
2735 
2736   // No tiles to decode.
2737   if (tile_rows_end <= tile_rows_start || tile_cols_end <= tile_cols_start ||
2738       // First tile is larger than end_tile.
2739       tile_rows_start * tiles->cols + tile_cols_start > end_tile ||
2740       // Last tile is smaller than start_tile.
2741       (tile_rows_end - 1) * tiles->cols + tile_cols_end - 1 < start_tile)
2742     return data;
2743 
2744   allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update;
2745 
2746   assert(tile_rows <= MAX_TILE_ROWS);
2747   assert(tile_cols <= MAX_TILE_COLS);
2748 
2749 #if EXT_TILE_DEBUG
2750   if (tiles->large_scale && !pbi->ext_tile_debug)
2751     raw_data_end = get_ls_single_tile_buffer(pbi, data, tile_buffers);
2752   else if (tiles->large_scale && pbi->ext_tile_debug)
2753     raw_data_end = get_ls_tile_buffers(pbi, data, data_end, tile_buffers);
2754   else
2755 #endif  // EXT_TILE_DEBUG
2756     get_tile_buffers(pbi, data, data_end, tile_buffers, start_tile, end_tile);
2757 
2758   if (pbi->tile_data == NULL || n_tiles != pbi->allocated_tiles) {
2759     decoder_alloc_tile_data(pbi, n_tiles);
2760   }
2761   if (pbi->dcb.xd.seg_mask == NULL)
2762     CHECK_MEM_ERROR(cm, pbi->dcb.xd.seg_mask,
2763                     (uint8_t *)aom_memalign(
2764                         16, 2 * MAX_SB_SQUARE * sizeof(*pbi->dcb.xd.seg_mask)));
2765 #if CONFIG_ACCOUNTING
2766   if (pbi->acct_enabled) {
2767     aom_accounting_reset(&pbi->accounting);
2768   }
2769 #endif
2770 
2771   set_decode_func_pointers(&pbi->td, 0x3);
2772 
2773   // Load all tile information into thread_data.
2774   td->dcb = pbi->dcb;
2775 
2776   td->dcb.corrupted = 0;
2777   td->dcb.mc_buf[0] = td->mc_buf[0];
2778   td->dcb.mc_buf[1] = td->mc_buf[1];
2779   td->dcb.xd.tmp_conv_dst = td->tmp_conv_dst;
2780   for (int j = 0; j < 2; ++j) {
2781     td->dcb.xd.tmp_obmc_bufs[j] = td->tmp_obmc_bufs[j];
2782   }
2783 
2784   for (tile_row = tile_rows_start; tile_row < tile_rows_end; ++tile_row) {
2785     const int row = inv_row_order ? tile_rows - 1 - tile_row : tile_row;
2786 
2787     for (tile_col = tile_cols_start; tile_col < tile_cols_end; ++tile_col) {
2788       const int col = inv_col_order ? tile_cols - 1 - tile_col : tile_col;
2789       TileDataDec *const tile_data = pbi->tile_data + row * tiles->cols + col;
2790       const TileBufferDec *const tile_bs_buf = &tile_buffers[row][col];
2791 
2792       if (row * tiles->cols + col < start_tile ||
2793           row * tiles->cols + col > end_tile)
2794         continue;
2795 
2796       td->bit_reader = &tile_data->bit_reader;
2797       av1_zero(td->cb_buffer_base.dqcoeff);
2798       av1_tile_init(&td->dcb.xd.tile, cm, row, col);
2799       td->dcb.xd.current_base_qindex = cm->quant_params.base_qindex;
2800       setup_bool_decoder(tile_bs_buf->data, data_end, tile_bs_buf->size,
2801                          &pbi->error, td->bit_reader, allow_update_cdf);
2802 #if CONFIG_ACCOUNTING
2803       if (pbi->acct_enabled) {
2804         td->bit_reader->accounting = &pbi->accounting;
2805         td->bit_reader->accounting->last_tell_frac =
2806             aom_reader_tell_frac(td->bit_reader);
2807       } else {
2808         td->bit_reader->accounting = NULL;
2809       }
2810 #endif
2811       av1_init_macroblockd(cm, &td->dcb.xd);
2812       av1_init_above_context(&cm->above_contexts, av1_num_planes(cm), row,
2813                              &td->dcb.xd);
2814 
2815       // Initialise the tile context from the frame context
2816       tile_data->tctx = *cm->fc;
2817       td->dcb.xd.tile_ctx = &tile_data->tctx;
2818 
2819       // decode tile
2820       decode_tile(pbi, td, row, col);
2821       aom_merge_corrupted_flag(&pbi->dcb.corrupted, td->dcb.corrupted);
2822       if (pbi->dcb.corrupted)
2823         aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
2824                            "Failed to decode tile data");
2825     }
2826   }
2827 
2828   if (tiles->large_scale) {
2829     if (n_tiles == 1) {
2830       // Find the end of the single tile buffer
2831       return aom_reader_find_end(&pbi->tile_data->bit_reader);
2832     }
2833     // Return the end of the last tile buffer
2834     return raw_data_end;
2835   }
2836   TileDataDec *const tile_data = pbi->tile_data + end_tile;
2837 
2838   return aom_reader_find_end(&tile_data->bit_reader);
2839 }
2840 
get_dec_job_info(AV1DecTileMT * tile_mt_info)2841 static TileJobsDec *get_dec_job_info(AV1DecTileMT *tile_mt_info) {
2842   TileJobsDec *cur_job_info = NULL;
2843 #if CONFIG_MULTITHREAD
2844   pthread_mutex_lock(tile_mt_info->job_mutex);
2845 
2846   if (tile_mt_info->jobs_dequeued < tile_mt_info->jobs_enqueued) {
2847     cur_job_info = tile_mt_info->job_queue + tile_mt_info->jobs_dequeued;
2848     tile_mt_info->jobs_dequeued++;
2849   }
2850 
2851   pthread_mutex_unlock(tile_mt_info->job_mutex);
2852 #else
2853   (void)tile_mt_info;
2854 #endif
2855   return cur_job_info;
2856 }
2857 
tile_worker_hook_init(AV1Decoder * const pbi,DecWorkerData * const thread_data,const TileBufferDec * const tile_buffer,TileDataDec * const tile_data,uint8_t allow_update_cdf)2858 static AOM_INLINE void tile_worker_hook_init(
2859     AV1Decoder *const pbi, DecWorkerData *const thread_data,
2860     const TileBufferDec *const tile_buffer, TileDataDec *const tile_data,
2861     uint8_t allow_update_cdf) {
2862   AV1_COMMON *cm = &pbi->common;
2863   ThreadData *const td = thread_data->td;
2864   int tile_row = tile_data->tile_info.tile_row;
2865   int tile_col = tile_data->tile_info.tile_col;
2866 
2867   td->bit_reader = &tile_data->bit_reader;
2868   av1_zero(td->cb_buffer_base.dqcoeff);
2869 
2870   MACROBLOCKD *const xd = &td->dcb.xd;
2871   av1_tile_init(&xd->tile, cm, tile_row, tile_col);
2872   xd->current_base_qindex = cm->quant_params.base_qindex;
2873   setup_bool_decoder(tile_buffer->data, thread_data->data_end,
2874                      tile_buffer->size, &thread_data->error_info,
2875                      td->bit_reader, allow_update_cdf);
2876 #if CONFIG_ACCOUNTING
2877   if (pbi->acct_enabled) {
2878     td->bit_reader->accounting = &pbi->accounting;
2879     td->bit_reader->accounting->last_tell_frac =
2880         aom_reader_tell_frac(td->bit_reader);
2881   } else {
2882     td->bit_reader->accounting = NULL;
2883   }
2884 #endif
2885   av1_init_macroblockd(cm, xd);
2886   xd->error_info = &thread_data->error_info;
2887   av1_init_above_context(&cm->above_contexts, av1_num_planes(cm), tile_row, xd);
2888 
2889   // Initialise the tile context from the frame context
2890   tile_data->tctx = *cm->fc;
2891   xd->tile_ctx = &tile_data->tctx;
2892 #if CONFIG_ACCOUNTING
2893   if (pbi->acct_enabled) {
2894     tile_data->bit_reader.accounting->last_tell_frac =
2895         aom_reader_tell_frac(&tile_data->bit_reader);
2896   }
2897 #endif
2898 }
2899 
tile_worker_hook(void * arg1,void * arg2)2900 static int tile_worker_hook(void *arg1, void *arg2) {
2901   DecWorkerData *const thread_data = (DecWorkerData *)arg1;
2902   AV1Decoder *const pbi = (AV1Decoder *)arg2;
2903   AV1_COMMON *cm = &pbi->common;
2904   ThreadData *const td = thread_data->td;
2905   uint8_t allow_update_cdf;
2906 
2907   // The jmp_buf is valid only for the duration of the function that calls
2908   // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
2909   // before it returns.
2910   if (setjmp(thread_data->error_info.jmp)) {
2911     thread_data->error_info.setjmp = 0;
2912     thread_data->td->dcb.corrupted = 1;
2913     return 0;
2914   }
2915   thread_data->error_info.setjmp = 1;
2916 
2917   allow_update_cdf = cm->tiles.large_scale ? 0 : 1;
2918   allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update;
2919 
2920   set_decode_func_pointers(td, 0x3);
2921 
2922   assert(cm->tiles.cols > 0);
2923   while (!td->dcb.corrupted) {
2924     TileJobsDec *cur_job_info = get_dec_job_info(&pbi->tile_mt_info);
2925 
2926     if (cur_job_info != NULL) {
2927       const TileBufferDec *const tile_buffer = cur_job_info->tile_buffer;
2928       TileDataDec *const tile_data = cur_job_info->tile_data;
2929       tile_worker_hook_init(pbi, thread_data, tile_buffer, tile_data,
2930                             allow_update_cdf);
2931       // decode tile
2932       int tile_row = tile_data->tile_info.tile_row;
2933       int tile_col = tile_data->tile_info.tile_col;
2934       decode_tile(pbi, td, tile_row, tile_col);
2935     } else {
2936       break;
2937     }
2938   }
2939   thread_data->error_info.setjmp = 0;
2940   return !td->dcb.corrupted;
2941 }
2942 
get_max_row_mt_workers_per_tile(AV1_COMMON * cm,TileInfo tile)2943 static INLINE int get_max_row_mt_workers_per_tile(AV1_COMMON *cm,
2944                                                   TileInfo tile) {
2945   // NOTE: Currently value of max workers is calculated based
2946   // on the parse and decode time. As per the theoretical estimate
2947   // when percentage of parse time is equal to percentage of decode
2948   // time, number of workers needed to parse + decode a tile can not
2949   // exceed more than 2.
2950   // TODO(any): Modify this value if parsing is optimized in future.
2951   int sb_rows = av1_get_sb_rows_in_tile(cm, tile);
2952   int max_workers =
2953       sb_rows == 1 ? AOM_MIN_THREADS_PER_TILE : AOM_MAX_THREADS_PER_TILE;
2954   return max_workers;
2955 }
2956 
2957 // The caller must hold pbi->row_mt_mutex_ when calling this function.
2958 // Returns 1 if either the next job is stored in *next_job_info or 1 is stored
2959 // in *end_of_frame.
2960 // NOTE: The caller waits on pbi->row_mt_cond_ if this function returns 0.
2961 // The return value of this function depends on the following variables:
2962 // - frame_row_mt_info->mi_rows_parse_done
2963 // - frame_row_mt_info->mi_rows_decode_started
2964 // - frame_row_mt_info->row_mt_exit
2965 // Therefore we may need to signal or broadcast pbi->row_mt_cond_ if any of
2966 // these variables is modified.
get_next_job_info(AV1Decoder * const pbi,AV1DecRowMTJobInfo * next_job_info,int * end_of_frame)2967 static int get_next_job_info(AV1Decoder *const pbi,
2968                              AV1DecRowMTJobInfo *next_job_info,
2969                              int *end_of_frame) {
2970   AV1_COMMON *cm = &pbi->common;
2971   TileDataDec *tile_data;
2972   AV1DecRowMTSync *dec_row_mt_sync;
2973   AV1DecRowMTInfo *frame_row_mt_info = &pbi->frame_row_mt_info;
2974   TileInfo tile_info;
2975   const int tile_rows_start = frame_row_mt_info->tile_rows_start;
2976   const int tile_rows_end = frame_row_mt_info->tile_rows_end;
2977   const int tile_cols_start = frame_row_mt_info->tile_cols_start;
2978   const int tile_cols_end = frame_row_mt_info->tile_cols_end;
2979   const int start_tile = frame_row_mt_info->start_tile;
2980   const int end_tile = frame_row_mt_info->end_tile;
2981   const int sb_mi_size = mi_size_wide[cm->seq_params->sb_size];
2982   int num_mis_to_decode, num_threads_working;
2983   int num_mis_waiting_for_decode;
2984   int min_threads_working = INT_MAX;
2985   int max_mis_to_decode = 0;
2986   int tile_row_idx, tile_col_idx;
2987   int tile_row = -1;
2988   int tile_col = -1;
2989 
2990   memset(next_job_info, 0, sizeof(*next_job_info));
2991 
2992   // Frame decode is completed or error is encountered.
2993   *end_of_frame = (frame_row_mt_info->mi_rows_decode_started ==
2994                    frame_row_mt_info->mi_rows_to_decode) ||
2995                   (frame_row_mt_info->row_mt_exit == 1);
2996   if (*end_of_frame) {
2997     return 1;
2998   }
2999 
3000   // Decoding cannot start as bit-stream parsing is not complete.
3001   assert(frame_row_mt_info->mi_rows_parse_done >=
3002          frame_row_mt_info->mi_rows_decode_started);
3003   if (frame_row_mt_info->mi_rows_parse_done ==
3004       frame_row_mt_info->mi_rows_decode_started)
3005     return 0;
3006 
3007   // Choose the tile to decode.
3008   for (tile_row_idx = tile_rows_start; tile_row_idx < tile_rows_end;
3009        ++tile_row_idx) {
3010     for (tile_col_idx = tile_cols_start; tile_col_idx < tile_cols_end;
3011          ++tile_col_idx) {
3012       if (tile_row_idx * cm->tiles.cols + tile_col_idx < start_tile ||
3013           tile_row_idx * cm->tiles.cols + tile_col_idx > end_tile)
3014         continue;
3015 
3016       tile_data = pbi->tile_data + tile_row_idx * cm->tiles.cols + tile_col_idx;
3017       dec_row_mt_sync = &tile_data->dec_row_mt_sync;
3018 
3019       num_threads_working = dec_row_mt_sync->num_threads_working;
3020       num_mis_waiting_for_decode = (dec_row_mt_sync->mi_rows_parse_done -
3021                                     dec_row_mt_sync->mi_rows_decode_started) *
3022                                    dec_row_mt_sync->mi_cols;
3023       num_mis_to_decode =
3024           (dec_row_mt_sync->mi_rows - dec_row_mt_sync->mi_rows_decode_started) *
3025           dec_row_mt_sync->mi_cols;
3026 
3027       assert(num_mis_to_decode >= num_mis_waiting_for_decode);
3028 
3029       // Pick the tile which has minimum number of threads working on it.
3030       if (num_mis_waiting_for_decode > 0) {
3031         if (num_threads_working < min_threads_working) {
3032           min_threads_working = num_threads_working;
3033           max_mis_to_decode = 0;
3034         }
3035         if (num_threads_working == min_threads_working &&
3036             num_mis_to_decode > max_mis_to_decode &&
3037             num_threads_working <
3038                 get_max_row_mt_workers_per_tile(cm, tile_data->tile_info)) {
3039           max_mis_to_decode = num_mis_to_decode;
3040           tile_row = tile_row_idx;
3041           tile_col = tile_col_idx;
3042         }
3043       }
3044     }
3045   }
3046   // No job found to process
3047   if (tile_row == -1 || tile_col == -1) return 0;
3048 
3049   tile_data = pbi->tile_data + tile_row * cm->tiles.cols + tile_col;
3050   tile_info = tile_data->tile_info;
3051   dec_row_mt_sync = &tile_data->dec_row_mt_sync;
3052 
3053   next_job_info->tile_row = tile_row;
3054   next_job_info->tile_col = tile_col;
3055   next_job_info->mi_row =
3056       dec_row_mt_sync->mi_rows_decode_started + tile_info.mi_row_start;
3057 
3058   dec_row_mt_sync->num_threads_working++;
3059   dec_row_mt_sync->mi_rows_decode_started += sb_mi_size;
3060   frame_row_mt_info->mi_rows_decode_started += sb_mi_size;
3061   assert(frame_row_mt_info->mi_rows_parse_done >=
3062          frame_row_mt_info->mi_rows_decode_started);
3063 #if CONFIG_MULTITHREAD
3064   if (frame_row_mt_info->mi_rows_decode_started ==
3065       frame_row_mt_info->mi_rows_to_decode) {
3066     pthread_cond_broadcast(pbi->row_mt_cond_);
3067   }
3068 #endif
3069 
3070   return 1;
3071 }
3072 
signal_parse_sb_row_done(AV1Decoder * const pbi,TileDataDec * const tile_data,const int sb_mi_size)3073 static INLINE void signal_parse_sb_row_done(AV1Decoder *const pbi,
3074                                             TileDataDec *const tile_data,
3075                                             const int sb_mi_size) {
3076   AV1DecRowMTInfo *frame_row_mt_info = &pbi->frame_row_mt_info;
3077 #if CONFIG_MULTITHREAD
3078   pthread_mutex_lock(pbi->row_mt_mutex_);
3079 #endif
3080   assert(frame_row_mt_info->mi_rows_parse_done >=
3081          frame_row_mt_info->mi_rows_decode_started);
3082   tile_data->dec_row_mt_sync.mi_rows_parse_done += sb_mi_size;
3083   frame_row_mt_info->mi_rows_parse_done += sb_mi_size;
3084 #if CONFIG_MULTITHREAD
3085   // A new decode job is available. Wake up one worker thread to handle the
3086   // new decode job.
3087   // NOTE: This assumes we bump mi_rows_parse_done and mi_rows_decode_started
3088   // by the same increment (sb_mi_size).
3089   pthread_cond_signal(pbi->row_mt_cond_);
3090   pthread_mutex_unlock(pbi->row_mt_mutex_);
3091 #endif
3092 }
3093 
3094 // This function is very similar to decode_tile(). It would be good to figure
3095 // out how to share code.
parse_tile_row_mt(AV1Decoder * pbi,ThreadData * const td,TileDataDec * const tile_data)3096 static AOM_INLINE void parse_tile_row_mt(AV1Decoder *pbi, ThreadData *const td,
3097                                          TileDataDec *const tile_data) {
3098   AV1_COMMON *const cm = &pbi->common;
3099   const int sb_mi_size = mi_size_wide[cm->seq_params->sb_size];
3100   const int num_planes = av1_num_planes(cm);
3101   TileInfo tile_info = tile_data->tile_info;
3102   int tile_row = tile_info.tile_row;
3103   DecoderCodingBlock *const dcb = &td->dcb;
3104   MACROBLOCKD *const xd = &dcb->xd;
3105 
3106   av1_zero_above_context(cm, xd, tile_info.mi_col_start, tile_info.mi_col_end,
3107                          tile_row);
3108   av1_reset_loop_filter_delta(xd, num_planes);
3109   av1_reset_loop_restoration(xd, num_planes);
3110 
3111   for (int mi_row = tile_info.mi_row_start; mi_row < tile_info.mi_row_end;
3112        mi_row += cm->seq_params->mib_size) {
3113     av1_zero_left_context(xd);
3114 
3115     for (int mi_col = tile_info.mi_col_start; mi_col < tile_info.mi_col_end;
3116          mi_col += cm->seq_params->mib_size) {
3117       set_cb_buffer(pbi, dcb, pbi->cb_buffer_base, num_planes, mi_row, mi_col);
3118 
3119       // Bit-stream parsing of the superblock
3120       decode_partition(pbi, td, mi_row, mi_col, td->bit_reader,
3121                        cm->seq_params->sb_size, 0x1);
3122 
3123       if (aom_reader_has_overflowed(td->bit_reader)) {
3124         aom_merge_corrupted_flag(&dcb->corrupted, 1);
3125         return;
3126       }
3127     }
3128     signal_parse_sb_row_done(pbi, tile_data, sb_mi_size);
3129   }
3130 
3131   int corrupted =
3132       (check_trailing_bits_after_symbol_coder(td->bit_reader)) ? 1 : 0;
3133   aom_merge_corrupted_flag(&dcb->corrupted, corrupted);
3134 }
3135 
row_mt_worker_hook(void * arg1,void * arg2)3136 static int row_mt_worker_hook(void *arg1, void *arg2) {
3137   DecWorkerData *const thread_data = (DecWorkerData *)arg1;
3138   AV1Decoder *const pbi = (AV1Decoder *)arg2;
3139   AV1_COMMON *cm = &pbi->common;
3140   ThreadData *const td = thread_data->td;
3141   uint8_t allow_update_cdf;
3142   AV1DecRowMTInfo *frame_row_mt_info = &pbi->frame_row_mt_info;
3143   td->dcb.corrupted = 0;
3144 
3145   // The jmp_buf is valid only for the duration of the function that calls
3146   // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
3147   // before it returns.
3148   if (setjmp(thread_data->error_info.jmp)) {
3149     thread_data->error_info.setjmp = 0;
3150     thread_data->td->dcb.corrupted = 1;
3151 #if CONFIG_MULTITHREAD
3152     pthread_mutex_lock(pbi->row_mt_mutex_);
3153 #endif
3154     frame_row_mt_info->row_mt_exit = 1;
3155 #if CONFIG_MULTITHREAD
3156     pthread_cond_broadcast(pbi->row_mt_cond_);
3157     pthread_mutex_unlock(pbi->row_mt_mutex_);
3158 #endif
3159     return 0;
3160   }
3161   thread_data->error_info.setjmp = 1;
3162 
3163   allow_update_cdf = cm->tiles.large_scale ? 0 : 1;
3164   allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update;
3165 
3166   set_decode_func_pointers(td, 0x1);
3167 
3168   assert(cm->tiles.cols > 0);
3169   while (!td->dcb.corrupted) {
3170     TileJobsDec *cur_job_info = get_dec_job_info(&pbi->tile_mt_info);
3171 
3172     if (cur_job_info != NULL) {
3173       const TileBufferDec *const tile_buffer = cur_job_info->tile_buffer;
3174       TileDataDec *const tile_data = cur_job_info->tile_data;
3175       tile_worker_hook_init(pbi, thread_data, tile_buffer, tile_data,
3176                             allow_update_cdf);
3177 #if CONFIG_MULTITHREAD
3178       pthread_mutex_lock(pbi->row_mt_mutex_);
3179 #endif
3180       tile_data->dec_row_mt_sync.num_threads_working++;
3181 #if CONFIG_MULTITHREAD
3182       pthread_mutex_unlock(pbi->row_mt_mutex_);
3183 #endif
3184       // decode tile
3185       parse_tile_row_mt(pbi, td, tile_data);
3186 #if CONFIG_MULTITHREAD
3187       pthread_mutex_lock(pbi->row_mt_mutex_);
3188 #endif
3189       tile_data->dec_row_mt_sync.num_threads_working--;
3190 #if CONFIG_MULTITHREAD
3191       pthread_mutex_unlock(pbi->row_mt_mutex_);
3192 #endif
3193     } else {
3194       break;
3195     }
3196   }
3197 
3198   if (td->dcb.corrupted) {
3199     thread_data->error_info.setjmp = 0;
3200 #if CONFIG_MULTITHREAD
3201     pthread_mutex_lock(pbi->row_mt_mutex_);
3202 #endif
3203     frame_row_mt_info->row_mt_exit = 1;
3204 #if CONFIG_MULTITHREAD
3205     pthread_cond_broadcast(pbi->row_mt_cond_);
3206     pthread_mutex_unlock(pbi->row_mt_mutex_);
3207 #endif
3208     return 0;
3209   }
3210 
3211   set_decode_func_pointers(td, 0x2);
3212 
3213   while (1) {
3214     AV1DecRowMTJobInfo next_job_info;
3215     int end_of_frame = 0;
3216 
3217 #if CONFIG_MULTITHREAD
3218     pthread_mutex_lock(pbi->row_mt_mutex_);
3219 #endif
3220     while (!get_next_job_info(pbi, &next_job_info, &end_of_frame)) {
3221 #if CONFIG_MULTITHREAD
3222       pthread_cond_wait(pbi->row_mt_cond_, pbi->row_mt_mutex_);
3223 #endif
3224     }
3225 #if CONFIG_MULTITHREAD
3226     pthread_mutex_unlock(pbi->row_mt_mutex_);
3227 #endif
3228 
3229     if (end_of_frame) break;
3230 
3231     int tile_row = next_job_info.tile_row;
3232     int tile_col = next_job_info.tile_col;
3233     int mi_row = next_job_info.mi_row;
3234 
3235     TileDataDec *tile_data =
3236         pbi->tile_data + tile_row * cm->tiles.cols + tile_col;
3237     AV1DecRowMTSync *dec_row_mt_sync = &tile_data->dec_row_mt_sync;
3238     TileInfo tile_info = tile_data->tile_info;
3239 
3240     av1_tile_init(&td->dcb.xd.tile, cm, tile_row, tile_col);
3241     av1_init_macroblockd(cm, &td->dcb.xd);
3242     td->dcb.xd.error_info = &thread_data->error_info;
3243 
3244     decode_tile_sb_row(pbi, td, tile_info, mi_row);
3245 
3246 #if CONFIG_MULTITHREAD
3247     pthread_mutex_lock(pbi->row_mt_mutex_);
3248 #endif
3249     dec_row_mt_sync->num_threads_working--;
3250 #if CONFIG_MULTITHREAD
3251     pthread_mutex_unlock(pbi->row_mt_mutex_);
3252 #endif
3253   }
3254   thread_data->error_info.setjmp = 0;
3255   return !td->dcb.corrupted;
3256 }
3257 
3258 // sorts in descending order
compare_tile_buffers(const void * a,const void * b)3259 static int compare_tile_buffers(const void *a, const void *b) {
3260   const TileJobsDec *const buf1 = (const TileJobsDec *)a;
3261   const TileJobsDec *const buf2 = (const TileJobsDec *)b;
3262   return (((int)buf2->tile_buffer->size) - ((int)buf1->tile_buffer->size));
3263 }
3264 
enqueue_tile_jobs(AV1Decoder * pbi,AV1_COMMON * cm,int tile_rows_start,int tile_rows_end,int tile_cols_start,int tile_cols_end,int start_tile,int end_tile)3265 static AOM_INLINE void enqueue_tile_jobs(AV1Decoder *pbi, AV1_COMMON *cm,
3266                                          int tile_rows_start, int tile_rows_end,
3267                                          int tile_cols_start, int tile_cols_end,
3268                                          int start_tile, int end_tile) {
3269   AV1DecTileMT *tile_mt_info = &pbi->tile_mt_info;
3270   TileJobsDec *tile_job_queue = tile_mt_info->job_queue;
3271   tile_mt_info->jobs_enqueued = 0;
3272   tile_mt_info->jobs_dequeued = 0;
3273 
3274   for (int row = tile_rows_start; row < tile_rows_end; row++) {
3275     for (int col = tile_cols_start; col < tile_cols_end; col++) {
3276       if (row * cm->tiles.cols + col < start_tile ||
3277           row * cm->tiles.cols + col > end_tile)
3278         continue;
3279       tile_job_queue->tile_buffer = &pbi->tile_buffers[row][col];
3280       tile_job_queue->tile_data = pbi->tile_data + row * cm->tiles.cols + col;
3281       tile_job_queue++;
3282       tile_mt_info->jobs_enqueued++;
3283     }
3284   }
3285 }
3286 
alloc_dec_jobs(AV1DecTileMT * tile_mt_info,AV1_COMMON * cm,int tile_rows,int tile_cols)3287 static AOM_INLINE void alloc_dec_jobs(AV1DecTileMT *tile_mt_info,
3288                                       AV1_COMMON *cm, int tile_rows,
3289                                       int tile_cols) {
3290   tile_mt_info->alloc_tile_rows = tile_rows;
3291   tile_mt_info->alloc_tile_cols = tile_cols;
3292   int num_tiles = tile_rows * tile_cols;
3293 #if CONFIG_MULTITHREAD
3294   {
3295     CHECK_MEM_ERROR(cm, tile_mt_info->job_mutex,
3296                     aom_malloc(sizeof(*tile_mt_info->job_mutex) * num_tiles));
3297 
3298     for (int i = 0; i < num_tiles; i++) {
3299       pthread_mutex_init(&tile_mt_info->job_mutex[i], NULL);
3300     }
3301   }
3302 #endif
3303   CHECK_MEM_ERROR(cm, tile_mt_info->job_queue,
3304                   aom_malloc(sizeof(*tile_mt_info->job_queue) * num_tiles));
3305 }
3306 
av1_free_mc_tmp_buf(ThreadData * thread_data)3307 void av1_free_mc_tmp_buf(ThreadData *thread_data) {
3308   int ref;
3309   for (ref = 0; ref < 2; ref++) {
3310     if (thread_data->mc_buf_use_highbd)
3311       aom_free(CONVERT_TO_SHORTPTR(thread_data->mc_buf[ref]));
3312     else
3313       aom_free(thread_data->mc_buf[ref]);
3314     thread_data->mc_buf[ref] = NULL;
3315   }
3316   thread_data->mc_buf_size = 0;
3317   thread_data->mc_buf_use_highbd = 0;
3318 
3319   aom_free(thread_data->tmp_conv_dst);
3320   thread_data->tmp_conv_dst = NULL;
3321   aom_free(thread_data->seg_mask);
3322   thread_data->seg_mask = NULL;
3323   for (int i = 0; i < 2; ++i) {
3324     aom_free(thread_data->tmp_obmc_bufs[i]);
3325     thread_data->tmp_obmc_bufs[i] = NULL;
3326   }
3327 }
3328 
allocate_mc_tmp_buf(AV1_COMMON * const cm,ThreadData * thread_data,int buf_size,int use_highbd)3329 static AOM_INLINE void allocate_mc_tmp_buf(AV1_COMMON *const cm,
3330                                            ThreadData *thread_data,
3331                                            int buf_size, int use_highbd) {
3332   for (int ref = 0; ref < 2; ref++) {
3333     // The mc_buf/hbd_mc_buf must be zeroed to fix a intermittent valgrind error
3334     // 'Conditional jump or move depends on uninitialised value' from the loop
3335     // filter. Uninitialized reads in convolve function (e.g. horiz_4tap path in
3336     // av1_convolve_2d_sr_avx2()) from mc_buf/hbd_mc_buf are seen to be the
3337     // potential reason for this issue.
3338     if (use_highbd) {
3339       uint16_t *hbd_mc_buf;
3340       CHECK_MEM_ERROR(cm, hbd_mc_buf, (uint16_t *)aom_memalign(16, buf_size));
3341       memset(hbd_mc_buf, 0, buf_size);
3342       thread_data->mc_buf[ref] = CONVERT_TO_BYTEPTR(hbd_mc_buf);
3343     } else {
3344       CHECK_MEM_ERROR(cm, thread_data->mc_buf[ref],
3345                       (uint8_t *)aom_memalign(16, buf_size));
3346       memset(thread_data->mc_buf[ref], 0, buf_size);
3347     }
3348   }
3349   thread_data->mc_buf_size = buf_size;
3350   thread_data->mc_buf_use_highbd = use_highbd;
3351 
3352   CHECK_MEM_ERROR(cm, thread_data->tmp_conv_dst,
3353                   aom_memalign(32, MAX_SB_SIZE * MAX_SB_SIZE *
3354                                        sizeof(*thread_data->tmp_conv_dst)));
3355   CHECK_MEM_ERROR(cm, thread_data->seg_mask,
3356                   (uint8_t *)aom_memalign(
3357                       16, 2 * MAX_SB_SQUARE * sizeof(*thread_data->seg_mask)));
3358 
3359   for (int i = 0; i < 2; ++i) {
3360     CHECK_MEM_ERROR(
3361         cm, thread_data->tmp_obmc_bufs[i],
3362         aom_memalign(16, 2 * MAX_MB_PLANE * MAX_SB_SQUARE *
3363                              sizeof(*thread_data->tmp_obmc_bufs[i])));
3364   }
3365 }
3366 
reset_dec_workers(AV1Decoder * pbi,AVxWorkerHook worker_hook,int num_workers)3367 static AOM_INLINE void reset_dec_workers(AV1Decoder *pbi,
3368                                          AVxWorkerHook worker_hook,
3369                                          int num_workers) {
3370   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
3371 
3372   // Reset tile decoding hook
3373   for (int worker_idx = 0; worker_idx < num_workers; ++worker_idx) {
3374     AVxWorker *const worker = &pbi->tile_workers[worker_idx];
3375     DecWorkerData *const thread_data = pbi->thread_data + worker_idx;
3376     thread_data->td->dcb = pbi->dcb;
3377     thread_data->td->dcb.corrupted = 0;
3378     thread_data->td->dcb.mc_buf[0] = thread_data->td->mc_buf[0];
3379     thread_data->td->dcb.mc_buf[1] = thread_data->td->mc_buf[1];
3380     thread_data->td->dcb.xd.tmp_conv_dst = thread_data->td->tmp_conv_dst;
3381     if (worker_idx)
3382       thread_data->td->dcb.xd.seg_mask = thread_data->td->seg_mask;
3383     for (int j = 0; j < 2; ++j) {
3384       thread_data->td->dcb.xd.tmp_obmc_bufs[j] =
3385           thread_data->td->tmp_obmc_bufs[j];
3386     }
3387     winterface->sync(worker);
3388 
3389     worker->hook = worker_hook;
3390     worker->data1 = thread_data;
3391     worker->data2 = pbi;
3392   }
3393 #if CONFIG_ACCOUNTING
3394   if (pbi->acct_enabled) {
3395     aom_accounting_reset(&pbi->accounting);
3396   }
3397 #endif
3398 }
3399 
launch_dec_workers(AV1Decoder * pbi,const uint8_t * data_end,int num_workers)3400 static AOM_INLINE void launch_dec_workers(AV1Decoder *pbi,
3401                                           const uint8_t *data_end,
3402                                           int num_workers) {
3403   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
3404 
3405   for (int worker_idx = num_workers - 1; worker_idx >= 0; --worker_idx) {
3406     AVxWorker *const worker = &pbi->tile_workers[worker_idx];
3407     DecWorkerData *const thread_data = (DecWorkerData *)worker->data1;
3408 
3409     thread_data->data_end = data_end;
3410 
3411     worker->had_error = 0;
3412     if (worker_idx == 0) {
3413       winterface->execute(worker);
3414     } else {
3415       winterface->launch(worker);
3416     }
3417   }
3418 }
3419 
sync_dec_workers(AV1Decoder * pbi,int num_workers)3420 static AOM_INLINE void sync_dec_workers(AV1Decoder *pbi, int num_workers) {
3421   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
3422   int corrupted = 0;
3423 
3424   for (int worker_idx = num_workers; worker_idx > 0; --worker_idx) {
3425     AVxWorker *const worker = &pbi->tile_workers[worker_idx - 1];
3426     aom_merge_corrupted_flag(&corrupted, !winterface->sync(worker));
3427   }
3428 
3429   pbi->dcb.corrupted = corrupted;
3430 }
3431 
decode_mt_init(AV1Decoder * pbi)3432 static AOM_INLINE void decode_mt_init(AV1Decoder *pbi) {
3433   AV1_COMMON *const cm = &pbi->common;
3434   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
3435   int worker_idx;
3436 
3437   // Create workers and thread_data
3438   if (pbi->num_workers == 0) {
3439     const int num_threads = pbi->max_threads;
3440     CHECK_MEM_ERROR(cm, pbi->tile_workers,
3441                     aom_malloc(num_threads * sizeof(*pbi->tile_workers)));
3442     CHECK_MEM_ERROR(cm, pbi->thread_data,
3443                     aom_malloc(num_threads * sizeof(*pbi->thread_data)));
3444 
3445     for (worker_idx = 0; worker_idx < num_threads; ++worker_idx) {
3446       AVxWorker *const worker = &pbi->tile_workers[worker_idx];
3447       DecWorkerData *const thread_data = pbi->thread_data + worker_idx;
3448       ++pbi->num_workers;
3449 
3450       winterface->init(worker);
3451       worker->thread_name = "aom tile worker";
3452       if (worker_idx != 0 && !winterface->reset(worker)) {
3453         aom_internal_error(&pbi->error, AOM_CODEC_ERROR,
3454                            "Tile decoder thread creation failed");
3455       }
3456 
3457       if (worker_idx != 0) {
3458         // Allocate thread data.
3459         CHECK_MEM_ERROR(cm, thread_data->td,
3460                         aom_memalign(32, sizeof(*thread_data->td)));
3461         av1_zero(*thread_data->td);
3462       } else {
3463         // Main thread acts as a worker and uses the thread data in pbi
3464         thread_data->td = &pbi->td;
3465       }
3466       thread_data->error_info.error_code = AOM_CODEC_OK;
3467       thread_data->error_info.setjmp = 0;
3468     }
3469   }
3470   const int use_highbd = cm->seq_params->use_highbitdepth;
3471   const int buf_size = MC_TEMP_BUF_PELS << use_highbd;
3472   for (worker_idx = 1; worker_idx < pbi->max_threads; ++worker_idx) {
3473     DecWorkerData *const thread_data = pbi->thread_data + worker_idx;
3474     if (thread_data->td->mc_buf_size != buf_size) {
3475       av1_free_mc_tmp_buf(thread_data->td);
3476       allocate_mc_tmp_buf(cm, thread_data->td, buf_size, use_highbd);
3477     }
3478   }
3479 }
3480 
tile_mt_queue(AV1Decoder * pbi,int tile_cols,int tile_rows,int tile_rows_start,int tile_rows_end,int tile_cols_start,int tile_cols_end,int start_tile,int end_tile)3481 static AOM_INLINE void tile_mt_queue(AV1Decoder *pbi, int tile_cols,
3482                                      int tile_rows, int tile_rows_start,
3483                                      int tile_rows_end, int tile_cols_start,
3484                                      int tile_cols_end, int start_tile,
3485                                      int end_tile) {
3486   AV1_COMMON *const cm = &pbi->common;
3487   if (pbi->tile_mt_info.alloc_tile_cols != tile_cols ||
3488       pbi->tile_mt_info.alloc_tile_rows != tile_rows) {
3489     av1_dealloc_dec_jobs(&pbi->tile_mt_info);
3490     alloc_dec_jobs(&pbi->tile_mt_info, cm, tile_rows, tile_cols);
3491   }
3492   enqueue_tile_jobs(pbi, cm, tile_rows_start, tile_rows_end, tile_cols_start,
3493                     tile_cols_end, start_tile, end_tile);
3494   qsort(pbi->tile_mt_info.job_queue, pbi->tile_mt_info.jobs_enqueued,
3495         sizeof(pbi->tile_mt_info.job_queue[0]), compare_tile_buffers);
3496 }
3497 
decode_tiles_mt(AV1Decoder * pbi,const uint8_t * data,const uint8_t * data_end,int start_tile,int end_tile)3498 static const uint8_t *decode_tiles_mt(AV1Decoder *pbi, const uint8_t *data,
3499                                       const uint8_t *data_end, int start_tile,
3500                                       int end_tile) {
3501   AV1_COMMON *const cm = &pbi->common;
3502   CommonTileParams *const tiles = &cm->tiles;
3503   const int tile_cols = tiles->cols;
3504   const int tile_rows = tiles->rows;
3505   const int n_tiles = tile_cols * tile_rows;
3506   TileBufferDec(*const tile_buffers)[MAX_TILE_COLS] = pbi->tile_buffers;
3507   const int dec_tile_row = AOMMIN(pbi->dec_tile_row, tile_rows);
3508   const int single_row = pbi->dec_tile_row >= 0;
3509   const int dec_tile_col = AOMMIN(pbi->dec_tile_col, tile_cols);
3510   const int single_col = pbi->dec_tile_col >= 0;
3511   int tile_rows_start;
3512   int tile_rows_end;
3513   int tile_cols_start;
3514   int tile_cols_end;
3515   int tile_count_tg;
3516   int num_workers;
3517   const uint8_t *raw_data_end = NULL;
3518 
3519   if (tiles->large_scale) {
3520     tile_rows_start = single_row ? dec_tile_row : 0;
3521     tile_rows_end = single_row ? dec_tile_row + 1 : tile_rows;
3522     tile_cols_start = single_col ? dec_tile_col : 0;
3523     tile_cols_end = single_col ? tile_cols_start + 1 : tile_cols;
3524   } else {
3525     tile_rows_start = 0;
3526     tile_rows_end = tile_rows;
3527     tile_cols_start = 0;
3528     tile_cols_end = tile_cols;
3529   }
3530   tile_count_tg = end_tile - start_tile + 1;
3531   num_workers = AOMMIN(pbi->max_threads, tile_count_tg);
3532 
3533   // No tiles to decode.
3534   if (tile_rows_end <= tile_rows_start || tile_cols_end <= tile_cols_start ||
3535       // First tile is larger than end_tile.
3536       tile_rows_start * tile_cols + tile_cols_start > end_tile ||
3537       // Last tile is smaller than start_tile.
3538       (tile_rows_end - 1) * tile_cols + tile_cols_end - 1 < start_tile)
3539     return data;
3540 
3541   assert(tile_rows <= MAX_TILE_ROWS);
3542   assert(tile_cols <= MAX_TILE_COLS);
3543   assert(tile_count_tg > 0);
3544   assert(num_workers > 0);
3545   assert(start_tile <= end_tile);
3546   assert(start_tile >= 0 && end_tile < n_tiles);
3547 
3548   decode_mt_init(pbi);
3549 
3550   // get tile size in tile group
3551 #if EXT_TILE_DEBUG
3552   if (tiles->large_scale) assert(pbi->ext_tile_debug == 1);
3553   if (tiles->large_scale)
3554     raw_data_end = get_ls_tile_buffers(pbi, data, data_end, tile_buffers);
3555   else
3556 #endif  // EXT_TILE_DEBUG
3557     get_tile_buffers(pbi, data, data_end, tile_buffers, start_tile, end_tile);
3558 
3559   if (pbi->tile_data == NULL || n_tiles != pbi->allocated_tiles) {
3560     decoder_alloc_tile_data(pbi, n_tiles);
3561   }
3562   if (pbi->dcb.xd.seg_mask == NULL)
3563     CHECK_MEM_ERROR(cm, pbi->dcb.xd.seg_mask,
3564                     (uint8_t *)aom_memalign(
3565                         16, 2 * MAX_SB_SQUARE * sizeof(*pbi->dcb.xd.seg_mask)));
3566 
3567   for (int row = 0; row < tile_rows; row++) {
3568     for (int col = 0; col < tile_cols; col++) {
3569       TileDataDec *tile_data = pbi->tile_data + row * tiles->cols + col;
3570       av1_tile_init(&tile_data->tile_info, cm, row, col);
3571     }
3572   }
3573 
3574   tile_mt_queue(pbi, tile_cols, tile_rows, tile_rows_start, tile_rows_end,
3575                 tile_cols_start, tile_cols_end, start_tile, end_tile);
3576 
3577   reset_dec_workers(pbi, tile_worker_hook, num_workers);
3578   launch_dec_workers(pbi, data_end, num_workers);
3579   sync_dec_workers(pbi, num_workers);
3580 
3581   if (pbi->dcb.corrupted)
3582     aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
3583                        "Failed to decode tile data");
3584 
3585   if (tiles->large_scale) {
3586     if (n_tiles == 1) {
3587       // Find the end of the single tile buffer
3588       return aom_reader_find_end(&pbi->tile_data->bit_reader);
3589     }
3590     // Return the end of the last tile buffer
3591     return raw_data_end;
3592   }
3593   TileDataDec *const tile_data = pbi->tile_data + end_tile;
3594 
3595   return aom_reader_find_end(&tile_data->bit_reader);
3596 }
3597 
dec_alloc_cb_buf(AV1Decoder * pbi)3598 static AOM_INLINE void dec_alloc_cb_buf(AV1Decoder *pbi) {
3599   AV1_COMMON *const cm = &pbi->common;
3600   int size = ((cm->mi_params.mi_rows >> cm->seq_params->mib_size_log2) + 1) *
3601              ((cm->mi_params.mi_cols >> cm->seq_params->mib_size_log2) + 1);
3602 
3603   if (pbi->cb_buffer_alloc_size < size) {
3604     av1_dec_free_cb_buf(pbi);
3605     CHECK_MEM_ERROR(cm, pbi->cb_buffer_base,
3606                     aom_memalign(32, sizeof(*pbi->cb_buffer_base) * size));
3607     memset(pbi->cb_buffer_base, 0, sizeof(*pbi->cb_buffer_base) * size);
3608     pbi->cb_buffer_alloc_size = size;
3609   }
3610 }
3611 
row_mt_frame_init(AV1Decoder * pbi,int tile_rows_start,int tile_rows_end,int tile_cols_start,int tile_cols_end,int start_tile,int end_tile,int max_sb_rows)3612 static AOM_INLINE void row_mt_frame_init(AV1Decoder *pbi, int tile_rows_start,
3613                                          int tile_rows_end, int tile_cols_start,
3614                                          int tile_cols_end, int start_tile,
3615                                          int end_tile, int max_sb_rows) {
3616   AV1_COMMON *const cm = &pbi->common;
3617   AV1DecRowMTInfo *frame_row_mt_info = &pbi->frame_row_mt_info;
3618 
3619   frame_row_mt_info->tile_rows_start = tile_rows_start;
3620   frame_row_mt_info->tile_rows_end = tile_rows_end;
3621   frame_row_mt_info->tile_cols_start = tile_cols_start;
3622   frame_row_mt_info->tile_cols_end = tile_cols_end;
3623   frame_row_mt_info->start_tile = start_tile;
3624   frame_row_mt_info->end_tile = end_tile;
3625   frame_row_mt_info->mi_rows_to_decode = 0;
3626   frame_row_mt_info->mi_rows_parse_done = 0;
3627   frame_row_mt_info->mi_rows_decode_started = 0;
3628   frame_row_mt_info->row_mt_exit = 0;
3629 
3630   for (int tile_row = tile_rows_start; tile_row < tile_rows_end; ++tile_row) {
3631     for (int tile_col = tile_cols_start; tile_col < tile_cols_end; ++tile_col) {
3632       if (tile_row * cm->tiles.cols + tile_col < start_tile ||
3633           tile_row * cm->tiles.cols + tile_col > end_tile)
3634         continue;
3635 
3636       TileDataDec *const tile_data =
3637           pbi->tile_data + tile_row * cm->tiles.cols + tile_col;
3638       TileInfo tile_info = tile_data->tile_info;
3639 
3640       tile_data->dec_row_mt_sync.mi_rows_parse_done = 0;
3641       tile_data->dec_row_mt_sync.mi_rows_decode_started = 0;
3642       tile_data->dec_row_mt_sync.num_threads_working = 0;
3643       tile_data->dec_row_mt_sync.mi_rows =
3644           ALIGN_POWER_OF_TWO(tile_info.mi_row_end - tile_info.mi_row_start,
3645                              cm->seq_params->mib_size_log2);
3646       tile_data->dec_row_mt_sync.mi_cols =
3647           ALIGN_POWER_OF_TWO(tile_info.mi_col_end - tile_info.mi_col_start,
3648                              cm->seq_params->mib_size_log2);
3649 
3650       frame_row_mt_info->mi_rows_to_decode +=
3651           tile_data->dec_row_mt_sync.mi_rows;
3652 
3653       // Initialize cur_sb_col to -1 for all SB rows.
3654       memset(tile_data->dec_row_mt_sync.cur_sb_col, -1,
3655              sizeof(*tile_data->dec_row_mt_sync.cur_sb_col) * max_sb_rows);
3656     }
3657   }
3658 
3659 #if CONFIG_MULTITHREAD
3660   if (pbi->row_mt_mutex_ == NULL) {
3661     CHECK_MEM_ERROR(cm, pbi->row_mt_mutex_,
3662                     aom_malloc(sizeof(*(pbi->row_mt_mutex_))));
3663     if (pbi->row_mt_mutex_) {
3664       pthread_mutex_init(pbi->row_mt_mutex_, NULL);
3665     }
3666   }
3667 
3668   if (pbi->row_mt_cond_ == NULL) {
3669     CHECK_MEM_ERROR(cm, pbi->row_mt_cond_,
3670                     aom_malloc(sizeof(*(pbi->row_mt_cond_))));
3671     if (pbi->row_mt_cond_) {
3672       pthread_cond_init(pbi->row_mt_cond_, NULL);
3673     }
3674   }
3675 #endif
3676 }
3677 
decode_tiles_row_mt(AV1Decoder * pbi,const uint8_t * data,const uint8_t * data_end,int start_tile,int end_tile)3678 static const uint8_t *decode_tiles_row_mt(AV1Decoder *pbi, const uint8_t *data,
3679                                           const uint8_t *data_end,
3680                                           int start_tile, int end_tile) {
3681   AV1_COMMON *const cm = &pbi->common;
3682   CommonTileParams *const tiles = &cm->tiles;
3683   const int tile_cols = tiles->cols;
3684   const int tile_rows = tiles->rows;
3685   const int n_tiles = tile_cols * tile_rows;
3686   TileBufferDec(*const tile_buffers)[MAX_TILE_COLS] = pbi->tile_buffers;
3687   const int dec_tile_row = AOMMIN(pbi->dec_tile_row, tile_rows);
3688   const int single_row = pbi->dec_tile_row >= 0;
3689   const int dec_tile_col = AOMMIN(pbi->dec_tile_col, tile_cols);
3690   const int single_col = pbi->dec_tile_col >= 0;
3691   int tile_rows_start;
3692   int tile_rows_end;
3693   int tile_cols_start;
3694   int tile_cols_end;
3695   int tile_count_tg;
3696   int num_workers = 0;
3697   int max_threads;
3698   const uint8_t *raw_data_end = NULL;
3699   int max_sb_rows = 0;
3700 
3701   if (tiles->large_scale) {
3702     tile_rows_start = single_row ? dec_tile_row : 0;
3703     tile_rows_end = single_row ? dec_tile_row + 1 : tile_rows;
3704     tile_cols_start = single_col ? dec_tile_col : 0;
3705     tile_cols_end = single_col ? tile_cols_start + 1 : tile_cols;
3706   } else {
3707     tile_rows_start = 0;
3708     tile_rows_end = tile_rows;
3709     tile_cols_start = 0;
3710     tile_cols_end = tile_cols;
3711   }
3712   tile_count_tg = end_tile - start_tile + 1;
3713   max_threads = pbi->max_threads;
3714 
3715   // No tiles to decode.
3716   if (tile_rows_end <= tile_rows_start || tile_cols_end <= tile_cols_start ||
3717       // First tile is larger than end_tile.
3718       tile_rows_start * tile_cols + tile_cols_start > end_tile ||
3719       // Last tile is smaller than start_tile.
3720       (tile_rows_end - 1) * tile_cols + tile_cols_end - 1 < start_tile)
3721     return data;
3722 
3723   assert(tile_rows <= MAX_TILE_ROWS);
3724   assert(tile_cols <= MAX_TILE_COLS);
3725   assert(tile_count_tg > 0);
3726   assert(max_threads > 0);
3727   assert(start_tile <= end_tile);
3728   assert(start_tile >= 0 && end_tile < n_tiles);
3729 
3730   (void)tile_count_tg;
3731 
3732   decode_mt_init(pbi);
3733 
3734   // get tile size in tile group
3735 #if EXT_TILE_DEBUG
3736   if (tiles->large_scale) assert(pbi->ext_tile_debug == 1);
3737   if (tiles->large_scale)
3738     raw_data_end = get_ls_tile_buffers(pbi, data, data_end, tile_buffers);
3739   else
3740 #endif  // EXT_TILE_DEBUG
3741     get_tile_buffers(pbi, data, data_end, tile_buffers, start_tile, end_tile);
3742 
3743   if (pbi->tile_data == NULL || n_tiles != pbi->allocated_tiles) {
3744     if (pbi->tile_data != NULL) {
3745       for (int i = 0; i < pbi->allocated_tiles; i++) {
3746         TileDataDec *const tile_data = pbi->tile_data + i;
3747         av1_dec_row_mt_dealloc(&tile_data->dec_row_mt_sync);
3748       }
3749     }
3750     decoder_alloc_tile_data(pbi, n_tiles);
3751   }
3752   if (pbi->dcb.xd.seg_mask == NULL)
3753     CHECK_MEM_ERROR(cm, pbi->dcb.xd.seg_mask,
3754                     (uint8_t *)aom_memalign(
3755                         16, 2 * MAX_SB_SQUARE * sizeof(*pbi->dcb.xd.seg_mask)));
3756 
3757   for (int row = 0; row < tile_rows; row++) {
3758     for (int col = 0; col < tile_cols; col++) {
3759       TileDataDec *tile_data = pbi->tile_data + row * tiles->cols + col;
3760       av1_tile_init(&tile_data->tile_info, cm, row, col);
3761 
3762       max_sb_rows = AOMMAX(max_sb_rows,
3763                            av1_get_sb_rows_in_tile(cm, tile_data->tile_info));
3764       num_workers += get_max_row_mt_workers_per_tile(cm, tile_data->tile_info);
3765     }
3766   }
3767   num_workers = AOMMIN(num_workers, max_threads);
3768 
3769   if (pbi->allocated_row_mt_sync_rows != max_sb_rows) {
3770     for (int i = 0; i < n_tiles; ++i) {
3771       TileDataDec *const tile_data = pbi->tile_data + i;
3772       av1_dec_row_mt_dealloc(&tile_data->dec_row_mt_sync);
3773       dec_row_mt_alloc(&tile_data->dec_row_mt_sync, cm, max_sb_rows);
3774     }
3775     pbi->allocated_row_mt_sync_rows = max_sb_rows;
3776   }
3777 
3778   tile_mt_queue(pbi, tile_cols, tile_rows, tile_rows_start, tile_rows_end,
3779                 tile_cols_start, tile_cols_end, start_tile, end_tile);
3780 
3781   dec_alloc_cb_buf(pbi);
3782 
3783   row_mt_frame_init(pbi, tile_rows_start, tile_rows_end, tile_cols_start,
3784                     tile_cols_end, start_tile, end_tile, max_sb_rows);
3785 
3786   reset_dec_workers(pbi, row_mt_worker_hook, num_workers);
3787   launch_dec_workers(pbi, data_end, num_workers);
3788   sync_dec_workers(pbi, num_workers);
3789 
3790   if (pbi->dcb.corrupted)
3791     aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
3792                        "Failed to decode tile data");
3793 
3794   if (tiles->large_scale) {
3795     if (n_tiles == 1) {
3796       // Find the end of the single tile buffer
3797       return aom_reader_find_end(&pbi->tile_data->bit_reader);
3798     }
3799     // Return the end of the last tile buffer
3800     return raw_data_end;
3801   }
3802   TileDataDec *const tile_data = pbi->tile_data + end_tile;
3803 
3804   return aom_reader_find_end(&tile_data->bit_reader);
3805 }
3806 
error_handler(void * data)3807 static AOM_INLINE void error_handler(void *data) {
3808   AV1_COMMON *const cm = (AV1_COMMON *)data;
3809   aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME, "Truncated packet");
3810 }
3811 
3812 // Reads the high_bitdepth and twelve_bit fields in color_config() and sets
3813 // seq_params->bit_depth based on the values of those fields and
3814 // seq_params->profile. Reports errors by calling rb->error_handler() or
3815 // aom_internal_error().
read_bitdepth(struct aom_read_bit_buffer * rb,SequenceHeader * seq_params,struct aom_internal_error_info * error_info)3816 static AOM_INLINE void read_bitdepth(
3817     struct aom_read_bit_buffer *rb, SequenceHeader *seq_params,
3818     struct aom_internal_error_info *error_info) {
3819   const int high_bitdepth = aom_rb_read_bit(rb);
3820   if (seq_params->profile == PROFILE_2 && high_bitdepth) {
3821     const int twelve_bit = aom_rb_read_bit(rb);
3822     seq_params->bit_depth = twelve_bit ? AOM_BITS_12 : AOM_BITS_10;
3823   } else if (seq_params->profile <= PROFILE_2) {
3824     seq_params->bit_depth = high_bitdepth ? AOM_BITS_10 : AOM_BITS_8;
3825   } else {
3826     aom_internal_error(error_info, AOM_CODEC_UNSUP_BITSTREAM,
3827                        "Unsupported profile/bit-depth combination");
3828   }
3829 #if !CONFIG_AV1_HIGHBITDEPTH
3830   if (seq_params->bit_depth > AOM_BITS_8) {
3831     aom_internal_error(error_info, AOM_CODEC_UNSUP_BITSTREAM,
3832                        "Bit-depth %d not supported", seq_params->bit_depth);
3833   }
3834 #endif
3835 }
3836 
av1_read_film_grain_params(AV1_COMMON * cm,struct aom_read_bit_buffer * rb)3837 void av1_read_film_grain_params(AV1_COMMON *cm,
3838                                 struct aom_read_bit_buffer *rb) {
3839   aom_film_grain_t *pars = &cm->film_grain_params;
3840   const SequenceHeader *const seq_params = cm->seq_params;
3841 
3842   pars->apply_grain = aom_rb_read_bit(rb);
3843   if (!pars->apply_grain) {
3844     memset(pars, 0, sizeof(*pars));
3845     return;
3846   }
3847 
3848   pars->random_seed = aom_rb_read_literal(rb, 16);
3849   if (cm->current_frame.frame_type == INTER_FRAME)
3850     pars->update_parameters = aom_rb_read_bit(rb);
3851   else
3852     pars->update_parameters = 1;
3853 
3854   pars->bit_depth = seq_params->bit_depth;
3855 
3856   if (!pars->update_parameters) {
3857     // inherit parameters from a previous reference frame
3858     int film_grain_params_ref_idx = aom_rb_read_literal(rb, 3);
3859     // Section 6.8.20: It is a requirement of bitstream conformance that
3860     // film_grain_params_ref_idx is equal to ref_frame_idx[ j ] for some value
3861     // of j in the range 0 to REFS_PER_FRAME - 1.
3862     int found = 0;
3863     for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
3864       if (film_grain_params_ref_idx == cm->remapped_ref_idx[i]) {
3865         found = 1;
3866         break;
3867       }
3868     }
3869     if (!found) {
3870       aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3871                          "Invalid film grain reference idx %d. ref_frame_idx = "
3872                          "{%d, %d, %d, %d, %d, %d, %d}",
3873                          film_grain_params_ref_idx, cm->remapped_ref_idx[0],
3874                          cm->remapped_ref_idx[1], cm->remapped_ref_idx[2],
3875                          cm->remapped_ref_idx[3], cm->remapped_ref_idx[4],
3876                          cm->remapped_ref_idx[5], cm->remapped_ref_idx[6]);
3877     }
3878     RefCntBuffer *const buf = cm->ref_frame_map[film_grain_params_ref_idx];
3879     if (buf == NULL) {
3880       aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3881                          "Invalid Film grain reference idx");
3882     }
3883     if (!buf->film_grain_params_present) {
3884       aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3885                          "Film grain reference parameters not available");
3886     }
3887     uint16_t random_seed = pars->random_seed;
3888     *pars = buf->film_grain_params;   // inherit paramaters
3889     pars->random_seed = random_seed;  // with new random seed
3890     return;
3891   }
3892 
3893   // Scaling functions parameters
3894   pars->num_y_points = aom_rb_read_literal(rb, 4);  // max 14
3895   if (pars->num_y_points > 14)
3896     aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3897                        "Number of points for film grain luma scaling function "
3898                        "exceeds the maximum value.");
3899   for (int i = 0; i < pars->num_y_points; i++) {
3900     pars->scaling_points_y[i][0] = aom_rb_read_literal(rb, 8);
3901     if (i && pars->scaling_points_y[i - 1][0] >= pars->scaling_points_y[i][0])
3902       aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3903                          "First coordinate of the scaling function points "
3904                          "shall be increasing.");
3905     pars->scaling_points_y[i][1] = aom_rb_read_literal(rb, 8);
3906   }
3907 
3908   if (!seq_params->monochrome)
3909     pars->chroma_scaling_from_luma = aom_rb_read_bit(rb);
3910   else
3911     pars->chroma_scaling_from_luma = 0;
3912 
3913   if (seq_params->monochrome || pars->chroma_scaling_from_luma ||
3914       ((seq_params->subsampling_x == 1) && (seq_params->subsampling_y == 1) &&
3915        (pars->num_y_points == 0))) {
3916     pars->num_cb_points = 0;
3917     pars->num_cr_points = 0;
3918   } else {
3919     pars->num_cb_points = aom_rb_read_literal(rb, 4);  // max 10
3920     if (pars->num_cb_points > 10)
3921       aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3922                          "Number of points for film grain cb scaling function "
3923                          "exceeds the maximum value.");
3924     for (int i = 0; i < pars->num_cb_points; i++) {
3925       pars->scaling_points_cb[i][0] = aom_rb_read_literal(rb, 8);
3926       if (i &&
3927           pars->scaling_points_cb[i - 1][0] >= pars->scaling_points_cb[i][0])
3928         aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3929                            "First coordinate of the scaling function points "
3930                            "shall be increasing.");
3931       pars->scaling_points_cb[i][1] = aom_rb_read_literal(rb, 8);
3932     }
3933 
3934     pars->num_cr_points = aom_rb_read_literal(rb, 4);  // max 10
3935     if (pars->num_cr_points > 10)
3936       aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3937                          "Number of points for film grain cr scaling function "
3938                          "exceeds the maximum value.");
3939     for (int i = 0; i < pars->num_cr_points; i++) {
3940       pars->scaling_points_cr[i][0] = aom_rb_read_literal(rb, 8);
3941       if (i &&
3942           pars->scaling_points_cr[i - 1][0] >= pars->scaling_points_cr[i][0])
3943         aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3944                            "First coordinate of the scaling function points "
3945                            "shall be increasing.");
3946       pars->scaling_points_cr[i][1] = aom_rb_read_literal(rb, 8);
3947     }
3948 
3949     if ((seq_params->subsampling_x == 1) && (seq_params->subsampling_y == 1) &&
3950         (((pars->num_cb_points == 0) && (pars->num_cr_points != 0)) ||
3951          ((pars->num_cb_points != 0) && (pars->num_cr_points == 0))))
3952       aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
3953                          "In YCbCr 4:2:0, film grain shall be applied "
3954                          "to both chroma components or neither.");
3955   }
3956 
3957   pars->scaling_shift = aom_rb_read_literal(rb, 2) + 8;  // 8 + value
3958 
3959   // AR coefficients
3960   // Only sent if the corresponsing scaling function has
3961   // more than 0 points
3962 
3963   pars->ar_coeff_lag = aom_rb_read_literal(rb, 2);
3964 
3965   int num_pos_luma = 2 * pars->ar_coeff_lag * (pars->ar_coeff_lag + 1);
3966   int num_pos_chroma = num_pos_luma;
3967   if (pars->num_y_points > 0) ++num_pos_chroma;
3968 
3969   if (pars->num_y_points)
3970     for (int i = 0; i < num_pos_luma; i++)
3971       pars->ar_coeffs_y[i] = aom_rb_read_literal(rb, 8) - 128;
3972 
3973   if (pars->num_cb_points || pars->chroma_scaling_from_luma)
3974     for (int i = 0; i < num_pos_chroma; i++)
3975       pars->ar_coeffs_cb[i] = aom_rb_read_literal(rb, 8) - 128;
3976 
3977   if (pars->num_cr_points || pars->chroma_scaling_from_luma)
3978     for (int i = 0; i < num_pos_chroma; i++)
3979       pars->ar_coeffs_cr[i] = aom_rb_read_literal(rb, 8) - 128;
3980 
3981   pars->ar_coeff_shift = aom_rb_read_literal(rb, 2) + 6;  // 6 + value
3982 
3983   pars->grain_scale_shift = aom_rb_read_literal(rb, 2);
3984 
3985   if (pars->num_cb_points) {
3986     pars->cb_mult = aom_rb_read_literal(rb, 8);
3987     pars->cb_luma_mult = aom_rb_read_literal(rb, 8);
3988     pars->cb_offset = aom_rb_read_literal(rb, 9);
3989   }
3990 
3991   if (pars->num_cr_points) {
3992     pars->cr_mult = aom_rb_read_literal(rb, 8);
3993     pars->cr_luma_mult = aom_rb_read_literal(rb, 8);
3994     pars->cr_offset = aom_rb_read_literal(rb, 9);
3995   }
3996 
3997   pars->overlap_flag = aom_rb_read_bit(rb);
3998 
3999   pars->clip_to_restricted_range = aom_rb_read_bit(rb);
4000 }
4001 
read_film_grain(AV1_COMMON * cm,struct aom_read_bit_buffer * rb)4002 static AOM_INLINE void read_film_grain(AV1_COMMON *cm,
4003                                        struct aom_read_bit_buffer *rb) {
4004   if (cm->seq_params->film_grain_params_present &&
4005       (cm->show_frame || cm->showable_frame)) {
4006     av1_read_film_grain_params(cm, rb);
4007   } else {
4008     memset(&cm->film_grain_params, 0, sizeof(cm->film_grain_params));
4009   }
4010   cm->film_grain_params.bit_depth = cm->seq_params->bit_depth;
4011   memcpy(&cm->cur_frame->film_grain_params, &cm->film_grain_params,
4012          sizeof(aom_film_grain_t));
4013 }
4014 
av1_read_color_config(struct aom_read_bit_buffer * rb,int allow_lowbitdepth,SequenceHeader * seq_params,struct aom_internal_error_info * error_info)4015 void av1_read_color_config(struct aom_read_bit_buffer *rb,
4016                            int allow_lowbitdepth, SequenceHeader *seq_params,
4017                            struct aom_internal_error_info *error_info) {
4018   read_bitdepth(rb, seq_params, error_info);
4019 
4020   seq_params->use_highbitdepth =
4021       seq_params->bit_depth > AOM_BITS_8 || !allow_lowbitdepth;
4022   // monochrome bit (not needed for PROFILE_1)
4023   const int is_monochrome =
4024       seq_params->profile != PROFILE_1 ? aom_rb_read_bit(rb) : 0;
4025   seq_params->monochrome = is_monochrome;
4026   int color_description_present_flag = aom_rb_read_bit(rb);
4027   if (color_description_present_flag) {
4028     seq_params->color_primaries = aom_rb_read_literal(rb, 8);
4029     seq_params->transfer_characteristics = aom_rb_read_literal(rb, 8);
4030     seq_params->matrix_coefficients = aom_rb_read_literal(rb, 8);
4031   } else {
4032     seq_params->color_primaries = AOM_CICP_CP_UNSPECIFIED;
4033     seq_params->transfer_characteristics = AOM_CICP_TC_UNSPECIFIED;
4034     seq_params->matrix_coefficients = AOM_CICP_MC_UNSPECIFIED;
4035   }
4036   if (is_monochrome) {
4037     // [16,235] (including xvycc) vs [0,255] range
4038     seq_params->color_range = aom_rb_read_bit(rb);
4039     seq_params->subsampling_y = seq_params->subsampling_x = 1;
4040     seq_params->chroma_sample_position = AOM_CSP_UNKNOWN;
4041     seq_params->separate_uv_delta_q = 0;
4042     return;
4043   }
4044   if (seq_params->color_primaries == AOM_CICP_CP_BT_709 &&
4045       seq_params->transfer_characteristics == AOM_CICP_TC_SRGB &&
4046       seq_params->matrix_coefficients == AOM_CICP_MC_IDENTITY) {
4047     seq_params->subsampling_y = seq_params->subsampling_x = 0;
4048     seq_params->color_range = 1;  // assume full color-range
4049     if (!(seq_params->profile == PROFILE_1 ||
4050           (seq_params->profile == PROFILE_2 &&
4051            seq_params->bit_depth == AOM_BITS_12))) {
4052       aom_internal_error(
4053           error_info, AOM_CODEC_UNSUP_BITSTREAM,
4054           "sRGB colorspace not compatible with specified profile");
4055     }
4056   } else {
4057     // [16,235] (including xvycc) vs [0,255] range
4058     seq_params->color_range = aom_rb_read_bit(rb);
4059     if (seq_params->profile == PROFILE_0) {
4060       // 420 only
4061       seq_params->subsampling_x = seq_params->subsampling_y = 1;
4062     } else if (seq_params->profile == PROFILE_1) {
4063       // 444 only
4064       seq_params->subsampling_x = seq_params->subsampling_y = 0;
4065     } else {
4066       assert(seq_params->profile == PROFILE_2);
4067       if (seq_params->bit_depth == AOM_BITS_12) {
4068         seq_params->subsampling_x = aom_rb_read_bit(rb);
4069         if (seq_params->subsampling_x)
4070           seq_params->subsampling_y = aom_rb_read_bit(rb);  // 422 or 420
4071         else
4072           seq_params->subsampling_y = 0;  // 444
4073       } else {
4074         // 422
4075         seq_params->subsampling_x = 1;
4076         seq_params->subsampling_y = 0;
4077       }
4078     }
4079     if (seq_params->matrix_coefficients == AOM_CICP_MC_IDENTITY &&
4080         (seq_params->subsampling_x || seq_params->subsampling_y)) {
4081       aom_internal_error(
4082           error_info, AOM_CODEC_UNSUP_BITSTREAM,
4083           "Identity CICP Matrix incompatible with non 4:4:4 color sampling");
4084     }
4085     if (seq_params->subsampling_x && seq_params->subsampling_y) {
4086       seq_params->chroma_sample_position = aom_rb_read_literal(rb, 2);
4087     }
4088   }
4089   seq_params->separate_uv_delta_q = aom_rb_read_bit(rb);
4090 }
4091 
av1_read_timing_info_header(aom_timing_info_t * timing_info,struct aom_internal_error_info * error,struct aom_read_bit_buffer * rb)4092 void av1_read_timing_info_header(aom_timing_info_t *timing_info,
4093                                  struct aom_internal_error_info *error,
4094                                  struct aom_read_bit_buffer *rb) {
4095   timing_info->num_units_in_display_tick =
4096       aom_rb_read_unsigned_literal(rb,
4097                                    32);  // Number of units in a display tick
4098   timing_info->time_scale = aom_rb_read_unsigned_literal(rb, 32);  // Time scale
4099   if (timing_info->num_units_in_display_tick == 0 ||
4100       timing_info->time_scale == 0) {
4101     aom_internal_error(
4102         error, AOM_CODEC_UNSUP_BITSTREAM,
4103         "num_units_in_display_tick and time_scale must be greater than 0.");
4104   }
4105   timing_info->equal_picture_interval =
4106       aom_rb_read_bit(rb);  // Equal picture interval bit
4107   if (timing_info->equal_picture_interval) {
4108     const uint32_t num_ticks_per_picture_minus_1 = aom_rb_read_uvlc(rb);
4109     if (num_ticks_per_picture_minus_1 == UINT32_MAX) {
4110       aom_internal_error(
4111           error, AOM_CODEC_UNSUP_BITSTREAM,
4112           "num_ticks_per_picture_minus_1 cannot be (1 << 32) - 1.");
4113     }
4114     timing_info->num_ticks_per_picture = num_ticks_per_picture_minus_1 + 1;
4115   }
4116 }
4117 
av1_read_decoder_model_info(aom_dec_model_info_t * decoder_model_info,struct aom_read_bit_buffer * rb)4118 void av1_read_decoder_model_info(aom_dec_model_info_t *decoder_model_info,
4119                                  struct aom_read_bit_buffer *rb) {
4120   decoder_model_info->encoder_decoder_buffer_delay_length =
4121       aom_rb_read_literal(rb, 5) + 1;
4122   decoder_model_info->num_units_in_decoding_tick =
4123       aom_rb_read_unsigned_literal(rb,
4124                                    32);  // Number of units in a decoding tick
4125   decoder_model_info->buffer_removal_time_length =
4126       aom_rb_read_literal(rb, 5) + 1;
4127   decoder_model_info->frame_presentation_time_length =
4128       aom_rb_read_literal(rb, 5) + 1;
4129 }
4130 
av1_read_op_parameters_info(aom_dec_model_op_parameters_t * op_params,int buffer_delay_length,struct aom_read_bit_buffer * rb)4131 void av1_read_op_parameters_info(aom_dec_model_op_parameters_t *op_params,
4132                                  int buffer_delay_length,
4133                                  struct aom_read_bit_buffer *rb) {
4134   op_params->decoder_buffer_delay =
4135       aom_rb_read_unsigned_literal(rb, buffer_delay_length);
4136   op_params->encoder_buffer_delay =
4137       aom_rb_read_unsigned_literal(rb, buffer_delay_length);
4138   op_params->low_delay_mode_flag = aom_rb_read_bit(rb);
4139 }
4140 
read_temporal_point_info(AV1_COMMON * const cm,struct aom_read_bit_buffer * rb)4141 static AOM_INLINE void read_temporal_point_info(
4142     AV1_COMMON *const cm, struct aom_read_bit_buffer *rb) {
4143   cm->frame_presentation_time = aom_rb_read_unsigned_literal(
4144       rb, cm->seq_params->decoder_model_info.frame_presentation_time_length);
4145 }
4146 
av1_read_sequence_header(AV1_COMMON * cm,struct aom_read_bit_buffer * rb,SequenceHeader * seq_params)4147 void av1_read_sequence_header(AV1_COMMON *cm, struct aom_read_bit_buffer *rb,
4148                               SequenceHeader *seq_params) {
4149   const int num_bits_width = aom_rb_read_literal(rb, 4) + 1;
4150   const int num_bits_height = aom_rb_read_literal(rb, 4) + 1;
4151   const int max_frame_width = aom_rb_read_literal(rb, num_bits_width) + 1;
4152   const int max_frame_height = aom_rb_read_literal(rb, num_bits_height) + 1;
4153 
4154   seq_params->num_bits_width = num_bits_width;
4155   seq_params->num_bits_height = num_bits_height;
4156   seq_params->max_frame_width = max_frame_width;
4157   seq_params->max_frame_height = max_frame_height;
4158 
4159   if (seq_params->reduced_still_picture_hdr) {
4160     seq_params->frame_id_numbers_present_flag = 0;
4161   } else {
4162     seq_params->frame_id_numbers_present_flag = aom_rb_read_bit(rb);
4163   }
4164   if (seq_params->frame_id_numbers_present_flag) {
4165     // We must always have delta_frame_id_length < frame_id_length,
4166     // in order for a frame to be referenced with a unique delta.
4167     // Avoid wasting bits by using a coding that enforces this restriction.
4168     seq_params->delta_frame_id_length = aom_rb_read_literal(rb, 4) + 2;
4169     seq_params->frame_id_length =
4170         aom_rb_read_literal(rb, 3) + seq_params->delta_frame_id_length + 1;
4171     if (seq_params->frame_id_length > 16)
4172       aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
4173                          "Invalid frame_id_length");
4174   }
4175 
4176   setup_sb_size(seq_params, rb);
4177 
4178   seq_params->enable_filter_intra = aom_rb_read_bit(rb);
4179   seq_params->enable_intra_edge_filter = aom_rb_read_bit(rb);
4180 
4181   if (seq_params->reduced_still_picture_hdr) {
4182     seq_params->enable_interintra_compound = 0;
4183     seq_params->enable_masked_compound = 0;
4184     seq_params->enable_warped_motion = 0;
4185     seq_params->enable_dual_filter = 0;
4186     seq_params->order_hint_info.enable_order_hint = 0;
4187     seq_params->order_hint_info.enable_dist_wtd_comp = 0;
4188     seq_params->order_hint_info.enable_ref_frame_mvs = 0;
4189     seq_params->force_screen_content_tools = 2;  // SELECT_SCREEN_CONTENT_TOOLS
4190     seq_params->force_integer_mv = 2;            // SELECT_INTEGER_MV
4191     seq_params->order_hint_info.order_hint_bits_minus_1 = -1;
4192   } else {
4193     seq_params->enable_interintra_compound = aom_rb_read_bit(rb);
4194     seq_params->enable_masked_compound = aom_rb_read_bit(rb);
4195     seq_params->enable_warped_motion = aom_rb_read_bit(rb);
4196     seq_params->enable_dual_filter = aom_rb_read_bit(rb);
4197 
4198     seq_params->order_hint_info.enable_order_hint = aom_rb_read_bit(rb);
4199     seq_params->order_hint_info.enable_dist_wtd_comp =
4200         seq_params->order_hint_info.enable_order_hint ? aom_rb_read_bit(rb) : 0;
4201     seq_params->order_hint_info.enable_ref_frame_mvs =
4202         seq_params->order_hint_info.enable_order_hint ? aom_rb_read_bit(rb) : 0;
4203 
4204     if (aom_rb_read_bit(rb)) {
4205       seq_params->force_screen_content_tools =
4206           2;  // SELECT_SCREEN_CONTENT_TOOLS
4207     } else {
4208       seq_params->force_screen_content_tools = aom_rb_read_bit(rb);
4209     }
4210 
4211     if (seq_params->force_screen_content_tools > 0) {
4212       if (aom_rb_read_bit(rb)) {
4213         seq_params->force_integer_mv = 2;  // SELECT_INTEGER_MV
4214       } else {
4215         seq_params->force_integer_mv = aom_rb_read_bit(rb);
4216       }
4217     } else {
4218       seq_params->force_integer_mv = 2;  // SELECT_INTEGER_MV
4219     }
4220     seq_params->order_hint_info.order_hint_bits_minus_1 =
4221         seq_params->order_hint_info.enable_order_hint
4222             ? aom_rb_read_literal(rb, 3)
4223             : -1;
4224   }
4225 
4226   seq_params->enable_superres = aom_rb_read_bit(rb);
4227   seq_params->enable_cdef = aom_rb_read_bit(rb);
4228   seq_params->enable_restoration = aom_rb_read_bit(rb);
4229 }
4230 
read_global_motion_params(WarpedMotionParams * params,const WarpedMotionParams * ref_params,struct aom_read_bit_buffer * rb,int allow_hp)4231 static int read_global_motion_params(WarpedMotionParams *params,
4232                                      const WarpedMotionParams *ref_params,
4233                                      struct aom_read_bit_buffer *rb,
4234                                      int allow_hp) {
4235   TransformationType type = aom_rb_read_bit(rb);
4236   if (type != IDENTITY) {
4237     if (aom_rb_read_bit(rb))
4238       type = ROTZOOM;
4239     else
4240       type = aom_rb_read_bit(rb) ? TRANSLATION : AFFINE;
4241   }
4242 
4243   *params = default_warp_params;
4244   params->wmtype = type;
4245 
4246   if (type >= ROTZOOM) {
4247     params->wmmat[2] = aom_rb_read_signed_primitive_refsubexpfin(
4248                            rb, GM_ALPHA_MAX + 1, SUBEXPFIN_K,
4249                            (ref_params->wmmat[2] >> GM_ALPHA_PREC_DIFF) -
4250                                (1 << GM_ALPHA_PREC_BITS)) *
4251                            GM_ALPHA_DECODE_FACTOR +
4252                        (1 << WARPEDMODEL_PREC_BITS);
4253     params->wmmat[3] = aom_rb_read_signed_primitive_refsubexpfin(
4254                            rb, GM_ALPHA_MAX + 1, SUBEXPFIN_K,
4255                            (ref_params->wmmat[3] >> GM_ALPHA_PREC_DIFF)) *
4256                        GM_ALPHA_DECODE_FACTOR;
4257   }
4258 
4259   if (type >= AFFINE) {
4260     params->wmmat[4] = aom_rb_read_signed_primitive_refsubexpfin(
4261                            rb, GM_ALPHA_MAX + 1, SUBEXPFIN_K,
4262                            (ref_params->wmmat[4] >> GM_ALPHA_PREC_DIFF)) *
4263                        GM_ALPHA_DECODE_FACTOR;
4264     params->wmmat[5] = aom_rb_read_signed_primitive_refsubexpfin(
4265                            rb, GM_ALPHA_MAX + 1, SUBEXPFIN_K,
4266                            (ref_params->wmmat[5] >> GM_ALPHA_PREC_DIFF) -
4267                                (1 << GM_ALPHA_PREC_BITS)) *
4268                            GM_ALPHA_DECODE_FACTOR +
4269                        (1 << WARPEDMODEL_PREC_BITS);
4270   } else {
4271     params->wmmat[4] = -params->wmmat[3];
4272     params->wmmat[5] = params->wmmat[2];
4273   }
4274 
4275   if (type >= TRANSLATION) {
4276     const int trans_bits = (type == TRANSLATION)
4277                                ? GM_ABS_TRANS_ONLY_BITS - !allow_hp
4278                                : GM_ABS_TRANS_BITS;
4279     const int trans_dec_factor =
4280         (type == TRANSLATION) ? GM_TRANS_ONLY_DECODE_FACTOR * (1 << !allow_hp)
4281                               : GM_TRANS_DECODE_FACTOR;
4282     const int trans_prec_diff = (type == TRANSLATION)
4283                                     ? GM_TRANS_ONLY_PREC_DIFF + !allow_hp
4284                                     : GM_TRANS_PREC_DIFF;
4285     params->wmmat[0] = aom_rb_read_signed_primitive_refsubexpfin(
4286                            rb, (1 << trans_bits) + 1, SUBEXPFIN_K,
4287                            (ref_params->wmmat[0] >> trans_prec_diff)) *
4288                        trans_dec_factor;
4289     params->wmmat[1] = aom_rb_read_signed_primitive_refsubexpfin(
4290                            rb, (1 << trans_bits) + 1, SUBEXPFIN_K,
4291                            (ref_params->wmmat[1] >> trans_prec_diff)) *
4292                        trans_dec_factor;
4293   }
4294 
4295 #if !CONFIG_REALTIME_ONLY
4296   // For realtime only build, warped motion is disabled, so this section is not
4297   // needed.
4298   if (params->wmtype <= AFFINE) {
4299     int good_shear_params = av1_get_shear_params(params);
4300     if (!good_shear_params) return 0;
4301   }
4302 #endif
4303 
4304   return 1;
4305 }
4306 
read_global_motion(AV1_COMMON * cm,struct aom_read_bit_buffer * rb)4307 static AOM_INLINE void read_global_motion(AV1_COMMON *cm,
4308                                           struct aom_read_bit_buffer *rb) {
4309   for (int frame = LAST_FRAME; frame <= ALTREF_FRAME; ++frame) {
4310     const WarpedMotionParams *ref_params =
4311         cm->prev_frame ? &cm->prev_frame->global_motion[frame]
4312                        : &default_warp_params;
4313     int good_params =
4314         read_global_motion_params(&cm->global_motion[frame], ref_params, rb,
4315                                   cm->features.allow_high_precision_mv);
4316     if (!good_params) {
4317 #if WARPED_MOTION_DEBUG
4318       printf("Warning: unexpected global motion shear params from aomenc\n");
4319 #endif
4320       cm->global_motion[frame].invalid = 1;
4321     }
4322 
4323     // TODO(sarahparker, debargha): The logic in the commented out code below
4324     // does not work currently and causes mismatches when resize is on. Fix it
4325     // before turning the optimization back on.
4326     /*
4327     YV12_BUFFER_CONFIG *ref_buf = get_ref_frame(cm, frame);
4328     if (cm->width == ref_buf->y_crop_width &&
4329         cm->height == ref_buf->y_crop_height) {
4330       read_global_motion_params(&cm->global_motion[frame],
4331                                 &cm->prev_frame->global_motion[frame], rb,
4332                                 cm->features.allow_high_precision_mv);
4333     } else {
4334       cm->global_motion[frame] = default_warp_params;
4335     }
4336     */
4337     /*
4338     printf("Dec Ref %d [%d/%d]: %d %d %d %d\n",
4339            frame, cm->current_frame.frame_number, cm->show_frame,
4340            cm->global_motion[frame].wmmat[0],
4341            cm->global_motion[frame].wmmat[1],
4342            cm->global_motion[frame].wmmat[2],
4343            cm->global_motion[frame].wmmat[3]);
4344            */
4345   }
4346   memcpy(cm->cur_frame->global_motion, cm->global_motion,
4347          REF_FRAMES * sizeof(WarpedMotionParams));
4348 }
4349 
4350 // Release the references to the frame buffers in cm->ref_frame_map and reset
4351 // all elements of cm->ref_frame_map to NULL.
reset_ref_frame_map(AV1_COMMON * const cm)4352 static AOM_INLINE void reset_ref_frame_map(AV1_COMMON *const cm) {
4353   BufferPool *const pool = cm->buffer_pool;
4354 
4355   for (int i = 0; i < REF_FRAMES; i++) {
4356     decrease_ref_count(cm->ref_frame_map[i], pool);
4357     cm->ref_frame_map[i] = NULL;
4358   }
4359 }
4360 
4361 // If the refresh_frame_flags bitmask is set, update reference frame id values
4362 // and mark frames as valid for reference.
update_ref_frame_id(AV1Decoder * const pbi)4363 static AOM_INLINE void update_ref_frame_id(AV1Decoder *const pbi) {
4364   AV1_COMMON *const cm = &pbi->common;
4365   int refresh_frame_flags = cm->current_frame.refresh_frame_flags;
4366   for (int i = 0; i < REF_FRAMES; i++) {
4367     if ((refresh_frame_flags >> i) & 1) {
4368       cm->ref_frame_id[i] = cm->current_frame_id;
4369       pbi->valid_for_referencing[i] = 1;
4370     }
4371   }
4372 }
4373 
show_existing_frame_reset(AV1Decoder * const pbi,int existing_frame_idx)4374 static AOM_INLINE void show_existing_frame_reset(AV1Decoder *const pbi,
4375                                                  int existing_frame_idx) {
4376   AV1_COMMON *const cm = &pbi->common;
4377 
4378   assert(cm->show_existing_frame);
4379 
4380   cm->current_frame.frame_type = KEY_FRAME;
4381 
4382   cm->current_frame.refresh_frame_flags = (1 << REF_FRAMES) - 1;
4383 
4384   for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
4385     cm->remapped_ref_idx[i] = INVALID_IDX;
4386   }
4387 
4388   if (pbi->need_resync) {
4389     reset_ref_frame_map(cm);
4390     pbi->need_resync = 0;
4391   }
4392 
4393   // Note that the displayed frame must be valid for referencing in order to
4394   // have been selected.
4395   cm->current_frame_id = cm->ref_frame_id[existing_frame_idx];
4396   update_ref_frame_id(pbi);
4397 
4398   cm->features.refresh_frame_context = REFRESH_FRAME_CONTEXT_DISABLED;
4399 }
4400 
reset_frame_buffers(AV1_COMMON * cm)4401 static INLINE void reset_frame_buffers(AV1_COMMON *cm) {
4402   RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
4403   int i;
4404 
4405   lock_buffer_pool(cm->buffer_pool);
4406   reset_ref_frame_map(cm);
4407   assert(cm->cur_frame->ref_count == 1);
4408   for (i = 0; i < FRAME_BUFFERS; ++i) {
4409     // Reset all unreferenced frame buffers. We can also reset cm->cur_frame
4410     // because we are the sole owner of cm->cur_frame.
4411     if (frame_bufs[i].ref_count > 0 && &frame_bufs[i] != cm->cur_frame) {
4412       continue;
4413     }
4414     frame_bufs[i].order_hint = 0;
4415     av1_zero(frame_bufs[i].ref_order_hints);
4416   }
4417   av1_zero_unused_internal_frame_buffers(&cm->buffer_pool->int_frame_buffers);
4418   unlock_buffer_pool(cm->buffer_pool);
4419 }
4420 
4421 // On success, returns 0. On failure, calls aom_internal_error and does not
4422 // return.
read_uncompressed_header(AV1Decoder * pbi,struct aom_read_bit_buffer * rb)4423 static int read_uncompressed_header(AV1Decoder *pbi,
4424                                     struct aom_read_bit_buffer *rb) {
4425   AV1_COMMON *const cm = &pbi->common;
4426   const SequenceHeader *const seq_params = cm->seq_params;
4427   CurrentFrame *const current_frame = &cm->current_frame;
4428   FeatureFlags *const features = &cm->features;
4429   MACROBLOCKD *const xd = &pbi->dcb.xd;
4430   BufferPool *const pool = cm->buffer_pool;
4431   RefCntBuffer *const frame_bufs = pool->frame_bufs;
4432   aom_s_frame_info *sframe_info = &pbi->sframe_info;
4433   sframe_info->is_s_frame = 0;
4434   sframe_info->is_s_frame_at_altref = 0;
4435 
4436   if (!pbi->sequence_header_ready) {
4437     aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4438                        "No sequence header");
4439   }
4440 
4441   if (seq_params->reduced_still_picture_hdr) {
4442     cm->show_existing_frame = 0;
4443     cm->show_frame = 1;
4444     current_frame->frame_type = KEY_FRAME;
4445     if (pbi->sequence_header_changed) {
4446       // This is the start of a new coded video sequence.
4447       pbi->sequence_header_changed = 0;
4448       pbi->decoding_first_frame = 1;
4449       reset_frame_buffers(cm);
4450     }
4451     features->error_resilient_mode = 1;
4452   } else {
4453     cm->show_existing_frame = aom_rb_read_bit(rb);
4454     pbi->reset_decoder_state = 0;
4455 
4456     if (cm->show_existing_frame) {
4457       if (pbi->sequence_header_changed) {
4458         aom_internal_error(
4459             &pbi->error, AOM_CODEC_CORRUPT_FRAME,
4460             "New sequence header starts with a show_existing_frame.");
4461       }
4462       // Show an existing frame directly.
4463       const int existing_frame_idx = aom_rb_read_literal(rb, 3);
4464       RefCntBuffer *const frame_to_show = cm->ref_frame_map[existing_frame_idx];
4465       if (frame_to_show == NULL) {
4466         aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
4467                            "Buffer does not contain a decoded frame");
4468       }
4469       if (seq_params->decoder_model_info_present_flag &&
4470           seq_params->timing_info.equal_picture_interval == 0) {
4471         read_temporal_point_info(cm, rb);
4472       }
4473       if (seq_params->frame_id_numbers_present_flag) {
4474         int frame_id_length = seq_params->frame_id_length;
4475         int display_frame_id = aom_rb_read_literal(rb, frame_id_length);
4476         /* Compare display_frame_id with ref_frame_id and check valid for
4477          * referencing */
4478         if (display_frame_id != cm->ref_frame_id[existing_frame_idx] ||
4479             pbi->valid_for_referencing[existing_frame_idx] == 0)
4480           aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4481                              "Reference buffer frame ID mismatch");
4482       }
4483       lock_buffer_pool(pool);
4484       assert(frame_to_show->ref_count > 0);
4485       // cm->cur_frame should be the buffer referenced by the return value
4486       // of the get_free_fb() call in assign_cur_frame_new_fb() (called by
4487       // av1_receive_compressed_data()), so the ref_count should be 1.
4488       assert(cm->cur_frame->ref_count == 1);
4489       // assign_frame_buffer_p() decrements ref_count directly rather than
4490       // call decrease_ref_count(). If cm->cur_frame->raw_frame_buffer has
4491       // already been allocated, it will not be released by
4492       // assign_frame_buffer_p()!
4493       assert(!cm->cur_frame->raw_frame_buffer.data);
4494       assign_frame_buffer_p(&cm->cur_frame, frame_to_show);
4495       pbi->reset_decoder_state = frame_to_show->frame_type == KEY_FRAME;
4496       unlock_buffer_pool(pool);
4497 
4498       cm->lf.filter_level[0] = 0;
4499       cm->lf.filter_level[1] = 0;
4500       cm->show_frame = 1;
4501       current_frame->order_hint = frame_to_show->order_hint;
4502 
4503       // Section 6.8.2: It is a requirement of bitstream conformance that when
4504       // show_existing_frame is used to show a previous frame, that the value
4505       // of showable_frame for the previous frame was equal to 1.
4506       if (!frame_to_show->showable_frame) {
4507         aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
4508                            "Buffer does not contain a showable frame");
4509       }
4510       // Section 6.8.2: It is a requirement of bitstream conformance that when
4511       // show_existing_frame is used to show a previous frame with
4512       // RefFrameType[ frame_to_show_map_idx ] equal to KEY_FRAME, that the
4513       // frame is output via the show_existing_frame mechanism at most once.
4514       if (pbi->reset_decoder_state) frame_to_show->showable_frame = 0;
4515 
4516       cm->film_grain_params = frame_to_show->film_grain_params;
4517 
4518       if (pbi->reset_decoder_state) {
4519         show_existing_frame_reset(pbi, existing_frame_idx);
4520       } else {
4521         current_frame->refresh_frame_flags = 0;
4522       }
4523 
4524       return 0;
4525     }
4526 
4527     current_frame->frame_type = (FRAME_TYPE)aom_rb_read_literal(rb, 2);
4528     if (pbi->sequence_header_changed) {
4529       if (current_frame->frame_type == KEY_FRAME) {
4530         // This is the start of a new coded video sequence.
4531         pbi->sequence_header_changed = 0;
4532         pbi->decoding_first_frame = 1;
4533         reset_frame_buffers(cm);
4534       } else {
4535         aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4536                            "Sequence header has changed without a keyframe.");
4537       }
4538     }
4539 
4540     cm->show_frame = aom_rb_read_bit(rb);
4541     if (cm->show_frame == 0) pbi->is_arf_frame_present = 1;
4542     if (cm->show_frame == 0 && cm->current_frame.frame_type == KEY_FRAME)
4543       pbi->is_fwd_kf_present = 1;
4544     if (cm->current_frame.frame_type == S_FRAME) {
4545       sframe_info->is_s_frame = 1;
4546       sframe_info->is_s_frame_at_altref = cm->show_frame ? 0 : 1;
4547     }
4548     if (seq_params->still_picture &&
4549         (current_frame->frame_type != KEY_FRAME || !cm->show_frame)) {
4550       aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4551                          "Still pictures must be coded as shown keyframes");
4552     }
4553     cm->showable_frame = current_frame->frame_type != KEY_FRAME;
4554     if (cm->show_frame) {
4555       if (seq_params->decoder_model_info_present_flag &&
4556           seq_params->timing_info.equal_picture_interval == 0)
4557         read_temporal_point_info(cm, rb);
4558     } else {
4559       // See if this frame can be used as show_existing_frame in future
4560       cm->showable_frame = aom_rb_read_bit(rb);
4561     }
4562     cm->cur_frame->showable_frame = cm->showable_frame;
4563     features->error_resilient_mode =
4564         frame_is_sframe(cm) ||
4565                 (current_frame->frame_type == KEY_FRAME && cm->show_frame)
4566             ? 1
4567             : aom_rb_read_bit(rb);
4568   }
4569 
4570   if (current_frame->frame_type == KEY_FRAME && cm->show_frame) {
4571     /* All frames need to be marked as not valid for referencing */
4572     for (int i = 0; i < REF_FRAMES; i++) {
4573       pbi->valid_for_referencing[i] = 0;
4574     }
4575   }
4576   features->disable_cdf_update = aom_rb_read_bit(rb);
4577   if (seq_params->force_screen_content_tools == 2) {
4578     features->allow_screen_content_tools = aom_rb_read_bit(rb);
4579   } else {
4580     features->allow_screen_content_tools =
4581         seq_params->force_screen_content_tools;
4582   }
4583 
4584   if (features->allow_screen_content_tools) {
4585     if (seq_params->force_integer_mv == 2) {
4586       features->cur_frame_force_integer_mv = aom_rb_read_bit(rb);
4587     } else {
4588       features->cur_frame_force_integer_mv = seq_params->force_integer_mv;
4589     }
4590   } else {
4591     features->cur_frame_force_integer_mv = 0;
4592   }
4593 
4594   int frame_size_override_flag = 0;
4595   features->allow_intrabc = 0;
4596   features->primary_ref_frame = PRIMARY_REF_NONE;
4597 
4598   if (!seq_params->reduced_still_picture_hdr) {
4599     if (seq_params->frame_id_numbers_present_flag) {
4600       int frame_id_length = seq_params->frame_id_length;
4601       int diff_len = seq_params->delta_frame_id_length;
4602       int prev_frame_id = 0;
4603       int have_prev_frame_id =
4604           !pbi->decoding_first_frame &&
4605           !(current_frame->frame_type == KEY_FRAME && cm->show_frame);
4606       if (have_prev_frame_id) {
4607         prev_frame_id = cm->current_frame_id;
4608       }
4609       cm->current_frame_id = aom_rb_read_literal(rb, frame_id_length);
4610 
4611       if (have_prev_frame_id) {
4612         int diff_frame_id;
4613         if (cm->current_frame_id > prev_frame_id) {
4614           diff_frame_id = cm->current_frame_id - prev_frame_id;
4615         } else {
4616           diff_frame_id =
4617               (1 << frame_id_length) + cm->current_frame_id - prev_frame_id;
4618         }
4619         /* Check current_frame_id for conformance */
4620         if (prev_frame_id == cm->current_frame_id ||
4621             diff_frame_id >= (1 << (frame_id_length - 1))) {
4622           aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4623                              "Invalid value of current_frame_id");
4624         }
4625       }
4626       /* Check if some frames need to be marked as not valid for referencing */
4627       for (int i = 0; i < REF_FRAMES; i++) {
4628         if (cm->current_frame_id - (1 << diff_len) > 0) {
4629           if (cm->ref_frame_id[i] > cm->current_frame_id ||
4630               cm->ref_frame_id[i] < cm->current_frame_id - (1 << diff_len))
4631             pbi->valid_for_referencing[i] = 0;
4632         } else {
4633           if (cm->ref_frame_id[i] > cm->current_frame_id &&
4634               cm->ref_frame_id[i] < (1 << frame_id_length) +
4635                                         cm->current_frame_id - (1 << diff_len))
4636             pbi->valid_for_referencing[i] = 0;
4637         }
4638       }
4639     }
4640 
4641     frame_size_override_flag = frame_is_sframe(cm) ? 1 : aom_rb_read_bit(rb);
4642 
4643     current_frame->order_hint = aom_rb_read_literal(
4644         rb, seq_params->order_hint_info.order_hint_bits_minus_1 + 1);
4645     current_frame->frame_number = current_frame->order_hint;
4646 
4647     if (!features->error_resilient_mode && !frame_is_intra_only(cm)) {
4648       features->primary_ref_frame = aom_rb_read_literal(rb, PRIMARY_REF_BITS);
4649     }
4650   }
4651 
4652   if (seq_params->decoder_model_info_present_flag) {
4653     pbi->buffer_removal_time_present = aom_rb_read_bit(rb);
4654     if (pbi->buffer_removal_time_present) {
4655       for (int op_num = 0;
4656            op_num < seq_params->operating_points_cnt_minus_1 + 1; op_num++) {
4657         if (seq_params->op_params[op_num].decoder_model_param_present_flag) {
4658           if (seq_params->operating_point_idc[op_num] == 0 ||
4659               (((seq_params->operating_point_idc[op_num] >>
4660                  cm->temporal_layer_id) &
4661                 0x1) &&
4662                ((seq_params->operating_point_idc[op_num] >>
4663                  (cm->spatial_layer_id + 8)) &
4664                 0x1))) {
4665             cm->buffer_removal_times[op_num] = aom_rb_read_unsigned_literal(
4666                 rb, seq_params->decoder_model_info.buffer_removal_time_length);
4667           } else {
4668             cm->buffer_removal_times[op_num] = 0;
4669           }
4670         } else {
4671           cm->buffer_removal_times[op_num] = 0;
4672         }
4673       }
4674     }
4675   }
4676   if (current_frame->frame_type == KEY_FRAME) {
4677     if (!cm->show_frame) {  // unshown keyframe (forward keyframe)
4678       current_frame->refresh_frame_flags = aom_rb_read_literal(rb, REF_FRAMES);
4679     } else {  // shown keyframe
4680       current_frame->refresh_frame_flags = (1 << REF_FRAMES) - 1;
4681     }
4682 
4683     for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
4684       cm->remapped_ref_idx[i] = INVALID_IDX;
4685     }
4686     if (pbi->need_resync) {
4687       reset_ref_frame_map(cm);
4688       pbi->need_resync = 0;
4689     }
4690   } else {
4691     if (current_frame->frame_type == INTRA_ONLY_FRAME) {
4692       current_frame->refresh_frame_flags = aom_rb_read_literal(rb, REF_FRAMES);
4693       if (current_frame->refresh_frame_flags == 0xFF) {
4694         aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
4695                            "Intra only frames cannot have refresh flags 0xFF");
4696       }
4697       if (pbi->need_resync) {
4698         reset_ref_frame_map(cm);
4699         pbi->need_resync = 0;
4700       }
4701     } else if (pbi->need_resync != 1) { /* Skip if need resync */
4702       current_frame->refresh_frame_flags =
4703           frame_is_sframe(cm) ? 0xFF : aom_rb_read_literal(rb, REF_FRAMES);
4704     }
4705   }
4706 
4707   if (!frame_is_intra_only(cm) || current_frame->refresh_frame_flags != 0xFF) {
4708     // Read all ref frame order hints if error_resilient_mode == 1
4709     if (features->error_resilient_mode &&
4710         seq_params->order_hint_info.enable_order_hint) {
4711       for (int ref_idx = 0; ref_idx < REF_FRAMES; ref_idx++) {
4712         // Read order hint from bit stream
4713         unsigned int order_hint = aom_rb_read_literal(
4714             rb, seq_params->order_hint_info.order_hint_bits_minus_1 + 1);
4715         // Get buffer
4716         RefCntBuffer *buf = cm->ref_frame_map[ref_idx];
4717         if (buf == NULL || order_hint != buf->order_hint) {
4718           if (buf != NULL) {
4719             lock_buffer_pool(pool);
4720             decrease_ref_count(buf, pool);
4721             unlock_buffer_pool(pool);
4722             cm->ref_frame_map[ref_idx] = NULL;
4723           }
4724           // If no corresponding buffer exists, allocate a new buffer with all
4725           // pixels set to neutral grey.
4726           int buf_idx = get_free_fb(cm);
4727           if (buf_idx == INVALID_IDX) {
4728             aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
4729                                "Unable to find free frame buffer");
4730           }
4731           buf = &frame_bufs[buf_idx];
4732           lock_buffer_pool(pool);
4733           if (aom_realloc_frame_buffer(
4734                   &buf->buf, seq_params->max_frame_width,
4735                   seq_params->max_frame_height, seq_params->subsampling_x,
4736                   seq_params->subsampling_y, seq_params->use_highbitdepth,
4737                   AOM_BORDER_IN_PIXELS, features->byte_alignment,
4738                   &buf->raw_frame_buffer, pool->get_fb_cb, pool->cb_priv, 0)) {
4739             decrease_ref_count(buf, pool);
4740             unlock_buffer_pool(pool);
4741             aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
4742                                "Failed to allocate frame buffer");
4743           }
4744           unlock_buffer_pool(pool);
4745           // According to the specification, valid bitstreams are required to
4746           // never use missing reference frames so the filling process for
4747           // missing frames is not normatively defined and RefValid for missing
4748           // frames is set to 0.
4749 
4750           // To make libaom more robust when the bitstream has been corrupted
4751           // by the loss of some frames of data, this code adds a neutral grey
4752           // buffer in place of missing frames, i.e.
4753           //
4754           set_planes_to_neutral_grey(seq_params, &buf->buf, 0);
4755           //
4756           // and allows the frames to be used for referencing, i.e.
4757           //
4758           pbi->valid_for_referencing[ref_idx] = 1;
4759           //
4760           // Please note such behavior is not normative and other decoders may
4761           // use a different approach.
4762           cm->ref_frame_map[ref_idx] = buf;
4763           buf->order_hint = order_hint;
4764         }
4765       }
4766     }
4767   }
4768 
4769   if (current_frame->frame_type == KEY_FRAME) {
4770     setup_frame_size(cm, frame_size_override_flag, rb);
4771 
4772     if (features->allow_screen_content_tools && !av1_superres_scaled(cm))
4773       features->allow_intrabc = aom_rb_read_bit(rb);
4774     features->allow_ref_frame_mvs = 0;
4775     cm->prev_frame = NULL;
4776   } else {
4777     features->allow_ref_frame_mvs = 0;
4778 
4779     if (current_frame->frame_type == INTRA_ONLY_FRAME) {
4780       cm->cur_frame->film_grain_params_present =
4781           seq_params->film_grain_params_present;
4782       setup_frame_size(cm, frame_size_override_flag, rb);
4783       if (features->allow_screen_content_tools && !av1_superres_scaled(cm))
4784         features->allow_intrabc = aom_rb_read_bit(rb);
4785 
4786     } else if (pbi->need_resync != 1) { /* Skip if need resync */
4787       int frame_refs_short_signaling = 0;
4788       // Frame refs short signaling is off when error resilient mode is on.
4789       if (seq_params->order_hint_info.enable_order_hint)
4790         frame_refs_short_signaling = aom_rb_read_bit(rb);
4791 
4792       if (frame_refs_short_signaling) {
4793         // == LAST_FRAME ==
4794         const int lst_ref = aom_rb_read_literal(rb, REF_FRAMES_LOG2);
4795         const RefCntBuffer *const lst_buf = cm->ref_frame_map[lst_ref];
4796 
4797         // == GOLDEN_FRAME ==
4798         const int gld_ref = aom_rb_read_literal(rb, REF_FRAMES_LOG2);
4799         const RefCntBuffer *const gld_buf = cm->ref_frame_map[gld_ref];
4800 
4801         // Most of the time, streams start with a keyframe. In that case,
4802         // ref_frame_map will have been filled in at that point and will not
4803         // contain any NULLs. However, streams are explicitly allowed to start
4804         // with an intra-only frame, so long as they don't then signal a
4805         // reference to a slot that hasn't been set yet. That's what we are
4806         // checking here.
4807         if (lst_buf == NULL)
4808           aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4809                              "Inter frame requests nonexistent reference");
4810         if (gld_buf == NULL)
4811           aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4812                              "Inter frame requests nonexistent reference");
4813 
4814         av1_set_frame_refs(cm, cm->remapped_ref_idx, lst_ref, gld_ref);
4815       }
4816 
4817       for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
4818         int ref = 0;
4819         if (!frame_refs_short_signaling) {
4820           ref = aom_rb_read_literal(rb, REF_FRAMES_LOG2);
4821 
4822           // Most of the time, streams start with a keyframe. In that case,
4823           // ref_frame_map will have been filled in at that point and will not
4824           // contain any NULLs. However, streams are explicitly allowed to start
4825           // with an intra-only frame, so long as they don't then signal a
4826           // reference to a slot that hasn't been set yet. That's what we are
4827           // checking here.
4828           if (cm->ref_frame_map[ref] == NULL)
4829             aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4830                                "Inter frame requests nonexistent reference");
4831           cm->remapped_ref_idx[i] = ref;
4832         } else {
4833           ref = cm->remapped_ref_idx[i];
4834         }
4835         // Check valid for referencing
4836         if (pbi->valid_for_referencing[ref] == 0)
4837           aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4838                              "Reference frame not valid for referencing");
4839 
4840         cm->ref_frame_sign_bias[LAST_FRAME + i] = 0;
4841 
4842         if (seq_params->frame_id_numbers_present_flag) {
4843           int frame_id_length = seq_params->frame_id_length;
4844           int diff_len = seq_params->delta_frame_id_length;
4845           int delta_frame_id_minus_1 = aom_rb_read_literal(rb, diff_len);
4846           int ref_frame_id =
4847               ((cm->current_frame_id - (delta_frame_id_minus_1 + 1) +
4848                 (1 << frame_id_length)) %
4849                (1 << frame_id_length));
4850           // Compare values derived from delta_frame_id_minus_1 and
4851           // refresh_frame_flags.
4852           if (ref_frame_id != cm->ref_frame_id[ref])
4853             aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4854                                "Reference buffer frame ID mismatch");
4855         }
4856       }
4857 
4858       if (!features->error_resilient_mode && frame_size_override_flag) {
4859         setup_frame_size_with_refs(cm, rb);
4860       } else {
4861         setup_frame_size(cm, frame_size_override_flag, rb);
4862       }
4863 
4864       if (features->cur_frame_force_integer_mv) {
4865         features->allow_high_precision_mv = 0;
4866       } else {
4867         features->allow_high_precision_mv = aom_rb_read_bit(rb);
4868       }
4869       features->interp_filter = read_frame_interp_filter(rb);
4870       features->switchable_motion_mode = aom_rb_read_bit(rb);
4871     }
4872 
4873     cm->prev_frame = get_primary_ref_frame_buf(cm);
4874     if (features->primary_ref_frame != PRIMARY_REF_NONE &&
4875         get_primary_ref_frame_buf(cm) == NULL) {
4876       aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4877                          "Reference frame containing this frame's initial "
4878                          "frame context is unavailable.");
4879     }
4880 
4881     if (!(current_frame->frame_type == INTRA_ONLY_FRAME) &&
4882         pbi->need_resync != 1) {
4883       if (frame_might_allow_ref_frame_mvs(cm))
4884         features->allow_ref_frame_mvs = aom_rb_read_bit(rb);
4885       else
4886         features->allow_ref_frame_mvs = 0;
4887 
4888       for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
4889         const RefCntBuffer *const ref_buf = get_ref_frame_buf(cm, i);
4890         struct scale_factors *const ref_scale_factors =
4891             get_ref_scale_factors(cm, i);
4892         av1_setup_scale_factors_for_frame(
4893             ref_scale_factors, ref_buf->buf.y_crop_width,
4894             ref_buf->buf.y_crop_height, cm->width, cm->height);
4895         if ((!av1_is_valid_scale(ref_scale_factors)))
4896           aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
4897                              "Reference frame has invalid dimensions");
4898       }
4899     }
4900   }
4901 
4902   av1_setup_frame_buf_refs(cm);
4903 
4904   av1_setup_frame_sign_bias(cm);
4905 
4906   cm->cur_frame->frame_type = current_frame->frame_type;
4907 
4908   update_ref_frame_id(pbi);
4909 
4910   const int might_bwd_adapt = !(seq_params->reduced_still_picture_hdr) &&
4911                               !(features->disable_cdf_update);
4912   if (might_bwd_adapt) {
4913     features->refresh_frame_context = aom_rb_read_bit(rb)
4914                                           ? REFRESH_FRAME_CONTEXT_DISABLED
4915                                           : REFRESH_FRAME_CONTEXT_BACKWARD;
4916   } else {
4917     features->refresh_frame_context = REFRESH_FRAME_CONTEXT_DISABLED;
4918   }
4919 
4920   cm->cur_frame->buf.bit_depth = seq_params->bit_depth;
4921   cm->cur_frame->buf.color_primaries = seq_params->color_primaries;
4922   cm->cur_frame->buf.transfer_characteristics =
4923       seq_params->transfer_characteristics;
4924   cm->cur_frame->buf.matrix_coefficients = seq_params->matrix_coefficients;
4925   cm->cur_frame->buf.monochrome = seq_params->monochrome;
4926   cm->cur_frame->buf.chroma_sample_position =
4927       seq_params->chroma_sample_position;
4928   cm->cur_frame->buf.color_range = seq_params->color_range;
4929   cm->cur_frame->buf.render_width = cm->render_width;
4930   cm->cur_frame->buf.render_height = cm->render_height;
4931 
4932   if (pbi->need_resync) {
4933     aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4934                        "Keyframe / intra-only frame required to reset decoder"
4935                        " state");
4936   }
4937 
4938   if (features->allow_intrabc) {
4939     // Set parameters corresponding to no filtering.
4940     struct loopfilter *lf = &cm->lf;
4941     lf->filter_level[0] = 0;
4942     lf->filter_level[1] = 0;
4943     cm->cdef_info.cdef_bits = 0;
4944     cm->cdef_info.cdef_strengths[0] = 0;
4945     cm->cdef_info.nb_cdef_strengths = 1;
4946     cm->cdef_info.cdef_uv_strengths[0] = 0;
4947     cm->rst_info[0].frame_restoration_type = RESTORE_NONE;
4948     cm->rst_info[1].frame_restoration_type = RESTORE_NONE;
4949     cm->rst_info[2].frame_restoration_type = RESTORE_NONE;
4950   }
4951 
4952   read_tile_info(pbi, rb);
4953   if (!av1_is_min_tile_width_satisfied(cm)) {
4954     aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
4955                        "Minimum tile width requirement not satisfied");
4956   }
4957 
4958   CommonQuantParams *const quant_params = &cm->quant_params;
4959   setup_quantization(quant_params, av1_num_planes(cm),
4960                      cm->seq_params->separate_uv_delta_q, rb);
4961   xd->bd = (int)seq_params->bit_depth;
4962 
4963   CommonContexts *const above_contexts = &cm->above_contexts;
4964   if (above_contexts->num_planes < av1_num_planes(cm) ||
4965       above_contexts->num_mi_cols < cm->mi_params.mi_cols ||
4966       above_contexts->num_tile_rows < cm->tiles.rows) {
4967     av1_free_above_context_buffers(above_contexts);
4968     if (av1_alloc_above_context_buffers(above_contexts, cm->tiles.rows,
4969                                         cm->mi_params.mi_cols,
4970                                         av1_num_planes(cm))) {
4971       aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
4972                          "Failed to allocate context buffers");
4973     }
4974   }
4975 
4976   if (features->primary_ref_frame == PRIMARY_REF_NONE) {
4977     av1_setup_past_independence(cm);
4978   }
4979 
4980   setup_segmentation(cm, rb);
4981 
4982   cm->delta_q_info.delta_q_res = 1;
4983   cm->delta_q_info.delta_lf_res = 1;
4984   cm->delta_q_info.delta_lf_present_flag = 0;
4985   cm->delta_q_info.delta_lf_multi = 0;
4986   cm->delta_q_info.delta_q_present_flag =
4987       quant_params->base_qindex > 0 ? aom_rb_read_bit(rb) : 0;
4988   if (cm->delta_q_info.delta_q_present_flag) {
4989     xd->current_base_qindex = quant_params->base_qindex;
4990     cm->delta_q_info.delta_q_res = 1 << aom_rb_read_literal(rb, 2);
4991     if (!features->allow_intrabc)
4992       cm->delta_q_info.delta_lf_present_flag = aom_rb_read_bit(rb);
4993     if (cm->delta_q_info.delta_lf_present_flag) {
4994       cm->delta_q_info.delta_lf_res = 1 << aom_rb_read_literal(rb, 2);
4995       cm->delta_q_info.delta_lf_multi = aom_rb_read_bit(rb);
4996       av1_reset_loop_filter_delta(xd, av1_num_planes(cm));
4997     }
4998   }
4999 
5000   xd->cur_frame_force_integer_mv = features->cur_frame_force_integer_mv;
5001 
5002   for (int i = 0; i < MAX_SEGMENTS; ++i) {
5003     const int qindex = av1_get_qindex(&cm->seg, i, quant_params->base_qindex);
5004     xd->lossless[i] =
5005         qindex == 0 && quant_params->y_dc_delta_q == 0 &&
5006         quant_params->u_dc_delta_q == 0 && quant_params->u_ac_delta_q == 0 &&
5007         quant_params->v_dc_delta_q == 0 && quant_params->v_ac_delta_q == 0;
5008     xd->qindex[i] = qindex;
5009   }
5010   features->coded_lossless = is_coded_lossless(cm, xd);
5011   features->all_lossless = features->coded_lossless && !av1_superres_scaled(cm);
5012   setup_segmentation_dequant(cm, xd);
5013   if (features->coded_lossless) {
5014     cm->lf.filter_level[0] = 0;
5015     cm->lf.filter_level[1] = 0;
5016   }
5017   if (features->coded_lossless || !seq_params->enable_cdef) {
5018     cm->cdef_info.cdef_bits = 0;
5019     cm->cdef_info.cdef_strengths[0] = 0;
5020     cm->cdef_info.cdef_uv_strengths[0] = 0;
5021   }
5022   if (features->all_lossless || !seq_params->enable_restoration) {
5023     cm->rst_info[0].frame_restoration_type = RESTORE_NONE;
5024     cm->rst_info[1].frame_restoration_type = RESTORE_NONE;
5025     cm->rst_info[2].frame_restoration_type = RESTORE_NONE;
5026   }
5027   setup_loopfilter(cm, rb);
5028 
5029   if (!features->coded_lossless && seq_params->enable_cdef) {
5030     setup_cdef(cm, rb);
5031   }
5032   if (!features->all_lossless && seq_params->enable_restoration) {
5033     decode_restoration_mode(cm, rb);
5034   }
5035 
5036   features->tx_mode = read_tx_mode(rb, features->coded_lossless);
5037   current_frame->reference_mode = read_frame_reference_mode(cm, rb);
5038 
5039   av1_setup_skip_mode_allowed(cm);
5040   current_frame->skip_mode_info.skip_mode_flag =
5041       current_frame->skip_mode_info.skip_mode_allowed ? aom_rb_read_bit(rb) : 0;
5042 
5043   if (frame_might_allow_warped_motion(cm))
5044     features->allow_warped_motion = aom_rb_read_bit(rb);
5045   else
5046     features->allow_warped_motion = 0;
5047 
5048   features->reduced_tx_set_used = aom_rb_read_bit(rb);
5049 
5050   if (features->allow_ref_frame_mvs && !frame_might_allow_ref_frame_mvs(cm)) {
5051     aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
5052                        "Frame wrongly requests reference frame MVs");
5053   }
5054 
5055   if (!frame_is_intra_only(cm)) read_global_motion(cm, rb);
5056 
5057   cm->cur_frame->film_grain_params_present =
5058       seq_params->film_grain_params_present;
5059   read_film_grain(cm, rb);
5060 
5061 #if EXT_TILE_DEBUG
5062   if (pbi->ext_tile_debug && cm->tiles.large_scale) {
5063     read_ext_tile_info(pbi, rb);
5064     av1_set_single_tile_decoding_mode(cm);
5065   }
5066 #endif  // EXT_TILE_DEBUG
5067   return 0;
5068 }
5069 
av1_init_read_bit_buffer(AV1Decoder * pbi,struct aom_read_bit_buffer * rb,const uint8_t * data,const uint8_t * data_end)5070 struct aom_read_bit_buffer *av1_init_read_bit_buffer(
5071     AV1Decoder *pbi, struct aom_read_bit_buffer *rb, const uint8_t *data,
5072     const uint8_t *data_end) {
5073   rb->bit_offset = 0;
5074   rb->error_handler = error_handler;
5075   rb->error_handler_data = &pbi->common;
5076   rb->bit_buffer = data;
5077   rb->bit_buffer_end = data_end;
5078   return rb;
5079 }
5080 
av1_read_frame_size(struct aom_read_bit_buffer * rb,int num_bits_width,int num_bits_height,int * width,int * height)5081 void av1_read_frame_size(struct aom_read_bit_buffer *rb, int num_bits_width,
5082                          int num_bits_height, int *width, int *height) {
5083   *width = aom_rb_read_literal(rb, num_bits_width) + 1;
5084   *height = aom_rb_read_literal(rb, num_bits_height) + 1;
5085 }
5086 
av1_read_profile(struct aom_read_bit_buffer * rb)5087 BITSTREAM_PROFILE av1_read_profile(struct aom_read_bit_buffer *rb) {
5088   int profile = aom_rb_read_literal(rb, PROFILE_BITS);
5089   return (BITSTREAM_PROFILE)profile;
5090 }
5091 
5092 #if !CONFIG_REALTIME_ONLY
superres_post_decode(AV1Decoder * pbi)5093 static AOM_INLINE void superres_post_decode(AV1Decoder *pbi) {
5094   AV1_COMMON *const cm = &pbi->common;
5095   BufferPool *const pool = cm->buffer_pool;
5096 
5097   if (!av1_superres_scaled(cm)) return;
5098   assert(!cm->features.all_lossless);
5099 
5100   av1_superres_upscale(cm, pool);
5101 }
5102 #endif
5103 
av1_decode_frame_headers_and_setup(AV1Decoder * pbi,struct aom_read_bit_buffer * rb,int trailing_bits_present)5104 uint32_t av1_decode_frame_headers_and_setup(AV1Decoder *pbi,
5105                                             struct aom_read_bit_buffer *rb,
5106                                             int trailing_bits_present) {
5107   AV1_COMMON *const cm = &pbi->common;
5108   const int num_planes = av1_num_planes(cm);
5109   MACROBLOCKD *const xd = &pbi->dcb.xd;
5110 
5111 #if CONFIG_BITSTREAM_DEBUG
5112   aom_bitstream_queue_set_frame_read(cm->current_frame.order_hint * 2 +
5113                                      cm->show_frame);
5114 #endif
5115 #if CONFIG_MISMATCH_DEBUG
5116   mismatch_move_frame_idx_r();
5117 #endif
5118 
5119   for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
5120     cm->global_motion[i] = default_warp_params;
5121     cm->cur_frame->global_motion[i] = default_warp_params;
5122   }
5123   xd->global_motion = cm->global_motion;
5124 
5125   read_uncompressed_header(pbi, rb);
5126 
5127   if (trailing_bits_present) av1_check_trailing_bits(pbi, rb);
5128 
5129   if (!cm->tiles.single_tile_decoding &&
5130       (pbi->dec_tile_row >= 0 || pbi->dec_tile_col >= 0)) {
5131     pbi->dec_tile_row = -1;
5132     pbi->dec_tile_col = -1;
5133   }
5134 
5135   const uint32_t uncomp_hdr_size =
5136       (uint32_t)aom_rb_bytes_read(rb);  // Size of the uncompressed header
5137   YV12_BUFFER_CONFIG *new_fb = &cm->cur_frame->buf;
5138   xd->cur_buf = new_fb;
5139   if (av1_allow_intrabc(cm)) {
5140     av1_setup_scale_factors_for_frame(
5141         &cm->sf_identity, xd->cur_buf->y_crop_width, xd->cur_buf->y_crop_height,
5142         xd->cur_buf->y_crop_width, xd->cur_buf->y_crop_height);
5143   }
5144 
5145   // Showing a frame directly.
5146   if (cm->show_existing_frame) {
5147     if (pbi->reset_decoder_state) {
5148       // Use the default frame context values.
5149       *cm->fc = *cm->default_frame_context;
5150       if (!cm->fc->initialized)
5151         aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
5152                            "Uninitialized entropy context.");
5153     }
5154     return uncomp_hdr_size;
5155   }
5156 
5157   cm->mi_params.setup_mi(&cm->mi_params);
5158 
5159   av1_calculate_ref_frame_side(cm);
5160   if (cm->features.allow_ref_frame_mvs) av1_setup_motion_field(cm);
5161 
5162   av1_setup_block_planes(xd, cm->seq_params->subsampling_x,
5163                          cm->seq_params->subsampling_y, num_planes);
5164   if (cm->features.primary_ref_frame == PRIMARY_REF_NONE) {
5165     // use the default frame context values
5166     *cm->fc = *cm->default_frame_context;
5167   } else {
5168     *cm->fc = get_primary_ref_frame_buf(cm)->frame_context;
5169   }
5170   if (!cm->fc->initialized)
5171     aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
5172                        "Uninitialized entropy context.");
5173 
5174   pbi->dcb.corrupted = 0;
5175   return uncomp_hdr_size;
5176 }
5177 
5178 // Once-per-frame initialization
setup_frame_info(AV1Decoder * pbi)5179 static AOM_INLINE void setup_frame_info(AV1Decoder *pbi) {
5180   AV1_COMMON *const cm = &pbi->common;
5181 
5182 #if !CONFIG_REALTIME_ONLY
5183   if (cm->rst_info[0].frame_restoration_type != RESTORE_NONE ||
5184       cm->rst_info[1].frame_restoration_type != RESTORE_NONE ||
5185       cm->rst_info[2].frame_restoration_type != RESTORE_NONE) {
5186     av1_alloc_restoration_buffers(cm);
5187   }
5188 #endif
5189   const int use_highbd = cm->seq_params->use_highbitdepth;
5190   const int buf_size = MC_TEMP_BUF_PELS << use_highbd;
5191   if (pbi->td.mc_buf_size != buf_size) {
5192     av1_free_mc_tmp_buf(&pbi->td);
5193     allocate_mc_tmp_buf(cm, &pbi->td, buf_size, use_highbd);
5194   }
5195 }
5196 
av1_decode_tg_tiles_and_wrapup(AV1Decoder * pbi,const uint8_t * data,const uint8_t * data_end,const uint8_t ** p_data_end,int start_tile,int end_tile,int initialize_flag)5197 void av1_decode_tg_tiles_and_wrapup(AV1Decoder *pbi, const uint8_t *data,
5198                                     const uint8_t *data_end,
5199                                     const uint8_t **p_data_end, int start_tile,
5200                                     int end_tile, int initialize_flag) {
5201   AV1_COMMON *const cm = &pbi->common;
5202   CommonTileParams *const tiles = &cm->tiles;
5203   MACROBLOCKD *const xd = &pbi->dcb.xd;
5204   const int tile_count_tg = end_tile - start_tile + 1;
5205 
5206   if (initialize_flag) setup_frame_info(pbi);
5207   const int num_planes = av1_num_planes(cm);
5208 
5209   if (pbi->max_threads > 1 && !(tiles->large_scale && !pbi->ext_tile_debug) &&
5210       pbi->row_mt)
5211     *p_data_end =
5212         decode_tiles_row_mt(pbi, data, data_end, start_tile, end_tile);
5213   else if (pbi->max_threads > 1 && tile_count_tg > 1 &&
5214            !(tiles->large_scale && !pbi->ext_tile_debug))
5215     *p_data_end = decode_tiles_mt(pbi, data, data_end, start_tile, end_tile);
5216   else
5217     *p_data_end = decode_tiles(pbi, data, data_end, start_tile, end_tile);
5218 
5219   // If the bit stream is monochrome, set the U and V buffers to a constant.
5220   if (num_planes < 3) {
5221     set_planes_to_neutral_grey(cm->seq_params, xd->cur_buf, 1);
5222   }
5223 
5224   if (end_tile != tiles->rows * tiles->cols - 1) {
5225     return;
5226   }
5227 
5228   av1_alloc_cdef_buffers(cm, &pbi->cdef_worker, &pbi->cdef_sync,
5229                          pbi->num_workers, 1);
5230   av1_alloc_cdef_sync(cm, &pbi->cdef_sync, pbi->num_workers);
5231 
5232   if (!cm->features.allow_intrabc && !tiles->single_tile_decoding) {
5233     if (cm->lf.filter_level[0] || cm->lf.filter_level[1]) {
5234       av1_loop_filter_frame_mt(&cm->cur_frame->buf, cm, &pbi->dcb.xd, 0,
5235                                num_planes, 0, pbi->tile_workers,
5236                                pbi->num_workers, &pbi->lf_row_sync, 0);
5237     }
5238 
5239     const int do_cdef =
5240         !pbi->skip_loop_filter && !cm->features.coded_lossless &&
5241         (cm->cdef_info.cdef_bits || cm->cdef_info.cdef_strengths[0] ||
5242          cm->cdef_info.cdef_uv_strengths[0]);
5243     const int do_superres = av1_superres_scaled(cm);
5244     const int optimized_loop_restoration = !do_cdef && !do_superres;
5245 
5246 #if !CONFIG_REALTIME_ONLY
5247     const int do_loop_restoration =
5248         cm->rst_info[0].frame_restoration_type != RESTORE_NONE ||
5249         cm->rst_info[1].frame_restoration_type != RESTORE_NONE ||
5250         cm->rst_info[2].frame_restoration_type != RESTORE_NONE;
5251     if (!optimized_loop_restoration) {
5252       if (do_loop_restoration)
5253         av1_loop_restoration_save_boundary_lines(&pbi->common.cur_frame->buf,
5254                                                  cm, 0);
5255 
5256       if (do_cdef) {
5257         if (pbi->num_workers > 1) {
5258           av1_cdef_frame_mt(cm, &pbi->dcb.xd, pbi->cdef_worker,
5259                             pbi->tile_workers, &pbi->cdef_sync,
5260                             pbi->num_workers, av1_cdef_init_fb_row_mt);
5261         } else {
5262           av1_cdef_frame(&pbi->common.cur_frame->buf, cm, &pbi->dcb.xd,
5263                          av1_cdef_init_fb_row);
5264         }
5265       }
5266 
5267       superres_post_decode(pbi);
5268 
5269       if (do_loop_restoration) {
5270         av1_loop_restoration_save_boundary_lines(&pbi->common.cur_frame->buf,
5271                                                  cm, 1);
5272         if (pbi->num_workers > 1) {
5273           av1_loop_restoration_filter_frame_mt(
5274               (YV12_BUFFER_CONFIG *)xd->cur_buf, cm, optimized_loop_restoration,
5275               pbi->tile_workers, pbi->num_workers, &pbi->lr_row_sync,
5276               &pbi->lr_ctxt);
5277         } else {
5278           av1_loop_restoration_filter_frame((YV12_BUFFER_CONFIG *)xd->cur_buf,
5279                                             cm, optimized_loop_restoration,
5280                                             &pbi->lr_ctxt);
5281         }
5282       }
5283     } else {
5284       // In no cdef and no superres case. Provide an optimized version of
5285       // loop_restoration_filter.
5286       if (do_loop_restoration) {
5287         if (pbi->num_workers > 1) {
5288           av1_loop_restoration_filter_frame_mt(
5289               (YV12_BUFFER_CONFIG *)xd->cur_buf, cm, optimized_loop_restoration,
5290               pbi->tile_workers, pbi->num_workers, &pbi->lr_row_sync,
5291               &pbi->lr_ctxt);
5292         } else {
5293           av1_loop_restoration_filter_frame((YV12_BUFFER_CONFIG *)xd->cur_buf,
5294                                             cm, optimized_loop_restoration,
5295                                             &pbi->lr_ctxt);
5296         }
5297       }
5298     }
5299 #else
5300     if (!optimized_loop_restoration) {
5301       if (do_cdef) {
5302         if (pbi->num_workers > 1) {
5303           av1_cdef_frame_mt(cm, &pbi->dcb.xd, pbi->cdef_worker,
5304                             pbi->tile_workers, &pbi->cdef_sync,
5305                             pbi->num_workers, av1_cdef_init_fb_row_mt);
5306         } else {
5307           av1_cdef_frame(&pbi->common.cur_frame->buf, cm, &pbi->dcb.xd,
5308                          av1_cdef_init_fb_row);
5309         }
5310       }
5311     }
5312 #endif  // !CONFIG_REALTIME_ONLY
5313   }
5314 
5315   if (!pbi->dcb.corrupted) {
5316     if (cm->features.refresh_frame_context == REFRESH_FRAME_CONTEXT_BACKWARD) {
5317       assert(pbi->context_update_tile_id < pbi->allocated_tiles);
5318       *cm->fc = pbi->tile_data[pbi->context_update_tile_id].tctx;
5319       av1_reset_cdf_symbol_counters(cm->fc);
5320     }
5321   } else {
5322     aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
5323                        "Decode failed. Frame data is corrupted.");
5324   }
5325 
5326 #if CONFIG_INSPECTION
5327   if (pbi->inspect_cb != NULL) {
5328     (*pbi->inspect_cb)(pbi, pbi->inspect_ctx);
5329   }
5330 #endif
5331 
5332   // Non frame parallel update frame context here.
5333   if (!tiles->large_scale) {
5334     cm->cur_frame->frame_context = *cm->fc;
5335   }
5336 }
5337