Coverage Report

Created: 2023-06-07 06:31

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