Coverage Report

Created: 2026-11-12 08:20

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