Coverage Report

Created: 2025-12-31 06:49

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