Coverage Report

Created: 2026-06-30 06:53

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