Coverage Report

Created: 2026-03-31 06:59

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