Coverage Report

Created: 2026-12-01 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/avm/av2/decoder/decoder.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2021, Alliance for Open Media. All rights reserved
3
 *
4
 * This source code is subject to the terms of the BSD 3-Clause Clear License
5
 * and the Alliance for Open Media Patent License 1.0. If the BSD 3-Clause Clear
6
 * License was not distributed with this source code in the LICENSE file, you
7
 * can obtain it at aomedia.org/license/software-license/bsd-3-c-c/.  If the
8
 * Alliance for Open Media Patent License 1.0 was not distributed with this
9
 * source code in the PATENTS file, you can obtain it at
10
 * aomedia.org/license/patent-license/.
11
 */
12
13
#include <assert.h>
14
#include <limits.h>
15
#include <stdio.h>
16
17
#include "config/av2_rtcd.h"
18
#include "config/avm_dsp_rtcd.h"
19
#include "config/avm_scale_rtcd.h"
20
21
#include "avm_dsp/avm_dsp_common.h"
22
#include "avm_mem/avm_mem.h"
23
#include "avm_ports/system_state.h"
24
#include "avm_ports/avm_once.h"
25
#include "avm_ports/avm_timer.h"
26
#include "avm_scale/avm_scale.h"
27
#include "avm_util/avm_thread.h"
28
#if CONFIG_MISMATCH_DEBUG
29
#include "avm_util/debug_util.h"
30
#endif  // CONFIG_MISMATCH_DEBUG
31
32
#include "av2/common/alloccommon.h"
33
#include "av2/common/av2_common_int.h"
34
#include "av2/common/av2_loopfilter.h"
35
#include "av2/common/bru.h"
36
#include "av2/common/pred_common.h"
37
#include "av2/common/quant_common.h"
38
#include "av2/common/reconinter.h"
39
#include "av2/common/reconintra.h"
40
41
#include "av2/decoder/decodeframe.h"
42
#include "av2/decoder/decoder.h"
43
#include "av2/decoder/detokenize.h"
44
#include "av2/decoder/obu.h"
45
46
#if CONFIG_PARAKIT_COLLECT_DATA
47
#include "av2/common/entropy_sideinfo.h"
48
int beginningFrameFlag[MAX_NUMBER_CONTEXTS][MAX_DIMS_CONTEXT3]
49
                      [MAX_DIMS_CONTEXT2][MAX_DIMS_CONTEXT1][MAX_DIMS_CONTEXT0];
50
#endif
51
52
1
static void initialize_dec(void) {
53
1
  av2_rtcd();
54
1
  avm_dsp_rtcd();
55
1
  avm_scale_rtcd();
56
1
  av2_init_intra_predictors();
57
1
  av2_init_stxfm_kernels();
58
1
}
59
60
static void update_subgop_stats(const AV2_COMMON *const cm,
61
                                SubGOPStatsDec *const subgop_stats,
62
                                unsigned int display_order_hint,
63
229
                                unsigned int enable_subgop_stats) {
64
229
  if (!enable_subgop_stats) return;
65
  // Update subgop related frame data.
66
0
  subgop_stats->disp_frame_idx[subgop_stats->stat_count] = display_order_hint;
67
0
  subgop_stats->show_existing_frame[subgop_stats->stat_count] =
68
0
      cm->show_existing_frame;
69
0
  subgop_stats->immediate_output_picture[subgop_stats->stat_count] =
70
0
      cm->immediate_output_picture;
71
0
  subgop_stats->qindex[subgop_stats->stat_count] = cm->quant_params.base_qindex;
72
0
  subgop_stats->refresh_frame_flags[subgop_stats->stat_count] =
73
0
      cm->current_frame.refresh_frame_flags;
74
0
  for (MV_REFERENCE_FRAME ref_frame = 0; ref_frame < cm->seq_params.ref_frames;
75
0
       ++ref_frame)
76
0
    if (cm->ref_frame_map[ref_frame] != NULL) {
77
0
      subgop_stats->ref_frame_map[subgop_stats->stat_count][ref_frame] =
78
0
          cm->ref_frame_map[ref_frame]->order_hint;
79
0
    } else {
80
0
      subgop_stats->ref_frame_map[subgop_stats->stat_count][ref_frame] = 0;
81
0
    }
82
83
0
  assert(subgop_stats->stat_count < MAX_SUBGOP_STATS_SIZE);
84
0
  subgop_stats->stat_count++;
85
0
}
86
87
static void dec_set_mb_mi(CommonModeInfoParams *mi_params, int width,
88
1.92k
                          int height, int speed) {
89
1.92k
  (void)speed;
90
  // Ensure that the decoded width and height are both multiples of
91
  // 8 luma pixels (note: this may only be a multiple of 4 chroma pixels if
92
  // subsampling is used).
93
  // This simplifies the implementation of various experiments,
94
  // eg. cdef, which operates on units of 8x8 luma pixels.
95
1.92k
  const int aligned_width = ALIGN_POWER_OF_TWO(width, 3);
96
1.92k
  const int aligned_height = ALIGN_POWER_OF_TWO(height, 3);
97
98
1.92k
  mi_params->mi_cols = aligned_width >> MI_SIZE_LOG2;
99
1.92k
  mi_params->mi_rows = aligned_height >> MI_SIZE_LOG2;
100
1.92k
  mi_params->mi_stride = calc_mi_size(mi_params->mi_cols);
101
102
1.92k
  mi_params->mb_cols = (mi_params->mi_cols + 2) >> 2;
103
1.92k
  mi_params->mb_rows = (mi_params->mi_rows + 2) >> 2;
104
1.92k
  mi_params->MBs = mi_params->mb_rows * mi_params->mb_cols;
105
106
1.92k
  mi_params->mi_alloc_bsize = BLOCK_4X4;
107
1.92k
  mi_params->mi_alloc_stride = mi_params->mi_stride;
108
109
1.92k
  assert(mi_size_wide[mi_params->mi_alloc_bsize] ==
110
1.92k
         mi_size_high[mi_params->mi_alloc_bsize]);
111
1.92k
}
112
113
13.1k
static void dec_setup_mi(CommonModeInfoParams *mi_params) {
114
13.1k
  const int mi_grid_size =
115
13.1k
      mi_params->mi_stride * calc_mi_size(mi_params->mi_rows);
116
13.1k
  memset(mi_params->mi_grid_base, 0,
117
13.1k
         mi_grid_size * sizeof(*mi_params->mi_grid_base));
118
13.1k
  memset(mi_params->submi_grid_base, 0,
119
13.1k
         mi_grid_size * sizeof(*mi_params->submi_grid_base));
120
13.1k
  memset(mi_params->cctx_type_map, 0,
121
13.1k
         mi_grid_size * sizeof(*mi_params->cctx_type_map));
122
13.1k
  av2_reset_txk_skip_array_using_mi_params(mi_params);
123
13.1k
}
124
125
3.33k
static void dec_free_mi(CommonModeInfoParams *mi_params) {
126
3.33k
  avm_free(mi_params->mi_alloc);
127
3.33k
  mi_params->mi_alloc = NULL;
128
3.33k
  avm_free(mi_params->mi_grid_base);
129
3.33k
  mi_params->mi_grid_base = NULL;
130
3.33k
  avm_free(mi_params->mi_alloc_sub);
131
3.33k
  mi_params->mi_alloc_sub = NULL;
132
3.33k
  avm_free(mi_params->submi_grid_base);
133
3.33k
  mi_params->submi_grid_base = NULL;
134
3.33k
  mi_params->mi_alloc_size = 0;
135
3.33k
  avm_free(mi_params->tx_type_map);
136
3.33k
  mi_params->tx_type_map = NULL;
137
3.33k
  avm_free(mi_params->cctx_type_map);
138
3.33k
  mi_params->cctx_type_map = NULL;
139
3.33k
  av2_dealloc_class_id_array(mi_params);
140
3.33k
  av2_dealloc_txk_skip_array(mi_params);
141
3.33k
}
142
143
1.78k
static INLINE void dec_init_tip_ref_frame(AV2_COMMON *const cm) {
144
1.78k
  TIP *tip_ref = &cm->tip_ref;
145
1.78k
  tip_ref->tip_frame = avm_calloc(1, sizeof(*tip_ref->tip_frame));
146
1.78k
  tip_ref->tmp_tip_frame = avm_calloc(1, sizeof(*tip_ref->tmp_tip_frame));
147
1.78k
}
148
149
1.78k
static INLINE void dec_free_tip_ref_frame(AV2_COMMON *const cm) {
150
1.78k
  avm_free_frame_buffer(&cm->tip_ref.tip_frame->buf);
151
1.78k
  avm_free(cm->tip_ref.tip_frame);
152
1.78k
  cm->tip_ref.tip_frame = NULL;
153
154
1.78k
  avm_free_frame_buffer(&cm->tip_ref.tmp_tip_frame->buf);
155
1.78k
  avm_free(cm->tip_ref.tmp_tip_frame);
156
1.78k
  cm->tip_ref.tmp_tip_frame = NULL;
157
1.78k
}
158
159
#if CONFIG_PARAKIT_COLLECT_DATA
160
AV2Decoder *av2_decoder_create(BufferPool *const pool, const char *path,
161
                               const char *suffix) {
162
#else
163
1.78k
AV2Decoder *av2_decoder_create(BufferPool *const pool) {
164
1.78k
#endif
165
1.78k
  AV2Decoder *volatile const pbi = avm_memalign(32, sizeof(*pbi));
166
1.78k
  if (!pbi) return NULL;
167
1.78k
  av2_zero(*pbi);
168
169
1.78k
  AV2_COMMON *volatile const cm = &pbi->common;
170
171
  // The jmp_buf is valid only for the duration of the function that calls
172
  // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
173
  // before it returns.
174
1.78k
  if (setjmp(cm->error.jmp)) {
175
0
    cm->error.setjmp = 0;
176
0
    av2_decoder_remove(pbi);
177
0
    return NULL;
178
0
  }
179
180
1.78k
  cm->error.setjmp = 1;
181
182
1.78k
  CHECK_MEM_ERROR(cm, cm->fc,
183
1.78k
                  (FRAME_CONTEXT *)avm_memalign(32, sizeof(*cm->fc)));
184
1.78k
  CHECK_MEM_ERROR(
185
1.78k
      cm, cm->default_frame_context,
186
1.78k
      (FRAME_CONTEXT *)avm_memalign(32, sizeof(*cm->default_frame_context)));
187
1.78k
  memset(cm->fc, 0, sizeof(*cm->fc));
188
1.78k
  memset(cm->default_frame_context, 0, sizeof(*cm->default_frame_context));
189
190
1.78k
  pbi->need_resync = 1;
191
1.78k
  avm_once(initialize_dec);
192
193
  // Initialize the references to not point to any frame buffers.
194
30.2k
  for (int i = 0; i < NELEMENTS(cm->ref_frame_map); i++) {
195
28.4k
    cm->ref_frame_map[i] = NULL;
196
28.4k
  }
197
198
1.78k
  cm->current_frame.frame_number = 0;
199
1.78k
  pbi->decoding_first_frame = 1;
200
1.78k
  pbi->common.buffer_pool = pool;
201
202
1.78k
  cm->seq_params.bit_depth = AVM_BITS_8;
203
1.78k
  cm->mi_params.free_mi = dec_free_mi;
204
1.78k
  cm->mi_params.setup_mi = dec_setup_mi;
205
1.78k
  cm->mi_params.set_mb_mi = dec_set_mb_mi;
206
207
1.78k
  cm->frame_filter_dictionary_stride = 0;
208
1.78k
  cm->frame_filter_dictionary = NULL;
209
1.78k
  cm->translated_pcwiener_filters = NULL;
210
1.78k
  cm->num_ref_filters = NULL;
211
212
1.78k
  av2_loop_filter_init(cm);
213
28.4k
  for (int i = 0; i < NUM_CUSTOM_QMS; ++i) {
214
26.7k
    pbi->qm_protected[i] = 0;
215
26.7k
  }
216
217
28.4k
  for (int i = 0; i < NUM_CUSTOM_QMS; ++i) {
218
26.7k
    pbi->qm_list[i].qm_from_leading = 0;
219
26.7k
    pbi->qm_list[i].qm_id = -1;
220
26.7k
    pbi->qm_list[i].qm_tlayer_id = -1;
221
26.7k
    pbi->qm_list[i].qm_mlayer_id = -1;
222
26.7k
    pbi->qm_list[i].quantizer_matrix = NULL;
223
26.7k
    pbi->qm_list[i].quantizer_matrix_allocated = false;
224
26.7k
    pbi->qm_list[i].quantizer_matrix_num_planes = -1;
225
26.7k
  }
226
16.0k
  for (int i = 0; i < MAX_FGM_NUM; ++i) {
227
14.2k
    pbi->fgm_list[i].fgm_from_leading = 0;
228
14.2k
    pbi->fgm_list[i].fgm_id = -1;
229
14.2k
    pbi->fgm_list[i].fgm_tlayer_id = -1;
230
14.2k
    pbi->fgm_list[i].fgm_mlayer_id = -1;
231
14.2k
  }
232
233
1.78k
  pbi->selected_ops_id = -1;
234
1.78k
  pbi->selected_op_index = -1;
235
236
1.78k
  memset(&pbi->last_frame_unit, -1, sizeof(pbi->last_frame_unit));
237
1.78k
  memset(&pbi->last_displayable_frame_unit, -1,
238
1.78k
         sizeof(pbi->last_displayable_frame_unit));
239
1.78k
  memset(pbi->last_output_doh, -1, sizeof(pbi->last_output_doh));
240
1.78k
  pbi->this_is_first_vcl_obu_in_tu = 0;
241
1.78k
  pbi->last_decoded_xlayer_id = -1;
242
16.0k
  for (int i = 0; i < MAX_NUM_MLAYERS; i++) {
243
14.2k
    pbi->num_displayable_frame_unit[i] = 0;
244
14.2k
  }
245
8.90k
  for (int j = 0; j < MAX_NUM_TLAYERS; j++)
246
64.0k
    for (int i = 0; i < MAX_NUM_MLAYERS; i++)
247
56.9k
      memset(pbi->obus_in_frame_unit_data[j][i], 0,
248
56.9k
             sizeof(pbi->obus_in_frame_unit_data[j][i]));
249
250
58.7k
  for (int xlayer = 0; xlayer < MAX_NUM_XLAYERS; xlayer++)
251
968k
    for (int i = 0; i < MAX_SEQ_NUM; i++)
252
911k
      pbi->seq_list[xlayer][i].seq_header_id = -1;
253
254
#if CONFIG_ACCOUNTING
255
  pbi->acct_enabled = 1;
256
  avm_accounting_init(&pbi->accounting);
257
#endif
258
259
1.78k
  dec_init_tip_ref_frame(cm);
260
261
1.78k
  cm->error.setjmp = 0;
262
263
1.78k
  avm_get_worker_interface()->init(&pbi->lf_worker);
264
1.78k
  pbi->lf_worker.thread_name = "avm lf worker";
265
266
  // Initialize the Content Interpretation parameters
267
16.0k
  for (int i = 0; i < MAX_NUM_MLAYERS; i++) {
268
14.2k
    av2_initialize_ci_params(&cm->ci_params_per_layer[i]);
269
14.2k
  }
270
271
#if CONFIG_PARAKIT_COLLECT_DATA
272
#include "av2/common/entropy_inits_coeffs.h"
273
#include "av2/common/entropy_inits_modes.h"
274
#include "av2/common/entropy_inits_mv.h"
275
276
  // @ParaKit: add side information needed in array of prob_models structure to
277
  // be used in collecting data
278
  cm->prob_models[EOB_FLAG_CDF16] =
279
      (ProbModelInfo){ .ctx_group_name = "eob_flag_cdf16",
280
                       .prob = (avm_cdf_prob *)av2_default_eob_multi16_cdfs,
281
                       .cdf_stride = 0,
282
                       .num_symb = 5,
283
                       .num_dim = 2,
284
                       .num_idx = { 0, 0, 4, 3 } };
285
  cm->prob_models[EOB_FLAG_CDF32] =
286
      (ProbModelInfo){ .ctx_group_name = "eob_flag_cdf32",
287
                       .prob = (avm_cdf_prob *)av2_default_eob_multi32_cdfs,
288
                       .cdf_stride = 0,
289
                       .num_symb = 6,
290
                       .num_dim = 2,
291
                       .num_idx = { 0, 0, 4, 3 } };
292
293
  for (int i = 0; i < MAX_NUM_CTX_GROUPS; i++) {
294
    for (int j = 0; j < MAX_DIMS_CONTEXT3; j++)
295
      for (int k = 0; k < MAX_DIMS_CONTEXT2; k++)
296
        for (int l = 0; l < MAX_DIMS_CONTEXT1; l++)
297
          for (int h = 0; h < MAX_DIMS_CONTEXT0; h++)
298
            beginningFrameFlag[i][j][k][l][h] = 0;
299
  }
300
301
  for (int f = 0; f < MAX_NUM_CTX_GROUPS; f++) {
302
    cm->prob_models[f].model_idx = f;
303
    const int fixed_stride = cm->prob_models[f].cdf_stride;
304
    const int num_sym = cm->prob_models[f].num_symb;
305
    const int num_dims = cm->prob_models[f].num_dim;
306
    const int num_idx0 = cm->prob_models[f].num_idx[0];
307
    const int num_idx1 = cm->prob_models[f].num_idx[1];
308
    const int num_idx2 = cm->prob_models[f].num_idx[2];
309
    const int num_idx3 = cm->prob_models[f].num_idx[3];
310
    const char *str_ctx = cm->prob_models[f].ctx_group_name;
311
    const char *str_path = path ? path : ".";
312
    const char *str_suffix = suffix ? suffix : "data";
313
    char filename[2048];
314
    sprintf(filename, "%s/Stat_%s_%s.csv", str_path, str_ctx, str_suffix);
315
    FILE *fData = fopen(filename, "wt");
316
    cm->prob_models[f].fDataCollect = fData;
317
318
    fprintf(fData, "Header:%s,%d,%d", str_ctx, num_sym, num_dims);
319
    const int dim_offset = MAX_CTX_DIM - num_dims;
320
    for (int i = 0; i < num_dims; i++) {
321
      fprintf(fData, ",%d", cm->prob_models[f].num_idx[i + dim_offset]);
322
    }
323
    fprintf(fData, "\n");
324
325
    avm_cdf_prob *prob_ptr;
326
    prob_ptr = cm->prob_models[f].prob;
327
    int ctx_group_counter = 0;
328
    for (int d0 = 0; d0 < (num_idx0 == 0 ? 1 : num_idx0); d0++)
329
      for (int d1 = 0; d1 < (num_idx1 == 0 ? 1 : num_idx1); d1++)
330
        for (int d2 = 0; d2 < (num_idx2 == 0 ? 1 : num_idx2); d2++)
331
          for (int d3 = 0; d3 < (num_idx3 == 0 ? 1 : num_idx3); d3++) {
332
            // indexing according to MAX_CTX_DIM
333
            fprintf(fData, "%d,%d,%d,%d,%d,", ctx_group_counter, d0, d1, d2,
334
                    d3);
335
            ctx_group_counter++;
336
            for (int sym = 0; sym < CDF_SIZE(num_sym); sym++) {
337
              int cdf_stride = (fixed_stride == 0) ? num_sym : fixed_stride;
338
              int offset =
339
                  (d0 * num_idx3 * num_idx2 * num_idx1 * CDF_SIZE(cdf_stride)) +
340
                  (d1 * num_idx3 * num_idx2 * CDF_SIZE(cdf_stride)) +
341
                  (d2 * num_idx3 * CDF_SIZE(cdf_stride)) +
342
                  (d3 * CDF_SIZE(cdf_stride)) + sym;
343
              if (sym < num_sym)
344
                fprintf(fData, "%d", (int)AVM_ICDF(*(prob_ptr + offset)));
345
              else
346
                fprintf(fData, "%d", (int)*(prob_ptr + offset));
347
              if (sym < CDF_SIZE(num_sym - 1)) {
348
                fprintf(fData, ",");
349
              } else {
350
                fprintf(fData, "\n");
351
              }
352
            }
353
          }
354
    // main header
355
    for (int i = 0; i < num_dims; i++) {
356
      fprintf(fData, "Dim%d,", i);
357
    }
358
359
    fprintf(fData, "FrameNum,FrameType,isBeginFrame,Counter,Value,Cost");
360
361
    for (int sym = 0; sym < num_sym; sym++) {
362
      fprintf(fData, ",cdf%d", sym);
363
    }
364
    fprintf(fData, ",rate");
365
    fprintf(fData, "\n");
366
  }
367
#endif
368
1.78k
  return pbi;
369
1.78k
}
370
371
1.04k
void av2_dealloc_dec_jobs(struct AV2DecTileMTData *tile_mt_info) {
372
1.04k
  if (tile_mt_info != NULL) {
373
1.04k
#if CONFIG_MULTITHREAD
374
1.04k
    if (tile_mt_info->job_mutex != NULL) {
375
489
      pthread_mutex_destroy(tile_mt_info->job_mutex);
376
489
      avm_free(tile_mt_info->job_mutex);
377
489
    }
378
1.04k
#endif
379
1.04k
    avm_free(tile_mt_info->job_queue);
380
    // clear the structure as the source of this call may be a resize in which
381
    // case this call will be followed by an _alloc() which may fail.
382
1.04k
    av2_zero(*tile_mt_info);
383
1.04k
  }
384
1.04k
}
385
386
1.78k
void av2_dec_free_cb_buf(AV2Decoder *pbi) {
387
1.78k
  avm_free(pbi->cb_buffer_base);
388
1.78k
  pbi->cb_buffer_base = NULL;
389
1.78k
  pbi->cb_buffer_alloc_size = 0;
390
1.78k
}
391
392
1.78k
void av2_decoder_remove(AV2Decoder *pbi) {
393
1.78k
  int i;
394
395
1.78k
  if (!pbi) return;
396
397
1.78k
  avm_get_worker_interface()->end(&pbi->lf_worker);
398
1.78k
  avm_free(pbi->lf_worker.data1);
399
400
1.78k
  if (pbi->thread_data) {
401
23.8k
    for (int worker_idx = 0; worker_idx < pbi->max_threads - 1; worker_idx++) {
402
23.2k
      DecWorkerData *const thread_data = pbi->thread_data + worker_idx;
403
23.2k
      av2_free_mc_tmp_buf(thread_data->td);
404
23.2k
      av2_free_opfl_tmp_bufs(thread_data->td);
405
23.2k
      avm_free(thread_data->td);
406
23.2k
    }
407
558
    avm_free(pbi->thread_data);
408
558
  }
409
410
25.5k
  for (i = 0; i < pbi->num_workers; ++i) {
411
23.8k
    AVxWorker *const worker = &pbi->tile_workers[i];
412
23.8k
    avm_get_worker_interface()->end(worker);
413
23.8k
  }
414
1.78k
#if CONFIG_MULTITHREAD
415
1.78k
  if (pbi->row_mt_mutex_ != NULL) {
416
0
    pthread_mutex_destroy(pbi->row_mt_mutex_);
417
0
    avm_free(pbi->row_mt_mutex_);
418
0
  }
419
1.78k
  if (pbi->row_mt_cond_ != NULL) {
420
0
    pthread_cond_destroy(pbi->row_mt_cond_);
421
0
    avm_free(pbi->row_mt_cond_);
422
0
  }
423
1.78k
#endif
424
17.3k
  for (i = 0; i < pbi->allocated_tiles; i++) {
425
15.6k
    TileDataDec *const tile_data = pbi->tile_data + i;
426
15.6k
    av2_dec_row_mt_dealloc(&tile_data->dec_row_mt_sync);
427
15.6k
  }
428
1.78k
  avm_free(pbi->tile_data);
429
1.78k
  avm_free(pbi->tile_workers);
430
431
1.78k
  if (pbi->num_workers > 0) {
432
558
    av2_loop_filter_dealloc(&pbi->lf_row_sync);
433
558
    av2_ccso_filter_dealloc(&pbi->ccso_sync);
434
558
    av2_loop_restoration_dealloc(&pbi->lr_row_sync, pbi->num_workers);
435
558
    av2_dealloc_dec_jobs(&pbi->tile_mt_info);
436
558
    avm_free(pbi->tip_worker_data);
437
558
    av2_tip_dealloc(&pbi->tip_sync);
438
558
  }
439
440
1.78k
  dec_free_tip_ref_frame(&pbi->common);
441
442
1.78k
  free_bru_info(&pbi->common);
443
1.78k
  av2_dec_free_cb_buf(pbi);
444
#if CONFIG_ACCOUNTING
445
  avm_accounting_clear(&pbi->accounting);
446
#endif
447
1.78k
  av2_free_mc_tmp_buf(&pbi->td);
448
1.78k
  av2_free_opfl_tmp_bufs(&pbi->td);
449
1.78k
  avm_img_metadata_array_free(pbi->metadata);
450
451
#if CONFIG_PARAKIT_COLLECT_DATA
452
  for (int f = 0; f < MAX_NUM_CTX_GROUPS; f++) {
453
    if (pbi->common.prob_models[f].fDataCollect != NULL) {
454
      fclose(pbi->common.prob_models[f].fDataCollect);
455
    }
456
  }
457
#endif
458
28.4k
  for (int qm_pos = 0; qm_pos < NUM_CUSTOM_QMS; qm_pos++) {
459
26.7k
    if (pbi->qm_list[qm_pos].quantizer_matrix != NULL)
460
10
      av2_free_qmset(pbi->qm_list[qm_pos].quantizer_matrix);
461
26.7k
  }
462
463
1.78k
  if (pbi->is_multistream) {
464
    // Release intermediate buffers to store internal variables per sub-stream
465
149
    if (pbi->stream_info != NULL) {
466
123
      avm_free(pbi->stream_info);
467
123
      pbi->stream_info = NULL;
468
123
      pbi->glcr_stream_info_num_allocated = 0;
469
123
    }
470
149
  }
471
472
1.78k
  avm_free(pbi);
473
1.78k
}
474
475
void av2_visit_palette(AV2Decoder *const pbi, MACROBLOCKD *const xd,
476
1.56M
                       avm_reader *r, palette_visitor_fn_t visit) {
477
1.56M
  if (!is_inter_block(xd->mi[0], xd->tree_type)) {
478
1.45M
    const int plane_start = get_partition_plane_start(xd->tree_type);
479
1.45M
    const int plane_end = get_partition_plane_end(
480
1.45M
        xd->tree_type, AVMMIN(2, av2_num_planes(&pbi->common)));
481
3.77M
    for (int plane = plane_start; plane < plane_end; ++plane) {
482
2.32M
      if (plane == 0 || xd->is_chroma_ref) {
483
2.27M
        if (xd->mi[0]->palette_mode_info.palette_size[plane])
484
23.3k
          visit(xd, plane, r);
485
2.27M
      } else {
486
47.7k
        assert(xd->mi[0]->palette_mode_info.palette_size[plane] == 0);
487
47.7k
      }
488
2.32M
    }
489
1.45M
  }
490
1.56M
}
491
492
static int equal_dimensions(const YV12_BUFFER_CONFIG *a,
493
0
                            const YV12_BUFFER_CONFIG *b) {
494
0
  return a->y_height == b->y_height && a->y_width == b->y_width &&
495
0
         a->uv_height == b->uv_height && a->uv_width == b->uv_width;
496
0
}
497
498
avm_codec_err_t av2_copy_reference_dec(AV2Decoder *pbi, int idx,
499
0
                                       YV12_BUFFER_CONFIG *sd) {
500
0
  AV2_COMMON *cm = &pbi->common;
501
0
  const int num_planes = av2_num_planes(cm);
502
  // Ensure that avm_internal_error() calls longjmp().
503
0
  assert(cm->error.setjmp);
504
505
0
  const YV12_BUFFER_CONFIG *const cfg = get_ref_frame(cm, idx);
506
0
  if (cfg == NULL) {
507
0
    avm_internal_error(&cm->error, AVM_CODEC_ERROR, "No reference frame");
508
0
  }
509
0
  if (!equal_dimensions(cfg, sd))
510
0
    avm_internal_error(&cm->error, AVM_CODEC_ERROR,
511
0
                       "Incorrect buffer dimensions");
512
0
  else
513
0
    avm_yv12_copy_frame(cfg, sd, num_planes);
514
515
0
  return cm->error.error_code;
516
0
}
517
518
avm_codec_err_t av2_set_reference_dec(AV2_COMMON *cm, int idx,
519
                                      int use_external_ref,
520
0
                                      YV12_BUFFER_CONFIG *sd) {
521
0
  const int num_planes = av2_num_planes(cm);
522
0
  YV12_BUFFER_CONFIG *ref_buf = NULL;
523
  // Ensure that avm_internal_error() calls longjmp().
524
0
  assert(cm->error.setjmp);
525
  // Get the destination reference buffer.
526
0
  ref_buf = get_ref_frame(cm, idx);
527
528
0
  if (ref_buf == NULL) {
529
0
    avm_internal_error(&cm->error, AVM_CODEC_ERROR, "No reference frame");
530
0
  }
531
532
0
  if (!use_external_ref) {
533
0
    if (!equal_dimensions(ref_buf, sd)) {
534
0
      avm_internal_error(&cm->error, AVM_CODEC_ERROR,
535
0
                         "Incorrect buffer dimensions");
536
0
    } else {
537
      // Overwrite the reference frame buffer.
538
0
      avm_yv12_copy_frame(sd, ref_buf, num_planes);
539
0
    }
540
0
  } else {
541
0
    if (!avm_equal_dimensions_and_border(ref_buf, sd)) {
542
0
      avm_internal_error(&cm->error, AVM_CODEC_ERROR,
543
0
                         "Incorrect buffer dimensions");
544
0
    } else {
545
      // Overwrite the reference frame buffer pointers.
546
      // Once we no longer need the external reference buffer, these pointers
547
      // are restored.
548
0
      ref_buf->store_buf_adr[0] = ref_buf->y_buffer;
549
0
      ref_buf->store_buf_adr[1] = ref_buf->u_buffer;
550
0
      ref_buf->store_buf_adr[2] = ref_buf->v_buffer;
551
0
      ref_buf->y_buffer = sd->y_buffer;
552
0
      ref_buf->u_buffer = sd->u_buffer;
553
0
      ref_buf->v_buffer = sd->v_buffer;
554
0
      ref_buf->use_external_reference_buffers = 1;
555
0
    }
556
0
  }
557
558
0
  return cm->error.error_code;
559
0
}
560
561
avm_codec_err_t av2_copy_new_frame_dec(AV2_COMMON *cm,
562
                                       YV12_BUFFER_CONFIG *new_frame,
563
0
                                       YV12_BUFFER_CONFIG *sd) {
564
0
  const int num_planes = av2_num_planes(cm);
565
566
0
  if (!avm_equal_dimensions_and_border(new_frame, sd))
567
0
    avm_internal_error(&cm->error, AVM_CODEC_ERROR,
568
0
                       "Incorrect buffer dimensions");
569
0
  else
570
0
    avm_yv12_copy_frame(new_frame, sd, num_planes);
571
572
0
  return cm->error.error_code;
573
0
}
574
575
32.8k
static void release_current_frame(AV2Decoder *pbi) {
576
32.8k
  AV2_COMMON *const cm = &pbi->common;
577
32.8k
  BufferPool *const pool = cm->buffer_pool;
578
579
32.8k
  cm->cur_frame->buf.corrupted = 1;
580
32.8k
  lock_buffer_pool(pool);
581
32.8k
  decrease_ref_count(cm->cur_frame, pool);
582
32.8k
  unlock_buffer_pool(pool);
583
32.8k
  cm->cur_frame = NULL;
584
32.8k
}
585
586
// This function flushes out the DPB, all the slots in the dpb is free to use.
587
avm_codec_err_t flush_remaining_frames(struct AV2Decoder *pbi,
588
3.62k
                                       int order_hint_limit) {
589
3.62k
  avm_codec_err_t res = AVM_CODEC_OK;
590
3.62k
  AV2_COMMON *const cm = &pbi->common;
591
3.62k
  RefCntBuffer *output_candidate = NULL;
592
3.62k
  do {
593
3.62k
    output_candidate = NULL;
594
61.6k
    for (int i = 0; i < REF_FRAMES; i++) {
595
58.0k
      RefCntBuffer *const buf = cm->ref_frame_map[i];
596
58.0k
      if (buf == NULL) continue;
597
13
      if (!is_frame_eligible_for_output(buf)) continue;
598
0
      if ((int)buf->display_order_hint >= order_hint_limit) continue;
599
600
0
      if ((output_candidate == NULL ||
601
0
           derive_output_order_idx(cm, buf) <=
602
0
               derive_output_order_idx(cm, output_candidate))) {
603
0
        output_candidate = buf;
604
0
      }
605
0
    }
606
3.62k
    if (output_candidate != NULL) {
607
0
      if (pbi->num_output_frames >= (REF_FRAMES + 1) * AVM_MAX_NUM_STREAMS) {
608
0
        return AVM_CODEC_MEM_ERROR;
609
0
      }
610
0
      assign_output_frame_buffer_p(
611
0
          &pbi->output_frames[pbi->num_output_frames++], output_candidate);
612
0
      output_candidate->frame_output_done = 1;
613
0
    }
614
3.62k
  } while (output_candidate != NULL);
615
3.62k
  return res;
616
3.62k
}
617
618
// check uniqueness and ascending order at output time, then update
619
// last_output_doh.  Returns 0 on success, 1 on violation.
620
static int check_and_update_output_doh(AV2Decoder *pbi,
621
0
                                       const RefCntBuffer *frame) {
622
0
  const int xl = frame->xlayer_id;
623
0
  const int ml = frame->mlayer_id;
624
0
  const int doh = frame->display_order_hint;
625
626
0
  const int last_doh = pbi->last_output_doh[xl][ml];
627
0
  if (doh <= last_doh) return 1;
628
629
0
  pbi->last_output_doh[xl][ml] = doh;
630
0
  return 0;
631
0
}
632
633
225
int av2_output_frame_buffers(AV2Decoder *pbi, int ref_idx) {
634
225
  AV2_COMMON *const cm = &pbi->common;
635
225
  RefCntBuffer *trigger_frame = NULL;
636
225
  RefCntBuffer *output_candidate = NULL;
637
225
  int doh_error = 0;
638
639
  // Determine if the triggering frame is the current frame or a frame
640
  // already stored in the refrence buffer.
641
225
  trigger_frame = (ref_idx >= 0) ? cm->ref_frame_map[ref_idx] : cm->cur_frame;
642
643
  // Add the previous frames into the output queue.
644
225
  do {
645
225
    output_candidate = trigger_frame;
646
675
    for (int i = 0; i < cm->seq_params.ref_frames; i++) {
647
450
      if (is_frame_eligible_for_output(cm->ref_frame_map[i]) &&
648
0
          derive_output_order_idx(cm, cm->ref_frame_map[i]) <
649
0
              derive_output_order_idx(cm, output_candidate)) {
650
0
        output_candidate = cm->ref_frame_map[i];
651
0
      }
652
450
    }
653
225
    if (output_candidate != trigger_frame) {
654
0
      if (cm->seq_params.monotonic_output_order_flag == 0) {
655
0
        doh_error |= check_and_update_output_doh(pbi, output_candidate);
656
0
      }
657
0
      assign_output_frame_buffer_p(
658
0
          &pbi->output_frames[pbi->num_output_frames++], output_candidate);
659
0
      output_candidate->frame_output_done = 1;
660
#if CONFIG_BITSTREAM_DEBUG
661
      avm_bitstream_queue_set_frame_read(
662
          derive_output_order_idx(cm, output_candidate) * 2 + 1);
663
#endif  // CONFIG_BITSTREAM_DEBUG
664
#if CONFIG_MISMATCH_DEBUG
665
      mismatch_move_frame_idx_r(0);
666
#endif  // CONFIG_MISMATCH_DEBUG
667
0
    }
668
225
  } while (output_candidate != trigger_frame);
669
670
225
  if (cm->seq_params.monotonic_output_order_flag == 0) {
671
    // Add the output triggering frame into the output queue.
672
0
    doh_error |= check_and_update_output_doh(pbi, trigger_frame);
673
0
  }
674
225
  assign_output_frame_buffer_p(&pbi->output_frames[pbi->num_output_frames++],
675
225
                               trigger_frame);
676
225
  trigger_frame->frame_output_done = 1;
677
678
#if CONFIG_BITSTREAM_DEBUG
679
  if (trigger_frame->order_hint != cm->cur_frame->order_hint) {
680
    avm_bitstream_queue_set_frame_read(
681
        derive_output_order_idx(cm, trigger_frame) * 2 + 1);
682
  }
683
#endif  // CONFIG_BITSTREAM_DEBUG
684
#if CONFIG_MISMATCH_DEBUG
685
  if (trigger_frame->display_order_hint != cm->cur_frame->display_order_hint)
686
    mismatch_move_frame_idx_r(0);
687
#endif  // CONFIG_MISMATCH_DEBUG
688
689
  // Add the next frames (implicit_output_picture == 1) into the output queue.
690
225
  uint64_t trigger_frame_output_order =
691
225
      derive_output_order_idx(cm, trigger_frame);
692
693
225
  int successive_output = 1;
694
450
  for (int k = 1; k <= cm->seq_params.ref_frames && successive_output > 0;
695
225
       k++) {
696
225
    uint64_t next_frame_output_order = trigger_frame_output_order + k;
697
225
    successive_output = 0;
698
675
    for (int i = 0; i < cm->seq_params.ref_frames; i++) {
699
450
      if (is_frame_eligible_for_output(cm->ref_frame_map[i]) &&
700
0
          derive_output_order_idx(cm, cm->ref_frame_map[i]) ==
701
0
              next_frame_output_order) {
702
0
        if (cm->seq_params.monotonic_output_order_flag == 0) {
703
0
          doh_error |= check_and_update_output_doh(pbi, cm->ref_frame_map[i]);
704
0
        }
705
0
        assign_output_frame_buffer_p(
706
0
            &pbi->output_frames[pbi->num_output_frames++],
707
0
            cm->ref_frame_map[i]);
708
0
        cm->ref_frame_map[i]->frame_output_done = 1;
709
0
        successive_output++;
710
#if CONFIG_BITSTREAM_DEBUG
711
        avm_bitstream_queue_set_frame_read(
712
            derive_output_order_idx(cm, cm->ref_frame_map[i]) * 2 + 1);
713
#endif  // CONFIG_BITSTREAM_DEBUG
714
#if CONFIG_MISMATCH_DEBUG
715
        mismatch_move_frame_idx_r(0);
716
#endif  // CONFIG_MISMATCH_DEBUG
717
0
      }
718
450
    }
719
225
  }
720
225
  return doh_error;
721
225
}
722
723
// If any buffer updating is signaled it should be done here.
724
// Consumes a reference to cm->cur_frame.
725
//
726
// This functions returns void. It reports failure by setting
727
// cm->error.error_code.
728
229
static void update_frame_buffers(AV2Decoder *pbi, int frame_decoded) {
729
229
  int ref_index = 0;
730
229
  AV2_COMMON *const cm = &pbi->common;
731
229
  BufferPool *const pool = cm->buffer_pool;
732
229
  int doh_error = 0;
733
734
229
  pbi->output_frames_offset = 0;
735
736
229
  if (frame_decoded) {
737
229
    lock_buffer_pool(pool);
738
739
    // Don't clear is_restricted for bridge frames - they should maintain
740
    // the restricted status inherited from their reference frame
741
229
    if (!cm->bridge_frame_info.is_bridge_frame) {
742
229
      cm->cur_frame->is_restricted = false;
743
229
    }
744
745
229
    int first_ref_index;
746
229
    const bool clear_multiple_insert_in_one =
747
229
        av2_frame_clears_multiple_inserted_in_one(
748
229
            cm->current_frame.refresh_frame_flags, cm->current_frame.frame_type,
749
229
            &first_ref_index);
750
751
    // The following for loop needs to release the reference stored in
752
    // cm->ref_frame_map[ref_index] before storing a reference to
753
    // cm->cur_frame in cm->ref_frame_map[ref_index].
754
707
    for (int mask = cm->current_frame.refresh_frame_flags; mask; mask >>= 1) {
755
478
      if (mask & 1) {
756
475
        if (pbi->bru_opt_mode && cm->bru.enabled) {
757
0
          if (ref_index == cm->bru.explicit_ref_idx) {
758
0
            ++ref_index;
759
0
            continue;  // skip refresh BRU ref
760
0
          }
761
0
        }
762
475
        if (is_frame_eligible_for_output(cm->ref_frame_map[ref_index]))
763
0
          doh_error |= av2_output_frame_buffers(pbi, ref_index);
764
475
        decrease_ref_count(cm->ref_frame_map[ref_index], pool);
765
766
475
        if (av2_skip_reference_buffer_update(clear_multiple_insert_in_one,
767
475
                                             ref_index, first_ref_index)) {
768
246
          cm->ref_frame_map[ref_index] = NULL;
769
246
        } else {
770
229
          cm->ref_frame_map[ref_index] = cm->cur_frame;
771
229
          ++cm->cur_frame->ref_count;
772
229
        }
773
475
      }
774
478
      ++ref_index;
775
478
    }
776
229
    update_subgop_stats(cm, &pbi->subgop_stats, cm->cur_frame->order_hint,
777
229
                        pbi->enable_subgop_stats);
778
229
    if (((cm->immediate_output_picture && !cm->cur_frame->frame_output_done) ||
779
225
         cm->show_existing_frame)) {
780
225
      doh_error |= av2_output_frame_buffers(pbi, -1);
781
225
      decrease_ref_count(cm->cur_frame, pool);
782
225
    } else {
783
4
      decrease_ref_count(cm->cur_frame, pool);
784
4
    }
785
229
    unlock_buffer_pool(pool);
786
229
    if (cm->seq_params.monotonic_output_order_flag == 0) {
787
4
      if (doh_error) {
788
0
        avm_internal_error(
789
0
            &cm->error, AVM_CODEC_UNSUP_BITSTREAM,
790
0
            "Display order hint of an output picture is not unique"
791
0
            " in the same (xlayer_id %d) layer.",
792
0
            cm->xlayer_id);
793
0
      }
794
4
    }
795
229
  } else {
796
    // Nothing was decoded, so just drop this frame buffer
797
0
    lock_buffer_pool(pool);
798
0
    decrease_ref_count(cm->cur_frame, pool);
799
0
    unlock_buffer_pool(pool);
800
0
  }
801
229
  cm->cur_frame = NULL;
802
803
  // Invalidate these references until the next frame starts.
804
1.83k
  for (ref_index = 0; ref_index < INTER_REFS_PER_FRAME; ref_index++) {
805
1.60k
    cm->remapped_ref_idx[ref_index] = INVALID_IDX;
806
1.60k
  }
807
229
}
808
809
int av2_receive_compressed_data(AV2Decoder *pbi, size_t size,
810
33.0k
                                const uint8_t **psource) {
811
33.0k
  AV2_COMMON *volatile const cm = &pbi->common;
812
33.0k
  const uint8_t *source = *psource;
813
33.0k
  cm->error.error_code = AVM_CODEC_OK;
814
33.0k
  cm->error.has_detail = 0;
815
33.0k
  cm->decoding = 1;
816
817
33.0k
  if (size == 0) {
818
    // This is used to signal that we are missing frames.
819
    // We do not know if the missing frame(s) was supposed to update
820
    // any of the reference buffers, but we act conservative and
821
    // mark only the last buffer as corrupted.
822
    //
823
    // TODO(jkoleszar): Error concealment is undefined and non-normative
824
    // at this point, but if it becomes so, [0] may not always be the correct
825
    // thing to do here.
826
0
    const int last_frame = get_closest_pastcur_ref_or_ref0(cm);
827
0
    RefCntBuffer *ref_buf = get_ref_frame_buf(cm, last_frame);
828
0
    if (ref_buf != NULL) ref_buf->buf.corrupted = 1;
829
0
  }
830
33.0k
  check_ref_count_status_dec(pbi);
831
33.0k
  if (assign_cur_frame_new_fb(cm) == NULL) {
832
0
    cm->error.error_code = AVM_CODEC_MEM_ERROR;
833
0
    return 1;
834
0
  }
835
836
  // The jmp_buf is valid only for the duration of the function that calls
837
  // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
838
  // before it returns.
839
33.0k
  if (setjmp(cm->error.jmp)) {
840
28.0k
    const AVxWorkerInterface *const winterface = avm_get_worker_interface();
841
28.0k
    int i;
842
843
28.0k
    cm->error.setjmp = 0;
844
845
    // Synchronize all threads immediately as a subsequent decode call may
846
    // cause a resize invalidating some allocations.
847
28.0k
    winterface->sync(&pbi->lf_worker);
848
418k
    for (i = 0; i < pbi->num_workers; ++i) {
849
390k
      winterface->sync(&pbi->tile_workers[i]);
850
390k
    }
851
852
28.0k
    release_current_frame(pbi);
853
28.0k
    avm_clear_system_state();
854
28.0k
    return -1;
855
28.0k
  }
856
857
4.98k
  cm->error.setjmp = 1;
858
859
4.98k
  int frame_decoded =
860
4.98k
      avm_decode_frame_from_obus(pbi, source, source + size, psource);
861
#if CONFIG_INSPECTION
862
  if (cm->features.tip_frame_mode == TIP_FRAME_AS_OUTPUT) {
863
    if (pbi->inspect_tip_cb != NULL) {
864
      (*pbi->inspect_tip_cb)(pbi, pbi->inspect_ctx);
865
    }
866
  }
867
#endif
868
869
4.98k
  if (frame_decoded < 0) {
870
4.75k
    assert(cm->error.error_code != AVM_CODEC_OK);
871
4.75k
    release_current_frame(pbi);
872
4.75k
    cm->error.setjmp = 0;
873
4.75k
    return 1;
874
4.75k
  }
875
876
#if TXCOEFF_TIMER
877
  cm->cum_txcoeff_timer += cm->txcoeff_timer;
878
  fprintf(stderr,
879
          "txb coeff block number: %d, frame time: %ld, cum time %ld in us\n",
880
          cm->txb_count, cm->txcoeff_timer, cm->cum_txcoeff_timer);
881
  cm->txcoeff_timer = 0;
882
  cm->txb_count = 0;
883
#endif
884
885
  // Note: At this point, this function holds a reference to cm->cur_frame
886
  // in the buffer pool. This reference is consumed by update_frame_buffers().
887
229
  check_ref_count_status_dec(pbi);
888
229
  update_frame_buffers(pbi, frame_decoded);
889
229
  check_ref_count_status_dec(pbi);
890
891
229
  if (frame_decoded) {
892
229
    pbi->decoding_first_frame = 0;
893
229
  }
894
895
229
  if (cm->error.error_code != AVM_CODEC_OK) {
896
0
    cm->error.setjmp = 0;
897
0
    return 1;
898
0
  }
899
900
229
  avm_clear_system_state();
901
229
  if (cm->seg.enabled) {
902
27
    if (cm->prev_frame && (cm->mi_params.mi_rows == cm->prev_frame->mi_rows) &&
903
0
        (cm->mi_params.mi_cols == cm->prev_frame->mi_cols)) {
904
0
      cm->last_frame_seg_map = cm->prev_frame->seg_map;
905
27
    } else {
906
27
      cm->last_frame_seg_map = NULL;
907
27
    }
908
27
  }
909
910
  // Update progress in frame parallel decode.
911
229
  cm->error.setjmp = 0;
912
913
229
  return 0;
914
229
}
915
916
// Get the frame at a particular index in the output queue
917
int av2_get_raw_frame(AV2Decoder *pbi, size_t index, YV12_BUFFER_CONFIG **sd,
918
3.58k
                      avm_film_grain_t **grain_params) {
919
3.58k
  if (index >= pbi->num_output_frames) return -1;
920
210
  *sd = &pbi->output_frames[index]->buf;
921
210
  *grain_params = &pbi->output_frames[index]->film_grain_params;
922
210
  avm_clear_system_state();
923
210
  return 0;
924
3.58k
}
925
926
// Get the highest-spatial-layer output
927
// TODO(rachelbarker): What should this do?
928
0
int av2_get_frame_to_show(AV2Decoder *pbi, YV12_BUFFER_CONFIG *frame) {
929
0
  if (pbi->num_output_frames == 0) return -1;
930
0
  const size_t out_frame_idx = pbi->output_frames_offset;
931
0
  if (pbi->num_output_frames <= out_frame_idx) return -1;
932
0
  *frame = pbi->output_frames[out_frame_idx]->buf;
933
0
  return 0;
934
0
}