Coverage Report

Created: 2025-06-22 08:04

/src/aom/av1/encoder/encoder.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 <float.h>
14
#include <limits.h>
15
#include <math.h>
16
#include <stdbool.h>
17
#include <stdio.h>
18
#include <stdlib.h>
19
#include <time.h>
20
21
#include "av1/common/scale.h"
22
#include "config/aom_config.h"
23
#include "config/aom_dsp_rtcd.h"
24
25
#include "aom/aomcx.h"
26
27
#if CONFIG_DENOISE
28
#include "aom_dsp/grain_table.h"
29
#include "aom_dsp/noise_util.h"
30
#include "aom_dsp/noise_model.h"
31
#endif
32
#include "aom_dsp/flow_estimation/corner_detect.h"
33
#include "aom_dsp/psnr.h"
34
#if CONFIG_INTERNAL_STATS
35
#include "aom_dsp/ssim.h"
36
#endif
37
#include "aom_ports/aom_timer.h"
38
#include "aom_ports/mem.h"
39
#include "aom_util/aom_pthread.h"
40
#if CONFIG_BITSTREAM_DEBUG
41
#include "aom_util/debug_util.h"
42
#endif  // CONFIG_BITSTREAM_DEBUG
43
44
#include "av1/common/alloccommon.h"
45
#include "av1/common/debugmodes.h"
46
#include "av1/common/filter.h"
47
#include "av1/common/idct.h"
48
#include "av1/common/reconinter.h"
49
#include "av1/common/reconintra.h"
50
#include "av1/common/resize.h"
51
#include "av1/common/tile_common.h"
52
53
#include "av1/encoder/allintra_vis.h"
54
#include "av1/encoder/aq_complexity.h"
55
#include "av1/encoder/aq_cyclicrefresh.h"
56
#include "av1/encoder/aq_variance.h"
57
#include "av1/encoder/bitstream.h"
58
#if CONFIG_INTERNAL_STATS
59
#include "av1/encoder/blockiness.h"
60
#endif
61
#include "av1/encoder/context_tree.h"
62
#include "av1/encoder/dwt.h"
63
#include "av1/encoder/encodeframe.h"
64
#include "av1/encoder/encodemv.h"
65
#include "av1/encoder/encode_strategy.h"
66
#include "av1/encoder/encoder.h"
67
#include "av1/encoder/encoder_alloc.h"
68
#include "av1/encoder/encoder_utils.h"
69
#include "av1/encoder/encodetxb.h"
70
#include "av1/encoder/ethread.h"
71
#include "av1/encoder/firstpass.h"
72
#include "av1/encoder/hash_motion.h"
73
#include "av1/encoder/hybrid_fwd_txfm.h"
74
#include "av1/encoder/intra_mode_search.h"
75
#include "av1/encoder/mv_prec.h"
76
#include "av1/encoder/pass2_strategy.h"
77
#include "av1/encoder/pickcdef.h"
78
#include "av1/encoder/picklpf.h"
79
#include "av1/encoder/pickrst.h"
80
#include "av1/encoder/random.h"
81
#include "av1/encoder/ratectrl.h"
82
#include "av1/encoder/rc_utils.h"
83
#include "av1/encoder/rd.h"
84
#include "av1/encoder/rdopt.h"
85
#if CONFIG_SALIENCY_MAP
86
#include "av1/encoder/saliency_map.h"
87
#endif
88
#include "av1/encoder/segmentation.h"
89
#include "av1/encoder/speed_features.h"
90
#include "av1/encoder/superres_scale.h"
91
#if CONFIG_THREE_PASS
92
#include "av1/encoder/thirdpass.h"
93
#endif
94
#include "av1/encoder/tpl_model.h"
95
#include "av1/encoder/reconinter_enc.h"
96
#include "av1/encoder/var_based_part.h"
97
98
0
#define DEFAULT_EXPLICIT_ORDER_HINT_BITS 7
99
100
// #define OUTPUT_YUV_REC
101
#ifdef OUTPUT_YUV_REC
102
FILE *yuv_rec_file;
103
#define FILE_NAME_LEN 100
104
#endif
105
106
#ifdef OUTPUT_YUV_DENOISED
107
FILE *yuv_denoised_file = NULL;
108
#endif
109
110
0
static inline void Scale2Ratio(AOM_SCALING_MODE mode, int *hr, int *hs) {
111
0
  switch (mode) {
112
0
    case AOME_NORMAL:
113
0
      *hr = 1;
114
0
      *hs = 1;
115
0
      break;
116
0
    case AOME_FOURFIVE:
117
0
      *hr = 4;
118
0
      *hs = 5;
119
0
      break;
120
0
    case AOME_THREEFIVE:
121
0
      *hr = 3;
122
0
      *hs = 5;
123
0
      break;
124
0
    case AOME_THREEFOUR:
125
0
      *hr = 3;
126
0
      *hs = 4;
127
0
      break;
128
0
    case AOME_ONEFOUR:
129
0
      *hr = 1;
130
0
      *hs = 4;
131
0
      break;
132
0
    case AOME_ONEEIGHT:
133
0
      *hr = 1;
134
0
      *hs = 8;
135
0
      break;
136
0
    case AOME_ONETWO:
137
0
      *hr = 1;
138
0
      *hs = 2;
139
0
      break;
140
0
    case AOME_TWOTHREE:
141
0
      *hr = 2;
142
0
      *hs = 3;
143
0
      break;
144
0
    case AOME_ONETHREE:
145
0
      *hr = 1;
146
0
      *hs = 3;
147
0
      break;
148
0
    default:
149
0
      *hr = 1;
150
0
      *hs = 1;
151
0
      assert(0);
152
0
      break;
153
0
  }
154
0
}
155
156
int av1_set_active_map(AV1_COMP *cpi, unsigned char *new_map_16x16, int rows,
157
0
                       int cols) {
158
0
  const CommonModeInfoParams *const mi_params = &cpi->common.mi_params;
159
0
  if (rows == mi_params->mb_rows && cols == mi_params->mb_cols) {
160
0
    unsigned char *const active_map_4x4 = cpi->active_map.map;
161
0
    const int mi_rows = mi_params->mi_rows;
162
0
    const int mi_cols = mi_params->mi_cols;
163
0
    cpi->active_map.update = 0;
164
0
    cpi->rc.percent_blocks_inactive = 0;
165
0
    assert(mi_rows % 2 == 0 && mi_rows > 0);
166
0
    assert(mi_cols % 2 == 0 && mi_cols > 0);
167
0
    if (new_map_16x16) {
168
0
      int num_samples = 0;
169
0
      int num_blocks_inactive = 0;
170
0
      for (int r = 0; r < mi_rows; r += 4) {
171
0
        for (int c = 0; c < mi_cols; c += 4) {
172
0
          const uint8_t val = new_map_16x16[(r >> 2) * cols + (c >> 2)]
173
0
                                  ? AM_SEGMENT_ID_ACTIVE
174
0
                                  : AM_SEGMENT_ID_INACTIVE;
175
0
          num_samples++;
176
0
          if (val == AM_SEGMENT_ID_INACTIVE) num_blocks_inactive++;
177
0
          const int row_max = AOMMIN(4, mi_rows - r);
178
0
          const int col_max = AOMMIN(4, mi_cols - c);
179
0
          for (int x = 0; x < row_max; ++x) {
180
0
            for (int y = 0; y < col_max; ++y) {
181
0
              active_map_4x4[(r + x) * mi_cols + (c + y)] = val;
182
0
            }
183
0
          }
184
0
        }
185
0
      }
186
0
      cpi->active_map.enabled = 1;
187
0
      cpi->active_map.update = 1;
188
0
      assert(num_samples);
189
0
      cpi->rc.percent_blocks_inactive =
190
0
          (num_blocks_inactive * 100) / num_samples;
191
0
    }
192
0
    return 0;
193
0
  }
194
195
0
  return -1;
196
0
}
197
198
int av1_get_active_map(AV1_COMP *cpi, unsigned char *new_map_16x16, int rows,
199
0
                       int cols) {
200
0
  const CommonModeInfoParams *const mi_params = &cpi->common.mi_params;
201
0
  if (rows == mi_params->mb_rows && cols == mi_params->mb_cols &&
202
0
      new_map_16x16) {
203
0
    unsigned char *const seg_map_8x8 = cpi->enc_seg.map;
204
0
    const int mi_rows = mi_params->mi_rows;
205
0
    const int mi_cols = mi_params->mi_cols;
206
0
    const int row_scale = mi_size_high_log2[BLOCK_16X16];
207
0
    const int col_scale = mi_size_wide_log2[BLOCK_16X16];
208
0
    assert(mi_rows % 2 == 0);
209
0
    assert(mi_cols % 2 == 0);
210
211
0
    memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
212
0
    if (cpi->active_map.enabled) {
213
0
      for (int r = 0; r < (mi_rows >> row_scale); ++r) {
214
0
        for (int c = 0; c < (mi_cols >> col_scale); ++c) {
215
          // Cyclic refresh segments are considered active despite not having
216
          // AM_SEGMENT_ID_ACTIVE
217
0
          uint8_t temp = 0;
218
0
          temp |= seg_map_8x8[(2 * r + 0) * mi_cols + (2 * c + 0)] !=
219
0
                  AM_SEGMENT_ID_INACTIVE;
220
0
          temp |= seg_map_8x8[(2 * r + 0) * mi_cols + (2 * c + 1)] !=
221
0
                  AM_SEGMENT_ID_INACTIVE;
222
0
          temp |= seg_map_8x8[(2 * r + 1) * mi_cols + (2 * c + 0)] !=
223
0
                  AM_SEGMENT_ID_INACTIVE;
224
0
          temp |= seg_map_8x8[(2 * r + 1) * mi_cols + (2 * c + 1)] !=
225
0
                  AM_SEGMENT_ID_INACTIVE;
226
0
          new_map_16x16[r * cols + c] |= temp;
227
0
        }
228
0
      }
229
0
    }
230
0
    return 0;
231
0
  }
232
233
0
  return -1;
234
0
}
235
236
0
void av1_initialize_enc(unsigned int usage, enum aom_rc_mode end_usage) {
237
0
  bool is_allintra = usage == ALLINTRA;
238
239
0
  av1_rtcd();
240
0
  aom_dsp_rtcd();
241
0
  aom_scale_rtcd();
242
0
  av1_init_intra_predictors();
243
0
  av1_init_me_luts();
244
0
  if (!is_allintra) av1_init_wedge_masks();
245
0
  if (!is_allintra || end_usage != AOM_Q) av1_rc_init_minq_luts();
246
0
}
247
248
0
void av1_new_framerate(AV1_COMP *cpi, double framerate) {
249
0
  cpi->framerate = framerate < 0.1 ? 30 : framerate;
250
0
  av1_rc_update_framerate(cpi, cpi->common.width, cpi->common.height);
251
0
}
252
253
double av1_get_compression_ratio(const AV1_COMMON *const cm,
254
0
                                 size_t encoded_frame_size) {
255
0
  const int upscaled_width = cm->superres_upscaled_width;
256
0
  const int height = cm->height;
257
0
  const int64_t luma_pic_size = (int64_t)upscaled_width * height;
258
0
  const SequenceHeader *const seq_params = cm->seq_params;
259
0
  const BITSTREAM_PROFILE profile = seq_params->profile;
260
0
  const int pic_size_profile_factor =
261
0
      profile == PROFILE_0 ? 15 : (profile == PROFILE_1 ? 30 : 36);
262
0
  encoded_frame_size =
263
0
      (encoded_frame_size > 129 ? encoded_frame_size - 128 : 1);
264
0
  const int64_t uncompressed_frame_size =
265
0
      (luma_pic_size * pic_size_profile_factor) >> 3;
266
0
  return (double)uncompressed_frame_size / encoded_frame_size;
267
0
}
268
269
static void auto_tile_size_balancing(AV1_COMMON *const cm, int num_sbs,
270
0
                                     int num_tiles_lg, int tile_col_row) {
271
0
  CommonTileParams *const tiles = &cm->tiles;
272
0
  int i, start_sb;
273
0
  int size_sb = num_sbs >> num_tiles_lg;
274
0
  int res_sbs = num_sbs - (size_sb << num_tiles_lg);
275
0
  int num_tiles = 1 << num_tiles_lg;
276
0
  int inc_index = num_tiles - res_sbs;
277
278
0
  tiles->uniform_spacing = 0;
279
280
0
  for (i = 0, start_sb = 0; start_sb < num_sbs && i < MAX_TILE_COLS; ++i) {
281
0
    if (i == inc_index) ++size_sb;
282
0
    if (tile_col_row)
283
0
      tiles->col_start_sb[i] = start_sb;
284
0
    else
285
0
      tiles->row_start_sb[i] = start_sb;
286
287
0
    start_sb += AOMMIN(size_sb, tiles->max_width_sb);
288
0
  }
289
290
0
  if (tile_col_row) {
291
0
    tiles->cols = i;
292
0
    tiles->col_start_sb[i] = num_sbs;
293
0
  } else {
294
0
    tiles->rows = i;
295
0
    tiles->row_start_sb[i] = num_sbs;
296
0
  }
297
0
}
298
299
static void set_tile_info(AV1_COMMON *const cm,
300
0
                          const TileConfig *const tile_cfg) {
301
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
302
0
  const SequenceHeader *const seq_params = cm->seq_params;
303
0
  CommonTileParams *const tiles = &cm->tiles;
304
0
  int i, start_sb;
305
306
0
  av1_get_tile_limits(cm);
307
308
0
  int sb_cols =
309
0
      CEIL_POWER_OF_TWO(mi_params->mi_cols, seq_params->mib_size_log2);
310
  // configure tile columns
311
0
  if (tile_cfg->tile_width_count == 0 || tile_cfg->tile_height_count == 0) {
312
0
    tiles->uniform_spacing = 1;
313
0
    tiles->log2_cols = AOMMAX(tile_cfg->tile_columns, tiles->min_log2_cols);
314
    // Add a special case to handle super resolution
315
0
    sb_cols = coded_to_superres_mi(sb_cols, cm->superres_scale_denominator);
316
0
    int min_log2_cols = 0;
317
0
    for (; (tiles->max_width_sb << min_log2_cols) <= sb_cols; ++min_log2_cols) {
318
0
    }
319
0
    tiles->log2_cols = AOMMAX(tiles->log2_cols, min_log2_cols);
320
321
0
    tiles->log2_cols = AOMMIN(tiles->log2_cols, tiles->max_log2_cols);
322
0
  } else if (tile_cfg->tile_widths[0] < 0) {
323
0
    auto_tile_size_balancing(cm, sb_cols, tile_cfg->tile_columns, 1);
324
0
  } else {
325
0
    int size_sb, j = 0;
326
0
    tiles->uniform_spacing = 0;
327
0
    for (i = 0, start_sb = 0; start_sb < sb_cols && i < MAX_TILE_COLS; i++) {
328
0
      tiles->col_start_sb[i] = start_sb;
329
0
      size_sb = tile_cfg->tile_widths[j++];
330
0
      if (j >= tile_cfg->tile_width_count) j = 0;
331
0
      start_sb += AOMMIN(size_sb, tiles->max_width_sb);
332
0
    }
333
0
    tiles->cols = i;
334
0
    tiles->col_start_sb[i] = sb_cols;
335
0
  }
336
0
  av1_calculate_tile_cols(seq_params, mi_params->mi_rows, mi_params->mi_cols,
337
0
                          tiles);
338
339
  // configure tile rows
340
0
  int sb_rows =
341
0
      CEIL_POWER_OF_TWO(mi_params->mi_rows, seq_params->mib_size_log2);
342
0
  if (tiles->uniform_spacing) {
343
0
    tiles->log2_rows = AOMMAX(tile_cfg->tile_rows, tiles->min_log2_rows);
344
0
    tiles->log2_rows = AOMMIN(tiles->log2_rows, tiles->max_log2_rows);
345
0
  } else if (tile_cfg->tile_heights[0] < 0) {
346
0
    auto_tile_size_balancing(cm, sb_rows, tile_cfg->tile_rows, 0);
347
0
  } else {
348
0
    int size_sb, j = 0;
349
0
    for (i = 0, start_sb = 0; start_sb < sb_rows && i < MAX_TILE_ROWS; i++) {
350
0
      tiles->row_start_sb[i] = start_sb;
351
0
      size_sb = tile_cfg->tile_heights[j++];
352
0
      if (j >= tile_cfg->tile_height_count) j = 0;
353
0
      start_sb += AOMMIN(size_sb, tiles->max_height_sb);
354
0
    }
355
0
    tiles->rows = i;
356
0
    tiles->row_start_sb[i] = sb_rows;
357
0
  }
358
0
  av1_calculate_tile_rows(seq_params, mi_params->mi_rows, tiles);
359
0
}
360
361
0
void av1_update_frame_size(AV1_COMP *cpi) {
362
0
  AV1_COMMON *const cm = &cpi->common;
363
0
  MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
364
365
  // Setup mi_params here in case we need more mi's.
366
0
  CommonModeInfoParams *const mi_params = &cm->mi_params;
367
0
  mi_params->set_mb_mi(mi_params, cm->width, cm->height,
368
0
                       cpi->sf.part_sf.default_min_partition_size);
369
370
0
  av1_init_macroblockd(cm, xd);
371
372
0
  if (!cpi->ppi->seq_params_locked)
373
0
    set_sb_size(cm->seq_params,
374
0
                av1_select_sb_size(&cpi->oxcf, cm->width, cm->height,
375
0
                                   cpi->ppi->number_spatial_layers));
376
377
0
  set_tile_info(cm, &cpi->oxcf.tile_cfg);
378
0
}
379
380
static inline int does_level_match(int width, int height, double fps,
381
                                   int lvl_width, int lvl_height,
382
0
                                   double lvl_fps, int lvl_dim_mult) {
383
0
  const int64_t lvl_luma_pels = (int64_t)lvl_width * lvl_height;
384
0
  const double lvl_display_sample_rate = lvl_luma_pels * lvl_fps;
385
0
  const int64_t luma_pels = (int64_t)width * height;
386
0
  const double display_sample_rate = luma_pels * fps;
387
0
  return luma_pels <= lvl_luma_pels &&
388
0
         display_sample_rate <= lvl_display_sample_rate &&
389
0
         width <= lvl_width * lvl_dim_mult &&
390
0
         height <= lvl_height * lvl_dim_mult;
391
0
}
392
393
static void set_bitstream_level_tier(AV1_PRIMARY *const ppi, int width,
394
0
                                     int height, double init_framerate) {
395
0
  SequenceHeader *const seq_params = &ppi->seq_params;
396
0
  const AV1LevelParams *const level_params = &ppi->level_params;
397
  // TODO(any): This is a placeholder function that only addresses dimensions
398
  // and max display sample rates.
399
  // Need to add checks for max bit rate, max decoded luma sample rate, header
400
  // rate, etc. that are not covered by this function.
401
0
  AV1_LEVEL level = SEQ_LEVEL_MAX;
402
0
  if (does_level_match(width, height, init_framerate, 512, 288, 30.0, 4)) {
403
0
    level = SEQ_LEVEL_2_0;
404
0
  } else if (does_level_match(width, height, init_framerate, 704, 396, 30.0,
405
0
                              4)) {
406
0
    level = SEQ_LEVEL_2_1;
407
0
  } else if (does_level_match(width, height, init_framerate, 1088, 612, 30.0,
408
0
                              4)) {
409
0
    level = SEQ_LEVEL_3_0;
410
0
  } else if (does_level_match(width, height, init_framerate, 1376, 774, 30.0,
411
0
                              4)) {
412
0
    level = SEQ_LEVEL_3_1;
413
0
  } else if (does_level_match(width, height, init_framerate, 2048, 1152, 30.0,
414
0
                              3)) {
415
0
    level = SEQ_LEVEL_4_0;
416
0
  } else if (does_level_match(width, height, init_framerate, 2048, 1152, 60.0,
417
0
                              3)) {
418
0
    level = SEQ_LEVEL_4_1;
419
0
  } else if (does_level_match(width, height, init_framerate, 4096, 2176, 30.0,
420
0
                              2)) {
421
0
    level = SEQ_LEVEL_5_0;
422
0
  } else if (does_level_match(width, height, init_framerate, 4096, 2176, 60.0,
423
0
                              2)) {
424
0
    level = SEQ_LEVEL_5_1;
425
0
  } else if (does_level_match(width, height, init_framerate, 4096, 2176, 120.0,
426
0
                              2)) {
427
0
    level = SEQ_LEVEL_5_2;
428
0
  } else if (does_level_match(width, height, init_framerate, 8192, 4352, 30.0,
429
0
                              2)) {
430
0
    level = SEQ_LEVEL_6_0;
431
0
  } else if (does_level_match(width, height, init_framerate, 8192, 4352, 60.0,
432
0
                              2)) {
433
0
    level = SEQ_LEVEL_6_1;
434
0
  } else if (does_level_match(width, height, init_framerate, 8192, 4352, 120.0,
435
0
                              2)) {
436
0
    level = SEQ_LEVEL_6_2;
437
0
  }
438
#if CONFIG_CWG_C013
439
  // TODO(bohanli): currently target level is only working for the 0th operating
440
  // point, so scalable coding is not supported.
441
  else if (level_params->target_seq_level_idx[0] >= SEQ_LEVEL_7_0 &&
442
           level_params->target_seq_level_idx[0] <= SEQ_LEVEL_8_3) {
443
    // Only use level 7.x to 8.x when explicitly asked to.
444
    if (does_level_match(width, height, init_framerate, 16384, 8704, 30.0, 2)) {
445
      level = SEQ_LEVEL_7_0;
446
    } else if (does_level_match(width, height, init_framerate, 16384, 8704,
447
                                60.0, 2)) {
448
      level = SEQ_LEVEL_7_1;
449
    } else if (does_level_match(width, height, init_framerate, 16384, 8704,
450
                                120.0, 2)) {
451
      level = SEQ_LEVEL_7_2;
452
    } else if (does_level_match(width, height, init_framerate, 32768, 17408,
453
                                30.0, 2)) {
454
      level = SEQ_LEVEL_8_0;
455
    } else if (does_level_match(width, height, init_framerate, 32768, 17408,
456
                                60.0, 2)) {
457
      level = SEQ_LEVEL_8_1;
458
    } else if (does_level_match(width, height, init_framerate, 32768, 17408,
459
                                120.0, 2)) {
460
      level = SEQ_LEVEL_8_2;
461
    }
462
  }
463
#endif
464
465
0
  for (int i = 0; i < MAX_NUM_OPERATING_POINTS; ++i) {
466
0
    assert(is_valid_seq_level_idx(level_params->target_seq_level_idx[i]) ||
467
0
           level_params->target_seq_level_idx[i] == SEQ_LEVEL_KEEP_STATS);
468
    // If a higher target level is specified, it is then used rather than the
469
    // inferred one from resolution and framerate.
470
0
    seq_params->seq_level_idx[i] =
471
0
        level_params->target_seq_level_idx[i] < SEQ_LEVELS &&
472
0
                level_params->target_seq_level_idx[i] > level
473
0
            ? level_params->target_seq_level_idx[i]
474
0
            : level;
475
    // Set the maximum parameters for bitrate and buffer size for this profile,
476
    // level, and tier
477
0
    seq_params->op_params[i].bitrate = av1_max_level_bitrate(
478
0
        seq_params->profile, seq_params->seq_level_idx[i], seq_params->tier[i]);
479
    // Level with seq_level_idx = 31 returns a high "dummy" bitrate to pass the
480
    // check
481
0
    if (seq_params->op_params[i].bitrate == 0)
482
0
      aom_internal_error(
483
0
          &ppi->error, AOM_CODEC_UNSUP_BITSTREAM,
484
0
          "AV1 does not support this combination of profile, level, and tier.");
485
    // Buffer size in bits/s is bitrate in bits/s * 1 s
486
0
    seq_params->op_params[i].buffer_size = seq_params->op_params[i].bitrate;
487
0
  }
488
0
}
489
490
static void init_seq_coding_tools(AV1_PRIMARY *const ppi,
491
                                  const AV1EncoderConfig *oxcf,
492
0
                                  int disable_frame_id_numbers) {
493
0
  SequenceHeader *const seq = &ppi->seq_params;
494
0
  const FrameDimensionCfg *const frm_dim_cfg = &oxcf->frm_dim_cfg;
495
0
  const ToolCfg *const tool_cfg = &oxcf->tool_cfg;
496
497
0
  seq->still_picture =
498
0
      !tool_cfg->force_video_mode && (oxcf->input_cfg.limit == 1);
499
0
  seq->reduced_still_picture_hdr =
500
0
      seq->still_picture && !tool_cfg->full_still_picture_hdr;
501
0
  seq->force_screen_content_tools = 2;
502
0
  seq->force_integer_mv = 2;
503
0
  seq->order_hint_info.enable_order_hint = tool_cfg->enable_order_hint;
504
0
  seq->frame_id_numbers_present_flag =
505
0
      !seq->reduced_still_picture_hdr &&
506
0
      !oxcf->tile_cfg.enable_large_scale_tile &&
507
0
      tool_cfg->error_resilient_mode && !disable_frame_id_numbers;
508
0
  if (seq->reduced_still_picture_hdr) {
509
0
    seq->order_hint_info.enable_order_hint = 0;
510
0
    seq->force_screen_content_tools = 2;
511
0
    seq->force_integer_mv = 2;
512
0
  }
513
0
  seq->order_hint_info.order_hint_bits_minus_1 =
514
0
      seq->order_hint_info.enable_order_hint
515
0
          ? DEFAULT_EXPLICIT_ORDER_HINT_BITS - 1
516
0
          : -1;
517
518
0
  seq->max_frame_width = frm_dim_cfg->forced_max_frame_width
519
0
                             ? frm_dim_cfg->forced_max_frame_width
520
0
                             : frm_dim_cfg->width;
521
0
  seq->max_frame_height = frm_dim_cfg->forced_max_frame_height
522
0
                              ? frm_dim_cfg->forced_max_frame_height
523
0
                              : frm_dim_cfg->height;
524
0
  seq->num_bits_width =
525
0
      (seq->max_frame_width > 1) ? get_msb(seq->max_frame_width - 1) + 1 : 1;
526
0
  seq->num_bits_height =
527
0
      (seq->max_frame_height > 1) ? get_msb(seq->max_frame_height - 1) + 1 : 1;
528
0
  assert(seq->num_bits_width <= 16);
529
0
  assert(seq->num_bits_height <= 16);
530
531
0
  seq->frame_id_length = FRAME_ID_LENGTH;
532
0
  seq->delta_frame_id_length = DELTA_FRAME_ID_LENGTH;
533
534
0
  seq->enable_dual_filter = tool_cfg->enable_dual_filter;
535
0
  seq->order_hint_info.enable_dist_wtd_comp =
536
0
      oxcf->comp_type_cfg.enable_dist_wtd_comp;
537
0
  seq->order_hint_info.enable_dist_wtd_comp &=
538
0
      seq->order_hint_info.enable_order_hint;
539
0
  seq->order_hint_info.enable_ref_frame_mvs = tool_cfg->ref_frame_mvs_present;
540
0
  seq->order_hint_info.enable_ref_frame_mvs &=
541
0
      seq->order_hint_info.enable_order_hint;
542
0
  seq->enable_superres = oxcf->superres_cfg.enable_superres;
543
0
  seq->enable_cdef = tool_cfg->cdef_control != CDEF_NONE ? 1 : 0;
544
0
  seq->enable_restoration = tool_cfg->enable_restoration;
545
0
  seq->enable_warped_motion = oxcf->motion_mode_cfg.enable_warped_motion;
546
0
  seq->enable_interintra_compound = tool_cfg->enable_interintra_comp;
547
0
  seq->enable_masked_compound = oxcf->comp_type_cfg.enable_masked_comp;
548
0
  seq->enable_intra_edge_filter = oxcf->intra_mode_cfg.enable_intra_edge_filter;
549
0
  seq->enable_filter_intra = oxcf->intra_mode_cfg.enable_filter_intra;
550
551
0
  set_bitstream_level_tier(ppi, frm_dim_cfg->width, frm_dim_cfg->height,
552
0
                           oxcf->input_cfg.init_framerate);
553
554
0
  if (seq->operating_points_cnt_minus_1 == 0) {
555
0
    seq->operating_point_idc[0] = 0;
556
0
    seq->has_nonzero_operating_point_idc = false;
557
0
  } else {
558
    // Set operating_point_idc[] such that the i=0 point corresponds to the
559
    // highest quality operating point (all layers), and subsequent
560
    // operarting points (i > 0) are lower quality corresponding to
561
    // skip decoding enhancement  layers (temporal first).
562
0
    int i = 0;
563
0
    assert(seq->operating_points_cnt_minus_1 ==
564
0
           (int)(ppi->number_spatial_layers * ppi->number_temporal_layers - 1));
565
0
    for (unsigned int sl = 0; sl < ppi->number_spatial_layers; sl++) {
566
0
      for (unsigned int tl = 0; tl < ppi->number_temporal_layers; tl++) {
567
0
        seq->operating_point_idc[i] =
568
0
            (~(~0u << (ppi->number_spatial_layers - sl)) << 8) |
569
0
            ~(~0u << (ppi->number_temporal_layers - tl));
570
0
        assert(seq->operating_point_idc[i] != 0);
571
0
        i++;
572
0
      }
573
0
    }
574
0
    seq->has_nonzero_operating_point_idc = true;
575
0
  }
576
0
}
577
578
static void init_config_sequence(struct AV1_PRIMARY *ppi,
579
0
                                 const AV1EncoderConfig *oxcf) {
580
0
  SequenceHeader *const seq_params = &ppi->seq_params;
581
0
  const DecoderModelCfg *const dec_model_cfg = &oxcf->dec_model_cfg;
582
0
  const ColorCfg *const color_cfg = &oxcf->color_cfg;
583
584
0
  ppi->use_svc = 0;
585
0
  ppi->number_spatial_layers = 1;
586
0
  ppi->number_temporal_layers = 1;
587
588
0
  seq_params->profile = oxcf->profile;
589
0
  seq_params->bit_depth = oxcf->tool_cfg.bit_depth;
590
0
  seq_params->use_highbitdepth = oxcf->use_highbitdepth;
591
0
  seq_params->color_primaries = color_cfg->color_primaries;
592
0
  seq_params->transfer_characteristics = color_cfg->transfer_characteristics;
593
0
  seq_params->matrix_coefficients = color_cfg->matrix_coefficients;
594
0
  seq_params->monochrome = oxcf->tool_cfg.enable_monochrome;
595
0
  seq_params->chroma_sample_position = color_cfg->chroma_sample_position;
596
0
  seq_params->color_range = color_cfg->color_range;
597
0
  seq_params->timing_info_present = dec_model_cfg->timing_info_present;
598
0
  seq_params->timing_info.num_units_in_display_tick =
599
0
      dec_model_cfg->timing_info.num_units_in_display_tick;
600
0
  seq_params->timing_info.time_scale = dec_model_cfg->timing_info.time_scale;
601
0
  seq_params->timing_info.equal_picture_interval =
602
0
      dec_model_cfg->timing_info.equal_picture_interval;
603
0
  seq_params->timing_info.num_ticks_per_picture =
604
0
      dec_model_cfg->timing_info.num_ticks_per_picture;
605
606
0
  seq_params->display_model_info_present_flag =
607
0
      dec_model_cfg->display_model_info_present_flag;
608
0
  seq_params->decoder_model_info_present_flag =
609
0
      dec_model_cfg->decoder_model_info_present_flag;
610
0
  if (dec_model_cfg->decoder_model_info_present_flag) {
611
    // set the decoder model parameters in schedule mode
612
0
    seq_params->decoder_model_info.num_units_in_decoding_tick =
613
0
        dec_model_cfg->num_units_in_decoding_tick;
614
0
    ppi->buffer_removal_time_present = 1;
615
0
    av1_set_aom_dec_model_info(&seq_params->decoder_model_info);
616
0
    av1_set_dec_model_op_parameters(&seq_params->op_params[0]);
617
0
  } else if (seq_params->timing_info_present &&
618
0
             seq_params->timing_info.equal_picture_interval &&
619
0
             !seq_params->decoder_model_info_present_flag) {
620
    // set the decoder model parameters in resource availability mode
621
0
    av1_set_resource_availability_parameters(&seq_params->op_params[0]);
622
0
  } else {
623
0
    seq_params->op_params[0].initial_display_delay =
624
0
        10;  // Default value (not signaled)
625
0
  }
626
627
0
  if (seq_params->monochrome) {
628
0
    seq_params->subsampling_x = 1;
629
0
    seq_params->subsampling_y = 1;
630
0
  } else if (seq_params->color_primaries == AOM_CICP_CP_BT_709 &&
631
0
             seq_params->transfer_characteristics == AOM_CICP_TC_SRGB &&
632
0
             seq_params->matrix_coefficients == AOM_CICP_MC_IDENTITY) {
633
0
    seq_params->subsampling_x = 0;
634
0
    seq_params->subsampling_y = 0;
635
0
  } else {
636
0
    if (seq_params->profile == 0) {
637
0
      seq_params->subsampling_x = 1;
638
0
      seq_params->subsampling_y = 1;
639
0
    } else if (seq_params->profile == 1) {
640
0
      seq_params->subsampling_x = 0;
641
0
      seq_params->subsampling_y = 0;
642
0
    } else {
643
0
      if (seq_params->bit_depth == AOM_BITS_12) {
644
0
        seq_params->subsampling_x = oxcf->input_cfg.chroma_subsampling_x;
645
0
        seq_params->subsampling_y = oxcf->input_cfg.chroma_subsampling_y;
646
0
      } else {
647
0
        seq_params->subsampling_x = 1;
648
0
        seq_params->subsampling_y = 0;
649
0
      }
650
0
    }
651
0
  }
652
0
  av1_change_config_seq(ppi, oxcf, NULL);
653
0
}
654
655
0
static void init_config(struct AV1_COMP *cpi, const AV1EncoderConfig *oxcf) {
656
0
  AV1_COMMON *const cm = &cpi->common;
657
0
  ResizePendingParams *resize_pending_params = &cpi->resize_pending_params;
658
659
0
  cpi->oxcf = *oxcf;
660
0
  cpi->framerate = oxcf->input_cfg.init_framerate;
661
662
0
  cm->width = oxcf->frm_dim_cfg.width;
663
0
  cm->height = oxcf->frm_dim_cfg.height;
664
0
  cpi->is_dropped_frame = false;
665
666
0
  alloc_compressor_data(cpi);
667
668
0
  cpi->data_alloc_width = cm->width;
669
0
  cpi->data_alloc_height = cm->height;
670
0
  cpi->frame_size_related_setup_done = false;
671
672
  // Single thread case: use counts in common.
673
0
  cpi->td.counts = &cpi->counts;
674
675
  // Init SVC parameters.
676
0
  cpi->svc.number_spatial_layers = 1;
677
0
  cpi->svc.number_temporal_layers = 1;
678
0
  cm->spatial_layer_id = 0;
679
0
  cm->temporal_layer_id = 0;
680
  // Init rtc_ref parameters.
681
0
  cpi->ppi->rtc_ref.set_ref_frame_config = 0;
682
0
  cpi->ppi->rtc_ref.non_reference_frame = 0;
683
0
  cpi->ppi->rtc_ref.ref_frame_comp[0] = 0;
684
0
  cpi->ppi->rtc_ref.ref_frame_comp[1] = 0;
685
0
  cpi->ppi->rtc_ref.ref_frame_comp[2] = 0;
686
687
  // change includes all joint functionality
688
0
  av1_change_config(cpi, oxcf, false);
689
690
0
  cpi->ref_frame_flags = 0;
691
692
  // Reset resize pending flags
693
0
  resize_pending_params->width = 0;
694
0
  resize_pending_params->height = 0;
695
696
  // Setup identity scale factor
697
0
  av1_setup_scale_factors_for_frame(&cm->sf_identity, 1, 1, 1, 1);
698
699
0
  init_buffer_indices(&cpi->force_intpel_info, cm->remapped_ref_idx);
700
701
0
  av1_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
702
0
}
703
704
void av1_change_config_seq(struct AV1_PRIMARY *ppi,
705
                           const AV1EncoderConfig *oxcf,
706
0
                           bool *is_sb_size_changed) {
707
0
  SequenceHeader *const seq_params = &ppi->seq_params;
708
0
  const FrameDimensionCfg *const frm_dim_cfg = &oxcf->frm_dim_cfg;
709
0
  const DecoderModelCfg *const dec_model_cfg = &oxcf->dec_model_cfg;
710
0
  const ColorCfg *const color_cfg = &oxcf->color_cfg;
711
712
0
  if (seq_params->profile != oxcf->profile) seq_params->profile = oxcf->profile;
713
0
  seq_params->bit_depth = oxcf->tool_cfg.bit_depth;
714
0
  seq_params->color_primaries = color_cfg->color_primaries;
715
0
  seq_params->transfer_characteristics = color_cfg->transfer_characteristics;
716
0
  seq_params->matrix_coefficients = color_cfg->matrix_coefficients;
717
0
  seq_params->monochrome = oxcf->tool_cfg.enable_monochrome;
718
0
  seq_params->chroma_sample_position = color_cfg->chroma_sample_position;
719
0
  seq_params->color_range = color_cfg->color_range;
720
721
0
  assert(IMPLIES(seq_params->profile <= PROFILE_1,
722
0
                 seq_params->bit_depth <= AOM_BITS_10));
723
724
0
  seq_params->timing_info_present = dec_model_cfg->timing_info_present;
725
0
  seq_params->timing_info.num_units_in_display_tick =
726
0
      dec_model_cfg->timing_info.num_units_in_display_tick;
727
0
  seq_params->timing_info.time_scale = dec_model_cfg->timing_info.time_scale;
728
0
  seq_params->timing_info.equal_picture_interval =
729
0
      dec_model_cfg->timing_info.equal_picture_interval;
730
0
  seq_params->timing_info.num_ticks_per_picture =
731
0
      dec_model_cfg->timing_info.num_ticks_per_picture;
732
733
0
  seq_params->display_model_info_present_flag =
734
0
      dec_model_cfg->display_model_info_present_flag;
735
0
  seq_params->decoder_model_info_present_flag =
736
0
      dec_model_cfg->decoder_model_info_present_flag;
737
0
  if (dec_model_cfg->decoder_model_info_present_flag) {
738
    // set the decoder model parameters in schedule mode
739
0
    seq_params->decoder_model_info.num_units_in_decoding_tick =
740
0
        dec_model_cfg->num_units_in_decoding_tick;
741
0
    ppi->buffer_removal_time_present = 1;
742
0
    av1_set_aom_dec_model_info(&seq_params->decoder_model_info);
743
0
    av1_set_dec_model_op_parameters(&seq_params->op_params[0]);
744
0
  } else if (seq_params->timing_info_present &&
745
0
             seq_params->timing_info.equal_picture_interval &&
746
0
             !seq_params->decoder_model_info_present_flag) {
747
    // set the decoder model parameters in resource availability mode
748
0
    av1_set_resource_availability_parameters(&seq_params->op_params[0]);
749
0
  } else {
750
0
    seq_params->op_params[0].initial_display_delay =
751
0
        10;  // Default value (not signaled)
752
0
  }
753
754
0
#if !CONFIG_REALTIME_ONLY
755
0
  av1_update_film_grain_parameters_seq(ppi, oxcf);
756
0
#endif
757
758
0
  int sb_size = seq_params->sb_size;
759
  // Superblock size should not be updated after the first key frame.
760
0
  if (!ppi->seq_params_locked) {
761
0
    set_sb_size(seq_params, av1_select_sb_size(oxcf, frm_dim_cfg->width,
762
0
                                               frm_dim_cfg->height,
763
0
                                               ppi->number_spatial_layers));
764
0
    for (int i = 0; i < MAX_NUM_OPERATING_POINTS; ++i)
765
0
      seq_params->tier[i] = (oxcf->tier_mask >> i) & 1;
766
0
  }
767
0
  if (is_sb_size_changed != NULL && sb_size != seq_params->sb_size)
768
0
    *is_sb_size_changed = true;
769
770
  // Init sequence level coding tools
771
  // This should not be called after the first key frame.
772
0
  if (!ppi->seq_params_locked) {
773
0
    seq_params->operating_points_cnt_minus_1 =
774
0
        (ppi->number_spatial_layers > 1 || ppi->number_temporal_layers > 1)
775
0
            ? ppi->number_spatial_layers * ppi->number_temporal_layers - 1
776
0
            : 0;
777
0
    init_seq_coding_tools(ppi, oxcf,
778
0
                          ppi->use_svc || ppi->rtc_ref.set_ref_frame_config);
779
0
  }
780
0
  seq_params->timing_info_present &= !seq_params->reduced_still_picture_hdr;
781
782
0
#if CONFIG_AV1_HIGHBITDEPTH
783
0
  highbd_set_var_fns(ppi);
784
0
#endif
785
786
0
  set_primary_rc_buffer_sizes(oxcf, ppi);
787
0
}
788
789
void av1_change_config(struct AV1_COMP *cpi, const AV1EncoderConfig *oxcf,
790
0
                       bool is_sb_size_changed) {
791
0
  AV1_COMMON *const cm = &cpi->common;
792
0
  SequenceHeader *const seq_params = cm->seq_params;
793
0
  RATE_CONTROL *const rc = &cpi->rc;
794
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
795
0
  MACROBLOCK *const x = &cpi->td.mb;
796
0
  AV1LevelParams *const level_params = &cpi->ppi->level_params;
797
0
  RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
798
0
  const FrameDimensionCfg *const frm_dim_cfg = &cpi->oxcf.frm_dim_cfg;
799
0
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
800
0
  FeatureFlags *const features = &cm->features;
801
802
  // in case of LAP, lag in frames is set according to number of lap buffers
803
  // calculated at init time. This stores and restores LAP's lag in frames to
804
  // prevent override by new cfg.
805
0
  int lap_lag_in_frames = -1;
806
0
  if (cpi->ppi->lap_enabled && cpi->compressor_stage == LAP_STAGE) {
807
0
    lap_lag_in_frames = cpi->oxcf.gf_cfg.lag_in_frames;
808
0
  }
809
810
0
  cpi->oxcf = *oxcf;
811
812
0
#if !CONFIG_REALTIME_ONLY
813
0
  av1_update_film_grain_parameters(cpi, oxcf);
814
0
#endif
815
816
  // When user provides superres_mode = AOM_SUPERRES_AUTO, we still initialize
817
  // superres mode for current encoding = AOM_SUPERRES_NONE. This is to ensure
818
  // that any analysis (e.g. TPL) happening outside the main encoding loop still
819
  // happens at full resolution.
820
  // This value will later be set appropriately just before main encoding loop.
821
0
  cpi->superres_mode = oxcf->superres_cfg.superres_mode == AOM_SUPERRES_AUTO
822
0
                           ? AOM_SUPERRES_NONE
823
0
                           : oxcf->superres_cfg.superres_mode;  // default
824
0
  x->e_mbd.bd = (int)seq_params->bit_depth;
825
0
  x->e_mbd.global_motion = cm->global_motion;
826
827
0
  memcpy(level_params->target_seq_level_idx, cpi->oxcf.target_seq_level_idx,
828
0
         sizeof(level_params->target_seq_level_idx));
829
0
  level_params->keep_level_stats = 0;
830
0
  for (int i = 0; i < MAX_NUM_OPERATING_POINTS; ++i) {
831
0
    if (level_params->target_seq_level_idx[i] < SEQ_LEVELS ||
832
0
        level_params->target_seq_level_idx[i] == SEQ_LEVEL_KEEP_STATS) {
833
0
      level_params->keep_level_stats |= 1u << i;
834
0
      if (!level_params->level_info[i]) {
835
0
        CHECK_MEM_ERROR(cm, level_params->level_info[i],
836
0
                        aom_calloc(1, sizeof(*level_params->level_info[i])));
837
0
      }
838
0
    }
839
0
  }
840
841
  // TODO(huisu@): level targeting currently only works for the 0th operating
842
  // point, so scalable coding is not supported yet.
843
0
  if (level_params->target_seq_level_idx[0] < SEQ_LEVELS) {
844
    // Adjust encoder config in order to meet target level.
845
0
    config_target_level(cpi, level_params->target_seq_level_idx[0],
846
0
                        seq_params->tier[0]);
847
0
  }
848
849
0
  if (has_no_stats_stage(cpi) && (rc_cfg->mode == AOM_Q)) {
850
0
    p_rc->baseline_gf_interval = FIXED_GF_INTERVAL;
851
0
  } else if (!is_one_pass_rt_params(cpi) ||
852
0
             cm->current_frame.frame_number == 0) {
853
    // For rtc mode: logic for setting the baseline_gf_interval is done
854
    // in av1_get_one_pass_rt_params(), and it should not be reset here in
855
    // change_config(), unless after init_config (first frame).
856
0
    p_rc->baseline_gf_interval = (MIN_GF_INTERVAL + MAX_GF_INTERVAL) / 2;
857
0
  }
858
859
0
  refresh_frame->golden_frame = false;
860
0
  refresh_frame->bwd_ref_frame = false;
861
862
0
  features->refresh_frame_context =
863
0
      (oxcf->tool_cfg.frame_parallel_decoding_mode)
864
0
          ? REFRESH_FRAME_CONTEXT_DISABLED
865
0
          : REFRESH_FRAME_CONTEXT_BACKWARD;
866
0
  if (oxcf->tile_cfg.enable_large_scale_tile)
867
0
    features->refresh_frame_context = REFRESH_FRAME_CONTEXT_DISABLED;
868
869
0
  if (x->palette_buffer == NULL) {
870
0
    CHECK_MEM_ERROR(cm, x->palette_buffer,
871
0
                    aom_memalign(16, sizeof(*x->palette_buffer)));
872
0
  }
873
874
0
  if (x->tmp_conv_dst == NULL) {
875
0
    CHECK_MEM_ERROR(
876
0
        cm, x->tmp_conv_dst,
877
0
        aom_memalign(32, MAX_SB_SIZE * MAX_SB_SIZE * sizeof(*x->tmp_conv_dst)));
878
0
    x->e_mbd.tmp_conv_dst = x->tmp_conv_dst;
879
0
  }
880
  // The buffers 'tmp_pred_bufs[]' and 'comp_rd_buffer' are used in inter frames
881
  // to store intermediate inter mode prediction results and are not required
882
  // for allintra encoding mode. Hence, the memory allocations for these buffers
883
  // are avoided for allintra encoding mode.
884
0
  if (cpi->oxcf.kf_cfg.key_freq_max != 0) {
885
0
    if (x->comp_rd_buffer.pred0 == NULL)
886
0
      alloc_compound_type_rd_buffers(cm->error, &x->comp_rd_buffer);
887
888
0
    for (int i = 0; i < 2; ++i) {
889
0
      if (x->tmp_pred_bufs[i] == NULL) {
890
0
        CHECK_MEM_ERROR(cm, x->tmp_pred_bufs[i],
891
0
                        aom_memalign(32, 2 * MAX_MB_PLANE * MAX_SB_SQUARE *
892
0
                                             sizeof(*x->tmp_pred_bufs[i])));
893
0
        x->e_mbd.tmp_obmc_bufs[i] = x->tmp_pred_bufs[i];
894
0
      }
895
0
    }
896
0
  }
897
898
0
  av1_reset_segment_features(cm);
899
900
0
  av1_set_high_precision_mv(cpi, 1, 0);
901
902
  // Under a configuration change, where maximum_buffer_size may change,
903
  // keep buffer level clipped to the maximum allowed buffer size.
904
0
  p_rc->bits_off_target =
905
0
      AOMMIN(p_rc->bits_off_target, p_rc->maximum_buffer_size);
906
0
  p_rc->buffer_level = AOMMIN(p_rc->buffer_level, p_rc->maximum_buffer_size);
907
908
  // Set up frame rate and related parameters rate control values.
909
0
  av1_new_framerate(cpi, cpi->framerate);
910
911
  // Set absolute upper and lower quality limits
912
0
  rc->worst_quality = rc_cfg->worst_allowed_q;
913
0
  rc->best_quality = rc_cfg->best_allowed_q;
914
915
  // If lossless has been requested make sure average Q accumulators are reset.
916
0
  if (is_lossless_requested(&cpi->oxcf.rc_cfg)) {
917
0
    int i;
918
0
    for (i = 0; i < FRAME_TYPES; ++i) {
919
0
      p_rc->avg_frame_qindex[i] = 0;
920
0
    }
921
0
  }
922
923
0
  features->interp_filter =
924
0
      oxcf->tile_cfg.enable_large_scale_tile ? EIGHTTAP_REGULAR : SWITCHABLE;
925
0
  features->switchable_motion_mode = is_switchable_motion_mode_allowed(
926
0
      features->allow_warped_motion, oxcf->motion_mode_cfg.enable_obmc);
927
928
0
  if (frm_dim_cfg->render_width > 0 && frm_dim_cfg->render_height > 0) {
929
0
    cm->render_width = frm_dim_cfg->render_width;
930
0
    cm->render_height = frm_dim_cfg->render_height;
931
0
  } else {
932
0
    cm->render_width = frm_dim_cfg->width;
933
0
    cm->render_height = frm_dim_cfg->height;
934
0
  }
935
0
  cm->width = frm_dim_cfg->width;
936
0
  cm->height = frm_dim_cfg->height;
937
938
0
  if (cm->width > cpi->data_alloc_width ||
939
0
      cm->height > cpi->data_alloc_height || is_sb_size_changed) {
940
0
    av1_free_context_buffers(cm);
941
0
    av1_free_shared_coeff_buffer(&cpi->td.shared_coeff_buf);
942
0
    av1_free_sms_tree(&cpi->td);
943
0
    av1_free_pmc(cpi->td.firstpass_ctx, av1_num_planes(cm));
944
0
    cpi->td.firstpass_ctx = NULL;
945
0
    alloc_compressor_data(cpi);
946
0
    realloc_segmentation_maps(cpi);
947
0
    cpi->data_alloc_width = cm->width;
948
0
    cpi->data_alloc_height = cm->height;
949
0
    cpi->frame_size_related_setup_done = false;
950
0
  }
951
0
  av1_update_frame_size(cpi);
952
953
0
  rc->is_src_frame_alt_ref = 0;
954
955
0
  if (!cpi->ppi->rtc_ref.set_ref_frame_config)
956
0
    cpi->ext_flags.refresh_frame.update_pending = 0;
957
0
  cpi->ext_flags.refresh_frame_context_pending = 0;
958
959
0
  if (cpi->ppi->use_svc)
960
0
    av1_update_layer_context_change_config(cpi, rc_cfg->target_bandwidth);
961
962
0
  check_reset_rc_flag(cpi);
963
964
  // restore the value of lag_in_frame for LAP stage.
965
0
  if (lap_lag_in_frames != -1) {
966
0
    cpi->oxcf.gf_cfg.lag_in_frames = lap_lag_in_frames;
967
0
  }
968
969
#if CONFIG_REALTIME_ONLY
970
  assert(!oxcf->tool_cfg.enable_global_motion);
971
  cpi->alloc_pyramid = false;
972
#else
973
0
  cpi->alloc_pyramid = oxcf->tool_cfg.enable_global_motion;
974
0
#endif  // CONFIG_REALTIME_ONLY
975
0
}
976
977
static inline void init_frame_info(FRAME_INFO *frame_info,
978
0
                                   const AV1_COMMON *const cm) {
979
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
980
0
  const SequenceHeader *const seq_params = cm->seq_params;
981
0
  frame_info->frame_width = cm->width;
982
0
  frame_info->frame_height = cm->height;
983
0
  frame_info->mi_cols = mi_params->mi_cols;
984
0
  frame_info->mi_rows = mi_params->mi_rows;
985
0
  frame_info->mb_cols = mi_params->mb_cols;
986
0
  frame_info->mb_rows = mi_params->mb_rows;
987
0
  frame_info->num_mbs = mi_params->MBs;
988
0
  frame_info->bit_depth = seq_params->bit_depth;
989
0
  frame_info->subsampling_x = seq_params->subsampling_x;
990
0
  frame_info->subsampling_y = seq_params->subsampling_y;
991
0
}
992
993
0
static inline void init_frame_index_set(FRAME_INDEX_SET *frame_index_set) {
994
0
  frame_index_set->show_frame_count = 0;
995
0
}
996
997
0
static inline void update_counters_for_show_frame(AV1_COMP *const cpi) {
998
0
  assert(cpi->common.show_frame);
999
0
  cpi->frame_index_set.show_frame_count++;
1000
0
  cpi->common.current_frame.frame_number++;
1001
0
}
1002
1003
AV1_PRIMARY *av1_create_primary_compressor(
1004
    struct aom_codec_pkt_list *pkt_list_head, int num_lap_buffers,
1005
0
    const AV1EncoderConfig *oxcf) {
1006
0
  AV1_PRIMARY *volatile const ppi = aom_memalign(32, sizeof(AV1_PRIMARY));
1007
0
  if (!ppi) return NULL;
1008
0
  av1_zero(*ppi);
1009
1010
  // The jmp_buf is valid only for the duration of the function that calls
1011
  // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
1012
  // before it returns.
1013
0
  if (setjmp(ppi->error.jmp)) {
1014
0
    ppi->error.setjmp = 0;
1015
0
    av1_remove_primary_compressor(ppi);
1016
0
    return 0;
1017
0
  }
1018
0
  ppi->error.setjmp = 1;
1019
1020
0
  ppi->seq_params_locked = 0;
1021
0
  ppi->lap_enabled = num_lap_buffers > 0;
1022
0
  ppi->output_pkt_list = pkt_list_head;
1023
0
  ppi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1024
0
  ppi->frames_left = oxcf->input_cfg.limit;
1025
0
  ppi->num_fp_contexts = 1;
1026
1027
0
  init_config_sequence(ppi, oxcf);
1028
1029
#if CONFIG_ENTROPY_STATS
1030
  av1_zero(ppi->aggregate_fc);
1031
#endif  // CONFIG_ENTROPY_STATS
1032
1033
0
  av1_primary_rc_init(oxcf, &ppi->p_rc);
1034
1035
  // For two pass and lag_in_frames > 33 in LAP.
1036
0
  ppi->p_rc.enable_scenecut_detection = ENABLE_SCENECUT_MODE_2;
1037
0
  if (ppi->lap_enabled) {
1038
0
    if ((num_lap_buffers <
1039
0
         (MAX_GF_LENGTH_LAP + SCENE_CUT_KEY_TEST_INTERVAL + 1)) &&
1040
0
        num_lap_buffers >= (MAX_GF_LENGTH_LAP + 3)) {
1041
      /*
1042
       * For lag in frames >= 19 and <33, enable scenecut
1043
       * with limited future frame prediction.
1044
       */
1045
0
      ppi->p_rc.enable_scenecut_detection = ENABLE_SCENECUT_MODE_1;
1046
0
    } else if (num_lap_buffers < (MAX_GF_LENGTH_LAP + 3)) {
1047
      // Disable scenecut when lag_in_frames < 19.
1048
0
      ppi->p_rc.enable_scenecut_detection = DISABLE_SCENECUT;
1049
0
    }
1050
0
  }
1051
1052
0
#define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX4DF, SDX3DF) \
1053
0
  ppi->fn_ptr[BT].sdf = SDF;                              \
1054
0
  ppi->fn_ptr[BT].sdaf = SDAF;                            \
1055
0
  ppi->fn_ptr[BT].vf = VF;                                \
1056
0
  ppi->fn_ptr[BT].svf = SVF;                              \
1057
0
  ppi->fn_ptr[BT].svaf = SVAF;                            \
1058
0
  ppi->fn_ptr[BT].sdx4df = SDX4DF;                        \
1059
0
  ppi->fn_ptr[BT].sdx3df = SDX3DF;
1060
1061
// Realtime mode doesn't use 4x rectangular blocks.
1062
0
#if !CONFIG_REALTIME_ONLY
1063
  // sdaf (used in compound prediction, get_mvpred_compound_sad()) is unused
1064
  // for 4xN and Nx4 blocks.
1065
0
  BFP(BLOCK_4X16, aom_sad4x16, /*SDAF=*/NULL, aom_variance4x16,
1066
0
      aom_sub_pixel_variance4x16, aom_sub_pixel_avg_variance4x16,
1067
0
      aom_sad4x16x4d, aom_sad4x16x3d)
1068
1069
  // sdaf (used in compound prediction, get_mvpred_compound_sad()) is unused
1070
  // for 4xN and Nx4 blocks.
1071
0
  BFP(BLOCK_16X4, aom_sad16x4, /*SDAF=*/NULL, aom_variance16x4,
1072
0
      aom_sub_pixel_variance16x4, aom_sub_pixel_avg_variance16x4,
1073
0
      aom_sad16x4x4d, aom_sad16x4x3d)
1074
1075
0
  BFP(BLOCK_8X32, aom_sad8x32, aom_sad8x32_avg, aom_variance8x32,
1076
0
      aom_sub_pixel_variance8x32, aom_sub_pixel_avg_variance8x32,
1077
0
      aom_sad8x32x4d, aom_sad8x32x3d)
1078
1079
0
  BFP(BLOCK_32X8, aom_sad32x8, aom_sad32x8_avg, aom_variance32x8,
1080
0
      aom_sub_pixel_variance32x8, aom_sub_pixel_avg_variance32x8,
1081
0
      aom_sad32x8x4d, aom_sad32x8x3d)
1082
1083
0
  BFP(BLOCK_16X64, aom_sad16x64, aom_sad16x64_avg, aom_variance16x64,
1084
0
      aom_sub_pixel_variance16x64, aom_sub_pixel_avg_variance16x64,
1085
0
      aom_sad16x64x4d, aom_sad16x64x3d)
1086
1087
0
  BFP(BLOCK_64X16, aom_sad64x16, aom_sad64x16_avg, aom_variance64x16,
1088
0
      aom_sub_pixel_variance64x16, aom_sub_pixel_avg_variance64x16,
1089
0
      aom_sad64x16x4d, aom_sad64x16x3d)
1090
0
#endif  // !CONFIG_REALTIME_ONLY
1091
1092
0
  BFP(BLOCK_128X128, aom_sad128x128, aom_sad128x128_avg, aom_variance128x128,
1093
0
      aom_sub_pixel_variance128x128, aom_sub_pixel_avg_variance128x128,
1094
0
      aom_sad128x128x4d, aom_sad128x128x3d)
1095
1096
0
  BFP(BLOCK_128X64, aom_sad128x64, aom_sad128x64_avg, aom_variance128x64,
1097
0
      aom_sub_pixel_variance128x64, aom_sub_pixel_avg_variance128x64,
1098
0
      aom_sad128x64x4d, aom_sad128x64x3d)
1099
1100
0
  BFP(BLOCK_64X128, aom_sad64x128, aom_sad64x128_avg, aom_variance64x128,
1101
0
      aom_sub_pixel_variance64x128, aom_sub_pixel_avg_variance64x128,
1102
0
      aom_sad64x128x4d, aom_sad64x128x3d)
1103
1104
0
  BFP(BLOCK_32X16, aom_sad32x16, aom_sad32x16_avg, aom_variance32x16,
1105
0
      aom_sub_pixel_variance32x16, aom_sub_pixel_avg_variance32x16,
1106
0
      aom_sad32x16x4d, aom_sad32x16x3d)
1107
1108
0
  BFP(BLOCK_16X32, aom_sad16x32, aom_sad16x32_avg, aom_variance16x32,
1109
0
      aom_sub_pixel_variance16x32, aom_sub_pixel_avg_variance16x32,
1110
0
      aom_sad16x32x4d, aom_sad16x32x3d)
1111
1112
0
  BFP(BLOCK_64X32, aom_sad64x32, aom_sad64x32_avg, aom_variance64x32,
1113
0
      aom_sub_pixel_variance64x32, aom_sub_pixel_avg_variance64x32,
1114
0
      aom_sad64x32x4d, aom_sad64x32x3d)
1115
1116
0
  BFP(BLOCK_32X64, aom_sad32x64, aom_sad32x64_avg, aom_variance32x64,
1117
0
      aom_sub_pixel_variance32x64, aom_sub_pixel_avg_variance32x64,
1118
0
      aom_sad32x64x4d, aom_sad32x64x3d)
1119
1120
0
  BFP(BLOCK_32X32, aom_sad32x32, aom_sad32x32_avg, aom_variance32x32,
1121
0
      aom_sub_pixel_variance32x32, aom_sub_pixel_avg_variance32x32,
1122
0
      aom_sad32x32x4d, aom_sad32x32x3d)
1123
1124
0
  BFP(BLOCK_64X64, aom_sad64x64, aom_sad64x64_avg, aom_variance64x64,
1125
0
      aom_sub_pixel_variance64x64, aom_sub_pixel_avg_variance64x64,
1126
0
      aom_sad64x64x4d, aom_sad64x64x3d)
1127
1128
0
  BFP(BLOCK_16X16, aom_sad16x16, aom_sad16x16_avg, aom_variance16x16,
1129
0
      aom_sub_pixel_variance16x16, aom_sub_pixel_avg_variance16x16,
1130
0
      aom_sad16x16x4d, aom_sad16x16x3d)
1131
1132
0
  BFP(BLOCK_16X8, aom_sad16x8, aom_sad16x8_avg, aom_variance16x8,
1133
0
      aom_sub_pixel_variance16x8, aom_sub_pixel_avg_variance16x8,
1134
0
      aom_sad16x8x4d, aom_sad16x8x3d)
1135
1136
0
  BFP(BLOCK_8X16, aom_sad8x16, aom_sad8x16_avg, aom_variance8x16,
1137
0
      aom_sub_pixel_variance8x16, aom_sub_pixel_avg_variance8x16,
1138
0
      aom_sad8x16x4d, aom_sad8x16x3d)
1139
1140
0
  BFP(BLOCK_8X8, aom_sad8x8, aom_sad8x8_avg, aom_variance8x8,
1141
0
      aom_sub_pixel_variance8x8, aom_sub_pixel_avg_variance8x8, aom_sad8x8x4d,
1142
0
      aom_sad8x8x3d)
1143
1144
  // sdaf (used in compound prediction, get_mvpred_compound_sad()) is unused
1145
  // for 4xN and Nx4 blocks.
1146
0
  BFP(BLOCK_8X4, aom_sad8x4, /*SDAF=*/NULL, aom_variance8x4,
1147
0
      aom_sub_pixel_variance8x4, aom_sub_pixel_avg_variance8x4, aom_sad8x4x4d,
1148
0
      aom_sad8x4x3d)
1149
1150
  // sdaf (used in compound prediction, get_mvpred_compound_sad()) is unused
1151
  // for 4xN and Nx4 blocks.
1152
0
  BFP(BLOCK_4X8, aom_sad4x8, /*SDAF=*/NULL, aom_variance4x8,
1153
0
      aom_sub_pixel_variance4x8, aom_sub_pixel_avg_variance4x8, aom_sad4x8x4d,
1154
0
      aom_sad4x8x3d)
1155
1156
  // sdaf (used in compound prediction, get_mvpred_compound_sad()) is unused
1157
  // for 4xN and Nx4 blocks.
1158
0
  BFP(BLOCK_4X4, aom_sad4x4, /*SDAF=*/NULL, aom_variance4x4,
1159
0
      aom_sub_pixel_variance4x4, aom_sub_pixel_avg_variance4x4, aom_sad4x4x4d,
1160
0
      aom_sad4x4x3d)
1161
1162
0
#if !CONFIG_REALTIME_ONLY
1163
0
#define OBFP(BT, OSDF, OVF, OSVF) \
1164
0
  ppi->fn_ptr[BT].osdf = OSDF;    \
1165
0
  ppi->fn_ptr[BT].ovf = OVF;      \
1166
0
  ppi->fn_ptr[BT].osvf = OSVF;
1167
1168
0
  OBFP(BLOCK_128X128, aom_obmc_sad128x128, aom_obmc_variance128x128,
1169
0
       aom_obmc_sub_pixel_variance128x128)
1170
0
  OBFP(BLOCK_128X64, aom_obmc_sad128x64, aom_obmc_variance128x64,
1171
0
       aom_obmc_sub_pixel_variance128x64)
1172
0
  OBFP(BLOCK_64X128, aom_obmc_sad64x128, aom_obmc_variance64x128,
1173
0
       aom_obmc_sub_pixel_variance64x128)
1174
0
  OBFP(BLOCK_64X64, aom_obmc_sad64x64, aom_obmc_variance64x64,
1175
0
       aom_obmc_sub_pixel_variance64x64)
1176
0
  OBFP(BLOCK_64X32, aom_obmc_sad64x32, aom_obmc_variance64x32,
1177
0
       aom_obmc_sub_pixel_variance64x32)
1178
0
  OBFP(BLOCK_32X64, aom_obmc_sad32x64, aom_obmc_variance32x64,
1179
0
       aom_obmc_sub_pixel_variance32x64)
1180
0
  OBFP(BLOCK_32X32, aom_obmc_sad32x32, aom_obmc_variance32x32,
1181
0
       aom_obmc_sub_pixel_variance32x32)
1182
0
  OBFP(BLOCK_32X16, aom_obmc_sad32x16, aom_obmc_variance32x16,
1183
0
       aom_obmc_sub_pixel_variance32x16)
1184
0
  OBFP(BLOCK_16X32, aom_obmc_sad16x32, aom_obmc_variance16x32,
1185
0
       aom_obmc_sub_pixel_variance16x32)
1186
0
  OBFP(BLOCK_16X16, aom_obmc_sad16x16, aom_obmc_variance16x16,
1187
0
       aom_obmc_sub_pixel_variance16x16)
1188
0
  OBFP(BLOCK_16X8, aom_obmc_sad16x8, aom_obmc_variance16x8,
1189
0
       aom_obmc_sub_pixel_variance16x8)
1190
0
  OBFP(BLOCK_8X16, aom_obmc_sad8x16, aom_obmc_variance8x16,
1191
0
       aom_obmc_sub_pixel_variance8x16)
1192
0
  OBFP(BLOCK_8X8, aom_obmc_sad8x8, aom_obmc_variance8x8,
1193
0
       aom_obmc_sub_pixel_variance8x8)
1194
0
  OBFP(BLOCK_4X8, aom_obmc_sad4x8, aom_obmc_variance4x8,
1195
0
       aom_obmc_sub_pixel_variance4x8)
1196
0
  OBFP(BLOCK_8X4, aom_obmc_sad8x4, aom_obmc_variance8x4,
1197
0
       aom_obmc_sub_pixel_variance8x4)
1198
0
  OBFP(BLOCK_4X4, aom_obmc_sad4x4, aom_obmc_variance4x4,
1199
0
       aom_obmc_sub_pixel_variance4x4)
1200
0
  OBFP(BLOCK_4X16, aom_obmc_sad4x16, aom_obmc_variance4x16,
1201
0
       aom_obmc_sub_pixel_variance4x16)
1202
0
  OBFP(BLOCK_16X4, aom_obmc_sad16x4, aom_obmc_variance16x4,
1203
0
       aom_obmc_sub_pixel_variance16x4)
1204
0
  OBFP(BLOCK_8X32, aom_obmc_sad8x32, aom_obmc_variance8x32,
1205
0
       aom_obmc_sub_pixel_variance8x32)
1206
0
  OBFP(BLOCK_32X8, aom_obmc_sad32x8, aom_obmc_variance32x8,
1207
0
       aom_obmc_sub_pixel_variance32x8)
1208
0
  OBFP(BLOCK_16X64, aom_obmc_sad16x64, aom_obmc_variance16x64,
1209
0
       aom_obmc_sub_pixel_variance16x64)
1210
0
  OBFP(BLOCK_64X16, aom_obmc_sad64x16, aom_obmc_variance64x16,
1211
0
       aom_obmc_sub_pixel_variance64x16)
1212
0
#endif  // !CONFIG_REALTIME_ONLY
1213
1214
0
#define MBFP(BT, MCSDF, MCSVF)  \
1215
0
  ppi->fn_ptr[BT].msdf = MCSDF; \
1216
0
  ppi->fn_ptr[BT].msvf = MCSVF;
1217
1218
0
  MBFP(BLOCK_128X128, aom_masked_sad128x128,
1219
0
       aom_masked_sub_pixel_variance128x128)
1220
0
  MBFP(BLOCK_128X64, aom_masked_sad128x64, aom_masked_sub_pixel_variance128x64)
1221
0
  MBFP(BLOCK_64X128, aom_masked_sad64x128, aom_masked_sub_pixel_variance64x128)
1222
0
  MBFP(BLOCK_64X64, aom_masked_sad64x64, aom_masked_sub_pixel_variance64x64)
1223
0
  MBFP(BLOCK_64X32, aom_masked_sad64x32, aom_masked_sub_pixel_variance64x32)
1224
0
  MBFP(BLOCK_32X64, aom_masked_sad32x64, aom_masked_sub_pixel_variance32x64)
1225
0
  MBFP(BLOCK_32X32, aom_masked_sad32x32, aom_masked_sub_pixel_variance32x32)
1226
0
  MBFP(BLOCK_32X16, aom_masked_sad32x16, aom_masked_sub_pixel_variance32x16)
1227
0
  MBFP(BLOCK_16X32, aom_masked_sad16x32, aom_masked_sub_pixel_variance16x32)
1228
0
  MBFP(BLOCK_16X16, aom_masked_sad16x16, aom_masked_sub_pixel_variance16x16)
1229
0
  MBFP(BLOCK_16X8, aom_masked_sad16x8, aom_masked_sub_pixel_variance16x8)
1230
0
  MBFP(BLOCK_8X16, aom_masked_sad8x16, aom_masked_sub_pixel_variance8x16)
1231
0
  MBFP(BLOCK_8X8, aom_masked_sad8x8, aom_masked_sub_pixel_variance8x8)
1232
0
  MBFP(BLOCK_4X8, aom_masked_sad4x8, aom_masked_sub_pixel_variance4x8)
1233
0
  MBFP(BLOCK_8X4, aom_masked_sad8x4, aom_masked_sub_pixel_variance8x4)
1234
0
  MBFP(BLOCK_4X4, aom_masked_sad4x4, aom_masked_sub_pixel_variance4x4)
1235
1236
0
#if !CONFIG_REALTIME_ONLY
1237
0
  MBFP(BLOCK_4X16, aom_masked_sad4x16, aom_masked_sub_pixel_variance4x16)
1238
0
  MBFP(BLOCK_16X4, aom_masked_sad16x4, aom_masked_sub_pixel_variance16x4)
1239
0
  MBFP(BLOCK_8X32, aom_masked_sad8x32, aom_masked_sub_pixel_variance8x32)
1240
0
  MBFP(BLOCK_32X8, aom_masked_sad32x8, aom_masked_sub_pixel_variance32x8)
1241
0
  MBFP(BLOCK_16X64, aom_masked_sad16x64, aom_masked_sub_pixel_variance16x64)
1242
0
  MBFP(BLOCK_64X16, aom_masked_sad64x16, aom_masked_sub_pixel_variance64x16)
1243
0
#endif
1244
1245
0
#define SDSFP(BT, SDSF, SDSX4DF) \
1246
0
  ppi->fn_ptr[BT].sdsf = SDSF;   \
1247
0
  ppi->fn_ptr[BT].sdsx4df = SDSX4DF;
1248
1249
0
  SDSFP(BLOCK_128X128, aom_sad_skip_128x128, aom_sad_skip_128x128x4d)
1250
0
  SDSFP(BLOCK_128X64, aom_sad_skip_128x64, aom_sad_skip_128x64x4d)
1251
0
  SDSFP(BLOCK_64X128, aom_sad_skip_64x128, aom_sad_skip_64x128x4d)
1252
0
  SDSFP(BLOCK_64X64, aom_sad_skip_64x64, aom_sad_skip_64x64x4d)
1253
0
  SDSFP(BLOCK_64X32, aom_sad_skip_64x32, aom_sad_skip_64x32x4d)
1254
1255
0
  SDSFP(BLOCK_32X64, aom_sad_skip_32x64, aom_sad_skip_32x64x4d)
1256
0
  SDSFP(BLOCK_32X32, aom_sad_skip_32x32, aom_sad_skip_32x32x4d)
1257
0
  SDSFP(BLOCK_32X16, aom_sad_skip_32x16, aom_sad_skip_32x16x4d)
1258
1259
0
  SDSFP(BLOCK_16X32, aom_sad_skip_16x32, aom_sad_skip_16x32x4d)
1260
0
  SDSFP(BLOCK_16X16, aom_sad_skip_16x16, aom_sad_skip_16x16x4d)
1261
0
  SDSFP(BLOCK_8X16, aom_sad_skip_8x16, aom_sad_skip_8x16x4d)
1262
1263
0
#if !CONFIG_REALTIME_ONLY
1264
0
  SDSFP(BLOCK_64X16, aom_sad_skip_64x16, aom_sad_skip_64x16x4d)
1265
0
  SDSFP(BLOCK_16X64, aom_sad_skip_16x64, aom_sad_skip_16x64x4d)
1266
0
  SDSFP(BLOCK_8X32, aom_sad_skip_8x32, aom_sad_skip_8x32x4d)
1267
0
  SDSFP(BLOCK_4X16, aom_sad_skip_4x16, aom_sad_skip_4x16x4d)
1268
0
#endif
1269
0
#undef SDSFP
1270
1271
0
#if CONFIG_AV1_HIGHBITDEPTH
1272
0
  highbd_set_var_fns(ppi);
1273
0
#endif
1274
1275
0
  {
1276
    // As cm->mi_params is a part of the frame level context (cpi), it is
1277
    // unavailable at this point. mi_params is created as a local temporary
1278
    // variable, to be passed into the functions used for allocating tpl
1279
    // buffers. The values in this variable are populated according to initial
1280
    // width and height of the frame.
1281
0
    CommonModeInfoParams mi_params;
1282
0
    enc_set_mb_mi(&mi_params, oxcf->frm_dim_cfg.width, oxcf->frm_dim_cfg.height,
1283
0
                  BLOCK_4X4);
1284
1285
0
    const BLOCK_SIZE bsize = BLOCK_16X16;
1286
0
    const int w = mi_size_wide[bsize];
1287
0
    const int h = mi_size_high[bsize];
1288
0
    const int num_cols = (mi_params.mi_cols + w - 1) / w;
1289
0
    const int num_rows = (mi_params.mi_rows + h - 1) / h;
1290
0
    AOM_CHECK_MEM_ERROR(
1291
0
        &ppi->error, ppi->tpl_sb_rdmult_scaling_factors,
1292
0
        aom_calloc(num_rows * num_cols,
1293
0
                   sizeof(*ppi->tpl_sb_rdmult_scaling_factors)));
1294
1295
#if CONFIG_INTERNAL_STATS
1296
    ppi->b_calculate_blockiness = 1;
1297
    ppi->b_calculate_consistency = 1;
1298
1299
    for (int i = 0; i <= STAT_ALL; i++) {
1300
      ppi->psnr[0].stat[i] = 0;
1301
      ppi->psnr[1].stat[i] = 0;
1302
1303
      ppi->fastssim.stat[i] = 0;
1304
      ppi->psnrhvs.stat[i] = 0;
1305
    }
1306
1307
    ppi->psnr[0].worst = 100.0;
1308
    ppi->psnr[1].worst = 100.0;
1309
    ppi->worst_ssim = 100.0;
1310
    ppi->worst_ssim_hbd = 100.0;
1311
1312
    ppi->count[0] = 0;
1313
    ppi->count[1] = 0;
1314
    ppi->total_bytes = 0;
1315
1316
    if (ppi->b_calculate_psnr) {
1317
      ppi->total_sq_error[0] = 0;
1318
      ppi->total_samples[0] = 0;
1319
      ppi->total_sq_error[1] = 0;
1320
      ppi->total_samples[1] = 0;
1321
      ppi->total_recode_hits = 0;
1322
      ppi->summed_quality = 0;
1323
      ppi->summed_weights = 0;
1324
      ppi->summed_quality_hbd = 0;
1325
      ppi->summed_weights_hbd = 0;
1326
    }
1327
1328
    ppi->fastssim.worst = 100.0;
1329
    ppi->psnrhvs.worst = 100.0;
1330
1331
    if (ppi->b_calculate_blockiness) {
1332
      ppi->total_blockiness = 0;
1333
      ppi->worst_blockiness = 0.0;
1334
    }
1335
1336
    ppi->total_inconsistency = 0;
1337
    ppi->worst_consistency = 100.0;
1338
    if (ppi->b_calculate_consistency) {
1339
      AOM_CHECK_MEM_ERROR(&ppi->error, ppi->ssim_vars,
1340
                          aom_malloc(sizeof(*ppi->ssim_vars) * 4 *
1341
                                     mi_params.mi_rows * mi_params.mi_cols));
1342
    }
1343
#endif
1344
0
  }
1345
1346
0
  ppi->error.setjmp = 0;
1347
0
  return ppi;
1348
0
}
1349
1350
AV1_COMP *av1_create_compressor(AV1_PRIMARY *ppi, const AV1EncoderConfig *oxcf,
1351
                                BufferPool *const pool, COMPRESSOR_STAGE stage,
1352
0
                                int lap_lag_in_frames) {
1353
0
  AV1_COMP *volatile const cpi = aom_memalign(32, sizeof(AV1_COMP));
1354
1355
0
  if (!cpi) return NULL;
1356
1357
0
  av1_zero(*cpi);
1358
1359
0
  cpi->ppi = ppi;
1360
1361
0
  AV1_COMMON *volatile const cm = &cpi->common;
1362
0
  cm->seq_params = &ppi->seq_params;
1363
0
  cm->error =
1364
0
      (struct aom_internal_error_info *)aom_calloc(1, sizeof(*cm->error));
1365
0
  if (!cm->error) {
1366
0
    aom_free(cpi);
1367
0
    return NULL;
1368
0
  }
1369
1370
  // The jmp_buf is valid only for the duration of the function that calls
1371
  // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
1372
  // before it returns.
1373
0
  if (setjmp(cm->error->jmp)) {
1374
0
    cm->error->setjmp = 0;
1375
0
    av1_remove_compressor(cpi);
1376
0
    return NULL;
1377
0
  }
1378
1379
0
  cm->error->setjmp = 1;
1380
0
  cpi->compressor_stage = stage;
1381
1382
0
  cpi->do_frame_data_update = true;
1383
1384
0
  CommonModeInfoParams *const mi_params = &cm->mi_params;
1385
0
  mi_params->free_mi = enc_free_mi;
1386
0
  mi_params->setup_mi = enc_setup_mi;
1387
0
  mi_params->set_mb_mi =
1388
0
      (oxcf->pass == AOM_RC_FIRST_PASS || cpi->compressor_stage == LAP_STAGE)
1389
0
          ? stat_stage_set_mb_mi
1390
0
          : enc_set_mb_mi;
1391
1392
0
  mi_params->mi_alloc_bsize = BLOCK_4X4;
1393
1394
0
  CHECK_MEM_ERROR(cm, cm->fc,
1395
0
                  (FRAME_CONTEXT *)aom_memalign(32, sizeof(*cm->fc)));
1396
0
  CHECK_MEM_ERROR(
1397
0
      cm, cm->default_frame_context,
1398
0
      (FRAME_CONTEXT *)aom_memalign(32, sizeof(*cm->default_frame_context)));
1399
0
  memset(cm->fc, 0, sizeof(*cm->fc));
1400
0
  memset(cm->default_frame_context, 0, sizeof(*cm->default_frame_context));
1401
1402
0
  cpi->common.buffer_pool = pool;
1403
1404
0
  init_config(cpi, oxcf);
1405
0
  if (cpi->compressor_stage == LAP_STAGE) {
1406
0
    cpi->oxcf.gf_cfg.lag_in_frames = lap_lag_in_frames;
1407
0
  }
1408
1409
0
  av1_rc_init(&cpi->oxcf, &cpi->rc);
1410
1411
0
  init_frame_info(&cpi->frame_info, cm);
1412
0
  init_frame_index_set(&cpi->frame_index_set);
1413
1414
0
  cm->current_frame.frame_number = 0;
1415
0
  cpi->rc.frame_number_encoded = 0;
1416
0
  cpi->rc.prev_frame_is_dropped = 0;
1417
0
  cpi->rc.max_consec_drop = INT_MAX;
1418
0
  cpi->rc.drop_count_consec = 0;
1419
0
  cm->current_frame_id = -1;
1420
0
  cpi->tile_data = NULL;
1421
0
  cpi->last_show_frame_buf = NULL;
1422
0
  realloc_segmentation_maps(cpi);
1423
1424
0
  cpi->refresh_frame.alt_ref_frame = false;
1425
1426
#if CONFIG_SPEED_STATS
1427
  cpi->tx_search_count = 0;
1428
#endif  // CONFIG_SPEED_STATS
1429
1430
0
  cpi->time_stamps.first_ts_start = INT64_MAX;
1431
1432
#ifdef OUTPUT_YUV_REC
1433
  yuv_rec_file = fopen("rec.yuv", "wb");
1434
#endif
1435
#ifdef OUTPUT_YUV_DENOISED
1436
  yuv_denoised_file = fopen("denoised.yuv", "wb");
1437
#endif
1438
1439
0
#if !CONFIG_REALTIME_ONLY
1440
0
  if (is_stat_consumption_stage(cpi)) {
1441
0
    const size_t packet_sz = sizeof(FIRSTPASS_STATS);
1442
0
    const int packets = (int)(oxcf->twopass_stats_in.sz / packet_sz);
1443
1444
0
    if (!cpi->ppi->lap_enabled) {
1445
      /*Re-initialize to stats buffer, populated by application in the case of
1446
       * two pass*/
1447
0
      cpi->ppi->twopass.stats_buf_ctx->stats_in_start =
1448
0
          oxcf->twopass_stats_in.buf;
1449
0
      cpi->twopass_frame.stats_in =
1450
0
          cpi->ppi->twopass.stats_buf_ctx->stats_in_start;
1451
0
      cpi->ppi->twopass.stats_buf_ctx->stats_in_end =
1452
0
          &cpi->ppi->twopass.stats_buf_ctx->stats_in_start[packets - 1];
1453
1454
      // The buffer size is packets - 1 because the last packet is total_stats.
1455
0
      av1_firstpass_info_init(&cpi->ppi->twopass.firstpass_info,
1456
0
                              oxcf->twopass_stats_in.buf, packets - 1);
1457
0
      av1_init_second_pass(cpi);
1458
0
    } else {
1459
0
      av1_firstpass_info_init(&cpi->ppi->twopass.firstpass_info, NULL, 0);
1460
0
      av1_init_single_pass_lap(cpi);
1461
0
    }
1462
0
  }
1463
0
#endif
1464
1465
  // The buffer "obmc_buffer" is used in inter frames for fast obmc search.
1466
  // Hence, the memory allocation for the same is avoided for allintra encoding
1467
  // mode.
1468
0
  if (cpi->oxcf.kf_cfg.key_freq_max != 0)
1469
0
    alloc_obmc_buffers(&cpi->td.mb.obmc_buffer, cm->error);
1470
1471
0
  for (int x = 0; x < 2; x++)
1472
0
    for (int y = 0; y < 2; y++)
1473
0
      CHECK_MEM_ERROR(
1474
0
          cm, cpi->td.mb.intrabc_hash_info.hash_value_buffer[x][y],
1475
0
          (uint32_t *)aom_malloc(
1476
0
              AOM_BUFFER_SIZE_FOR_BLOCK_HASH *
1477
0
              sizeof(*cpi->td.mb.intrabc_hash_info.hash_value_buffer[0][0])));
1478
1479
0
  cpi->td.mb.intrabc_hash_info.g_crc_initialized = 0;
1480
1481
0
  av1_set_speed_features_framesize_independent(cpi, oxcf->speed);
1482
0
  av1_set_speed_features_framesize_dependent(cpi, oxcf->speed);
1483
1484
0
  int max_mi_cols = mi_params->mi_cols;
1485
0
  int max_mi_rows = mi_params->mi_rows;
1486
0
  if (oxcf->frm_dim_cfg.forced_max_frame_width) {
1487
0
    max_mi_cols = size_in_mi(oxcf->frm_dim_cfg.forced_max_frame_width);
1488
0
  }
1489
0
  if (oxcf->frm_dim_cfg.forced_max_frame_height) {
1490
0
    max_mi_rows = size_in_mi(oxcf->frm_dim_cfg.forced_max_frame_height);
1491
0
  }
1492
1493
0
  const int consec_zero_mv_alloc_size = (max_mi_rows * max_mi_cols) >> 2;
1494
0
  CHECK_MEM_ERROR(
1495
0
      cm, cpi->consec_zero_mv,
1496
0
      aom_calloc(consec_zero_mv_alloc_size, sizeof(*cpi->consec_zero_mv)));
1497
0
  cpi->consec_zero_mv_alloc_size = consec_zero_mv_alloc_size;
1498
1499
0
  cpi->mb_weber_stats = NULL;
1500
0
  cpi->mb_delta_q = NULL;
1501
0
  cpi->palette_pixel_num = 0;
1502
0
  cpi->scaled_last_source_available = 0;
1503
1504
0
  {
1505
0
    const BLOCK_SIZE bsize = BLOCK_16X16;
1506
0
    const int w = mi_size_wide[bsize];
1507
0
    const int h = mi_size_high[bsize];
1508
0
    const int num_cols = (max_mi_cols + w - 1) / w;
1509
0
    const int num_rows = (max_mi_rows + h - 1) / h;
1510
0
    CHECK_MEM_ERROR(cm, cpi->ssim_rdmult_scaling_factors,
1511
0
                    aom_calloc(num_rows * num_cols,
1512
0
                               sizeof(*cpi->ssim_rdmult_scaling_factors)));
1513
0
    CHECK_MEM_ERROR(cm, cpi->tpl_rdmult_scaling_factors,
1514
0
                    aom_calloc(num_rows * num_cols,
1515
0
                               sizeof(*cpi->tpl_rdmult_scaling_factors)));
1516
0
  }
1517
1518
#if CONFIG_TUNE_VMAF
1519
  {
1520
    const BLOCK_SIZE bsize = BLOCK_64X64;
1521
    const int w = mi_size_wide[bsize];
1522
    const int h = mi_size_high[bsize];
1523
    const int num_cols = (mi_params->mi_cols + w - 1) / w;
1524
    const int num_rows = (mi_params->mi_rows + h - 1) / h;
1525
    CHECK_MEM_ERROR(cm, cpi->vmaf_info.rdmult_scaling_factors,
1526
                    aom_calloc(num_rows * num_cols,
1527
                               sizeof(*cpi->vmaf_info.rdmult_scaling_factors)));
1528
    for (int i = 0; i < MAX_ARF_LAYERS; i++) {
1529
      cpi->vmaf_info.last_frame_unsharp_amount[i] = -1.0;
1530
      cpi->vmaf_info.last_frame_ysse[i] = -1.0;
1531
      cpi->vmaf_info.last_frame_vmaf[i] = -1.0;
1532
    }
1533
    cpi->vmaf_info.original_qindex = -1;
1534
    cpi->vmaf_info.vmaf_model = NULL;
1535
  }
1536
#endif
1537
1538
#if CONFIG_TUNE_BUTTERAUGLI
1539
  {
1540
    const int w = mi_size_wide[butteraugli_rdo_bsize];
1541
    const int h = mi_size_high[butteraugli_rdo_bsize];
1542
    const int num_cols = (mi_params->mi_cols + w - 1) / w;
1543
    const int num_rows = (mi_params->mi_rows + h - 1) / h;
1544
    CHECK_MEM_ERROR(
1545
        cm, cpi->butteraugli_info.rdmult_scaling_factors,
1546
        aom_malloc(num_rows * num_cols *
1547
                   sizeof(*cpi->butteraugli_info.rdmult_scaling_factors)));
1548
    memset(&cpi->butteraugli_info.source, 0,
1549
           sizeof(cpi->butteraugli_info.source));
1550
    memset(&cpi->butteraugli_info.resized_source, 0,
1551
           sizeof(cpi->butteraugli_info.resized_source));
1552
    cpi->butteraugli_info.recon_set = false;
1553
  }
1554
#endif
1555
1556
#if CONFIG_SALIENCY_MAP
1557
  {
1558
    CHECK_MEM_ERROR(cm, cpi->saliency_map,
1559
                    (uint8_t *)aom_calloc(cm->height * cm->width,
1560
                                          sizeof(*cpi->saliency_map)));
1561
    // Buffer initialization based on MIN_MIB_SIZE_LOG2 to ensure that
1562
    // cpi->sm_scaling_factor buffer is allocated big enough, since we have no
1563
    // idea of the actual superblock size we are going to use yet.
1564
    const int min_mi_w_sb = (1 << MIN_MIB_SIZE_LOG2);
1565
    const int min_mi_h_sb = (1 << MIN_MIB_SIZE_LOG2);
1566
    const int max_sb_cols =
1567
        (cm->mi_params.mi_cols + min_mi_w_sb - 1) / min_mi_w_sb;
1568
    const int max_sb_rows =
1569
        (cm->mi_params.mi_rows + min_mi_h_sb - 1) / min_mi_h_sb;
1570
    CHECK_MEM_ERROR(cm, cpi->sm_scaling_factor,
1571
                    (double *)aom_calloc(max_sb_rows * max_sb_cols,
1572
                                         sizeof(*cpi->sm_scaling_factor)));
1573
  }
1574
#endif
1575
1576
#if CONFIG_COLLECT_PARTITION_STATS
1577
  av1_zero(cpi->partition_stats);
1578
#endif  // CONFIG_COLLECT_PARTITION_STATS
1579
1580
  // Initialize the members of DeltaQuantParams with INT_MAX to ensure that
1581
  // the quantizer tables are correctly initialized using the default deltaq
1582
  // parameters when av1_init_quantizer is called for the first time.
1583
0
  DeltaQuantParams *const prev_deltaq_params =
1584
0
      &cpi->enc_quant_dequant_params.prev_deltaq_params;
1585
0
  prev_deltaq_params->y_dc_delta_q = INT_MAX;
1586
0
  prev_deltaq_params->u_dc_delta_q = INT_MAX;
1587
0
  prev_deltaq_params->v_dc_delta_q = INT_MAX;
1588
0
  prev_deltaq_params->u_ac_delta_q = INT_MAX;
1589
0
  prev_deltaq_params->v_ac_delta_q = INT_MAX;
1590
1591
0
  av1_init_quantizer(&cpi->enc_quant_dequant_params, &cm->quant_params,
1592
0
                     cm->seq_params->bit_depth);
1593
0
  av1_qm_init(&cm->quant_params, av1_num_planes(cm));
1594
1595
0
  av1_loop_filter_init(cm);
1596
0
  cm->superres_scale_denominator = SCALE_NUMERATOR;
1597
0
  cm->superres_upscaled_width = oxcf->frm_dim_cfg.width;
1598
0
  cm->superres_upscaled_height = oxcf->frm_dim_cfg.height;
1599
0
#if !CONFIG_REALTIME_ONLY
1600
0
  av1_loop_restoration_precal();
1601
0
#endif
1602
1603
#if CONFIG_THREE_PASS
1604
  cpi->third_pass_ctx = NULL;
1605
  if (cpi->oxcf.pass == AOM_RC_THIRD_PASS) {
1606
    av1_init_thirdpass_ctx(cm, &cpi->third_pass_ctx, NULL);
1607
  }
1608
#endif
1609
1610
0
  cpi->second_pass_log_stream = NULL;
1611
0
  cpi->use_ducky_encode = 0;
1612
1613
0
  cm->error->setjmp = 0;
1614
0
  return cpi;
1615
0
}
1616
1617
#if CONFIG_INTERNAL_STATS
1618
#define SNPRINT(H, T) snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T))
1619
1620
#define SNPRINT2(H, T, V) \
1621
  snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T), (V))
1622
#endif  // CONFIG_INTERNAL_STATS
1623
1624
0
void av1_remove_primary_compressor(AV1_PRIMARY *ppi) {
1625
0
  if (!ppi) return;
1626
0
#if !CONFIG_REALTIME_ONLY
1627
0
  av1_tf_info_free(&ppi->tf_info);
1628
0
#endif  // !CONFIG_REALTIME_ONLY
1629
1630
0
  for (int i = 0; i < MAX_NUM_OPERATING_POINTS; ++i) {
1631
0
    aom_free(ppi->level_params.level_info[i]);
1632
0
  }
1633
0
  av1_lookahead_destroy(ppi->lookahead);
1634
1635
0
  aom_free(ppi->tpl_sb_rdmult_scaling_factors);
1636
0
  ppi->tpl_sb_rdmult_scaling_factors = NULL;
1637
1638
0
  TplParams *const tpl_data = &ppi->tpl_data;
1639
0
  aom_free(tpl_data->txfm_stats_list);
1640
1641
0
  for (int frame = 0; frame < MAX_LAG_BUFFERS; ++frame) {
1642
0
    aom_free(tpl_data->tpl_stats_pool[frame]);
1643
0
    aom_free_frame_buffer(&tpl_data->tpl_rec_pool[frame]);
1644
0
    tpl_data->tpl_stats_pool[frame] = NULL;
1645
0
  }
1646
1647
0
#if !CONFIG_REALTIME_ONLY
1648
0
  av1_tpl_dealloc(&tpl_data->tpl_mt_sync);
1649
0
#endif
1650
1651
0
  av1_terminate_workers(ppi);
1652
0
  free_thread_data(ppi);
1653
1654
0
  aom_free(ppi->p_mt_info.tile_thr_data);
1655
0
  ppi->p_mt_info.tile_thr_data = NULL;
1656
0
  aom_free(ppi->p_mt_info.workers);
1657
0
  ppi->p_mt_info.workers = NULL;
1658
0
  ppi->p_mt_info.num_workers = 0;
1659
1660
0
  aom_free(ppi);
1661
0
}
1662
1663
0
void av1_remove_compressor(AV1_COMP *cpi) {
1664
0
  if (!cpi) return;
1665
#if CONFIG_RATECTRL_LOG
1666
  if (cpi->oxcf.pass == 3) {
1667
    rc_log_show(&cpi->rc_log);
1668
  }
1669
#endif  // CONFIG_RATECTRL_LOG
1670
1671
0
  AV1_COMMON *cm = &cpi->common;
1672
0
  if (cm->current_frame.frame_number > 0) {
1673
#if CONFIG_SPEED_STATS
1674
    if (!is_stat_generation_stage(cpi)) {
1675
      fprintf(stdout, "tx_search_count = %d\n", cpi->tx_search_count);
1676
    }
1677
#endif  // CONFIG_SPEED_STATS
1678
1679
#if CONFIG_COLLECT_PARTITION_STATS == 2
1680
    if (!is_stat_generation_stage(cpi)) {
1681
      av1_print_fr_partition_timing_stats(&cpi->partition_stats,
1682
                                          "fr_part_timing_data.csv");
1683
    }
1684
#endif
1685
0
  }
1686
1687
#if CONFIG_AV1_TEMPORAL_DENOISING
1688
  av1_denoiser_free(&(cpi->denoiser));
1689
#endif
1690
1691
0
  if (cm->error) {
1692
    // Help detect use after free of the error detail string.
1693
0
    memset(cm->error->detail, 'A', sizeof(cm->error->detail) - 1);
1694
0
    cm->error->detail[sizeof(cm->error->detail) - 1] = '\0';
1695
0
    aom_free(cm->error);
1696
0
  }
1697
0
  aom_free(cpi->td.tctx);
1698
0
  MultiThreadInfo *const mt_info = &cpi->mt_info;
1699
0
#if CONFIG_MULTITHREAD
1700
0
  pthread_mutex_t *const enc_row_mt_mutex_ = mt_info->enc_row_mt.mutex_;
1701
0
  pthread_cond_t *const enc_row_mt_cond_ = mt_info->enc_row_mt.cond_;
1702
0
  pthread_mutex_t *const gm_mt_mutex_ = mt_info->gm_sync.mutex_;
1703
0
  pthread_mutex_t *const tpl_error_mutex_ = mt_info->tpl_row_mt.mutex_;
1704
0
  pthread_mutex_t *const pack_bs_mt_mutex_ = mt_info->pack_bs_sync.mutex_;
1705
0
  if (enc_row_mt_mutex_ != NULL) {
1706
0
    pthread_mutex_destroy(enc_row_mt_mutex_);
1707
0
    aom_free(enc_row_mt_mutex_);
1708
0
  }
1709
0
  if (enc_row_mt_cond_ != NULL) {
1710
0
    pthread_cond_destroy(enc_row_mt_cond_);
1711
0
    aom_free(enc_row_mt_cond_);
1712
0
  }
1713
0
  if (gm_mt_mutex_ != NULL) {
1714
0
    pthread_mutex_destroy(gm_mt_mutex_);
1715
0
    aom_free(gm_mt_mutex_);
1716
0
  }
1717
0
  if (tpl_error_mutex_ != NULL) {
1718
0
    pthread_mutex_destroy(tpl_error_mutex_);
1719
0
    aom_free(tpl_error_mutex_);
1720
0
  }
1721
0
  if (pack_bs_mt_mutex_ != NULL) {
1722
0
    pthread_mutex_destroy(pack_bs_mt_mutex_);
1723
0
    aom_free(pack_bs_mt_mutex_);
1724
0
  }
1725
0
#endif
1726
0
  av1_row_mt_mem_dealloc(cpi);
1727
1728
0
  if (mt_info->num_workers > 1) {
1729
0
    av1_row_mt_sync_mem_dealloc(&cpi->ppi->intra_row_mt_sync);
1730
0
    av1_loop_filter_dealloc(&mt_info->lf_row_sync);
1731
0
    av1_cdef_mt_dealloc(&mt_info->cdef_sync);
1732
0
#if !CONFIG_REALTIME_ONLY
1733
0
    av1_loop_restoration_dealloc(&mt_info->lr_row_sync);
1734
0
    av1_tf_mt_dealloc(&mt_info->tf_sync);
1735
0
#endif
1736
0
  }
1737
1738
#if CONFIG_THREE_PASS
1739
  av1_free_thirdpass_ctx(cpi->third_pass_ctx);
1740
1741
  av1_close_second_pass_log(cpi);
1742
#endif
1743
1744
0
  dealloc_compressor_data(cpi);
1745
1746
0
  av1_ext_part_delete(&cpi->ext_part_controller);
1747
1748
0
  av1_remove_common(cm);
1749
1750
0
  aom_free(cpi);
1751
1752
#ifdef OUTPUT_YUV_REC
1753
  fclose(yuv_rec_file);
1754
#endif
1755
1756
#ifdef OUTPUT_YUV_DENOISED
1757
  fclose(yuv_denoised_file);
1758
#endif
1759
0
}
1760
1761
0
static void generate_psnr_packet(AV1_COMP *cpi) {
1762
0
  struct aom_codec_cx_pkt pkt;
1763
0
  int i;
1764
0
  PSNR_STATS psnr;
1765
0
#if CONFIG_AV1_HIGHBITDEPTH
1766
0
  const uint32_t in_bit_depth = cpi->oxcf.input_cfg.input_bit_depth;
1767
0
  const uint32_t bit_depth = cpi->td.mb.e_mbd.bd;
1768
0
  aom_calc_highbd_psnr(cpi->source, &cpi->common.cur_frame->buf, &psnr,
1769
0
                       bit_depth, in_bit_depth);
1770
#else
1771
  aom_calc_psnr(cpi->source, &cpi->common.cur_frame->buf, &psnr);
1772
#endif
1773
1774
0
  for (i = 0; i < 4; ++i) {
1775
0
    pkt.data.psnr.samples[i] = psnr.samples[i];
1776
0
    pkt.data.psnr.sse[i] = psnr.sse[i];
1777
0
    pkt.data.psnr.psnr[i] = psnr.psnr[i];
1778
0
  }
1779
1780
0
#if CONFIG_AV1_HIGHBITDEPTH
1781
0
  if ((cpi->source->flags & YV12_FLAG_HIGHBITDEPTH) &&
1782
0
      (in_bit_depth < bit_depth)) {
1783
0
    for (i = 0; i < 4; ++i) {
1784
0
      pkt.data.psnr.samples_hbd[i] = psnr.samples_hbd[i];
1785
0
      pkt.data.psnr.sse_hbd[i] = psnr.sse_hbd[i];
1786
0
      pkt.data.psnr.psnr_hbd[i] = psnr.psnr_hbd[i];
1787
0
    }
1788
0
  }
1789
0
#endif
1790
1791
0
  pkt.kind = AOM_CODEC_PSNR_PKT;
1792
0
  aom_codec_pkt_list_add(cpi->ppi->output_pkt_list, &pkt);
1793
0
}
1794
1795
0
int av1_use_as_reference(int *ext_ref_frame_flags, int ref_frame_flags) {
1796
0
  if (ref_frame_flags > ((1 << INTER_REFS_PER_FRAME) - 1)) return -1;
1797
1798
0
  *ext_ref_frame_flags = ref_frame_flags;
1799
0
  return 0;
1800
0
}
1801
1802
0
int av1_copy_reference_enc(AV1_COMP *cpi, int idx, YV12_BUFFER_CONFIG *sd) {
1803
0
  AV1_COMMON *const cm = &cpi->common;
1804
0
  const int num_planes = av1_num_planes(cm);
1805
0
  YV12_BUFFER_CONFIG *cfg = get_ref_frame(cm, idx);
1806
0
  if (cfg) {
1807
0
    aom_yv12_copy_frame(cfg, sd, num_planes);
1808
0
    return 0;
1809
0
  } else {
1810
0
    return -1;
1811
0
  }
1812
0
}
1813
1814
0
int av1_set_reference_enc(AV1_COMP *cpi, int idx, YV12_BUFFER_CONFIG *sd) {
1815
0
  AV1_COMMON *const cm = &cpi->common;
1816
0
  const int num_planes = av1_num_planes(cm);
1817
0
  YV12_BUFFER_CONFIG *cfg = get_ref_frame(cm, idx);
1818
0
  if (cfg) {
1819
0
    aom_yv12_copy_frame(sd, cfg, num_planes);
1820
0
    return 0;
1821
0
  } else {
1822
0
    return -1;
1823
0
  }
1824
0
}
1825
1826
#ifdef OUTPUT_YUV_REC
1827
void aom_write_one_yuv_frame(AV1_COMMON *cm, YV12_BUFFER_CONFIG *s) {
1828
  uint8_t *src = s->y_buffer;
1829
  int h = cm->height;
1830
  if (yuv_rec_file == NULL) return;
1831
  if (s->flags & YV12_FLAG_HIGHBITDEPTH) {
1832
    uint16_t *src16 = CONVERT_TO_SHORTPTR(s->y_buffer);
1833
1834
    do {
1835
      fwrite(src16, s->y_width, 2, yuv_rec_file);
1836
      src16 += s->y_stride;
1837
    } while (--h);
1838
1839
    src16 = CONVERT_TO_SHORTPTR(s->u_buffer);
1840
    h = s->uv_height;
1841
1842
    do {
1843
      fwrite(src16, s->uv_width, 2, yuv_rec_file);
1844
      src16 += s->uv_stride;
1845
    } while (--h);
1846
1847
    src16 = CONVERT_TO_SHORTPTR(s->v_buffer);
1848
    h = s->uv_height;
1849
1850
    do {
1851
      fwrite(src16, s->uv_width, 2, yuv_rec_file);
1852
      src16 += s->uv_stride;
1853
    } while (--h);
1854
1855
    fflush(yuv_rec_file);
1856
    return;
1857
  }
1858
1859
  do {
1860
    fwrite(src, s->y_width, 1, yuv_rec_file);
1861
    src += s->y_stride;
1862
  } while (--h);
1863
1864
  src = s->u_buffer;
1865
  h = s->uv_height;
1866
1867
  do {
1868
    fwrite(src, s->uv_width, 1, yuv_rec_file);
1869
    src += s->uv_stride;
1870
  } while (--h);
1871
1872
  src = s->v_buffer;
1873
  h = s->uv_height;
1874
1875
  do {
1876
    fwrite(src, s->uv_width, 1, yuv_rec_file);
1877
    src += s->uv_stride;
1878
  } while (--h);
1879
1880
  fflush(yuv_rec_file);
1881
}
1882
#endif  // OUTPUT_YUV_REC
1883
1884
0
void av1_set_mv_search_params(AV1_COMP *cpi) {
1885
0
  const AV1_COMMON *const cm = &cpi->common;
1886
0
  MotionVectorSearchParams *const mv_search_params = &cpi->mv_search_params;
1887
0
  const int max_mv_def = AOMMAX(cm->width, cm->height);
1888
1889
  // Default based on max resolution.
1890
0
  mv_search_params->mv_step_param = av1_init_search_range(max_mv_def);
1891
1892
0
  if (cpi->sf.mv_sf.auto_mv_step_size) {
1893
0
    if (frame_is_intra_only(cm)) {
1894
      // Initialize max_mv_magnitude for use in the first INTER frame
1895
      // after a key/intra-only frame.
1896
0
      mv_search_params->max_mv_magnitude = max_mv_def;
1897
0
    } else {
1898
      // Use adaptive mv steps based on previous frame stats for show frames and
1899
      // internal arfs.
1900
0
      FRAME_UPDATE_TYPE cur_update_type =
1901
0
          cpi->ppi->gf_group.update_type[cpi->gf_frame_index];
1902
0
      int use_auto_mv_step =
1903
0
          (cm->show_frame || cur_update_type == INTNL_ARF_UPDATE) &&
1904
0
          mv_search_params->max_mv_magnitude != -1 &&
1905
0
          cpi->sf.mv_sf.auto_mv_step_size >= 2;
1906
0
      if (use_auto_mv_step) {
1907
        // Allow mv_steps to correspond to twice the max mv magnitude found
1908
        // in the previous frame, capped by the default max_mv_magnitude based
1909
        // on resolution.
1910
0
        mv_search_params->mv_step_param = av1_init_search_range(
1911
0
            AOMMIN(max_mv_def, 2 * mv_search_params->max_mv_magnitude));
1912
0
      }
1913
      // Reset max_mv_magnitude based on update flag.
1914
0
      if (cpi->do_frame_data_update) mv_search_params->max_mv_magnitude = -1;
1915
0
    }
1916
0
  }
1917
0
}
1918
1919
0
void av1_set_screen_content_options(AV1_COMP *cpi, FeatureFlags *features) {
1920
0
  const AV1_COMMON *const cm = &cpi->common;
1921
0
  const MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
1922
1923
0
  if (cm->seq_params->force_screen_content_tools != 2) {
1924
0
    features->allow_screen_content_tools = features->allow_intrabc =
1925
0
        cm->seq_params->force_screen_content_tools;
1926
0
    return;
1927
0
  }
1928
1929
0
  if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN) {
1930
0
    features->allow_screen_content_tools = 1;
1931
0
    features->allow_intrabc = cpi->oxcf.mode == REALTIME ? 0 : 1;
1932
0
    cpi->is_screen_content_type = 1;
1933
0
    cpi->use_screen_content_tools = 1;
1934
0
    return;
1935
0
  }
1936
1937
0
  if (cpi->oxcf.mode == REALTIME) {
1938
0
    features->allow_screen_content_tools = features->allow_intrabc = 0;
1939
0
    return;
1940
0
  }
1941
1942
  // Screen content tools are not evaluated in non-RD encoding mode unless
1943
  // content type is not set explicitly, i.e., when
1944
  // cpi->oxcf.tune_cfg.content != AOM_CONTENT_SCREEN, use_nonrd_pick_mode = 1
1945
  // and hybrid_intra_pickmode = 0. Hence, screen content detection is
1946
  // disabled.
1947
0
  if (cpi->sf.rt_sf.use_nonrd_pick_mode &&
1948
0
      !cpi->sf.rt_sf.hybrid_intra_pickmode) {
1949
0
    features->allow_screen_content_tools = features->allow_intrabc = 0;
1950
0
    return;
1951
0
  }
1952
1953
  // Estimate if the source frame is screen content, based on the portion of
1954
  // blocks that have few luma colors.
1955
0
  const uint8_t *src = cpi->unfiltered_source->y_buffer;
1956
0
  assert(src != NULL);
1957
0
  const int use_hbd = cpi->unfiltered_source->flags & YV12_FLAG_HIGHBITDEPTH;
1958
0
  const int stride = cpi->unfiltered_source->y_stride;
1959
0
  const int width = cpi->unfiltered_source->y_width;
1960
0
  const int height = cpi->unfiltered_source->y_height;
1961
0
  const int64_t area = (int64_t)width * height;
1962
0
  const int bd = cm->seq_params->bit_depth;
1963
0
  const int blk_w = 16;
1964
0
  const int blk_h = 16;
1965
  // These threshold values are selected experimentally.
1966
0
  const int color_thresh = 4;
1967
0
  const unsigned int var_thresh = 0;
1968
  // Counts of blocks with no more than color_thresh colors.
1969
0
  int64_t counts_1 = 0;
1970
  // Counts of blocks with no more than color_thresh colors and variance larger
1971
  // than var_thresh.
1972
0
  int64_t counts_2 = 0;
1973
1974
0
  for (int r = 0; r + blk_h <= height; r += blk_h) {
1975
0
    for (int c = 0; c + blk_w <= width; c += blk_w) {
1976
0
      int count_buf[1 << 8];  // Maximum (1 << 8) bins for hbd path.
1977
0
      const uint8_t *const this_src = src + r * stride + c;
1978
0
      int n_colors;
1979
0
      if (use_hbd)
1980
0
        av1_count_colors_highbd(this_src, stride, blk_w, blk_h, bd, NULL,
1981
0
                                count_buf, &n_colors, NULL);
1982
0
      else
1983
0
        av1_count_colors(this_src, stride, blk_w, blk_h, count_buf, &n_colors);
1984
0
      if (n_colors > 1 && n_colors <= color_thresh) {
1985
0
        ++counts_1;
1986
0
        struct buf_2d buf;
1987
0
        buf.stride = stride;
1988
0
        buf.buf = (uint8_t *)this_src;
1989
0
        const unsigned int var = av1_get_perpixel_variance(
1990
0
            cpi, xd, &buf, BLOCK_16X16, AOM_PLANE_Y, use_hbd);
1991
0
        if (var > var_thresh) ++counts_2;
1992
0
      }
1993
0
    }
1994
0
  }
1995
1996
  // The threshold values are selected experimentally.
1997
0
  features->allow_screen_content_tools = counts_1 * blk_h * blk_w * 10 > area;
1998
  // IntraBC would force loop filters off, so we use more strict rules that also
1999
  // requires that the block has high variance.
2000
0
  features->allow_intrabc = features->allow_screen_content_tools &&
2001
0
                            counts_2 * blk_h * blk_w * 12 > area;
2002
0
  cpi->use_screen_content_tools = features->allow_screen_content_tools;
2003
0
  cpi->is_screen_content_type =
2004
0
      features->allow_intrabc || (counts_1 * blk_h * blk_w * 10 > area * 4 &&
2005
0
                                  counts_2 * blk_h * blk_w * 30 > area);
2006
0
}
2007
2008
0
static void init_motion_estimation(AV1_COMP *cpi) {
2009
0
  AV1_COMMON *const cm = &cpi->common;
2010
0
  MotionVectorSearchParams *const mv_search_params = &cpi->mv_search_params;
2011
0
  const int aligned_width = (cm->width + 7) & ~7;
2012
0
  const int y_stride =
2013
0
      aom_calc_y_stride(aligned_width, cpi->oxcf.border_in_pixels);
2014
0
  const int y_stride_src = ((cpi->oxcf.frm_dim_cfg.width != cm->width ||
2015
0
                             cpi->oxcf.frm_dim_cfg.height != cm->height) ||
2016
0
                            av1_superres_scaled(cm))
2017
0
                               ? y_stride
2018
0
                               : cpi->ppi->lookahead->buf->img.y_stride;
2019
0
  int fpf_y_stride =
2020
0
      cm->cur_frame != NULL ? cm->cur_frame->buf.y_stride : y_stride;
2021
2022
  // Update if search_site_cfg is uninitialized or the current frame has a new
2023
  // stride
2024
0
  const int should_update =
2025
0
      !mv_search_params->search_site_cfg[SS_CFG_SRC][DIAMOND].stride ||
2026
0
      !mv_search_params->search_site_cfg[SS_CFG_LOOKAHEAD][DIAMOND].stride ||
2027
0
      (y_stride !=
2028
0
       mv_search_params->search_site_cfg[SS_CFG_SRC][DIAMOND].stride);
2029
2030
0
  if (!should_update) {
2031
0
    return;
2032
0
  }
2033
2034
  // Initialization of search_site_cfg for NUM_DISTINCT_SEARCH_METHODS.
2035
0
  for (SEARCH_METHODS i = DIAMOND; i < NUM_DISTINCT_SEARCH_METHODS; i++) {
2036
0
    const int level = ((i == NSTEP_8PT) || (i == CLAMPED_DIAMOND)) ? 1 : 0;
2037
0
    av1_init_motion_compensation[i](
2038
0
        &mv_search_params->search_site_cfg[SS_CFG_SRC][i], y_stride, level);
2039
0
    av1_init_motion_compensation[i](
2040
0
        &mv_search_params->search_site_cfg[SS_CFG_LOOKAHEAD][i], y_stride_src,
2041
0
        level);
2042
0
  }
2043
2044
  // First pass search site config initialization.
2045
0
  av1_init_motion_fpf(&mv_search_params->search_site_cfg[SS_CFG_FPF][DIAMOND],
2046
0
                      fpf_y_stride);
2047
0
  for (SEARCH_METHODS i = NSTEP; i < NUM_DISTINCT_SEARCH_METHODS; i++) {
2048
0
    memcpy(&mv_search_params->search_site_cfg[SS_CFG_FPF][i],
2049
0
           &mv_search_params->search_site_cfg[SS_CFG_FPF][DIAMOND],
2050
0
           sizeof(search_site_config));
2051
0
  }
2052
0
}
2053
2054
0
static void init_ref_frame_bufs(AV1_COMP *cpi) {
2055
0
  AV1_COMMON *const cm = &cpi->common;
2056
0
  int i;
2057
0
  if (cm->cur_frame) {
2058
0
    cm->cur_frame->ref_count--;
2059
0
    cm->cur_frame = NULL;
2060
0
  }
2061
0
  for (i = 0; i < REF_FRAMES; ++i) {
2062
0
    if (cm->ref_frame_map[i]) {
2063
0
      cm->ref_frame_map[i]->ref_count--;
2064
0
      cm->ref_frame_map[i] = NULL;
2065
0
    }
2066
0
  }
2067
#ifndef NDEBUG
2068
  BufferPool *const pool = cm->buffer_pool;
2069
  for (i = 0; i < pool->num_frame_bufs; ++i) {
2070
    assert(pool->frame_bufs[i].ref_count == 0);
2071
  }
2072
#endif
2073
0
}
2074
2075
// TODO(chengchen): consider renaming this function as it is necessary
2076
// for the encoder to setup critical parameters, and it does not
2077
// deal with initial width any longer.
2078
aom_codec_err_t av1_check_initial_width(AV1_COMP *cpi, int use_highbitdepth,
2079
0
                                        int subsampling_x, int subsampling_y) {
2080
0
  AV1_COMMON *const cm = &cpi->common;
2081
0
  SequenceHeader *const seq_params = cm->seq_params;
2082
2083
0
  if (!cpi->frame_size_related_setup_done ||
2084
0
      seq_params->use_highbitdepth != use_highbitdepth ||
2085
0
      seq_params->subsampling_x != subsampling_x ||
2086
0
      seq_params->subsampling_y != subsampling_y) {
2087
0
    seq_params->subsampling_x = subsampling_x;
2088
0
    seq_params->subsampling_y = subsampling_y;
2089
0
    seq_params->use_highbitdepth = use_highbitdepth;
2090
2091
0
    av1_set_speed_features_framesize_independent(cpi, cpi->oxcf.speed);
2092
0
    av1_set_speed_features_framesize_dependent(cpi, cpi->oxcf.speed);
2093
2094
0
    if (!is_stat_generation_stage(cpi)) {
2095
0
#if !CONFIG_REALTIME_ONLY
2096
0
      if (!av1_tf_info_alloc(&cpi->ppi->tf_info, cpi))
2097
0
        return AOM_CODEC_MEM_ERROR;
2098
0
#endif  // !CONFIG_REALTIME_ONLY
2099
0
    }
2100
0
    init_ref_frame_bufs(cpi);
2101
2102
0
    init_motion_estimation(cpi);  // TODO(agrange) This can be removed.
2103
2104
0
    cpi->initial_mbs = cm->mi_params.MBs;
2105
0
    cpi->frame_size_related_setup_done = true;
2106
0
  }
2107
0
  return AOM_CODEC_OK;
2108
0
}
2109
2110
#if CONFIG_AV1_TEMPORAL_DENOISING
2111
static void setup_denoiser_buffer(AV1_COMP *cpi) {
2112
  AV1_COMMON *const cm = &cpi->common;
2113
  if (cpi->oxcf.noise_sensitivity > 0 &&
2114
      !cpi->denoiser.frame_buffer_initialized) {
2115
    if (av1_denoiser_alloc(
2116
            cm, &cpi->svc, &cpi->denoiser, cpi->ppi->use_svc,
2117
            cpi->oxcf.noise_sensitivity, cm->width, cm->height,
2118
            cm->seq_params->subsampling_x, cm->seq_params->subsampling_y,
2119
            cm->seq_params->use_highbitdepth, AOM_BORDER_IN_PIXELS))
2120
      aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
2121
                         "Failed to allocate denoiser");
2122
  }
2123
}
2124
#endif
2125
2126
// Returns 1 if the assigned width or height was <= 0.
2127
0
static int set_size_literal(AV1_COMP *cpi, int width, int height) {
2128
0
  AV1_COMMON *cm = &cpi->common;
2129
0
  aom_codec_err_t err = av1_check_initial_width(
2130
0
      cpi, cm->seq_params->use_highbitdepth, cm->seq_params->subsampling_x,
2131
0
      cm->seq_params->subsampling_y);
2132
0
  if (err != AOM_CODEC_OK) {
2133
0
    aom_internal_error(cm->error, err, "av1_check_initial_width() failed");
2134
0
  }
2135
2136
0
  if (width <= 0 || height <= 0) return 1;
2137
2138
0
  cm->width = width;
2139
0
  cm->height = height;
2140
2141
#if CONFIG_AV1_TEMPORAL_DENOISING
2142
  setup_denoiser_buffer(cpi);
2143
#endif
2144
2145
0
  if (cm->width > cpi->data_alloc_width ||
2146
0
      cm->height > cpi->data_alloc_height) {
2147
0
    av1_free_context_buffers(cm);
2148
0
    av1_free_shared_coeff_buffer(&cpi->td.shared_coeff_buf);
2149
0
    av1_free_sms_tree(&cpi->td);
2150
0
    av1_free_pmc(cpi->td.firstpass_ctx, av1_num_planes(cm));
2151
0
    cpi->td.firstpass_ctx = NULL;
2152
0
    alloc_compressor_data(cpi);
2153
0
    realloc_segmentation_maps(cpi);
2154
0
    cpi->data_alloc_width = cm->width;
2155
0
    cpi->data_alloc_height = cm->height;
2156
0
    cpi->frame_size_related_setup_done = false;
2157
0
  }
2158
0
  alloc_mb_mode_info_buffers(cpi);
2159
0
  av1_update_frame_size(cpi);
2160
2161
0
  return 0;
2162
0
}
2163
2164
0
void av1_set_frame_size(AV1_COMP *cpi, int width, int height) {
2165
0
  AV1_COMMON *const cm = &cpi->common;
2166
0
  const SequenceHeader *const seq_params = cm->seq_params;
2167
0
  const int num_planes = av1_num_planes(cm);
2168
0
  MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
2169
0
  int ref_frame;
2170
2171
0
  if (width != cm->width || height != cm->height) {
2172
    // There has been a change in the encoded frame size
2173
0
    set_size_literal(cpi, width, height);
2174
    // Recalculate 'all_lossless' in case super-resolution was (un)selected.
2175
0
    cm->features.all_lossless =
2176
0
        cm->features.coded_lossless && !av1_superres_scaled(cm);
2177
2178
0
    av1_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
2179
#if CONFIG_AV1_TEMPORAL_DENOISING
2180
    // Reset the denoiser on the resized frame.
2181
    if (cpi->oxcf.noise_sensitivity > 0) {
2182
      av1_denoiser_free(&(cpi->denoiser));
2183
      setup_denoiser_buffer(cpi);
2184
    }
2185
#endif
2186
0
  }
2187
0
  if (is_stat_consumption_stage(cpi)) {
2188
0
    av1_set_target_rate(cpi, cm->width, cm->height);
2189
0
  }
2190
2191
0
  alloc_frame_mvs(cm, cm->cur_frame);
2192
2193
  // Allocate above context buffers
2194
0
  CommonContexts *const above_contexts = &cm->above_contexts;
2195
0
  if (above_contexts->num_planes < av1_num_planes(cm) ||
2196
0
      above_contexts->num_mi_cols < cm->mi_params.mi_cols ||
2197
0
      above_contexts->num_tile_rows < cm->tiles.rows) {
2198
0
    av1_free_above_context_buffers(above_contexts);
2199
0
    if (av1_alloc_above_context_buffers(above_contexts, cm->tiles.rows,
2200
0
                                        cm->mi_params.mi_cols,
2201
0
                                        av1_num_planes(cm)))
2202
0
      aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
2203
0
                         "Failed to allocate context buffers");
2204
0
  }
2205
2206
0
  AV1EncoderConfig *oxcf = &cpi->oxcf;
2207
0
  oxcf->border_in_pixels = av1_get_enc_border_size(
2208
0
      av1_is_resize_needed(oxcf), oxcf->kf_cfg.key_freq_max == 0,
2209
0
      cm->seq_params->sb_size);
2210
2211
  // Reset the frame pointers to the current frame size.
2212
0
  if (aom_realloc_frame_buffer(
2213
0
          &cm->cur_frame->buf, cm->width, cm->height, seq_params->subsampling_x,
2214
0
          seq_params->subsampling_y, seq_params->use_highbitdepth,
2215
0
          cpi->oxcf.border_in_pixels, cm->features.byte_alignment, NULL, NULL,
2216
0
          NULL, cpi->alloc_pyramid, 0))
2217
0
    aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
2218
0
                       "Failed to allocate frame buffer");
2219
2220
0
  if (!is_stat_generation_stage(cpi)) av1_init_cdef_worker(cpi);
2221
2222
0
#if !CONFIG_REALTIME_ONLY
2223
0
  if (is_restoration_used(cm)) {
2224
0
    for (int i = 0; i < num_planes; ++i)
2225
0
      cm->rst_info[i].frame_restoration_type = RESTORE_NONE;
2226
2227
0
    const bool is_sgr_enabled = !cpi->sf.lpf_sf.disable_sgr_filter;
2228
0
    av1_alloc_restoration_buffers(cm, is_sgr_enabled);
2229
    // Store the allocated restoration buffers in MT object.
2230
0
    if (cpi->ppi->p_mt_info.num_workers > 1) {
2231
0
      av1_init_lr_mt_buffers(cpi);
2232
0
    }
2233
0
  }
2234
0
#endif
2235
2236
0
  init_motion_estimation(cpi);
2237
2238
0
  int has_valid_ref_frame = 0;
2239
0
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2240
0
    RefCntBuffer *const buf = get_ref_frame_buf(cm, ref_frame);
2241
0
    if (buf != NULL) {
2242
0
      struct scale_factors *sf = get_ref_scale_factors(cm, ref_frame);
2243
0
      av1_setup_scale_factors_for_frame(sf, buf->buf.y_crop_width,
2244
0
                                        buf->buf.y_crop_height, cm->width,
2245
0
                                        cm->height);
2246
0
      has_valid_ref_frame |= av1_is_valid_scale(sf);
2247
0
      if (av1_is_scaled(sf)) aom_extend_frame_borders(&buf->buf, num_planes);
2248
0
    }
2249
0
  }
2250
0
  if (!frame_is_intra_only(cm) && !has_valid_ref_frame) {
2251
0
    aom_internal_error(
2252
0
        cm->error, AOM_CODEC_CORRUPT_FRAME,
2253
0
        "Can't find at least one reference frame with valid size");
2254
0
  }
2255
2256
0
  av1_setup_scale_factors_for_frame(&cm->sf_identity, cm->width, cm->height,
2257
0
                                    cm->width, cm->height);
2258
2259
0
  set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
2260
0
}
2261
2262
static inline int extend_borders_mt(const AV1_COMP *cpi,
2263
0
                                    MULTI_THREADED_MODULES stage, int plane) {
2264
0
  const AV1_COMMON *const cm = &cpi->common;
2265
0
  if (cpi->mt_info.num_mod_workers[stage] < 2) return 0;
2266
0
  switch (stage) {
2267
    // TODO(deepa.kg@ittiam.com): When cdef and loop-restoration are disabled,
2268
    // multi-thread frame border extension along with loop filter frame.
2269
    // As loop-filtering of a superblock row modifies the pixels of the
2270
    // above superblock row, border extension requires that loop filtering
2271
    // of the current and above superblock row is complete.
2272
0
    case MOD_LPF: return 0;
2273
0
    case MOD_CDEF:
2274
0
      return is_cdef_used(cm) && !cpi->ppi->rtc_ref.non_reference_frame &&
2275
0
             !is_restoration_used(cm) && !av1_superres_scaled(cm);
2276
0
    case MOD_LR:
2277
0
      return is_restoration_used(cm) &&
2278
0
             (cm->rst_info[plane].frame_restoration_type != RESTORE_NONE);
2279
0
    default: assert(0);
2280
0
  }
2281
0
  return 0;
2282
0
}
2283
2284
/*!\brief Select and apply cdef filters and switchable restoration filters
2285
 *
2286
 * \ingroup high_level_algo
2287
 */
2288
static void cdef_restoration_frame(AV1_COMP *cpi, AV1_COMMON *cm,
2289
                                   MACROBLOCKD *xd, int use_restoration,
2290
                                   int use_cdef,
2291
0
                                   unsigned int skip_apply_postproc_filters) {
2292
0
#if !CONFIG_REALTIME_ONLY
2293
0
  if (use_restoration)
2294
0
    av1_loop_restoration_save_boundary_lines(&cm->cur_frame->buf, cm, 0);
2295
#else
2296
  (void)use_restoration;
2297
#endif
2298
2299
0
  if (use_cdef) {
2300
#if CONFIG_COLLECT_COMPONENT_TIMING
2301
    start_timing(cpi, cdef_time);
2302
#endif
2303
0
    const int num_workers = cpi->mt_info.num_mod_workers[MOD_CDEF];
2304
    // Find CDEF parameters
2305
0
    av1_cdef_search(cpi);
2306
2307
    // Apply the filter
2308
0
    if ((skip_apply_postproc_filters & SKIP_APPLY_CDEF) == 0) {
2309
0
      assert(!cpi->ppi->rtc_ref.non_reference_frame);
2310
0
      if (num_workers > 1) {
2311
        // Extension of frame borders is multi-threaded along with cdef.
2312
0
        const int do_extend_border =
2313
0
            extend_borders_mt(cpi, MOD_CDEF, /* plane */ 0);
2314
0
        av1_cdef_frame_mt(cm, xd, cpi->mt_info.cdef_worker,
2315
0
                          cpi->mt_info.workers, &cpi->mt_info.cdef_sync,
2316
0
                          num_workers, av1_cdef_init_fb_row_mt,
2317
0
                          do_extend_border);
2318
0
      } else {
2319
0
        av1_cdef_frame(&cm->cur_frame->buf, cm, xd, av1_cdef_init_fb_row);
2320
0
      }
2321
0
    }
2322
#if CONFIG_COLLECT_COMPONENT_TIMING
2323
    end_timing(cpi, cdef_time);
2324
#endif
2325
0
  }
2326
2327
0
  const int use_superres = av1_superres_scaled(cm);
2328
0
  if (use_superres) {
2329
0
    if ((skip_apply_postproc_filters & SKIP_APPLY_SUPERRES) == 0) {
2330
0
      av1_superres_post_encode(cpi);
2331
0
    }
2332
0
  }
2333
2334
0
#if !CONFIG_REALTIME_ONLY
2335
#if CONFIG_COLLECT_COMPONENT_TIMING
2336
  start_timing(cpi, loop_restoration_time);
2337
#endif
2338
0
  if (use_restoration) {
2339
0
    MultiThreadInfo *const mt_info = &cpi->mt_info;
2340
0
    const int num_workers = mt_info->num_mod_workers[MOD_LR];
2341
0
    av1_loop_restoration_save_boundary_lines(&cm->cur_frame->buf, cm, 1);
2342
0
    av1_pick_filter_restoration(cpi->source, cpi);
2343
0
    if ((skip_apply_postproc_filters & SKIP_APPLY_RESTORATION) == 0 &&
2344
0
        (cm->rst_info[0].frame_restoration_type != RESTORE_NONE ||
2345
0
         cm->rst_info[1].frame_restoration_type != RESTORE_NONE ||
2346
0
         cm->rst_info[2].frame_restoration_type != RESTORE_NONE)) {
2347
0
      if (num_workers > 1) {
2348
        // Extension of frame borders is multi-threaded along with loop
2349
        // restoration filter.
2350
0
        const int do_extend_border = 1;
2351
0
        av1_loop_restoration_filter_frame_mt(
2352
0
            &cm->cur_frame->buf, cm, 0, mt_info->workers, num_workers,
2353
0
            &mt_info->lr_row_sync, &cpi->lr_ctxt, do_extend_border);
2354
0
      } else {
2355
0
        av1_loop_restoration_filter_frame(&cm->cur_frame->buf, cm, 0,
2356
0
                                          &cpi->lr_ctxt);
2357
0
      }
2358
0
    }
2359
0
  }
2360
#if CONFIG_COLLECT_COMPONENT_TIMING
2361
  end_timing(cpi, loop_restoration_time);
2362
#endif
2363
0
#endif  // !CONFIG_REALTIME_ONLY
2364
0
}
2365
2366
0
static void extend_frame_borders(AV1_COMP *cpi) {
2367
0
  const AV1_COMMON *const cm = &cpi->common;
2368
  // TODO(debargha): Fix mv search range on encoder side
2369
0
  for (int plane = 0; plane < av1_num_planes(cm); ++plane) {
2370
0
    const bool extend_border_done = extend_borders_mt(cpi, MOD_CDEF, plane) ||
2371
0
                                    extend_borders_mt(cpi, MOD_LR, plane);
2372
0
    if (!extend_border_done) {
2373
0
      const YV12_BUFFER_CONFIG *const ybf = &cm->cur_frame->buf;
2374
0
      aom_extend_frame_borders_plane_row(ybf, plane, 0,
2375
0
                                         ybf->crop_heights[plane > 0]);
2376
0
    }
2377
0
  }
2378
0
}
2379
2380
/*!\brief Select and apply deblocking filters, cdef filters, and restoration
2381
 * filters.
2382
 *
2383
 * \ingroup high_level_algo
2384
 */
2385
0
static void loopfilter_frame(AV1_COMP *cpi, AV1_COMMON *cm) {
2386
0
  MultiThreadInfo *const mt_info = &cpi->mt_info;
2387
0
  const int num_workers = mt_info->num_mod_workers[MOD_LPF];
2388
0
  const int num_planes = av1_num_planes(cm);
2389
0
  MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
2390
0
  cpi->td.mb.rdmult = cpi->rd.RDMULT;
2391
2392
0
  assert(IMPLIES(is_lossless_requested(&cpi->oxcf.rc_cfg),
2393
0
                 cm->features.coded_lossless && cm->features.all_lossless));
2394
2395
0
  const int use_loopfilter =
2396
0
      is_loopfilter_used(cm) && !cpi->mt_info.pipeline_lpf_mt_with_enc;
2397
0
  const int use_cdef = is_cdef_used(cm);
2398
0
  const int use_superres = av1_superres_scaled(cm);
2399
0
  const int use_restoration = is_restoration_used(cm);
2400
2401
0
  const unsigned int skip_apply_postproc_filters =
2402
0
      derive_skip_apply_postproc_filters(cpi, use_loopfilter, use_cdef,
2403
0
                                         use_superres, use_restoration);
2404
2405
#if CONFIG_COLLECT_COMPONENT_TIMING
2406
  start_timing(cpi, loop_filter_time);
2407
#endif
2408
0
  if (use_loopfilter) {
2409
0
    av1_pick_filter_level(cpi->source, cpi, cpi->sf.lpf_sf.lpf_pick);
2410
0
    struct loopfilter *lf = &cm->lf;
2411
0
    if ((lf->filter_level[0] || lf->filter_level[1]) &&
2412
0
        (skip_apply_postproc_filters & SKIP_APPLY_LOOPFILTER) == 0) {
2413
0
      assert(!cpi->ppi->rtc_ref.non_reference_frame);
2414
      // lpf_opt_level = 1 : Enables dual/quad loop-filtering.
2415
      // lpf_opt_level is set to 1 if transform size search depth in inter
2416
      // blocks is limited to one as quad loop filtering assumes that all the
2417
      // transform blocks within a 16x8/8x16/16x16 prediction block are of the
2418
      // same size. lpf_opt_level = 2 : Filters both chroma planes together, in
2419
      // addition to enabling dual/quad loop-filtering. This is enabled when lpf
2420
      // pick method is LPF_PICK_FROM_Q as u and v plane filter levels are
2421
      // equal.
2422
0
      int lpf_opt_level = get_lpf_opt_level(&cpi->sf);
2423
0
      av1_loop_filter_frame_mt(&cm->cur_frame->buf, cm, xd, 0, num_planes, 0,
2424
0
                               mt_info->workers, num_workers,
2425
0
                               &mt_info->lf_row_sync, lpf_opt_level);
2426
0
    }
2427
0
  }
2428
2429
#if CONFIG_COLLECT_COMPONENT_TIMING
2430
  end_timing(cpi, loop_filter_time);
2431
#endif
2432
2433
0
  cdef_restoration_frame(cpi, cm, xd, use_restoration, use_cdef,
2434
0
                         skip_apply_postproc_filters);
2435
0
}
2436
2437
0
static void update_motion_stat(AV1_COMP *const cpi) {
2438
0
  AV1_COMMON *const cm = &cpi->common;
2439
0
  const CommonModeInfoParams *const mi_params = &cm->mi_params;
2440
0
  RATE_CONTROL *const rc = &cpi->rc;
2441
0
  SVC *const svc = &cpi->svc;
2442
0
  const int avg_cnt_zeromv =
2443
0
      100 * cpi->rc.cnt_zeromv / (mi_params->mi_rows * mi_params->mi_cols);
2444
0
  if (!cpi->ppi->use_svc ||
2445
0
      (cpi->ppi->use_svc &&
2446
0
       !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
2447
0
       cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)) {
2448
0
    rc->avg_frame_low_motion =
2449
0
        (rc->avg_frame_low_motion == 0)
2450
0
            ? avg_cnt_zeromv
2451
0
            : (3 * rc->avg_frame_low_motion + avg_cnt_zeromv) / 4;
2452
    // For SVC: set avg_frame_low_motion (only computed on top spatial layer)
2453
    // to all lower spatial layers.
2454
0
    if (cpi->ppi->use_svc &&
2455
0
        svc->spatial_layer_id == svc->number_spatial_layers - 1) {
2456
0
      for (int i = 0; i < svc->number_spatial_layers - 1; ++i) {
2457
0
        const int layer = LAYER_IDS_TO_IDX(i, svc->temporal_layer_id,
2458
0
                                           svc->number_temporal_layers);
2459
0
        LAYER_CONTEXT *const lc = &svc->layer_context[layer];
2460
0
        RATE_CONTROL *const lrc = &lc->rc;
2461
0
        lrc->avg_frame_low_motion = rc->avg_frame_low_motion;
2462
0
      }
2463
0
    }
2464
0
  }
2465
0
}
2466
2467
/*!\brief Encode a frame without the recode loop, usually used in one-pass
2468
 * encoding and realtime coding.
2469
 *
2470
 * \ingroup high_level_algo
2471
 *
2472
 * \param[in]    cpi             Top-level encoder structure
2473
 *
2474
 * \return Returns a value to indicate if the encoding is done successfully.
2475
 * \retval #AOM_CODEC_OK
2476
 * \retval #AOM_CODEC_ERROR
2477
 */
2478
0
static int encode_without_recode(AV1_COMP *cpi) {
2479
0
  AV1_COMMON *const cm = &cpi->common;
2480
0
  const QuantizationCfg *const q_cfg = &cpi->oxcf.q_cfg;
2481
0
  SVC *const svc = &cpi->svc;
2482
0
  const int resize_pending = is_frame_resize_pending(cpi);
2483
0
  int top_index = 0, bottom_index = 0, q = 0;
2484
0
  YV12_BUFFER_CONFIG *unscaled = cpi->unscaled_source;
2485
0
  InterpFilter filter_scaler =
2486
0
      cpi->ppi->use_svc ? svc->downsample_filter_type[svc->spatial_layer_id]
2487
0
                        : EIGHTTAP_SMOOTH;
2488
0
  int phase_scaler = cpi->ppi->use_svc
2489
0
                         ? svc->downsample_filter_phase[svc->spatial_layer_id]
2490
0
                         : 0;
2491
2492
0
  if (cpi->rc.postencode_drop && allow_postencode_drop_rtc(cpi))
2493
0
    av1_save_all_coding_context(cpi);
2494
2495
0
  set_size_independent_vars(cpi);
2496
0
  av1_setup_frame_size(cpi);
2497
0
  cm->prev_frame = get_primary_ref_frame_buf(cm);
2498
0
  av1_set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
2499
0
  av1_set_mv_search_params(cpi);
2500
2501
0
  if (cm->current_frame.frame_number == 0 &&
2502
0
      (cpi->ppi->use_svc || cpi->oxcf.rc_cfg.drop_frames_water_mark > 0) &&
2503
0
      cpi->svc.temporal_layer_id == 0) {
2504
0
    const SequenceHeader *seq_params = cm->seq_params;
2505
0
    if (aom_alloc_frame_buffer(
2506
0
            &cpi->svc.source_last_TL0, cpi->oxcf.frm_dim_cfg.width,
2507
0
            cpi->oxcf.frm_dim_cfg.height, seq_params->subsampling_x,
2508
0
            seq_params->subsampling_y, seq_params->use_highbitdepth,
2509
0
            cpi->oxcf.border_in_pixels, cm->features.byte_alignment, false,
2510
0
            0)) {
2511
0
      aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
2512
0
                         "Failed to allocate buffer for source_last_TL0");
2513
0
    }
2514
0
  }
2515
2516
0
  if (!cpi->ppi->use_svc) {
2517
0
    phase_scaler = 8;
2518
    // 2:1 scaling.
2519
0
    if ((cm->width << 1) == unscaled->y_crop_width &&
2520
0
        (cm->height << 1) == unscaled->y_crop_height) {
2521
0
      filter_scaler = BILINEAR;
2522
      // For lower resolutions use eighttap_smooth.
2523
0
      if (cm->width * cm->height <= 320 * 180) filter_scaler = EIGHTTAP_SMOOTH;
2524
0
    } else if ((cm->width << 2) == unscaled->y_crop_width &&
2525
0
               (cm->height << 2) == unscaled->y_crop_height) {
2526
      // 4:1 scaling.
2527
0
      filter_scaler = EIGHTTAP_SMOOTH;
2528
0
    } else if ((cm->width << 2) == 3 * unscaled->y_crop_width &&
2529
0
               (cm->height << 2) == 3 * unscaled->y_crop_height) {
2530
      // 4:3 scaling.
2531
0
      filter_scaler = EIGHTTAP_REGULAR;
2532
0
    }
2533
0
  }
2534
2535
0
  allocate_gradient_info_for_hog(cpi);
2536
2537
0
  allocate_src_var_of_4x4_sub_block_buf(cpi);
2538
2539
0
  const SPEED_FEATURES *sf = &cpi->sf;
2540
0
  if (sf->part_sf.partition_search_type == VAR_BASED_PARTITION)
2541
0
    variance_partition_alloc(cpi);
2542
2543
0
  if (cm->current_frame.frame_type == KEY_FRAME ||
2544
0
      ((sf->inter_sf.extra_prune_warped && cpi->refresh_frame.golden_frame)))
2545
0
    copy_frame_prob_info(cpi);
2546
2547
#if CONFIG_COLLECT_COMPONENT_TIMING
2548
  printf("\n Encoding a frame: \n");
2549
#endif
2550
2551
#if CONFIG_TUNE_BUTTERAUGLI
2552
  if (cpi->oxcf.tune_cfg.tuning == AOM_TUNE_BUTTERAUGLI) {
2553
    av1_setup_butteraugli_rdmult(cpi);
2554
  }
2555
#endif
2556
2557
0
  cpi->source = av1_realloc_and_scale_if_required(
2558
0
      cm, unscaled, &cpi->scaled_source, filter_scaler, phase_scaler, true,
2559
0
      false, cpi->oxcf.border_in_pixels, cpi->alloc_pyramid);
2560
0
  if (frame_is_intra_only(cm) || resize_pending != 0) {
2561
0
    const int current_size =
2562
0
        (cm->mi_params.mi_rows * cm->mi_params.mi_cols) >> 2;
2563
0
    if (cpi->consec_zero_mv &&
2564
0
        (cpi->consec_zero_mv_alloc_size < current_size)) {
2565
0
      aom_free(cpi->consec_zero_mv);
2566
0
      cpi->consec_zero_mv_alloc_size = 0;
2567
0
      CHECK_MEM_ERROR(cm, cpi->consec_zero_mv,
2568
0
                      aom_malloc(current_size * sizeof(*cpi->consec_zero_mv)));
2569
0
      cpi->consec_zero_mv_alloc_size = current_size;
2570
0
    }
2571
0
    assert(cpi->consec_zero_mv != NULL);
2572
0
    memset(cpi->consec_zero_mv, 0, current_size * sizeof(*cpi->consec_zero_mv));
2573
0
  }
2574
2575
0
  if (cpi->scaled_last_source_available) {
2576
0
    cpi->last_source = &cpi->scaled_last_source;
2577
0
    cpi->scaled_last_source_available = 0;
2578
0
  } else if (cpi->unscaled_last_source != NULL) {
2579
0
    cpi->last_source = av1_realloc_and_scale_if_required(
2580
0
        cm, cpi->unscaled_last_source, &cpi->scaled_last_source, filter_scaler,
2581
0
        phase_scaler, true, false, cpi->oxcf.border_in_pixels,
2582
0
        cpi->alloc_pyramid);
2583
0
  }
2584
2585
0
  if (cpi->sf.rt_sf.use_temporal_noise_estimate) {
2586
0
    av1_update_noise_estimate(cpi);
2587
0
  }
2588
2589
#if CONFIG_AV1_TEMPORAL_DENOISING
2590
  if (cpi->oxcf.noise_sensitivity > 0 && cpi->ppi->use_svc)
2591
    av1_denoiser_reset_on_first_frame(cpi);
2592
#endif
2593
2594
  // For 1 spatial layer encoding: if the (non-LAST) reference has different
2595
  // resolution from the source then disable that reference. This is to avoid
2596
  // significant increase in encode time from scaling the references in
2597
  // av1_scale_references. Note GOLDEN is forced to update on the (first/tigger)
2598
  // resized frame and ALTREF will be refreshed ~4 frames later, so both
2599
  // references become available again after few frames.
2600
  // For superres: don't disable golden reference.
2601
0
  if (svc->number_spatial_layers == 1) {
2602
0
    if (!cpi->oxcf.superres_cfg.enable_superres) {
2603
0
      if (cpi->ref_frame_flags & av1_ref_frame_flag_list[GOLDEN_FRAME]) {
2604
0
        const YV12_BUFFER_CONFIG *const ref =
2605
0
            get_ref_frame_yv12_buf(cm, GOLDEN_FRAME);
2606
0
        if (ref == NULL || ref->y_crop_width != cm->width ||
2607
0
            ref->y_crop_height != cm->height) {
2608
0
          cpi->ref_frame_flags ^= AOM_GOLD_FLAG;
2609
0
        }
2610
0
      }
2611
0
    }
2612
0
    if (cpi->ref_frame_flags & av1_ref_frame_flag_list[ALTREF_FRAME]) {
2613
0
      const YV12_BUFFER_CONFIG *const ref =
2614
0
          get_ref_frame_yv12_buf(cm, ALTREF_FRAME);
2615
0
      if (ref == NULL || ref->y_crop_width != cm->width ||
2616
0
          ref->y_crop_height != cm->height) {
2617
0
        cpi->ref_frame_flags ^= AOM_ALT_FLAG;
2618
0
      }
2619
0
    }
2620
0
  }
2621
2622
0
  int scale_references = 0;
2623
#if CONFIG_FPMT_TEST
2624
  scale_references =
2625
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE ? 1 : 0;
2626
#endif  // CONFIG_FPMT_TEST
2627
0
  if (scale_references ||
2628
0
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] == 0) {
2629
0
    if (!frame_is_intra_only(cm)) {
2630
0
      av1_scale_references(cpi, filter_scaler, phase_scaler, 1);
2631
0
    }
2632
0
  }
2633
2634
0
  av1_set_quantizer(cm, q_cfg->qm_minlevel, q_cfg->qm_maxlevel, q,
2635
0
                    q_cfg->enable_chroma_deltaq, q_cfg->enable_hdr_deltaq,
2636
0
                    cpi->oxcf.mode == ALLINTRA, cpi->oxcf.tune_cfg.tuning);
2637
0
  av1_set_speed_features_qindex_dependent(cpi, cpi->oxcf.speed);
2638
0
  av1_init_quantizer(&cpi->enc_quant_dequant_params, &cm->quant_params,
2639
0
                     cm->seq_params->bit_depth);
2640
0
  av1_set_variance_partition_thresholds(cpi, q, 0);
2641
0
  av1_setup_frame(cpi);
2642
2643
  // Check if this high_source_sad (scene/slide change) frame should be
2644
  // encoded at high/max QP, and if so, set the q and adjust some rate
2645
  // control parameters.
2646
0
  if (cpi->sf.rt_sf.overshoot_detection_cbr == FAST_DETECTION_MAXQ &&
2647
0
      cpi->rc.high_source_sad) {
2648
0
    if (av1_encodedframe_overshoot_cbr(cpi, &q)) {
2649
0
      av1_set_quantizer(cm, q_cfg->qm_minlevel, q_cfg->qm_maxlevel, q,
2650
0
                        q_cfg->enable_chroma_deltaq, q_cfg->enable_hdr_deltaq,
2651
0
                        cpi->oxcf.mode == ALLINTRA, cpi->oxcf.tune_cfg.tuning);
2652
0
      av1_set_speed_features_qindex_dependent(cpi, cpi->oxcf.speed);
2653
0
      av1_init_quantizer(&cpi->enc_quant_dequant_params, &cm->quant_params,
2654
0
                         cm->seq_params->bit_depth);
2655
0
      av1_set_variance_partition_thresholds(cpi, q, 0);
2656
0
      if (frame_is_intra_only(cm) || cm->features.error_resilient_mode ||
2657
0
          cm->features.primary_ref_frame == PRIMARY_REF_NONE)
2658
0
        av1_setup_frame(cpi);
2659
0
    }
2660
0
  }
2661
0
  av1_apply_active_map(cpi);
2662
0
  if (q_cfg->aq_mode == CYCLIC_REFRESH_AQ) av1_cyclic_refresh_setup(cpi);
2663
0
  if (cm->seg.enabled) {
2664
0
    if (!cm->seg.update_data && cm->prev_frame) {
2665
0
      segfeatures_copy(&cm->seg, &cm->prev_frame->seg);
2666
0
      cm->seg.enabled = cm->prev_frame->seg.enabled;
2667
0
    } else {
2668
0
      av1_calculate_segdata(&cm->seg);
2669
0
    }
2670
0
  } else {
2671
0
    memset(&cm->seg, 0, sizeof(cm->seg));
2672
0
  }
2673
0
  segfeatures_copy(&cm->cur_frame->seg, &cm->seg);
2674
0
  cm->cur_frame->seg.enabled = cm->seg.enabled;
2675
2676
  // This is for rtc temporal filtering case.
2677
0
  if (is_psnr_calc_enabled(cpi) && cpi->sf.rt_sf.use_rtc_tf) {
2678
0
    const SequenceHeader *seq_params = cm->seq_params;
2679
2680
0
    if (cpi->orig_source.buffer_alloc_sz == 0 ||
2681
0
        cpi->rc.prev_coded_width != cpi->oxcf.frm_dim_cfg.width ||
2682
0
        cpi->rc.prev_coded_height != cpi->oxcf.frm_dim_cfg.height) {
2683
      // Allocate a source buffer to store the true source for psnr calculation.
2684
0
      if (aom_alloc_frame_buffer(
2685
0
              &cpi->orig_source, cpi->oxcf.frm_dim_cfg.width,
2686
0
              cpi->oxcf.frm_dim_cfg.height, seq_params->subsampling_x,
2687
0
              seq_params->subsampling_y, seq_params->use_highbitdepth,
2688
0
              cpi->oxcf.border_in_pixels, cm->features.byte_alignment, false,
2689
0
              0))
2690
0
        aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
2691
0
                           "Failed to allocate scaled buffer");
2692
0
    }
2693
2694
0
    aom_yv12_copy_y(cpi->source, &cpi->orig_source, 1);
2695
0
    aom_yv12_copy_u(cpi->source, &cpi->orig_source, 1);
2696
0
    aom_yv12_copy_v(cpi->source, &cpi->orig_source, 1);
2697
0
  }
2698
2699
#if CONFIG_COLLECT_COMPONENT_TIMING
2700
  start_timing(cpi, av1_encode_frame_time);
2701
#endif
2702
2703
  // Set the motion vector precision based on mv stats from the last coded
2704
  // frame.
2705
0
  if (!frame_is_intra_only(cm)) av1_pick_and_set_high_precision_mv(cpi, q);
2706
2707
  // transform / motion compensation build reconstruction frame
2708
0
  av1_encode_frame(cpi);
2709
2710
0
  if (!cpi->rc.rtc_external_ratectrl && !frame_is_intra_only(cm))
2711
0
    update_motion_stat(cpi);
2712
2713
  // Adjust the refresh of the golden (longer-term) reference based on QP
2714
  // selected for this frame. This is for CBR real-time mode, and only
2715
  // for single layer without usage of the set_ref_frame_config (so
2716
  // reference structure for 1 layer is set internally).
2717
0
  if (!frame_is_intra_only(cm) && cpi->oxcf.rc_cfg.mode == AOM_CBR &&
2718
0
      cpi->oxcf.mode == REALTIME && svc->number_spatial_layers == 1 &&
2719
0
      svc->number_temporal_layers == 1 && !cpi->rc.rtc_external_ratectrl &&
2720
0
      !cpi->ppi->rtc_ref.set_ref_frame_config &&
2721
0
      sf->rt_sf.gf_refresh_based_on_qp)
2722
0
    av1_adjust_gf_refresh_qp_one_pass_rt(cpi);
2723
2724
  // For non-svc: if scaling is required, copy scaled_source
2725
  // into scaled_last_source.
2726
0
  if (cm->current_frame.frame_number > 1 && !cpi->ppi->use_svc &&
2727
0
      cpi->scaled_source.y_buffer != NULL &&
2728
0
      cpi->scaled_last_source.y_buffer != NULL &&
2729
0
      cpi->scaled_source.y_crop_width == cpi->scaled_last_source.y_crop_width &&
2730
0
      cpi->scaled_source.y_crop_height ==
2731
0
          cpi->scaled_last_source.y_crop_height &&
2732
0
      (cm->width != cpi->unscaled_source->y_crop_width ||
2733
0
       cm->height != cpi->unscaled_source->y_crop_height)) {
2734
0
    cpi->scaled_last_source_available = 1;
2735
0
    aom_yv12_copy_y(&cpi->scaled_source, &cpi->scaled_last_source, 1);
2736
0
    aom_yv12_copy_u(&cpi->scaled_source, &cpi->scaled_last_source, 1);
2737
0
    aom_yv12_copy_v(&cpi->scaled_source, &cpi->scaled_last_source, 1);
2738
0
  }
2739
2740
#if CONFIG_COLLECT_COMPONENT_TIMING
2741
  end_timing(cpi, av1_encode_frame_time);
2742
#endif
2743
#if CONFIG_INTERNAL_STATS
2744
  ++cpi->frame_recode_hits;
2745
#endif
2746
2747
0
  return AOM_CODEC_OK;
2748
0
}
2749
2750
#if !CONFIG_REALTIME_ONLY
2751
2752
/*!\brief Recode loop for encoding one frame. the purpose of encoding one frame
2753
 * for multiple times can be approaching a target bitrate or adjusting the usage
2754
 * of global motions.
2755
 *
2756
 * \ingroup high_level_algo
2757
 *
2758
 * \param[in]    cpi             Top-level encoder structure
2759
 * \param[in]    size            Bitstream size
2760
 * \param[out]   dest            Bitstream output buffer
2761
 * \param[in]    dest_size       Bitstream output buffer size
2762
 *
2763
 * \return Returns a value to indicate if the encoding is done successfully.
2764
 * \retval #AOM_CODEC_OK
2765
 * \retval -1
2766
 * \retval #AOM_CODEC_ERROR
2767
 */
2768
static int encode_with_recode_loop(AV1_COMP *cpi, size_t *size, uint8_t *dest,
2769
0
                                   size_t dest_size) {
2770
0
  AV1_COMMON *const cm = &cpi->common;
2771
0
  RATE_CONTROL *const rc = &cpi->rc;
2772
0
  GlobalMotionInfo *const gm_info = &cpi->gm_info;
2773
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2774
0
  const QuantizationCfg *const q_cfg = &oxcf->q_cfg;
2775
0
  const int allow_recode = (cpi->sf.hl_sf.recode_loop != DISALLOW_RECODE);
2776
  // Must allow recode if minimum compression ratio is set.
2777
0
  assert(IMPLIES(oxcf->rc_cfg.min_cr > 0, allow_recode));
2778
2779
0
  set_size_independent_vars(cpi);
2780
0
  if (is_stat_consumption_stage_twopass(cpi) &&
2781
0
      cpi->sf.interp_sf.adaptive_interp_filter_search)
2782
0
    cpi->interp_search_flags.interp_filter_search_mask =
2783
0
        av1_setup_interp_filter_search_mask(cpi);
2784
2785
0
  av1_setup_frame_size(cpi);
2786
2787
0
  if (av1_superres_in_recode_allowed(cpi) &&
2788
0
      cpi->superres_mode != AOM_SUPERRES_NONE &&
2789
0
      cm->superres_scale_denominator == SCALE_NUMERATOR) {
2790
    // Superres mode is currently enabled, but the denominator selected will
2791
    // disable superres. So no need to continue, as we will go through another
2792
    // recode loop for full-resolution after this anyway.
2793
0
    return -1;
2794
0
  }
2795
2796
0
  int top_index = 0, bottom_index = 0;
2797
0
  int q = 0, q_low = 0, q_high = 0;
2798
0
  av1_set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
2799
0
  q_low = bottom_index;
2800
0
  q_high = top_index;
2801
2802
0
  av1_set_mv_search_params(cpi);
2803
2804
0
  allocate_gradient_info_for_hog(cpi);
2805
2806
0
  allocate_src_var_of_4x4_sub_block_buf(cpi);
2807
2808
0
  if (cpi->sf.part_sf.partition_search_type == VAR_BASED_PARTITION)
2809
0
    variance_partition_alloc(cpi);
2810
2811
0
  if (cm->current_frame.frame_type == KEY_FRAME) copy_frame_prob_info(cpi);
2812
2813
#if CONFIG_COLLECT_COMPONENT_TIMING
2814
  printf("\n Encoding a frame: \n");
2815
#endif
2816
2817
0
#if !CONFIG_RD_COMMAND
2818
  // Determine whether to use screen content tools using two fast encoding.
2819
0
  if (!cpi->sf.hl_sf.disable_extra_sc_testing && !cpi->use_ducky_encode)
2820
0
    av1_determine_sc_tools_with_encoding(cpi, q);
2821
0
#endif  // !CONFIG_RD_COMMAND
2822
2823
#if CONFIG_TUNE_VMAF
2824
  if (oxcf->tune_cfg.tuning == AOM_TUNE_VMAF_NEG_MAX_GAIN) {
2825
    av1_vmaf_neg_preprocessing(cpi, cpi->unscaled_source);
2826
  }
2827
#endif
2828
2829
#if CONFIG_TUNE_BUTTERAUGLI
2830
  cpi->butteraugli_info.recon_set = false;
2831
  int original_q = 0;
2832
#endif
2833
2834
0
  cpi->num_frame_recode = 0;
2835
2836
  // Loop variables
2837
0
  int loop = 0;
2838
0
  int loop_count = 0;
2839
0
  int overshoot_seen = 0;
2840
0
  int undershoot_seen = 0;
2841
0
  int low_cr_seen = 0;
2842
0
  int last_loop_allow_hp = 0;
2843
2844
0
  do {
2845
0
    loop = 0;
2846
0
    int do_mv_stats_collection = 1;
2847
2848
    // if frame was scaled calculate global_motion_search again if already
2849
    // done
2850
0
    if (loop_count > 0 && cpi->source && gm_info->search_done) {
2851
0
      if (cpi->source->y_crop_width != cm->width ||
2852
0
          cpi->source->y_crop_height != cm->height) {
2853
0
        gm_info->search_done = 0;
2854
0
      }
2855
0
    }
2856
0
    cpi->source = av1_realloc_and_scale_if_required(
2857
0
        cm, cpi->unscaled_source, &cpi->scaled_source, EIGHTTAP_REGULAR, 0,
2858
0
        false, false, cpi->oxcf.border_in_pixels, cpi->alloc_pyramid);
2859
2860
#if CONFIG_TUNE_BUTTERAUGLI
2861
    if (oxcf->tune_cfg.tuning == AOM_TUNE_BUTTERAUGLI) {
2862
      if (loop_count == 0) {
2863
        original_q = q;
2864
        // TODO(sdeng): different q here does not make big difference. Use a
2865
        // faster pass instead.
2866
        q = 96;
2867
        av1_setup_butteraugli_source(cpi);
2868
      } else {
2869
        q = original_q;
2870
      }
2871
    }
2872
#endif
2873
2874
0
    if (cpi->unscaled_last_source != NULL) {
2875
0
      cpi->last_source = av1_realloc_and_scale_if_required(
2876
0
          cm, cpi->unscaled_last_source, &cpi->scaled_last_source,
2877
0
          EIGHTTAP_REGULAR, 0, false, false, cpi->oxcf.border_in_pixels,
2878
0
          cpi->alloc_pyramid);
2879
0
    }
2880
2881
0
    int scale_references = 0;
2882
#if CONFIG_FPMT_TEST
2883
    scale_references =
2884
        cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE ? 1 : 0;
2885
#endif  // CONFIG_FPMT_TEST
2886
0
    if (scale_references ||
2887
0
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] == 0) {
2888
0
      if (!frame_is_intra_only(cm)) {
2889
0
        if (loop_count > 0) {
2890
0
          release_scaled_references(cpi);
2891
0
        }
2892
0
        av1_scale_references(cpi, EIGHTTAP_REGULAR, 0, 0);
2893
0
      }
2894
0
    }
2895
2896
#if CONFIG_TUNE_VMAF
2897
    if (oxcf->tune_cfg.tuning >= AOM_TUNE_VMAF_WITH_PREPROCESSING &&
2898
        oxcf->tune_cfg.tuning <= AOM_TUNE_VMAF_NEG_MAX_GAIN) {
2899
      cpi->vmaf_info.original_qindex = q;
2900
      q = av1_get_vmaf_base_qindex(cpi, q);
2901
    }
2902
#endif
2903
2904
#if CONFIG_RD_COMMAND
2905
    RD_COMMAND *rd_command = &cpi->rd_command;
2906
    RD_OPTION option = rd_command->option_ls[rd_command->frame_index];
2907
    if (option == RD_OPTION_SET_Q || option == RD_OPTION_SET_Q_RDMULT) {
2908
      q = rd_command->q_index_ls[rd_command->frame_index];
2909
    }
2910
#endif  // CONFIG_RD_COMMAND
2911
2912
#if CONFIG_BITRATE_ACCURACY
2913
#if CONFIG_THREE_PASS
2914
    if (oxcf->pass == AOM_RC_THIRD_PASS && cpi->vbr_rc_info.ready == 1) {
2915
      int frame_coding_idx =
2916
          av1_vbr_rc_frame_coding_idx(&cpi->vbr_rc_info, cpi->gf_frame_index);
2917
      if (frame_coding_idx < cpi->vbr_rc_info.total_frame_count) {
2918
        q = cpi->vbr_rc_info.q_index_list[frame_coding_idx];
2919
      } else {
2920
        // TODO(angiebird): Investigate why sometimes there is an extra frame
2921
        // after the last GOP.
2922
        q = cpi->vbr_rc_info.base_q_index;
2923
      }
2924
    }
2925
#else
2926
    if (cpi->vbr_rc_info.q_index_list_ready) {
2927
      q = cpi->vbr_rc_info.q_index_list[cpi->gf_frame_index];
2928
    }
2929
#endif  // CONFIG_THREE_PASS
2930
#endif  // CONFIG_BITRATE_ACCURACY
2931
2932
#if CONFIG_RATECTRL_LOG && CONFIG_THREE_PASS && CONFIG_BITRATE_ACCURACY
2933
    // TODO(angiebird): Move this into a function.
2934
    if (oxcf->pass == AOM_RC_THIRD_PASS) {
2935
      int frame_coding_idx =
2936
          av1_vbr_rc_frame_coding_idx(&cpi->vbr_rc_info, cpi->gf_frame_index);
2937
      double qstep_ratio = cpi->vbr_rc_info.qstep_ratio_list[frame_coding_idx];
2938
      FRAME_UPDATE_TYPE update_type =
2939
          cpi->vbr_rc_info.update_type_list[frame_coding_idx];
2940
      rc_log_frame_encode_param(&cpi->rc_log, frame_coding_idx, qstep_ratio, q,
2941
                                update_type);
2942
    }
2943
#endif  // CONFIG_RATECTRL_LOG && CONFIG_THREE_PASS && CONFIG_BITRATE_ACCURACY
2944
2945
0
    if (cpi->use_ducky_encode) {
2946
0
      const DuckyEncodeFrameInfo *frame_info =
2947
0
          &cpi->ducky_encode_info.frame_info;
2948
0
      if (frame_info->qp_mode == DUCKY_ENCODE_FRAME_MODE_QINDEX) {
2949
0
        q = frame_info->q_index;
2950
0
        cm->delta_q_info.delta_q_present_flag = frame_info->delta_q_enabled;
2951
0
      }
2952
0
    }
2953
2954
0
    av1_set_quantizer(cm, q_cfg->qm_minlevel, q_cfg->qm_maxlevel, q,
2955
0
                      q_cfg->enable_chroma_deltaq, q_cfg->enable_hdr_deltaq,
2956
0
                      oxcf->mode == ALLINTRA, oxcf->tune_cfg.tuning);
2957
0
    av1_set_speed_features_qindex_dependent(cpi, oxcf->speed);
2958
0
    av1_init_quantizer(&cpi->enc_quant_dequant_params, &cm->quant_params,
2959
0
                       cm->seq_params->bit_depth);
2960
2961
0
    av1_set_variance_partition_thresholds(cpi, q, 0);
2962
2963
    // printf("Frame %d/%d: q = %d, frame_type = %d superres_denom = %d\n",
2964
    //        cm->current_frame.frame_number, cm->show_frame, q,
2965
    //        cm->current_frame.frame_type, cm->superres_scale_denominator);
2966
2967
0
    if (loop_count == 0) {
2968
0
      av1_setup_frame(cpi);
2969
0
    } else if (get_primary_ref_frame_buf(cm) == NULL) {
2970
      // Base q-index may have changed, so we need to assign proper default coef
2971
      // probs before every iteration.
2972
0
      av1_default_coef_probs(cm);
2973
0
      av1_setup_frame_contexts(cm);
2974
0
    }
2975
2976
0
    if (q_cfg->aq_mode == VARIANCE_AQ) {
2977
0
      av1_vaq_frame_setup(cpi);
2978
0
    } else if (q_cfg->aq_mode == COMPLEXITY_AQ) {
2979
0
      av1_setup_in_frame_q_adj(cpi);
2980
0
    }
2981
2982
0
    if (cm->seg.enabled) {
2983
0
      if (!cm->seg.update_data && cm->prev_frame) {
2984
0
        segfeatures_copy(&cm->seg, &cm->prev_frame->seg);
2985
0
        cm->seg.enabled = cm->prev_frame->seg.enabled;
2986
0
      } else {
2987
0
        av1_calculate_segdata(&cm->seg);
2988
0
      }
2989
0
    } else {
2990
0
      memset(&cm->seg, 0, sizeof(cm->seg));
2991
0
    }
2992
0
    segfeatures_copy(&cm->cur_frame->seg, &cm->seg);
2993
0
    cm->cur_frame->seg.enabled = cm->seg.enabled;
2994
2995
#if CONFIG_COLLECT_COMPONENT_TIMING
2996
    start_timing(cpi, av1_encode_frame_time);
2997
#endif
2998
    // Set the motion vector precision based on mv stats from the last coded
2999
    // frame.
3000
0
    if (!frame_is_intra_only(cm)) {
3001
0
      av1_pick_and_set_high_precision_mv(cpi, q);
3002
3003
      // If the precision has changed during different iteration of the loop,
3004
      // then we need to reset the global motion vectors
3005
0
      if (loop_count > 0 &&
3006
0
          cm->features.allow_high_precision_mv != last_loop_allow_hp) {
3007
0
        gm_info->search_done = 0;
3008
0
      }
3009
0
      last_loop_allow_hp = cm->features.allow_high_precision_mv;
3010
0
    }
3011
3012
    // transform / motion compensation build reconstruction frame
3013
0
    av1_encode_frame(cpi);
3014
3015
    // Disable mv_stats collection for parallel frames based on update flag.
3016
0
    if (!cpi->do_frame_data_update) do_mv_stats_collection = 0;
3017
3018
    // Reset the mv_stats in case we are interrupted by an intraframe or an
3019
    // overlay frame.
3020
0
    if (cpi->mv_stats.valid && do_mv_stats_collection) av1_zero(cpi->mv_stats);
3021
3022
    // Gather the mv_stats for the next frame
3023
0
    if (cpi->sf.hl_sf.high_precision_mv_usage == LAST_MV_DATA &&
3024
0
        av1_frame_allows_smart_mv(cpi) && do_mv_stats_collection) {
3025
0
      av1_collect_mv_stats(cpi, q);
3026
0
    }
3027
3028
#if CONFIG_COLLECT_COMPONENT_TIMING
3029
    end_timing(cpi, av1_encode_frame_time);
3030
#endif
3031
3032
#if CONFIG_BITRATE_ACCURACY || CONFIG_RD_COMMAND
3033
    const int do_dummy_pack = 1;
3034
#else   // CONFIG_BITRATE_ACCURACY
3035
    // Dummy pack of the bitstream using up to date stats to get an
3036
    // accurate estimate of output frame size to determine if we need
3037
    // to recode.
3038
0
    const int do_dummy_pack =
3039
0
        (cpi->sf.hl_sf.recode_loop >= ALLOW_RECODE_KFARFGF &&
3040
0
         oxcf->rc_cfg.mode != AOM_Q) ||
3041
0
        oxcf->rc_cfg.min_cr > 0;
3042
0
#endif  // CONFIG_BITRATE_ACCURACY
3043
0
    if (do_dummy_pack) {
3044
0
      av1_finalize_encoded_frame(cpi);
3045
0
      int largest_tile_id = 0;  // Output from bitstream: unused here
3046
0
      rc->coefficient_size = 0;
3047
0
      if (av1_pack_bitstream(cpi, dest, dest_size, size, &largest_tile_id) !=
3048
0
          AOM_CODEC_OK) {
3049
0
        return AOM_CODEC_ERROR;
3050
0
      }
3051
3052
      // bits used for this frame
3053
0
      rc->projected_frame_size = (int)(*size) << 3;
3054
#if CONFIG_RD_COMMAND
3055
      PSNR_STATS psnr;
3056
      aom_calc_psnr(cpi->source, &cpi->common.cur_frame->buf, &psnr);
3057
      printf("q %d rdmult %d rate %d dist %" PRIu64 "\n", q, cpi->rd.RDMULT,
3058
             rc->projected_frame_size, psnr.sse[0]);
3059
      ++rd_command->frame_index;
3060
      if (rd_command->frame_index == rd_command->frame_count) {
3061
        return AOM_CODEC_ERROR;
3062
      }
3063
#endif  // CONFIG_RD_COMMAND
3064
3065
#if CONFIG_RATECTRL_LOG && CONFIG_THREE_PASS && CONFIG_BITRATE_ACCURACY
3066
      if (oxcf->pass == AOM_RC_THIRD_PASS) {
3067
        int frame_coding_idx =
3068
            av1_vbr_rc_frame_coding_idx(&cpi->vbr_rc_info, cpi->gf_frame_index);
3069
        rc_log_frame_entropy(&cpi->rc_log, frame_coding_idx,
3070
                             rc->projected_frame_size, rc->coefficient_size);
3071
      }
3072
#endif  // CONFIG_RATECTRL_LOG && CONFIG_THREE_PASS && CONFIG_BITRATE_ACCURACY
3073
0
    }
3074
3075
#if CONFIG_TUNE_VMAF
3076
    if (oxcf->tune_cfg.tuning >= AOM_TUNE_VMAF_WITH_PREPROCESSING &&
3077
        oxcf->tune_cfg.tuning <= AOM_TUNE_VMAF_NEG_MAX_GAIN) {
3078
      q = cpi->vmaf_info.original_qindex;
3079
    }
3080
#endif
3081
0
    if (allow_recode) {
3082
      // Update q and decide whether to do a recode loop
3083
0
      recode_loop_update_q(cpi, &loop, &q, &q_low, &q_high, top_index,
3084
0
                           bottom_index, &undershoot_seen, &overshoot_seen,
3085
0
                           &low_cr_seen, loop_count);
3086
0
    }
3087
3088
#if CONFIG_TUNE_BUTTERAUGLI
3089
    if (loop_count == 0 && oxcf->tune_cfg.tuning == AOM_TUNE_BUTTERAUGLI) {
3090
      loop = 1;
3091
      av1_setup_butteraugli_rdmult_and_restore_source(cpi, 0.4);
3092
    }
3093
#endif
3094
3095
0
    if (cpi->use_ducky_encode) {
3096
      // Ducky encode currently does not support recode loop.
3097
0
      loop = 0;
3098
0
    }
3099
#if CONFIG_BITRATE_ACCURACY || CONFIG_RD_COMMAND
3100
    loop = 0;  // turn off recode loop when CONFIG_BITRATE_ACCURACY is on
3101
#endif         // CONFIG_BITRATE_ACCURACY || CONFIG_RD_COMMAND
3102
3103
0
    if (loop) {
3104
0
      ++loop_count;
3105
0
      cpi->num_frame_recode =
3106
0
          (cpi->num_frame_recode < (NUM_RECODES_PER_FRAME - 1))
3107
0
              ? (cpi->num_frame_recode + 1)
3108
0
              : (NUM_RECODES_PER_FRAME - 1);
3109
#if CONFIG_INTERNAL_STATS
3110
      ++cpi->frame_recode_hits;
3111
#endif
3112
0
    }
3113
#if CONFIG_COLLECT_COMPONENT_TIMING
3114
    if (loop) printf("\n Recoding:");
3115
#endif
3116
0
  } while (loop);
3117
3118
0
  return AOM_CODEC_OK;
3119
0
}
3120
#endif  // !CONFIG_REALTIME_ONLY
3121
3122
// TODO(jingning, paulwilkins): Set up high grain level to test
3123
// hardware decoders. Need to adapt the actual noise variance
3124
// according to the difference between reconstructed frame and the
3125
// source signal.
3126
0
static void set_grain_syn_params(AV1_COMMON *cm) {
3127
0
  aom_film_grain_t *film_grain_params = &cm->film_grain_params;
3128
0
  film_grain_params->apply_grain = 1;
3129
0
  film_grain_params->update_parameters = 1;
3130
0
  film_grain_params->random_seed = rand() & 0xffff;
3131
3132
0
  film_grain_params->num_y_points = 1;
3133
0
  film_grain_params->scaling_points_y[0][0] = 128;
3134
0
  film_grain_params->scaling_points_y[0][1] = 100;
3135
3136
0
  if (!cm->seq_params->monochrome) {
3137
0
    film_grain_params->num_cb_points = 1;
3138
0
    film_grain_params->scaling_points_cb[0][0] = 128;
3139
0
    film_grain_params->scaling_points_cb[0][1] = 100;
3140
3141
0
    film_grain_params->num_cr_points = 1;
3142
0
    film_grain_params->scaling_points_cr[0][0] = 128;
3143
0
    film_grain_params->scaling_points_cr[0][1] = 100;
3144
0
  } else {
3145
0
    film_grain_params->num_cb_points = 0;
3146
0
    film_grain_params->num_cr_points = 0;
3147
0
  }
3148
3149
0
  film_grain_params->chroma_scaling_from_luma = 0;
3150
3151
0
  film_grain_params->scaling_shift = 1;
3152
0
  film_grain_params->ar_coeff_lag = 0;
3153
0
  film_grain_params->ar_coeff_shift = 1;
3154
0
  film_grain_params->overlap_flag = 1;
3155
0
  film_grain_params->grain_scale_shift = 0;
3156
0
}
3157
3158
/*!\brief Recode loop or a single loop for encoding one frame, followed by
3159
 * in-loop deblocking filters, CDEF filters, and restoration filters.
3160
 *
3161
 * \ingroup high_level_algo
3162
 * \callgraph
3163
 * \callergraph
3164
 *
3165
 * \param[in]    cpi             Top-level encoder structure
3166
 * \param[in]    size            Bitstream size
3167
 * \param[out]   dest            Bitstream output buffer
3168
 * \param[in]    dest_size       Bitstream output buffer size
3169
 * \param[in]    sse             Total distortion of the frame
3170
 * \param[in]    rate            Total rate of the frame
3171
 * \param[in]    largest_tile_id Tile id of the last tile
3172
 *
3173
 * \return Returns a value to indicate if the encoding is done successfully.
3174
 * \retval #AOM_CODEC_OK
3175
 * \retval #AOM_CODEC_ERROR
3176
 */
3177
static int encode_with_recode_loop_and_filter(AV1_COMP *cpi, size_t *size,
3178
                                              uint8_t *dest, size_t dest_size,
3179
                                              int64_t *sse, int64_t *rate,
3180
0
                                              int *largest_tile_id) {
3181
#if CONFIG_COLLECT_COMPONENT_TIMING
3182
  start_timing(cpi, encode_with_or_without_recode_time);
3183
#endif
3184
0
  for (int i = 0; i < NUM_RECODES_PER_FRAME; i++) {
3185
0
    cpi->do_update_frame_probs_txtype[i] = 0;
3186
0
    cpi->do_update_frame_probs_obmc[i] = 0;
3187
0
    cpi->do_update_frame_probs_warp[i] = 0;
3188
0
    cpi->do_update_frame_probs_interpfilter[i] = 0;
3189
0
  }
3190
3191
0
  cpi->do_update_vbr_bits_off_target_fast = 0;
3192
0
  int err;
3193
#if CONFIG_REALTIME_ONLY
3194
  err = encode_without_recode(cpi);
3195
#else
3196
0
  if (cpi->sf.hl_sf.recode_loop == DISALLOW_RECODE)
3197
0
    err = encode_without_recode(cpi);
3198
0
  else
3199
0
    err = encode_with_recode_loop(cpi, size, dest, dest_size);
3200
0
#endif
3201
#if CONFIG_COLLECT_COMPONENT_TIMING
3202
  end_timing(cpi, encode_with_or_without_recode_time);
3203
#endif
3204
0
  if (err != AOM_CODEC_OK) {
3205
0
    if (err == -1) {
3206
      // special case as described in encode_with_recode_loop().
3207
      // Encoding was skipped.
3208
0
      err = AOM_CODEC_OK;
3209
0
      if (sse != NULL) *sse = INT64_MAX;
3210
0
      if (rate != NULL) *rate = INT64_MAX;
3211
0
      *largest_tile_id = 0;
3212
0
    }
3213
0
    return err;
3214
0
  }
3215
3216
#ifdef OUTPUT_YUV_DENOISED
3217
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
3218
  if (oxcf->noise_sensitivity > 0 && denoise_svc(cpi)) {
3219
    aom_write_yuv_frame(yuv_denoised_file,
3220
                        &cpi->denoiser.running_avg_y[INTRA_FRAME]);
3221
  }
3222
#endif
3223
3224
0
  AV1_COMMON *const cm = &cpi->common;
3225
0
  SequenceHeader *const seq_params = cm->seq_params;
3226
3227
  // Special case code to reduce pulsing when key frames are forced at a
3228
  // fixed interval. Note the reconstruction error if it is the frame before
3229
  // the force key frame
3230
0
  if (cpi->ppi->p_rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
3231
0
#if CONFIG_AV1_HIGHBITDEPTH
3232
0
    if (seq_params->use_highbitdepth) {
3233
0
      cpi->ambient_err = aom_highbd_get_y_sse(cpi->source, &cm->cur_frame->buf);
3234
0
    } else {
3235
0
      cpi->ambient_err = aom_get_y_sse(cpi->source, &cm->cur_frame->buf);
3236
0
    }
3237
#else
3238
    cpi->ambient_err = aom_get_y_sse(cpi->source, &cm->cur_frame->buf);
3239
#endif
3240
0
  }
3241
3242
0
  cm->cur_frame->buf.color_primaries = seq_params->color_primaries;
3243
0
  cm->cur_frame->buf.transfer_characteristics =
3244
0
      seq_params->transfer_characteristics;
3245
0
  cm->cur_frame->buf.matrix_coefficients = seq_params->matrix_coefficients;
3246
0
  cm->cur_frame->buf.monochrome = seq_params->monochrome;
3247
0
  cm->cur_frame->buf.chroma_sample_position =
3248
0
      seq_params->chroma_sample_position;
3249
0
  cm->cur_frame->buf.color_range = seq_params->color_range;
3250
0
  cm->cur_frame->buf.render_width = cm->render_width;
3251
0
  cm->cur_frame->buf.render_height = cm->render_height;
3252
3253
0
  if (!cpi->mt_info.pipeline_lpf_mt_with_enc)
3254
0
    set_postproc_filter_default_params(&cpi->common);
3255
3256
0
  if (!cm->features.allow_intrabc) {
3257
0
    loopfilter_frame(cpi, cm);
3258
0
  }
3259
3260
0
  if (cpi->oxcf.mode != ALLINTRA && !cpi->ppi->rtc_ref.non_reference_frame) {
3261
0
    extend_frame_borders(cpi);
3262
0
  }
3263
3264
#ifdef OUTPUT_YUV_REC
3265
  aom_write_one_yuv_frame(cm, &cm->cur_frame->buf);
3266
#endif
3267
3268
0
  if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_FILM) {
3269
0
    set_grain_syn_params(cm);
3270
0
  }
3271
3272
0
  av1_finalize_encoded_frame(cpi);
3273
  // Build the bitstream
3274
#if CONFIG_COLLECT_COMPONENT_TIMING
3275
  start_timing(cpi, av1_pack_bitstream_final_time);
3276
#endif
3277
0
  cpi->rc.coefficient_size = 0;
3278
0
  if (av1_pack_bitstream(cpi, dest, dest_size, size, largest_tile_id) !=
3279
0
      AOM_CODEC_OK)
3280
0
    return AOM_CODEC_ERROR;
3281
#if CONFIG_COLLECT_COMPONENT_TIMING
3282
  end_timing(cpi, av1_pack_bitstream_final_time);
3283
#endif
3284
3285
0
  if (cpi->rc.postencode_drop && allow_postencode_drop_rtc(cpi) &&
3286
0
      av1_postencode_drop_cbr(cpi, size)) {
3287
0
    return AOM_CODEC_OK;
3288
0
  }
3289
3290
  // Compute sse and rate.
3291
0
  if (sse != NULL) {
3292
0
#if CONFIG_AV1_HIGHBITDEPTH
3293
0
    *sse = (seq_params->use_highbitdepth)
3294
0
               ? aom_highbd_get_y_sse(cpi->source, &cm->cur_frame->buf)
3295
0
               : aom_get_y_sse(cpi->source, &cm->cur_frame->buf);
3296
#else
3297
    *sse = aom_get_y_sse(cpi->source, &cm->cur_frame->buf);
3298
#endif
3299
0
  }
3300
0
  if (rate != NULL) {
3301
0
    const int64_t bits = (*size << 3);
3302
0
    *rate = (bits << 5);  // To match scale.
3303
0
  }
3304
3305
0
#if !CONFIG_REALTIME_ONLY
3306
0
  if (cpi->use_ducky_encode) {
3307
0
    PSNR_STATS psnr;
3308
0
    aom_calc_psnr(cpi->source, &cpi->common.cur_frame->buf, &psnr);
3309
0
    DuckyEncodeFrameResult *frame_result = &cpi->ducky_encode_info.frame_result;
3310
0
    frame_result->global_order_idx = cm->cur_frame->display_order_hint;
3311
0
    frame_result->q_index = cm->quant_params.base_qindex;
3312
0
    frame_result->rdmult = cpi->rd.RDMULT;
3313
0
    frame_result->rate = (int)(*size) * 8;
3314
0
    frame_result->dist = psnr.sse[0];
3315
0
    frame_result->psnr = psnr.psnr[0];
3316
0
  }
3317
0
#endif  // !CONFIG_REALTIME_ONLY
3318
3319
0
  return AOM_CODEC_OK;
3320
0
}
3321
3322
static int encode_with_and_without_superres(AV1_COMP *cpi, size_t *size,
3323
                                            uint8_t *dest, size_t dest_size,
3324
0
                                            int *largest_tile_id) {
3325
0
  const AV1_COMMON *const cm = &cpi->common;
3326
0
  assert(cm->seq_params->enable_superres);
3327
0
  assert(av1_superres_in_recode_allowed(cpi));
3328
0
  aom_codec_err_t err = AOM_CODEC_OK;
3329
0
  av1_save_all_coding_context(cpi);
3330
3331
0
  int64_t sse1 = INT64_MAX;
3332
0
  int64_t rate1 = INT64_MAX;
3333
0
  int largest_tile_id1 = 0;
3334
0
  int64_t sse2 = INT64_MAX;
3335
0
  int64_t rate2 = INT64_MAX;
3336
0
  int largest_tile_id2;
3337
0
  double proj_rdcost1 = DBL_MAX;
3338
0
  const GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3339
0
  const FRAME_UPDATE_TYPE update_type =
3340
0
      gf_group->update_type[cpi->gf_frame_index];
3341
0
  const aom_bit_depth_t bit_depth = cm->seq_params->bit_depth;
3342
3343
  // Encode with superres.
3344
0
  if (cpi->sf.hl_sf.superres_auto_search_type == SUPERRES_AUTO_ALL) {
3345
0
    SuperResCfg *const superres_cfg = &cpi->oxcf.superres_cfg;
3346
0
    int64_t superres_sses[SCALE_NUMERATOR];
3347
0
    int64_t superres_rates[SCALE_NUMERATOR];
3348
0
    int superres_largest_tile_ids[SCALE_NUMERATOR];
3349
    // Use superres for Key-frames and Alt-ref frames only.
3350
0
    if (update_type != OVERLAY_UPDATE && update_type != INTNL_OVERLAY_UPDATE) {
3351
0
      for (int denom = SCALE_NUMERATOR + 1; denom <= 2 * SCALE_NUMERATOR;
3352
0
           ++denom) {
3353
0
        superres_cfg->superres_scale_denominator = denom;
3354
0
        superres_cfg->superres_kf_scale_denominator = denom;
3355
0
        const int this_index = denom - (SCALE_NUMERATOR + 1);
3356
3357
0
        cpi->superres_mode = AOM_SUPERRES_AUTO;  // Super-res on for this loop.
3358
0
        err = encode_with_recode_loop_and_filter(
3359
0
            cpi, size, dest, dest_size, &superres_sses[this_index],
3360
0
            &superres_rates[this_index],
3361
0
            &superres_largest_tile_ids[this_index]);
3362
0
        cpi->superres_mode = AOM_SUPERRES_NONE;  // Reset to default (full-res).
3363
0
        if (err != AOM_CODEC_OK) return err;
3364
0
        restore_all_coding_context(cpi);
3365
0
      }
3366
      // Reset.
3367
0
      superres_cfg->superres_scale_denominator = SCALE_NUMERATOR;
3368
0
      superres_cfg->superres_kf_scale_denominator = SCALE_NUMERATOR;
3369
0
    } else {
3370
0
      for (int denom = SCALE_NUMERATOR + 1; denom <= 2 * SCALE_NUMERATOR;
3371
0
           ++denom) {
3372
0
        const int this_index = denom - (SCALE_NUMERATOR + 1);
3373
0
        superres_sses[this_index] = INT64_MAX;
3374
0
        superres_rates[this_index] = INT64_MAX;
3375
0
        superres_largest_tile_ids[this_index] = 0;
3376
0
      }
3377
0
    }
3378
    // Encode without superres.
3379
0
    assert(cpi->superres_mode == AOM_SUPERRES_NONE);
3380
0
    err = encode_with_recode_loop_and_filter(cpi, size, dest, dest_size, &sse2,
3381
0
                                             &rate2, &largest_tile_id2);
3382
0
    if (err != AOM_CODEC_OK) return err;
3383
3384
    // Note: Both use common rdmult based on base qindex of fullres.
3385
0
    const int64_t rdmult = av1_compute_rd_mult_based_on_qindex(
3386
0
        bit_depth, update_type, cm->quant_params.base_qindex,
3387
0
        cpi->oxcf.tune_cfg.tuning);
3388
3389
    // Find the best rdcost among all superres denoms.
3390
0
    int best_denom = -1;
3391
0
    for (int denom = SCALE_NUMERATOR + 1; denom <= 2 * SCALE_NUMERATOR;
3392
0
         ++denom) {
3393
0
      const int this_index = denom - (SCALE_NUMERATOR + 1);
3394
0
      const int64_t this_sse = superres_sses[this_index];
3395
0
      const int64_t this_rate = superres_rates[this_index];
3396
0
      const int this_largest_tile_id = superres_largest_tile_ids[this_index];
3397
0
      const double this_rdcost = RDCOST_DBL_WITH_NATIVE_BD_DIST(
3398
0
          rdmult, this_rate, this_sse, bit_depth);
3399
0
      if (this_rdcost < proj_rdcost1) {
3400
0
        sse1 = this_sse;
3401
0
        rate1 = this_rate;
3402
0
        largest_tile_id1 = this_largest_tile_id;
3403
0
        proj_rdcost1 = this_rdcost;
3404
0
        best_denom = denom;
3405
0
      }
3406
0
    }
3407
0
    const double proj_rdcost2 =
3408
0
        RDCOST_DBL_WITH_NATIVE_BD_DIST(rdmult, rate2, sse2, bit_depth);
3409
    // Re-encode with superres if it's better.
3410
0
    if (proj_rdcost1 < proj_rdcost2) {
3411
0
      restore_all_coding_context(cpi);
3412
      // TODO(urvang): We should avoid rerunning the recode loop by saving
3413
      // previous output+state, or running encode only for the selected 'q' in
3414
      // previous step.
3415
      // Again, temporarily force the best denom.
3416
0
      superres_cfg->superres_scale_denominator = best_denom;
3417
0
      superres_cfg->superres_kf_scale_denominator = best_denom;
3418
0
      int64_t sse3 = INT64_MAX;
3419
0
      int64_t rate3 = INT64_MAX;
3420
0
      cpi->superres_mode =
3421
0
          AOM_SUPERRES_AUTO;  // Super-res on for this recode loop.
3422
0
      err = encode_with_recode_loop_and_filter(cpi, size, dest, dest_size,
3423
0
                                               &sse3, &rate3, largest_tile_id);
3424
0
      cpi->superres_mode = AOM_SUPERRES_NONE;  // Reset to default (full-res).
3425
0
      assert(sse1 == sse3);
3426
0
      assert(rate1 == rate3);
3427
0
      assert(largest_tile_id1 == *largest_tile_id);
3428
      // Reset.
3429
0
      superres_cfg->superres_scale_denominator = SCALE_NUMERATOR;
3430
0
      superres_cfg->superres_kf_scale_denominator = SCALE_NUMERATOR;
3431
0
    } else {
3432
0
      *largest_tile_id = largest_tile_id2;
3433
0
    }
3434
0
  } else {
3435
0
    assert(cpi->sf.hl_sf.superres_auto_search_type == SUPERRES_AUTO_DUAL);
3436
0
    cpi->superres_mode =
3437
0
        AOM_SUPERRES_AUTO;  // Super-res on for this recode loop.
3438
0
    err = encode_with_recode_loop_and_filter(cpi, size, dest, dest_size, &sse1,
3439
0
                                             &rate1, &largest_tile_id1);
3440
0
    cpi->superres_mode = AOM_SUPERRES_NONE;  // Reset to default (full-res).
3441
0
    if (err != AOM_CODEC_OK) return err;
3442
0
    restore_all_coding_context(cpi);
3443
    // Encode without superres.
3444
0
    assert(cpi->superres_mode == AOM_SUPERRES_NONE);
3445
0
    err = encode_with_recode_loop_and_filter(cpi, size, dest, dest_size, &sse2,
3446
0
                                             &rate2, &largest_tile_id2);
3447
0
    if (err != AOM_CODEC_OK) return err;
3448
3449
    // Note: Both use common rdmult based on base qindex of fullres.
3450
0
    const int64_t rdmult = av1_compute_rd_mult_based_on_qindex(
3451
0
        bit_depth, update_type, cm->quant_params.base_qindex,
3452
0
        cpi->oxcf.tune_cfg.tuning);
3453
0
    proj_rdcost1 =
3454
0
        RDCOST_DBL_WITH_NATIVE_BD_DIST(rdmult, rate1, sse1, bit_depth);
3455
0
    const double proj_rdcost2 =
3456
0
        RDCOST_DBL_WITH_NATIVE_BD_DIST(rdmult, rate2, sse2, bit_depth);
3457
    // Re-encode with superres if it's better.
3458
0
    if (proj_rdcost1 < proj_rdcost2) {
3459
0
      restore_all_coding_context(cpi);
3460
      // TODO(urvang): We should avoid rerunning the recode loop by saving
3461
      // previous output+state, or running encode only for the selected 'q' in
3462
      // previous step.
3463
0
      int64_t sse3 = INT64_MAX;
3464
0
      int64_t rate3 = INT64_MAX;
3465
0
      cpi->superres_mode =
3466
0
          AOM_SUPERRES_AUTO;  // Super-res on for this recode loop.
3467
0
      err = encode_with_recode_loop_and_filter(cpi, size, dest, dest_size,
3468
0
                                               &sse3, &rate3, largest_tile_id);
3469
0
      cpi->superres_mode = AOM_SUPERRES_NONE;  // Reset to default (full-res).
3470
0
      assert(sse1 == sse3);
3471
0
      assert(rate1 == rate3);
3472
0
      assert(largest_tile_id1 == *largest_tile_id);
3473
0
    } else {
3474
0
      *largest_tile_id = largest_tile_id2;
3475
0
    }
3476
0
  }
3477
3478
0
  return err;
3479
0
}
3480
3481
// Conditions to disable cdf_update mode in selective mode for real-time.
3482
// Handle case for layers, scene change, and resizing.
3483
0
static inline int selective_disable_cdf_rtc(const AV1_COMP *cpi) {
3484
0
  const AV1_COMMON *const cm = &cpi->common;
3485
0
  const RATE_CONTROL *const rc = &cpi->rc;
3486
  // For single layer.
3487
0
  if (cpi->svc.number_spatial_layers == 1 &&
3488
0
      cpi->svc.number_temporal_layers == 1) {
3489
    // Don't disable on intra_only, scene change (high_source_sad = 1),
3490
    // or resized frame. To avoid quality loss force enable at
3491
    // for ~30 frames after key or scene/slide change, and
3492
    // after 8 frames since last update if frame_source_sad > 0.
3493
0
    if (frame_is_intra_only(cm) || is_frame_resize_pending(cpi) ||
3494
0
        rc->high_source_sad || rc->frames_since_key < 30 ||
3495
0
        (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
3496
0
         cpi->cyclic_refresh->counter_encode_maxq_scene_change < 30) ||
3497
0
        (cpi->frames_since_last_update > 8 && cpi->rc.frame_source_sad > 0))
3498
0
      return 0;
3499
0
    else
3500
0
      return 1;
3501
0
  } else if (cpi->svc.number_temporal_layers > 1) {
3502
    // Disable only on top temporal enhancement layer for now.
3503
0
    return cpi->svc.temporal_layer_id == cpi->svc.number_temporal_layers - 1;
3504
0
  }
3505
0
  return 1;
3506
0
}
3507
3508
#if !CONFIG_REALTIME_ONLY
3509
static void subtract_stats(FIRSTPASS_STATS *section,
3510
0
                           const FIRSTPASS_STATS *frame) {
3511
0
  section->frame -= frame->frame;
3512
0
  section->weight -= frame->weight;
3513
0
  section->intra_error -= frame->intra_error;
3514
0
  section->frame_avg_wavelet_energy -= frame->frame_avg_wavelet_energy;
3515
0
  section->coded_error -= frame->coded_error;
3516
0
  section->sr_coded_error -= frame->sr_coded_error;
3517
0
  section->pcnt_inter -= frame->pcnt_inter;
3518
0
  section->pcnt_motion -= frame->pcnt_motion;
3519
0
  section->pcnt_second_ref -= frame->pcnt_second_ref;
3520
0
  section->pcnt_neutral -= frame->pcnt_neutral;
3521
0
  section->intra_skip_pct -= frame->intra_skip_pct;
3522
0
  section->inactive_zone_rows -= frame->inactive_zone_rows;
3523
0
  section->inactive_zone_cols -= frame->inactive_zone_cols;
3524
0
  section->MVr -= frame->MVr;
3525
0
  section->mvr_abs -= frame->mvr_abs;
3526
0
  section->MVc -= frame->MVc;
3527
0
  section->mvc_abs -= frame->mvc_abs;
3528
0
  section->MVrv -= frame->MVrv;
3529
0
  section->MVcv -= frame->MVcv;
3530
0
  section->mv_in_out_count -= frame->mv_in_out_count;
3531
0
  section->new_mv_count -= frame->new_mv_count;
3532
0
  section->count -= frame->count;
3533
0
  section->duration -= frame->duration;
3534
0
}
3535
3536
0
static void calculate_frame_avg_haar_energy(AV1_COMP *cpi) {
3537
0
  TWO_PASS *const twopass = &cpi->ppi->twopass;
3538
0
  const FIRSTPASS_STATS *const total_stats =
3539
0
      twopass->stats_buf_ctx->total_stats;
3540
3541
0
  if (is_one_pass_rt_params(cpi) ||
3542
0
      (cpi->oxcf.q_cfg.deltaq_mode != DELTA_Q_PERCEPTUAL) ||
3543
0
      (is_fp_wavelet_energy_invalid(total_stats) == 0))
3544
0
    return;
3545
3546
0
  const int num_mbs = (cpi->oxcf.resize_cfg.resize_mode != RESIZE_NONE)
3547
0
                          ? cpi->initial_mbs
3548
0
                          : cpi->common.mi_params.MBs;
3549
0
  const YV12_BUFFER_CONFIG *const unfiltered_source = cpi->unfiltered_source;
3550
0
  const uint8_t *const src = unfiltered_source->y_buffer;
3551
0
  const int hbd = unfiltered_source->flags & YV12_FLAG_HIGHBITDEPTH;
3552
0
  const int stride = unfiltered_source->y_stride;
3553
0
  const BLOCK_SIZE fp_block_size =
3554
0
      get_fp_block_size(cpi->is_screen_content_type);
3555
0
  const int fp_block_size_width = block_size_wide[fp_block_size];
3556
0
  const int fp_block_size_height = block_size_high[fp_block_size];
3557
0
  const int num_unit_cols =
3558
0
      get_num_blocks(unfiltered_source->y_crop_width, fp_block_size_width);
3559
0
  const int num_unit_rows =
3560
0
      get_num_blocks(unfiltered_source->y_crop_height, fp_block_size_height);
3561
0
  const int num_8x8_cols = num_unit_cols * (fp_block_size_width / 8);
3562
0
  const int num_8x8_rows = num_unit_rows * (fp_block_size_height / 8);
3563
0
  int64_t frame_avg_wavelet_energy = av1_haar_ac_sad_mxn_uint8_input(
3564
0
      src, stride, hbd, num_8x8_rows, num_8x8_cols);
3565
3566
0
  cpi->twopass_frame.frame_avg_haar_energy =
3567
0
      log1p((double)frame_avg_wavelet_energy / num_mbs);
3568
0
}
3569
#endif
3570
3571
/*!\brief Run the final pass encoding for 1-pass/2-pass encoding mode, and pack
3572
 * the bitstream
3573
 *
3574
 * \ingroup high_level_algo
3575
 * \callgraph
3576
 * \callergraph
3577
 *
3578
 * \param[in]    cpi             Top-level encoder structure
3579
 * \param[in]    size            Bitstream size
3580
 * \param[out]   dest            Bitstream output buffer
3581
 * \param[in]    dest_size       Bitstream output buffer size
3582
 *
3583
 * \return Returns a value to indicate if the encoding is done successfully.
3584
 * \retval #AOM_CODEC_OK
3585
 * \retval #AOM_CODEC_ERROR
3586
 */
3587
static int encode_frame_to_data_rate(AV1_COMP *cpi, size_t *size, uint8_t *dest,
3588
0
                                     size_t dest_size) {
3589
0
  AV1_COMMON *const cm = &cpi->common;
3590
0
  SequenceHeader *const seq_params = cm->seq_params;
3591
0
  CurrentFrame *const current_frame = &cm->current_frame;
3592
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
3593
0
  struct segmentation *const seg = &cm->seg;
3594
0
  FeatureFlags *const features = &cm->features;
3595
0
  const TileConfig *const tile_cfg = &oxcf->tile_cfg;
3596
0
  assert(cpi->source != NULL);
3597
0
  cpi->td.mb.e_mbd.cur_buf = cpi->source;
3598
3599
#if CONFIG_COLLECT_COMPONENT_TIMING
3600
  start_timing(cpi, encode_frame_to_data_rate_time);
3601
#endif
3602
3603
0
#if !CONFIG_REALTIME_ONLY
3604
0
  calculate_frame_avg_haar_energy(cpi);
3605
0
#endif
3606
3607
  // frame type has been decided outside of this function call
3608
0
  cm->cur_frame->frame_type = current_frame->frame_type;
3609
3610
0
  cm->tiles.large_scale = tile_cfg->enable_large_scale_tile;
3611
0
  cm->tiles.single_tile_decoding = tile_cfg->enable_single_tile_decoding;
3612
3613
0
  features->allow_ref_frame_mvs &= frame_might_allow_ref_frame_mvs(cm);
3614
  // features->allow_ref_frame_mvs needs to be written into the frame header
3615
  // while cm->tiles.large_scale is 1, therefore, "cm->tiles.large_scale=1" case
3616
  // is separated from frame_might_allow_ref_frame_mvs().
3617
0
  features->allow_ref_frame_mvs &= !cm->tiles.large_scale;
3618
3619
0
  features->allow_warped_motion = oxcf->motion_mode_cfg.allow_warped_motion &&
3620
0
                                  frame_might_allow_warped_motion(cm);
3621
3622
0
  cpi->last_frame_type = current_frame->frame_type;
3623
3624
0
  if (frame_is_intra_only(cm)) {
3625
0
    cpi->frames_since_last_update = 0;
3626
0
  }
3627
3628
0
  if (frame_is_sframe(cm)) {
3629
0
    GF_GROUP *gf_group = &cpi->ppi->gf_group;
3630
    // S frame will wipe out any previously encoded altref so we cannot place
3631
    // an overlay frame
3632
0
    gf_group->update_type[gf_group->size] = GF_UPDATE;
3633
0
  }
3634
3635
0
  if (encode_show_existing_frame(cm)) {
3636
#if CONFIG_RATECTRL_LOG && CONFIG_THREE_PASS && CONFIG_BITRATE_ACCURACY
3637
    // TODO(angiebird): Move this into a function.
3638
    if (oxcf->pass == AOM_RC_THIRD_PASS) {
3639
      int frame_coding_idx =
3640
          av1_vbr_rc_frame_coding_idx(&cpi->vbr_rc_info, cpi->gf_frame_index);
3641
      rc_log_frame_encode_param(
3642
          &cpi->rc_log, frame_coding_idx, 1, 255,
3643
          cpi->ppi->gf_group.update_type[cpi->gf_frame_index]);
3644
    }
3645
#endif
3646
0
    av1_finalize_encoded_frame(cpi);
3647
    // Build the bitstream
3648
0
    int largest_tile_id = 0;  // Output from bitstream: unused here
3649
0
    cpi->rc.coefficient_size = 0;
3650
0
    if (av1_pack_bitstream(cpi, dest, dest_size, size, &largest_tile_id) !=
3651
0
        AOM_CODEC_OK)
3652
0
      return AOM_CODEC_ERROR;
3653
3654
0
    if (seq_params->frame_id_numbers_present_flag &&
3655
0
        current_frame->frame_type == KEY_FRAME) {
3656
      // Displaying a forward key-frame, so reset the ref buffer IDs
3657
0
      int display_frame_id = cm->ref_frame_id[cpi->existing_fb_idx_to_show];
3658
0
      for (int i = 0; i < REF_FRAMES; i++)
3659
0
        cm->ref_frame_id[i] = display_frame_id;
3660
0
    }
3661
3662
#if DUMP_RECON_FRAMES == 1
3663
    // NOTE(zoeliu): For debug - Output the filtered reconstructed video.
3664
    av1_dump_filtered_recon_frames(cpi);
3665
#endif  // DUMP_RECON_FRAMES
3666
3667
    // NOTE: Save the new show frame buffer index for --test-code=warn, i.e.,
3668
    //       for the purpose to verify no mismatch between encoder and decoder.
3669
0
    if (cm->show_frame) cpi->last_show_frame_buf = cm->cur_frame;
3670
3671
#if CONFIG_AV1_TEMPORAL_DENOISING
3672
    av1_denoiser_update_ref_frame(cpi);
3673
#endif
3674
3675
    // Since we allocate a spot for the OVERLAY frame in the gf group, we need
3676
    // to do post-encoding update accordingly.
3677
0
    av1_set_target_rate(cpi, cm->width, cm->height);
3678
3679
0
    if (is_psnr_calc_enabled(cpi)) {
3680
0
      cpi->source =
3681
0
          realloc_and_scale_source(cpi, cm->cur_frame->buf.y_crop_width,
3682
0
                                   cm->cur_frame->buf.y_crop_height);
3683
0
    }
3684
3685
0
#if !CONFIG_REALTIME_ONLY
3686
0
    if (cpi->use_ducky_encode) {
3687
0
      PSNR_STATS psnr;
3688
0
      aom_calc_psnr(cpi->source, &cpi->common.cur_frame->buf, &psnr);
3689
0
      DuckyEncodeFrameResult *frame_result =
3690
0
          &cpi->ducky_encode_info.frame_result;
3691
0
      frame_result->global_order_idx = cm->cur_frame->display_order_hint;
3692
0
      frame_result->q_index = cm->quant_params.base_qindex;
3693
0
      frame_result->rdmult = cpi->rd.RDMULT;
3694
0
      frame_result->rate = (int)(*size) * 8;
3695
0
      frame_result->dist = psnr.sse[0];
3696
0
      frame_result->psnr = psnr.psnr[0];
3697
0
    }
3698
0
#endif  // !CONFIG_REALTIME_ONLY
3699
3700
0
    update_counters_for_show_frame(cpi);
3701
0
    return AOM_CODEC_OK;
3702
0
  }
3703
3704
  // Work out whether to force_integer_mv this frame
3705
0
  if (!is_stat_generation_stage(cpi) &&
3706
0
      cpi->common.features.allow_screen_content_tools &&
3707
0
      !frame_is_intra_only(cm) && !cpi->sf.rt_sf.use_nonrd_pick_mode) {
3708
0
    if (cpi->common.seq_params->force_integer_mv == 2) {
3709
      // Adaptive mode: see what previous frame encoded did
3710
0
      if (cpi->unscaled_last_source != NULL) {
3711
0
        features->cur_frame_force_integer_mv = av1_is_integer_mv(
3712
0
            cpi->source, cpi->unscaled_last_source, &cpi->force_intpel_info);
3713
0
      } else {
3714
0
        cpi->common.features.cur_frame_force_integer_mv = 0;
3715
0
      }
3716
0
    } else {
3717
0
      cpi->common.features.cur_frame_force_integer_mv =
3718
0
          cpi->common.seq_params->force_integer_mv;
3719
0
    }
3720
0
  } else {
3721
0
    cpi->common.features.cur_frame_force_integer_mv = 0;
3722
0
  }
3723
3724
  // This is used by av1_pack_bitstream. So this needs to be set in case of
3725
  // row-mt where the encoding code will use a temporary structure.
3726
0
  cpi->td.mb.e_mbd.cur_frame_force_integer_mv =
3727
0
      cpi->common.features.cur_frame_force_integer_mv;
3728
3729
  // Set default state for segment based loop filter update flags.
3730
0
  cm->lf.mode_ref_delta_update = 0;
3731
3732
  // Set various flags etc to special state if it is a key frame.
3733
0
  if (frame_is_intra_only(cm) || frame_is_sframe(cm)) {
3734
    // Reset the loop filter deltas and segmentation map.
3735
0
    av1_reset_segment_features(cm);
3736
3737
    // If segmentation is enabled force a map update for key frames.
3738
0
    if (seg->enabled) {
3739
0
      seg->update_map = 1;
3740
0
      seg->update_data = 1;
3741
0
    }
3742
0
  }
3743
0
  if (tile_cfg->mtu == 0) {
3744
0
    cpi->num_tg = tile_cfg->num_tile_groups;
3745
0
  } else {
3746
    // Use a default value for the purposes of weighting costs in probability
3747
    // updates
3748
0
    cpi->num_tg = DEFAULT_MAX_NUM_TG;
3749
0
  }
3750
3751
  // For 1 pass CBR mode: check if we are dropping this frame.
3752
0
  if (has_no_stats_stage(cpi) && oxcf->rc_cfg.mode == AOM_CBR) {
3753
    // Always drop for spatial enhancement layer if layer bandwidth is 0.
3754
    // Otherwise check for frame-dropping based on buffer level in
3755
    // av1_rc_drop_frame().
3756
0
    if ((cpi->svc.spatial_layer_id > 0 &&
3757
0
         cpi->oxcf.rc_cfg.target_bandwidth == 0) ||
3758
0
        av1_rc_drop_frame(cpi)) {
3759
0
      cpi->is_dropped_frame = true;
3760
0
    }
3761
0
    if (cpi->is_dropped_frame) {
3762
0
      av1_setup_frame_size(cpi);
3763
0
      av1_set_mv_search_params(cpi);
3764
0
      av1_rc_postencode_update_drop_frame(cpi);
3765
0
      release_scaled_references(cpi);
3766
0
      cpi->ppi->gf_group.is_frame_dropped[cpi->gf_frame_index] = true;
3767
      // A dropped frame might not be shown but it always takes a slot in the gf
3768
      // group. Therefore, even when it is not shown, we still need to update
3769
      // the relevant frame counters.
3770
0
      if (cm->show_frame) {
3771
0
        update_counters_for_show_frame(cpi);
3772
0
      }
3773
0
      return AOM_CODEC_OK;
3774
0
    }
3775
0
  }
3776
3777
0
  if (oxcf->tune_cfg.tuning == AOM_TUNE_SSIM ||
3778
0
      oxcf->tune_cfg.tuning == AOM_TUNE_IQ) {
3779
0
    av1_set_mb_ssim_rdmult_scaling(cpi);
3780
0
  }
3781
#if CONFIG_SALIENCY_MAP
3782
  else if (oxcf->tune_cfg.tuning == AOM_TUNE_VMAF_SALIENCY_MAP &&
3783
           !(cpi->source->flags & YV12_FLAG_HIGHBITDEPTH)) {
3784
    if (av1_set_saliency_map(cpi) == 0) {
3785
      return AOM_CODEC_MEM_ERROR;
3786
    }
3787
#if !CONFIG_REALTIME_ONLY
3788
    double motion_ratio = av1_setup_motion_ratio(cpi);
3789
#else
3790
    double motion_ratio = 1.0;
3791
#endif
3792
    if (av1_setup_sm_rdmult_scaling_factor(cpi, motion_ratio) == 0) {
3793
      return AOM_CODEC_MEM_ERROR;
3794
    }
3795
  }
3796
#endif
3797
#if CONFIG_TUNE_VMAF
3798
  else if (oxcf->tune_cfg.tuning == AOM_TUNE_VMAF_WITHOUT_PREPROCESSING ||
3799
           oxcf->tune_cfg.tuning == AOM_TUNE_VMAF_MAX_GAIN ||
3800
           oxcf->tune_cfg.tuning == AOM_TUNE_VMAF_NEG_MAX_GAIN) {
3801
    av1_set_mb_vmaf_rdmult_scaling(cpi);
3802
  }
3803
#endif
3804
3805
0
  if (cpi->oxcf.q_cfg.deltaq_mode == DELTA_Q_PERCEPTUAL_AI &&
3806
0
      cpi->sf.rt_sf.use_nonrd_pick_mode == 0) {
3807
0
    av1_init_mb_wiener_var_buffer(cpi);
3808
0
    av1_set_mb_wiener_variance(cpi);
3809
0
  }
3810
3811
0
  if (cpi->oxcf.q_cfg.deltaq_mode == DELTA_Q_USER_RATING_BASED) {
3812
0
    av1_init_mb_ur_var_buffer(cpi);
3813
0
    av1_set_mb_ur_variance(cpi);
3814
0
  }
3815
3816
#if CONFIG_INTERNAL_STATS
3817
  memset(cpi->mode_chosen_counts, 0,
3818
         MAX_MODES * sizeof(*cpi->mode_chosen_counts));
3819
#endif
3820
3821
0
  if (seq_params->frame_id_numbers_present_flag) {
3822
    /* Non-normative definition of current_frame_id ("frame counter" with
3823
     * wraparound) */
3824
0
    if (cm->current_frame_id == -1) {
3825
0
      int lsb, msb;
3826
      /* quasi-random initialization of current_frame_id for a key frame */
3827
0
      if (cpi->source->flags & YV12_FLAG_HIGHBITDEPTH) {
3828
0
        lsb = CONVERT_TO_SHORTPTR(cpi->source->y_buffer)[0] & 0xff;
3829
0
        msb = CONVERT_TO_SHORTPTR(cpi->source->y_buffer)[1] & 0xff;
3830
0
      } else {
3831
0
        lsb = cpi->source->y_buffer[0] & 0xff;
3832
0
        msb = cpi->source->y_buffer[1] & 0xff;
3833
0
      }
3834
0
      cm->current_frame_id =
3835
0
          ((msb << 8) + lsb) % (1 << seq_params->frame_id_length);
3836
3837
      // S_frame is meant for stitching different streams of different
3838
      // resolutions together, so current_frame_id must be the
3839
      // same across different streams of the same content current_frame_id
3840
      // should be the same and not random. 0x37 is a chosen number as start
3841
      // point
3842
0
      if (oxcf->kf_cfg.sframe_dist != 0) cm->current_frame_id = 0x37;
3843
0
    } else {
3844
0
      cm->current_frame_id =
3845
0
          (cm->current_frame_id + 1 + (1 << seq_params->frame_id_length)) %
3846
0
          (1 << seq_params->frame_id_length);
3847
0
    }
3848
0
  }
3849
3850
0
  switch (oxcf->algo_cfg.cdf_update_mode) {
3851
0
    case 0:  // No CDF update for any frames(4~6% compression loss).
3852
0
      features->disable_cdf_update = 1;
3853
0
      break;
3854
0
    case 1:  // Enable CDF update for all frames.
3855
0
      if (cpi->sf.rt_sf.disable_cdf_update_non_reference_frame &&
3856
0
          cpi->ppi->rtc_ref.non_reference_frame && cpi->rc.frames_since_key > 2)
3857
0
        features->disable_cdf_update = 1;
3858
0
      else if (cpi->sf.rt_sf.selective_cdf_update)
3859
0
        features->disable_cdf_update = selective_disable_cdf_rtc(cpi);
3860
0
      else
3861
0
        features->disable_cdf_update = 0;
3862
0
      break;
3863
0
    case 2:
3864
      // Strategically determine at which frames to do CDF update.
3865
      // Currently only enable CDF update for all-intra and no-show frames(1.5%
3866
      // compression loss) for good qualiy or allintra mode.
3867
0
      if (oxcf->mode == GOOD || oxcf->mode == ALLINTRA) {
3868
0
        features->disable_cdf_update =
3869
0
            (frame_is_intra_only(cm) || !cm->show_frame) ? 0 : 1;
3870
0
      } else {
3871
0
        features->disable_cdf_update = selective_disable_cdf_rtc(cpi);
3872
0
      }
3873
0
      break;
3874
0
  }
3875
3876
  // Disable cdf update for the INTNL_ARF_UPDATE frame with
3877
  // frame_parallel_level 1.
3878
0
  if (!cpi->do_frame_data_update &&
3879
0
      cpi->ppi->gf_group.update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE) {
3880
0
    assert(cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] == 1);
3881
0
    features->disable_cdf_update = 1;
3882
0
  }
3883
3884
0
#if !CONFIG_REALTIME_ONLY
3885
0
  if (cpi->oxcf.tool_cfg.enable_global_motion && !frame_is_intra_only(cm)) {
3886
    // Flush any stale global motion information, which may be left over
3887
    // from a previous frame
3888
0
    aom_invalidate_pyramid(cpi->source->y_pyramid);
3889
0
    av1_invalidate_corner_list(cpi->source->corners);
3890
0
  }
3891
0
#endif  // !CONFIG_REALTIME_ONLY
3892
3893
0
  int largest_tile_id = 0;
3894
0
  if (av1_superres_in_recode_allowed(cpi)) {
3895
0
    if (encode_with_and_without_superres(cpi, size, dest, dest_size,
3896
0
                                         &largest_tile_id) != AOM_CODEC_OK) {
3897
0
      return AOM_CODEC_ERROR;
3898
0
    }
3899
0
  } else {
3900
0
    const aom_superres_mode orig_superres_mode = cpi->superres_mode;  // save
3901
0
    cpi->superres_mode = cpi->oxcf.superres_cfg.superres_mode;
3902
0
    if (encode_with_recode_loop_and_filter(cpi, size, dest, dest_size, NULL,
3903
0
                                           NULL,
3904
0
                                           &largest_tile_id) != AOM_CODEC_OK) {
3905
0
      return AOM_CODEC_ERROR;
3906
0
    }
3907
0
    cpi->superres_mode = orig_superres_mode;  // restore
3908
0
  }
3909
3910
  // Update reference frame ids for reference frames this frame will overwrite
3911
0
  if (seq_params->frame_id_numbers_present_flag) {
3912
0
    for (int i = 0; i < REF_FRAMES; i++) {
3913
0
      if ((current_frame->refresh_frame_flags >> i) & 1) {
3914
0
        cm->ref_frame_id[i] = cm->current_frame_id;
3915
0
      }
3916
0
    }
3917
0
  }
3918
3919
0
  if (cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)
3920
0
    cpi->svc.num_encoded_top_layer++;
3921
3922
#if DUMP_RECON_FRAMES == 1
3923
  // NOTE(zoeliu): For debug - Output the filtered reconstructed video.
3924
  av1_dump_filtered_recon_frames(cpi);
3925
#endif  // DUMP_RECON_FRAMES
3926
3927
0
  if (cm->seg.enabled) {
3928
0
    if (cm->seg.update_map == 0 && cm->last_frame_seg_map) {
3929
0
      memcpy(cm->cur_frame->seg_map, cm->last_frame_seg_map,
3930
0
             cm->cur_frame->mi_cols * cm->cur_frame->mi_rows *
3931
0
                 sizeof(*cm->cur_frame->seg_map));
3932
0
    }
3933
0
  }
3934
3935
0
  int release_scaled_refs = 0;
3936
#if CONFIG_FPMT_TEST
3937
  release_scaled_refs =
3938
      (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) ? 1 : 0;
3939
#endif  // CONFIG_FPMT_TEST
3940
0
  if (release_scaled_refs ||
3941
0
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] == 0) {
3942
0
    if (frame_is_intra_only(cm) == 0) {
3943
0
      release_scaled_references(cpi);
3944
0
    }
3945
0
  }
3946
#if CONFIG_AV1_TEMPORAL_DENOISING
3947
  av1_denoiser_update_ref_frame(cpi);
3948
#endif
3949
3950
  // NOTE: Save the new show frame buffer index for --test-code=warn, i.e.,
3951
  //       for the purpose to verify no mismatch between encoder and decoder.
3952
0
  if (cm->show_frame) cpi->last_show_frame_buf = cm->cur_frame;
3953
3954
0
  if (features->refresh_frame_context == REFRESH_FRAME_CONTEXT_BACKWARD) {
3955
0
    *cm->fc = cpi->tile_data[largest_tile_id].tctx;
3956
0
    av1_reset_cdf_symbol_counters(cm->fc);
3957
0
  }
3958
0
  if (!cm->tiles.large_scale) {
3959
0
    cm->cur_frame->frame_context = *cm->fc;
3960
0
  }
3961
3962
0
  if (tile_cfg->enable_ext_tile_debug) {
3963
    // (yunqing) This test ensures the correctness of large scale tile coding.
3964
0
    if (cm->tiles.large_scale && is_stat_consumption_stage(cpi)) {
3965
0
      char fn[20] = "./fc";
3966
0
      fn[4] = current_frame->frame_number / 100 + '0';
3967
0
      fn[5] = (current_frame->frame_number % 100) / 10 + '0';
3968
0
      fn[6] = (current_frame->frame_number % 10) + '0';
3969
0
      fn[7] = '\0';
3970
0
      av1_print_frame_contexts(cm->fc, fn);
3971
0
    }
3972
0
  }
3973
3974
0
  cpi->last_frame_type = current_frame->frame_type;
3975
3976
0
  if (cm->features.disable_cdf_update) {
3977
0
    cpi->frames_since_last_update++;
3978
0
  } else {
3979
0
    cpi->frames_since_last_update = 1;
3980
0
  }
3981
3982
0
  if (cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)
3983
0
    cpi->svc.prev_number_spatial_layers = cpi->svc.number_spatial_layers;
3984
3985
  // Clear the one shot update flags for segmentation map and mode/ref loop
3986
  // filter deltas.
3987
0
  cm->seg.update_map = 0;
3988
0
  cm->seg.update_data = 0;
3989
0
  cm->lf.mode_ref_delta_update = 0;
3990
3991
0
  if (cm->show_frame) {
3992
0
    update_counters_for_show_frame(cpi);
3993
0
  }
3994
3995
#if CONFIG_COLLECT_COMPONENT_TIMING
3996
  end_timing(cpi, encode_frame_to_data_rate_time);
3997
#endif
3998
3999
0
  return AOM_CODEC_OK;
4000
0
}
4001
4002
int av1_encode(AV1_COMP *const cpi, uint8_t *const dest, size_t dest_size,
4003
               const EncodeFrameInput *const frame_input,
4004
               const EncodeFrameParams *const frame_params,
4005
0
               size_t *const frame_size) {
4006
0
  AV1_COMMON *const cm = &cpi->common;
4007
0
  CurrentFrame *const current_frame = &cm->current_frame;
4008
4009
0
  cpi->unscaled_source = frame_input->source;
4010
0
  cpi->source = frame_input->source;
4011
0
  cpi->unscaled_last_source = frame_input->last_source;
4012
4013
0
  current_frame->refresh_frame_flags = frame_params->refresh_frame_flags;
4014
0
  cm->features.error_resilient_mode = frame_params->error_resilient_mode;
4015
0
  cm->features.primary_ref_frame = frame_params->primary_ref_frame;
4016
0
  cm->current_frame.frame_type = frame_params->frame_type;
4017
0
  cm->show_frame = frame_params->show_frame;
4018
0
  cpi->ref_frame_flags = frame_params->ref_frame_flags;
4019
0
  cpi->speed = frame_params->speed;
4020
0
  cm->show_existing_frame = frame_params->show_existing_frame;
4021
0
  cpi->existing_fb_idx_to_show = frame_params->existing_fb_idx_to_show;
4022
4023
0
  memcpy(cm->remapped_ref_idx, frame_params->remapped_ref_idx,
4024
0
         REF_FRAMES * sizeof(*cm->remapped_ref_idx));
4025
4026
0
  memcpy(&cpi->refresh_frame, &frame_params->refresh_frame,
4027
0
         sizeof(cpi->refresh_frame));
4028
4029
0
  if (current_frame->frame_type == KEY_FRAME &&
4030
0
      cpi->ppi->gf_group.refbuf_state[cpi->gf_frame_index] == REFBUF_RESET) {
4031
0
    current_frame->frame_number = 0;
4032
0
  }
4033
4034
0
  current_frame->order_hint =
4035
0
      current_frame->frame_number + frame_params->order_offset;
4036
4037
0
  current_frame->display_order_hint = current_frame->order_hint;
4038
0
  current_frame->order_hint %=
4039
0
      (1 << (cm->seq_params->order_hint_info.order_hint_bits_minus_1 + 1));
4040
4041
0
  current_frame->pyramid_level = get_true_pyr_level(
4042
0
      cpi->ppi->gf_group.layer_depth[cpi->gf_frame_index],
4043
0
      current_frame->display_order_hint, cpi->ppi->gf_group.max_layer_depth);
4044
4045
0
  if (is_stat_generation_stage(cpi)) {
4046
0
#if !CONFIG_REALTIME_ONLY
4047
0
    if (cpi->oxcf.q_cfg.use_fixed_qp_offsets)
4048
0
      av1_noop_first_pass_frame(cpi, frame_input->ts_duration);
4049
0
    else
4050
0
      av1_first_pass(cpi, frame_input->ts_duration);
4051
0
#endif
4052
0
  } else if (cpi->oxcf.pass == AOM_RC_ONE_PASS ||
4053
0
             cpi->oxcf.pass >= AOM_RC_SECOND_PASS) {
4054
0
    if (encode_frame_to_data_rate(cpi, frame_size, dest, dest_size) !=
4055
0
        AOM_CODEC_OK) {
4056
0
      return AOM_CODEC_ERROR;
4057
0
    }
4058
0
  } else {
4059
0
    return AOM_CODEC_ERROR;
4060
0
  }
4061
4062
0
  return AOM_CODEC_OK;
4063
0
}
4064
4065
#if CONFIG_DENOISE && !CONFIG_REALTIME_ONLY
4066
static int apply_denoise_2d(AV1_COMP *cpi, const YV12_BUFFER_CONFIG *sd,
4067
                            int block_size, float noise_level,
4068
0
                            int64_t time_stamp, int64_t end_time) {
4069
0
  AV1_COMMON *const cm = &cpi->common;
4070
0
  if (!cpi->denoise_and_model) {
4071
0
    cpi->denoise_and_model = aom_denoise_and_model_alloc(
4072
0
        cm->seq_params->bit_depth, block_size, noise_level);
4073
0
    if (!cpi->denoise_and_model) {
4074
0
      aom_set_error(cm->error, AOM_CODEC_MEM_ERROR,
4075
0
                    "Error allocating denoise and model");
4076
0
      return -1;
4077
0
    }
4078
0
  }
4079
0
  if (!cpi->film_grain_table) {
4080
0
    cpi->film_grain_table = aom_malloc(sizeof(*cpi->film_grain_table));
4081
0
    if (!cpi->film_grain_table) {
4082
0
      aom_set_error(cm->error, AOM_CODEC_MEM_ERROR,
4083
0
                    "Error allocating grain table");
4084
0
      return -1;
4085
0
    }
4086
0
    memset(cpi->film_grain_table, 0, sizeof(*cpi->film_grain_table));
4087
0
  }
4088
0
  if (aom_denoise_and_model_run(cpi->denoise_and_model, sd,
4089
0
                                &cm->film_grain_params,
4090
0
                                cpi->oxcf.enable_dnl_denoising)) {
4091
0
    if (cm->film_grain_params.apply_grain) {
4092
0
      aom_film_grain_table_append(cpi->film_grain_table, time_stamp, end_time,
4093
0
                                  &cm->film_grain_params);
4094
0
    }
4095
0
  }
4096
0
  return 0;
4097
0
}
4098
#endif
4099
4100
int av1_receive_raw_frame(AV1_COMP *cpi, aom_enc_frame_flags_t frame_flags,
4101
                          const YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
4102
0
                          int64_t end_time) {
4103
0
  AV1_COMMON *const cm = &cpi->common;
4104
0
  const SequenceHeader *const seq_params = cm->seq_params;
4105
0
  int res = 0;
4106
0
  const int subsampling_x = sd->subsampling_x;
4107
0
  const int subsampling_y = sd->subsampling_y;
4108
0
  const int use_highbitdepth = (sd->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
4109
4110
#if CONFIG_TUNE_VMAF
4111
  if (!is_stat_generation_stage(cpi) &&
4112
      cpi->oxcf.tune_cfg.tuning == AOM_TUNE_VMAF_WITH_PREPROCESSING) {
4113
    av1_vmaf_frame_preprocessing(cpi, sd);
4114
  }
4115
  if (!is_stat_generation_stage(cpi) &&
4116
      cpi->oxcf.tune_cfg.tuning == AOM_TUNE_VMAF_MAX_GAIN) {
4117
    av1_vmaf_blk_preprocessing(cpi, sd);
4118
  }
4119
#endif
4120
4121
#if CONFIG_INTERNAL_STATS
4122
  struct aom_usec_timer timer;
4123
  aom_usec_timer_start(&timer);
4124
#endif
4125
4126
#if CONFIG_AV1_TEMPORAL_DENOISING
4127
  setup_denoiser_buffer(cpi);
4128
#endif
4129
4130
0
#if CONFIG_DENOISE
4131
  // even if denoise_noise_level is > 0, we don't need need to denoise on pass
4132
  // 1 of 2 if enable_dnl_denoising is disabled since the 2nd pass will be
4133
  // encoding the original (non-denoised) frame
4134
0
  if (cpi->oxcf.noise_level > 0 && !(cpi->oxcf.pass == AOM_RC_FIRST_PASS &&
4135
0
                                     !cpi->oxcf.enable_dnl_denoising)) {
4136
0
#if !CONFIG_REALTIME_ONLY
4137
    // Choose a synthetic noise level for still images for enhanced perceptual
4138
    // quality based on an estimated noise level in the source, but only if
4139
    // the noise level is set on the command line to > 0.
4140
0
    if (cpi->oxcf.mode == ALLINTRA) {
4141
      // No noise synthesis if source is very clean.
4142
      // Uses a low edge threshold to focus on smooth areas.
4143
      // Increase output noise setting a little compared to measured value.
4144
0
      double y_noise_level = 0.0;
4145
0
      av1_estimate_noise_level(sd, &y_noise_level, AOM_PLANE_Y, AOM_PLANE_Y,
4146
0
                               cm->seq_params->bit_depth, 16);
4147
0
      cpi->oxcf.noise_level = (float)(y_noise_level - 0.1);
4148
0
      cpi->oxcf.noise_level = (float)AOMMAX(0.0, cpi->oxcf.noise_level);
4149
0
      if (cpi->oxcf.noise_level > 0.0) {
4150
0
        cpi->oxcf.noise_level += (float)0.5;
4151
0
      }
4152
0
      cpi->oxcf.noise_level = (float)AOMMIN(5.0, cpi->oxcf.noise_level);
4153
0
    }
4154
4155
0
    if (apply_denoise_2d(cpi, sd, cpi->oxcf.noise_block_size,
4156
0
                         cpi->oxcf.noise_level, time_stamp, end_time) < 0)
4157
0
      res = -1;
4158
0
#endif  // !CONFIG_REALTIME_ONLY
4159
0
  }
4160
0
#endif  //  CONFIG_DENOISE
4161
4162
0
  if (av1_lookahead_push(cpi->ppi->lookahead, sd, time_stamp, end_time,
4163
0
                         use_highbitdepth, cpi->alloc_pyramid, frame_flags)) {
4164
0
    aom_set_error(cm->error, AOM_CODEC_ERROR, "av1_lookahead_push() failed");
4165
0
    res = -1;
4166
0
  }
4167
#if CONFIG_INTERNAL_STATS
4168
  aom_usec_timer_mark(&timer);
4169
  cpi->ppi->total_time_receive_data += aom_usec_timer_elapsed(&timer);
4170
#endif
4171
4172
  // Note: Regarding profile setting, the following checks are added to help
4173
  // choose a proper profile for the input video. The criterion is that all
4174
  // bitstreams must be designated as the lowest profile that match its content.
4175
  // E.G. A bitstream that contains 4:4:4 video must be designated as High
4176
  // Profile in the seq header, and likewise a bitstream that contains 4:2:2
4177
  // bitstream must be designated as Professional Profile in the sequence
4178
  // header.
4179
0
  if ((seq_params->profile == PROFILE_0) && !seq_params->monochrome &&
4180
0
      (subsampling_x != 1 || subsampling_y != 1)) {
4181
0
    aom_set_error(cm->error, AOM_CODEC_INVALID_PARAM,
4182
0
                  "Non-4:2:0 color format requires profile 1 or 2");
4183
0
    res = -1;
4184
0
  }
4185
0
  if ((seq_params->profile == PROFILE_1) &&
4186
0
      !(subsampling_x == 0 && subsampling_y == 0)) {
4187
0
    aom_set_error(cm->error, AOM_CODEC_INVALID_PARAM,
4188
0
                  "Profile 1 requires 4:4:4 color format");
4189
0
    res = -1;
4190
0
  }
4191
0
  if ((seq_params->profile == PROFILE_2) &&
4192
0
      (seq_params->bit_depth <= AOM_BITS_10) &&
4193
0
      !(subsampling_x == 1 && subsampling_y == 0)) {
4194
0
    aom_set_error(cm->error, AOM_CODEC_INVALID_PARAM,
4195
0
                  "Profile 2 bit-depth <= 10 requires 4:2:2 color format");
4196
0
    res = -1;
4197
0
  }
4198
4199
0
  return res;
4200
0
}
4201
4202
#if CONFIG_ENTROPY_STATS
4203
void print_entropy_stats(AV1_PRIMARY *const ppi) {
4204
  if (!ppi->cpi) return;
4205
4206
  if (ppi->cpi->oxcf.pass != 1 &&
4207
      ppi->cpi->common.current_frame.frame_number > 0) {
4208
    fprintf(stderr, "Writing counts.stt\n");
4209
    FILE *f = fopen("counts.stt", "wb");
4210
    fwrite(&ppi->aggregate_fc, sizeof(ppi->aggregate_fc), 1, f);
4211
    fclose(f);
4212
  }
4213
}
4214
#endif  // CONFIG_ENTROPY_STATS
4215
4216
#if CONFIG_INTERNAL_STATS
4217
static void adjust_image_stat(double y, double u, double v, double all,
4218
                              ImageStat *s) {
4219
  s->stat[STAT_Y] += y;
4220
  s->stat[STAT_U] += u;
4221
  s->stat[STAT_V] += v;
4222
  s->stat[STAT_ALL] += all;
4223
  s->worst = AOMMIN(s->worst, all);
4224
}
4225
4226
static void compute_internal_stats(AV1_COMP *cpi, int frame_bytes) {
4227
  AV1_PRIMARY *const ppi = cpi->ppi;
4228
  AV1_COMMON *const cm = &cpi->common;
4229
  double samples = 0.0;
4230
  const uint32_t in_bit_depth = cpi->oxcf.input_cfg.input_bit_depth;
4231
  const uint32_t bit_depth = cpi->td.mb.e_mbd.bd;
4232
4233
  if (cpi->ppi->use_svc &&
4234
      cpi->svc.spatial_layer_id < cpi->svc.number_spatial_layers - 1)
4235
    return;
4236
4237
#if CONFIG_INTER_STATS_ONLY
4238
  if (cm->current_frame.frame_type == KEY_FRAME) return;  // skip key frame
4239
#endif
4240
  cpi->bytes += frame_bytes;
4241
  if (cm->show_frame) {
4242
    const YV12_BUFFER_CONFIG *orig = cpi->source;
4243
    const YV12_BUFFER_CONFIG *recon = &cpi->common.cur_frame->buf;
4244
    double y, u, v, frame_all;
4245
4246
    ppi->count[0]++;
4247
    ppi->count[1]++;
4248
    if (cpi->ppi->b_calculate_psnr) {
4249
      PSNR_STATS psnr;
4250
      double weight[2] = { 0.0, 0.0 };
4251
      double frame_ssim2[2] = { 0.0, 0.0 };
4252
#if CONFIG_AV1_HIGHBITDEPTH
4253
      aom_calc_highbd_psnr(orig, recon, &psnr, bit_depth, in_bit_depth);
4254
#else
4255
      aom_calc_psnr(orig, recon, &psnr);
4256
#endif
4257
      adjust_image_stat(psnr.psnr[1], psnr.psnr[2], psnr.psnr[3], psnr.psnr[0],
4258
                        &(ppi->psnr[0]));
4259
      ppi->total_sq_error[0] += psnr.sse[0];
4260
      ppi->total_samples[0] += psnr.samples[0];
4261
      samples = psnr.samples[0];
4262
4263
      aom_calc_ssim(orig, recon, bit_depth, in_bit_depth,
4264
                    cm->seq_params->use_highbitdepth, weight, frame_ssim2);
4265
4266
      ppi->worst_ssim = AOMMIN(ppi->worst_ssim, frame_ssim2[0]);
4267
      ppi->summed_quality += frame_ssim2[0] * weight[0];
4268
      ppi->summed_weights += weight[0];
4269
4270
#if CONFIG_AV1_HIGHBITDEPTH
4271
      // Compute PSNR based on stream bit depth
4272
      if ((cpi->source->flags & YV12_FLAG_HIGHBITDEPTH) &&
4273
          (in_bit_depth < bit_depth)) {
4274
        adjust_image_stat(psnr.psnr_hbd[1], psnr.psnr_hbd[2], psnr.psnr_hbd[3],
4275
                          psnr.psnr_hbd[0], &ppi->psnr[1]);
4276
        ppi->total_sq_error[1] += psnr.sse_hbd[0];
4277
        ppi->total_samples[1] += psnr.samples_hbd[0];
4278
4279
        ppi->worst_ssim_hbd = AOMMIN(ppi->worst_ssim_hbd, frame_ssim2[1]);
4280
        ppi->summed_quality_hbd += frame_ssim2[1] * weight[1];
4281
        ppi->summed_weights_hbd += weight[1];
4282
      }
4283
#endif
4284
4285
#if 0
4286
      {
4287
        FILE *f = fopen("q_used.stt", "a");
4288
        double y2 = psnr.psnr[1];
4289
        double u2 = psnr.psnr[2];
4290
        double v2 = psnr.psnr[3];
4291
        double frame_psnr2 = psnr.psnr[0];
4292
        fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
4293
                cm->current_frame.frame_number, y2, u2, v2,
4294
                frame_psnr2, frame_ssim2);
4295
        fclose(f);
4296
      }
4297
#endif
4298
    }
4299
    if (ppi->b_calculate_blockiness) {
4300
      if (!cm->seq_params->use_highbitdepth) {
4301
        const double frame_blockiness =
4302
            av1_get_blockiness(orig->y_buffer, orig->y_stride, recon->y_buffer,
4303
                               recon->y_stride, orig->y_width, orig->y_height);
4304
        ppi->worst_blockiness = AOMMAX(ppi->worst_blockiness, frame_blockiness);
4305
        ppi->total_blockiness += frame_blockiness;
4306
      }
4307
4308
      if (ppi->b_calculate_consistency) {
4309
        if (!cm->seq_params->use_highbitdepth) {
4310
          const double this_inconsistency = aom_get_ssim_metrics(
4311
              orig->y_buffer, orig->y_stride, recon->y_buffer, recon->y_stride,
4312
              orig->y_width, orig->y_height, ppi->ssim_vars, &ppi->metrics, 1);
4313
4314
          const double peak = (double)((1 << in_bit_depth) - 1);
4315
          const double consistency =
4316
              aom_sse_to_psnr(samples, peak, ppi->total_inconsistency);
4317
          if (consistency > 0.0)
4318
            ppi->worst_consistency =
4319
                AOMMIN(ppi->worst_consistency, consistency);
4320
          ppi->total_inconsistency += this_inconsistency;
4321
        }
4322
      }
4323
    }
4324
4325
    frame_all =
4326
        aom_calc_fastssim(orig, recon, &y, &u, &v, bit_depth, in_bit_depth);
4327
    adjust_image_stat(y, u, v, frame_all, &ppi->fastssim);
4328
    frame_all = aom_psnrhvs(orig, recon, &y, &u, &v, bit_depth, in_bit_depth);
4329
    adjust_image_stat(y, u, v, frame_all, &ppi->psnrhvs);
4330
  }
4331
}
4332
4333
void print_internal_stats(AV1_PRIMARY *ppi) {
4334
  if (!ppi->cpi) return;
4335
  AV1_COMP *const cpi = ppi->cpi;
4336
4337
  if (ppi->cpi->oxcf.pass != 1 &&
4338
      ppi->cpi->common.current_frame.frame_number > 0) {
4339
    char headings[512] = { 0 };
4340
    char results[512] = { 0 };
4341
    FILE *f = fopen("opsnr.stt", "a");
4342
    double time_encoded =
4343
        (cpi->time_stamps.prev_ts_end - cpi->time_stamps.first_ts_start) /
4344
        10000000.000;
4345
    double total_encode_time =
4346
        (ppi->total_time_receive_data + ppi->total_time_compress_data) /
4347
        1000.000;
4348
    const double dr =
4349
        (double)ppi->total_bytes * (double)8 / (double)1000 / time_encoded;
4350
    const double peak =
4351
        (double)((1 << ppi->cpi->oxcf.input_cfg.input_bit_depth) - 1);
4352
    const double target_rate =
4353
        (double)ppi->cpi->oxcf.rc_cfg.target_bandwidth / 1000;
4354
    const double rate_err = ((100.0 * (dr - target_rate)) / target_rate);
4355
4356
    if (ppi->b_calculate_psnr) {
4357
      const double total_psnr = aom_sse_to_psnr(
4358
          (double)ppi->total_samples[0], peak, (double)ppi->total_sq_error[0]);
4359
      const double total_ssim =
4360
          100 * pow(ppi->summed_quality / ppi->summed_weights, 8.0);
4361
      snprintf(headings, sizeof(headings),
4362
               "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
4363
               "AOMSSIM\tVPSSIMP\tFASTSIM\tPSNRHVS\t"
4364
               "WstPsnr\tWstSsim\tWstFast\tWstHVS\t"
4365
               "AVPsrnY\tAPsnrCb\tAPsnrCr");
4366
      snprintf(results, sizeof(results),
4367
               "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
4368
               "%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
4369
               "%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
4370
               "%7.3f\t%7.3f\t%7.3f",
4371
               dr, ppi->psnr[0].stat[STAT_ALL] / ppi->count[0], total_psnr,
4372
               ppi->psnr[0].stat[STAT_ALL] / ppi->count[0], total_psnr,
4373
               total_ssim, total_ssim,
4374
               ppi->fastssim.stat[STAT_ALL] / ppi->count[0],
4375
               ppi->psnrhvs.stat[STAT_ALL] / ppi->count[0], ppi->psnr[0].worst,
4376
               ppi->worst_ssim, ppi->fastssim.worst, ppi->psnrhvs.worst,
4377
               ppi->psnr[0].stat[STAT_Y] / ppi->count[0],
4378
               ppi->psnr[0].stat[STAT_U] / ppi->count[0],
4379
               ppi->psnr[0].stat[STAT_V] / ppi->count[0]);
4380
4381
      if (ppi->b_calculate_blockiness) {
4382
        SNPRINT(headings, "\t  Block\tWstBlck");
4383
        SNPRINT2(results, "\t%7.3f", ppi->total_blockiness / ppi->count[0]);
4384
        SNPRINT2(results, "\t%7.3f", ppi->worst_blockiness);
4385
      }
4386
4387
      if (ppi->b_calculate_consistency) {
4388
        double consistency =
4389
            aom_sse_to_psnr((double)ppi->total_samples[0], peak,
4390
                            (double)ppi->total_inconsistency);
4391
4392
        SNPRINT(headings, "\tConsist\tWstCons");
4393
        SNPRINT2(results, "\t%7.3f", consistency);
4394
        SNPRINT2(results, "\t%7.3f", ppi->worst_consistency);
4395
      }
4396
4397
      SNPRINT(headings, "\t   Time\tRcErr\tAbsErr");
4398
      SNPRINT2(results, "\t%8.0f", total_encode_time);
4399
      SNPRINT2(results, " %7.2f", rate_err);
4400
      SNPRINT2(results, " %7.2f", fabs(rate_err));
4401
4402
      SNPRINT(headings, "\tAPsnr611");
4403
      SNPRINT2(results, " %7.3f",
4404
               (6 * ppi->psnr[0].stat[STAT_Y] + ppi->psnr[0].stat[STAT_U] +
4405
                ppi->psnr[0].stat[STAT_V]) /
4406
                   (ppi->count[0] * 8));
4407
4408
#if CONFIG_AV1_HIGHBITDEPTH
4409
      const uint32_t in_bit_depth = ppi->cpi->oxcf.input_cfg.input_bit_depth;
4410
      const uint32_t bit_depth = ppi->seq_params.bit_depth;
4411
      // Since cpi->source->flags is not available here, but total_samples[1]
4412
      // will be non-zero if cpi->source->flags & YV12_FLAG_HIGHBITDEPTH was
4413
      // true in compute_internal_stats
4414
      if ((ppi->total_samples[1] > 0) && (in_bit_depth < bit_depth)) {
4415
        const double peak_hbd = (double)((1 << bit_depth) - 1);
4416
        const double total_psnr_hbd =
4417
            aom_sse_to_psnr((double)ppi->total_samples[1], peak_hbd,
4418
                            (double)ppi->total_sq_error[1]);
4419
        const double total_ssim_hbd =
4420
            100 * pow(ppi->summed_quality_hbd / ppi->summed_weights_hbd, 8.0);
4421
        SNPRINT(headings,
4422
                "\t AVGPsnrH GLBPsnrH AVPsnrPH GLPsnrPH"
4423
                " AVPsnrYH APsnrCbH APsnrCrH WstPsnrH"
4424
                " AOMSSIMH VPSSIMPH WstSsimH");
4425
        SNPRINT2(results, "\t%7.3f",
4426
                 ppi->psnr[1].stat[STAT_ALL] / ppi->count[1]);
4427
        SNPRINT2(results, "  %7.3f", total_psnr_hbd);
4428
        SNPRINT2(results, "  %7.3f",
4429
                 ppi->psnr[1].stat[STAT_ALL] / ppi->count[1]);
4430
        SNPRINT2(results, "  %7.3f", total_psnr_hbd);
4431
        SNPRINT2(results, "  %7.3f", ppi->psnr[1].stat[STAT_Y] / ppi->count[1]);
4432
        SNPRINT2(results, "  %7.3f", ppi->psnr[1].stat[STAT_U] / ppi->count[1]);
4433
        SNPRINT2(results, "  %7.3f", ppi->psnr[1].stat[STAT_V] / ppi->count[1]);
4434
        SNPRINT2(results, "  %7.3f", ppi->psnr[1].worst);
4435
        SNPRINT2(results, "  %7.3f", total_ssim_hbd);
4436
        SNPRINT2(results, "  %7.3f", total_ssim_hbd);
4437
        SNPRINT2(results, "  %7.3f", ppi->worst_ssim_hbd);
4438
      }
4439
#endif
4440
      fprintf(f, "%s\n", headings);
4441
      fprintf(f, "%s\n", results);
4442
    }
4443
4444
    fclose(f);
4445
4446
    aom_free(ppi->ssim_vars);
4447
    ppi->ssim_vars = NULL;
4448
  }
4449
}
4450
#endif  // CONFIG_INTERNAL_STATS
4451
4452
0
static inline void update_keyframe_counters(AV1_COMP *cpi) {
4453
0
  if (cpi->common.show_frame && cpi->rc.frames_to_key) {
4454
0
#if !CONFIG_REALTIME_ONLY
4455
0
    FIRSTPASS_INFO *firstpass_info = &cpi->ppi->twopass.firstpass_info;
4456
0
    if (firstpass_info->past_stats_count > FIRSTPASS_INFO_STATS_PAST_MIN) {
4457
0
      av1_firstpass_info_move_cur_index_and_pop(firstpass_info);
4458
0
    } else {
4459
      // When there is not enough past stats, we move the current
4460
      // index without popping the past stats
4461
0
      av1_firstpass_info_move_cur_index(firstpass_info);
4462
0
    }
4463
0
#endif
4464
0
    if (cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1) {
4465
0
      cpi->rc.frames_since_key++;
4466
0
      cpi->rc.frames_to_key--;
4467
0
      cpi->rc.frames_to_fwd_kf--;
4468
0
      cpi->rc.frames_since_scene_change++;
4469
0
    }
4470
0
  }
4471
0
}
4472
4473
0
static inline void update_frames_till_gf_update(AV1_COMP *cpi) {
4474
  // TODO(weitinglin): Updating this counter for is_frame_droppable
4475
  // is a work-around to handle the condition when a frame is drop.
4476
  // We should fix the cpi->common.show_frame flag
4477
  // instead of checking the other condition to update the counter properly.
4478
0
  if (cpi->common.show_frame ||
4479
0
      is_frame_droppable(&cpi->ppi->rtc_ref, &cpi->ext_flags.refresh_frame)) {
4480
    // Decrement count down till next gf
4481
0
    if (cpi->rc.frames_till_gf_update_due > 0)
4482
0
      cpi->rc.frames_till_gf_update_due--;
4483
0
  }
4484
0
}
4485
4486
0
static inline void update_gf_group_index(AV1_COMP *cpi) {
4487
  // Increment the gf group index ready for the next frame.
4488
0
  if (is_one_pass_rt_params(cpi) &&
4489
0
      cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1) {
4490
0
    ++cpi->gf_frame_index;
4491
    // Reset gf_frame_index in case it reaches MAX_STATIC_GF_GROUP_LENGTH
4492
    // for real time encoding.
4493
0
    if (cpi->gf_frame_index == MAX_STATIC_GF_GROUP_LENGTH)
4494
0
      cpi->gf_frame_index = 0;
4495
0
  } else {
4496
0
    ++cpi->gf_frame_index;
4497
0
  }
4498
0
}
4499
4500
static void update_fb_of_context_type(const AV1_COMP *const cpi,
4501
0
                                      int *const fb_of_context_type) {
4502
0
  const AV1_COMMON *const cm = &cpi->common;
4503
0
  const int current_frame_ref_type = get_current_frame_ref_type(cpi);
4504
4505
0
  if (frame_is_intra_only(cm) || cm->features.error_resilient_mode ||
4506
0
      cpi->ext_flags.use_primary_ref_none) {
4507
0
    for (int i = 0; i < REF_FRAMES; i++) {
4508
0
      fb_of_context_type[i] = -1;
4509
0
    }
4510
0
    fb_of_context_type[current_frame_ref_type] =
4511
0
        cm->show_frame ? get_ref_frame_map_idx(cm, GOLDEN_FRAME)
4512
0
                       : get_ref_frame_map_idx(cm, ALTREF_FRAME);
4513
0
  }
4514
4515
0
  if (!encode_show_existing_frame(cm)) {
4516
    // Refresh fb_of_context_type[]: see encoder.h for explanation
4517
0
    if (cm->current_frame.frame_type == KEY_FRAME) {
4518
      // All ref frames are refreshed, pick one that will live long enough
4519
0
      fb_of_context_type[current_frame_ref_type] = 0;
4520
0
    } else {
4521
      // If more than one frame is refreshed, it doesn't matter which one we
4522
      // pick so pick the first.  LST sometimes doesn't refresh any: this is ok
4523
4524
0
      for (int i = 0; i < REF_FRAMES; i++) {
4525
0
        if (cm->current_frame.refresh_frame_flags & (1 << i)) {
4526
0
          fb_of_context_type[current_frame_ref_type] = i;
4527
0
          break;
4528
0
        }
4529
0
      }
4530
0
    }
4531
0
  }
4532
0
}
4533
4534
0
static void update_rc_counts(AV1_COMP *cpi) {
4535
0
  update_keyframe_counters(cpi);
4536
0
  update_frames_till_gf_update(cpi);
4537
0
  update_gf_group_index(cpi);
4538
0
}
4539
4540
0
static void update_end_of_frame_stats(AV1_COMP *cpi) {
4541
0
  if (cpi->do_frame_data_update) {
4542
    // Store current frame loopfilter levels in ppi, if update flag is set.
4543
0
    if (!cpi->common.show_existing_frame) {
4544
0
      AV1_COMMON *const cm = &cpi->common;
4545
0
      struct loopfilter *const lf = &cm->lf;
4546
0
      cpi->ppi->filter_level[0] = lf->filter_level[0];
4547
0
      cpi->ppi->filter_level[1] = lf->filter_level[1];
4548
0
      cpi->ppi->filter_level_u = lf->filter_level_u;
4549
0
      cpi->ppi->filter_level_v = lf->filter_level_v;
4550
0
    }
4551
0
  }
4552
  // Store frame level mv_stats from cpi to ppi.
4553
0
  cpi->ppi->mv_stats = cpi->mv_stats;
4554
0
}
4555
4556
// Updates frame level stats related to global motion
4557
0
static inline void update_gm_stats(AV1_COMP *cpi) {
4558
0
  FRAME_UPDATE_TYPE update_type =
4559
0
      cpi->ppi->gf_group.update_type[cpi->gf_frame_index];
4560
0
  int i, is_gm_present = 0;
4561
4562
  // Check if the current frame has any valid global motion model across its
4563
  // reference frames
4564
0
  for (i = 0; i < REF_FRAMES; i++) {
4565
0
    if (cpi->common.global_motion[i].wmtype != IDENTITY) {
4566
0
      is_gm_present = 1;
4567
0
      break;
4568
0
    }
4569
0
  }
4570
0
  int update_actual_stats = 1;
4571
#if CONFIG_FPMT_TEST
4572
  update_actual_stats =
4573
      (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) ? 0 : 1;
4574
  if (!update_actual_stats) {
4575
    if (cpi->ppi->temp_valid_gm_model_found[update_type] == INT32_MAX) {
4576
      cpi->ppi->temp_valid_gm_model_found[update_type] = is_gm_present;
4577
    } else {
4578
      cpi->ppi->temp_valid_gm_model_found[update_type] |= is_gm_present;
4579
    }
4580
    int show_existing_between_parallel_frames =
4581
        (cpi->ppi->gf_group.update_type[cpi->gf_frame_index] ==
4582
             INTNL_OVERLAY_UPDATE &&
4583
         cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index + 1] == 2);
4584
    if (cpi->do_frame_data_update == 1 &&
4585
        !show_existing_between_parallel_frames) {
4586
      for (i = 0; i < FRAME_UPDATE_TYPES; i++) {
4587
        cpi->ppi->valid_gm_model_found[i] =
4588
            cpi->ppi->temp_valid_gm_model_found[i];
4589
      }
4590
    }
4591
  }
4592
#endif
4593
0
  if (update_actual_stats) {
4594
0
    if (cpi->ppi->valid_gm_model_found[update_type] == INT32_MAX) {
4595
0
      cpi->ppi->valid_gm_model_found[update_type] = is_gm_present;
4596
0
    } else {
4597
0
      cpi->ppi->valid_gm_model_found[update_type] |= is_gm_present;
4598
0
    }
4599
0
  }
4600
0
}
4601
4602
void av1_post_encode_updates(AV1_COMP *const cpi,
4603
0
                             const AV1_COMP_DATA *const cpi_data) {
4604
0
  AV1_PRIMARY *const ppi = cpi->ppi;
4605
0
  AV1_COMMON *const cm = &cpi->common;
4606
4607
0
  update_gm_stats(cpi);
4608
4609
0
#if !CONFIG_REALTIME_ONLY
4610
  // Update the total stats remaining structure.
4611
0
  if (cpi->twopass_frame.this_frame != NULL &&
4612
0
      ppi->twopass.stats_buf_ctx->total_left_stats) {
4613
0
    subtract_stats(ppi->twopass.stats_buf_ctx->total_left_stats,
4614
0
                   cpi->twopass_frame.this_frame);
4615
0
  }
4616
0
#endif
4617
4618
#if CONFIG_OUTPUT_FRAME_SIZE
4619
  FILE *f = fopen("frame_sizes.csv", "a");
4620
  fprintf(f, "%d,", 8 * (int)cpi_data->frame_size);
4621
  fprintf(f, "%d\n", cm->quant_params.base_qindex);
4622
  fclose(f);
4623
#endif  // CONFIG_OUTPUT_FRAME_SIZE
4624
4625
0
  if (!is_stat_generation_stage(cpi) && !cpi->is_dropped_frame) {
4626
    // Before calling refresh_reference_frames(), copy ppi->ref_frame_map_copy
4627
    // to cm->ref_frame_map for frame_parallel_level 2 frame in a parallel
4628
    // encode set of lower layer frames.
4629
    // TODO(Remya): Move ref_frame_map from AV1_COMMON to AV1_PRIMARY to avoid
4630
    // copy.
4631
0
    if (ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] == 2 &&
4632
0
        ppi->gf_group.frame_parallel_level[cpi->gf_frame_index - 1] == 1 &&
4633
0
        ppi->gf_group.update_type[cpi->gf_frame_index - 1] ==
4634
0
            INTNL_ARF_UPDATE) {
4635
0
      memcpy(cm->ref_frame_map, ppi->ref_frame_map_copy,
4636
0
             sizeof(cm->ref_frame_map));
4637
0
    }
4638
0
    refresh_reference_frames(cpi);
4639
    // For frame_parallel_level 1 frame in a parallel encode set of lower layer
4640
    // frames, store the updated cm->ref_frame_map in ppi->ref_frame_map_copy.
4641
0
    if (ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] == 1 &&
4642
0
        ppi->gf_group.update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE) {
4643
0
      memcpy(ppi->ref_frame_map_copy, cm->ref_frame_map,
4644
0
             sizeof(cm->ref_frame_map));
4645
0
    }
4646
0
    av1_rc_postencode_update(cpi, cpi_data->frame_size);
4647
0
  }
4648
4649
0
  if (cpi_data->pop_lookahead == 1) {
4650
0
    av1_lookahead_pop(cpi->ppi->lookahead, cpi_data->flush,
4651
0
                      cpi->compressor_stage);
4652
0
  }
4653
0
  if (cpi->common.show_frame) {
4654
0
    cpi->ppi->ts_start_last_show_frame = cpi_data->ts_frame_start;
4655
0
    cpi->ppi->ts_end_last_show_frame = cpi_data->ts_frame_end;
4656
0
  }
4657
0
  if (ppi->level_params.keep_level_stats && !is_stat_generation_stage(cpi)) {
4658
    // Initialize level info. at the beginning of each sequence.
4659
0
    if (cm->current_frame.frame_type == KEY_FRAME &&
4660
0
        ppi->gf_group.refbuf_state[cpi->gf_frame_index] == REFBUF_RESET) {
4661
0
      av1_init_level_info(cpi);
4662
0
    }
4663
0
    av1_update_level_info(cpi, cpi_data->frame_size, cpi_data->ts_frame_start,
4664
0
                          cpi_data->ts_frame_end);
4665
0
  }
4666
4667
0
  if (!is_stat_generation_stage(cpi)) {
4668
0
#if !CONFIG_REALTIME_ONLY
4669
0
    if (!has_no_stats_stage(cpi)) av1_twopass_postencode_update(cpi);
4670
0
#endif
4671
0
    update_fb_of_context_type(cpi, ppi->fb_of_context_type);
4672
0
    update_rc_counts(cpi);
4673
0
    update_end_of_frame_stats(cpi);
4674
0
  }
4675
4676
#if CONFIG_THREE_PASS
4677
  if (cpi->oxcf.pass == AOM_RC_THIRD_PASS && cpi->third_pass_ctx) {
4678
    av1_pop_third_pass_info(cpi->third_pass_ctx);
4679
  }
4680
#endif
4681
4682
0
  if (ppi->rtc_ref.set_ref_frame_config && !cpi->is_dropped_frame) {
4683
0
    av1_svc_update_buffer_slot_refreshed(cpi);
4684
0
    av1_svc_set_reference_was_previous(cpi);
4685
0
  }
4686
4687
0
  if (ppi->use_svc) av1_save_layer_context(cpi);
4688
4689
  // Note *size = 0 indicates a dropped frame for which psnr is not calculated
4690
0
  if (ppi->b_calculate_psnr && cpi_data->frame_size > 0) {
4691
0
    if (cm->show_existing_frame ||
4692
0
        (!is_stat_generation_stage(cpi) && cm->show_frame)) {
4693
0
      generate_psnr_packet(cpi);
4694
0
    }
4695
0
  }
4696
4697
#if CONFIG_INTERNAL_STATS
4698
  if (!is_stat_generation_stage(cpi)) {
4699
    compute_internal_stats(cpi, (int)cpi_data->frame_size);
4700
  }
4701
#endif  // CONFIG_INTERNAL_STATS
4702
4703
#if CONFIG_THREE_PASS
4704
  // Write frame info. Subtract 1 from frame index since if was incremented in
4705
  // update_rc_counts.
4706
  av1_write_second_pass_per_frame_info(cpi, cpi->gf_frame_index - 1);
4707
#endif
4708
0
}
4709
4710
0
int av1_get_compressed_data(AV1_COMP *cpi, AV1_COMP_DATA *const cpi_data) {
4711
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
4712
0
  AV1_COMMON *const cm = &cpi->common;
4713
4714
  // The jmp_buf is valid only for the duration of the function that calls
4715
  // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
4716
  // before it returns.
4717
0
  if (setjmp(cm->error->jmp)) {
4718
0
    cm->error->setjmp = 0;
4719
0
    return cm->error->error_code;
4720
0
  }
4721
0
  cm->error->setjmp = 1;
4722
4723
#if CONFIG_INTERNAL_STATS
4724
  cpi->frame_recode_hits = 0;
4725
  cpi->time_compress_data = 0;
4726
  cpi->bytes = 0;
4727
#endif
4728
#if CONFIG_ENTROPY_STATS
4729
  if (cpi->compressor_stage == ENCODE_STAGE) {
4730
    av1_zero(cpi->counts);
4731
  }
4732
#endif
4733
4734
#if CONFIG_BITSTREAM_DEBUG
4735
  assert(cpi->oxcf.max_threads <= 1 &&
4736
         "bitstream debug tool does not support multithreading");
4737
  bitstream_queue_record_write();
4738
4739
  if (cm->seq_params->order_hint_info.enable_order_hint) {
4740
    aom_bitstream_queue_set_frame_write(cm->current_frame.order_hint * 2 +
4741
                                        cm->show_frame);
4742
  } else {
4743
    // This is currently used in RTC encoding. cm->show_frame is always 1.
4744
    aom_bitstream_queue_set_frame_write(cm->current_frame.frame_number);
4745
  }
4746
#endif
4747
0
  if (cpi->ppi->use_svc) {
4748
0
    av1_one_pass_cbr_svc_start_layer(cpi);
4749
0
  }
4750
4751
0
  cpi->is_dropped_frame = false;
4752
0
  cm->showable_frame = 0;
4753
0
  cpi_data->frame_size = 0;
4754
0
  cpi->available_bs_size = cpi_data->cx_data_sz;
4755
#if CONFIG_INTERNAL_STATS
4756
  struct aom_usec_timer cmptimer;
4757
  aom_usec_timer_start(&cmptimer);
4758
#endif
4759
0
  av1_set_high_precision_mv(cpi, 1, 0);
4760
4761
  // Normal defaults
4762
0
  cm->features.refresh_frame_context =
4763
0
      oxcf->tool_cfg.frame_parallel_decoding_mode
4764
0
          ? REFRESH_FRAME_CONTEXT_DISABLED
4765
0
          : REFRESH_FRAME_CONTEXT_BACKWARD;
4766
0
  if (oxcf->tile_cfg.enable_large_scale_tile)
4767
0
    cm->features.refresh_frame_context = REFRESH_FRAME_CONTEXT_DISABLED;
4768
4769
0
  if (assign_cur_frame_new_fb(cm) == NULL) {
4770
0
    aom_internal_error(cpi->common.error, AOM_CODEC_ERROR,
4771
0
                       "Failed to allocate new cur_frame");
4772
0
  }
4773
4774
#if CONFIG_COLLECT_COMPONENT_TIMING
4775
  // Accumulate 2nd pass time in 2-pass case or 1 pass time in 1-pass case.
4776
  if (cpi->oxcf.pass == 2 || cpi->oxcf.pass == 0)
4777
    start_timing(cpi, av1_encode_strategy_time);
4778
#endif
4779
4780
0
  const int result = av1_encode_strategy(
4781
0
      cpi, &cpi_data->frame_size, cpi_data->cx_data, cpi_data->cx_data_sz,
4782
0
      &cpi_data->lib_flags, &cpi_data->ts_frame_start, &cpi_data->ts_frame_end,
4783
0
      cpi_data->timestamp_ratio, &cpi_data->pop_lookahead, cpi_data->flush);
4784
4785
#if CONFIG_COLLECT_COMPONENT_TIMING
4786
  if (cpi->oxcf.pass == 2 || cpi->oxcf.pass == 0)
4787
    end_timing(cpi, av1_encode_strategy_time);
4788
4789
  // Print out timing information.
4790
  // Note: Use "cpi->frame_component_time[0] > 100 us" to avoid showing of
4791
  // show_existing_frame and lag-in-frames.
4792
  if ((cpi->oxcf.pass == 2 || cpi->oxcf.pass == 0) &&
4793
      cpi->frame_component_time[0] > 100) {
4794
    int i;
4795
    uint64_t frame_total = 0, total = 0;
4796
    const GF_GROUP *const gf_group = &cpi->ppi->gf_group;
4797
    FRAME_UPDATE_TYPE frame_update_type =
4798
        get_frame_update_type(gf_group, cpi->gf_frame_index);
4799
4800
    fprintf(stderr,
4801
            "\n Frame number: %d, Frame type: %s, Show Frame: %d, Frame Update "
4802
            "Type: %d, Q: %d\n",
4803
            cm->current_frame.frame_number,
4804
            get_frame_type_enum(cm->current_frame.frame_type), cm->show_frame,
4805
            frame_update_type, cm->quant_params.base_qindex);
4806
    for (i = 0; i < kTimingComponents; i++) {
4807
      cpi->component_time[i] += cpi->frame_component_time[i];
4808
      // Use av1_encode_strategy_time (i = 0) as the total time.
4809
      if (i == 0) {
4810
        frame_total = cpi->frame_component_time[0];
4811
        total = cpi->component_time[0];
4812
      }
4813
      fprintf(stderr,
4814
              " %50s:  %15" PRId64 " us [%6.2f%%] (total: %15" PRId64
4815
              " us [%6.2f%%])\n",
4816
              get_component_name(i), cpi->frame_component_time[i],
4817
              (float)((float)cpi->frame_component_time[i] * 100.0 /
4818
                      (float)frame_total),
4819
              cpi->component_time[i],
4820
              (float)((float)cpi->component_time[i] * 100.0 / (float)total));
4821
      cpi->frame_component_time[i] = 0;
4822
    }
4823
  }
4824
#endif
4825
4826
  // Reset the flag to 0 afer encoding.
4827
0
  cpi->rc.use_external_qp_one_pass = 0;
4828
4829
0
  if (result == -1) {
4830
0
    cm->error->setjmp = 0;
4831
    // Returning -1 indicates no frame encoded; more input is required
4832
0
    return -1;
4833
0
  }
4834
0
  if (result != AOM_CODEC_OK) {
4835
0
    aom_internal_error(cpi->common.error, AOM_CODEC_ERROR,
4836
0
                       "Failed to encode frame");
4837
0
  }
4838
#if CONFIG_INTERNAL_STATS
4839
  aom_usec_timer_mark(&cmptimer);
4840
  cpi->time_compress_data += aom_usec_timer_elapsed(&cmptimer);
4841
#endif  // CONFIG_INTERNAL_STATS
4842
4843
#if CONFIG_SPEED_STATS
4844
  if (!is_stat_generation_stage(cpi) && !cm->show_existing_frame) {
4845
    cpi->tx_search_count += cpi->td.mb.txfm_search_info.tx_search_count;
4846
    cpi->td.mb.txfm_search_info.tx_search_count = 0;
4847
  }
4848
#endif  // CONFIG_SPEED_STATS
4849
4850
0
  cm->error->setjmp = 0;
4851
0
  return AOM_CODEC_OK;
4852
0
}
4853
4854
// Populates cpi->scaled_ref_buf corresponding to frames in a parallel encode
4855
// set. Also sets the bitmask 'ref_buffers_used_map'.
4856
0
static void scale_references_fpmt(AV1_COMP *cpi, int *ref_buffers_used_map) {
4857
0
  AV1_COMMON *cm = &cpi->common;
4858
0
  MV_REFERENCE_FRAME ref_frame;
4859
4860
0
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
4861
    // Need to convert from AOM_REFFRAME to index into ref_mask (subtract 1).
4862
0
    if (cpi->ref_frame_flags & av1_ref_frame_flag_list[ref_frame]) {
4863
0
      const YV12_BUFFER_CONFIG *const ref =
4864
0
          get_ref_frame_yv12_buf(cm, ref_frame);
4865
4866
0
      if (ref == NULL) {
4867
0
        cpi->scaled_ref_buf[ref_frame - 1] = NULL;
4868
0
        continue;
4869
0
      }
4870
4871
      // FPMT does not support scaling yet.
4872
0
      assert(ref->y_crop_width == cm->width &&
4873
0
             ref->y_crop_height == cm->height);
4874
4875
0
      RefCntBuffer *buf = get_ref_frame_buf(cm, ref_frame);
4876
0
      cpi->scaled_ref_buf[ref_frame - 1] = buf;
4877
0
      for (int i = 0; i < cm->buffer_pool->num_frame_bufs; ++i) {
4878
0
        if (&cm->buffer_pool->frame_bufs[i] == buf) {
4879
0
          *ref_buffers_used_map |= (1 << i);
4880
0
        }
4881
0
      }
4882
0
    } else {
4883
0
      if (!has_no_stats_stage(cpi)) cpi->scaled_ref_buf[ref_frame - 1] = NULL;
4884
0
    }
4885
0
  }
4886
0
}
4887
4888
// Increments the ref_count of frame buffers referenced by cpi->scaled_ref_buf
4889
// corresponding to frames in a parallel encode set.
4890
static void increment_scaled_ref_counts_fpmt(BufferPool *buffer_pool,
4891
0
                                             int ref_buffers_used_map) {
4892
0
  for (int i = 0; i < buffer_pool->num_frame_bufs; ++i) {
4893
0
    if (ref_buffers_used_map & (1 << i)) {
4894
0
      ++buffer_pool->frame_bufs[i].ref_count;
4895
0
    }
4896
0
  }
4897
0
}
4898
4899
// Releases cpi->scaled_ref_buf corresponding to frames in a parallel encode
4900
// set.
4901
0
void av1_release_scaled_references_fpmt(AV1_COMP *cpi) {
4902
  // TODO(isbs): only refresh the necessary frames, rather than all of them
4903
0
  for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
4904
0
    RefCntBuffer *const buf = cpi->scaled_ref_buf[i];
4905
0
    if (buf != NULL) {
4906
0
      cpi->scaled_ref_buf[i] = NULL;
4907
0
    }
4908
0
  }
4909
0
}
4910
4911
// Decrements the ref_count of frame buffers referenced by cpi->scaled_ref_buf
4912
// corresponding to frames in a parallel encode set.
4913
void av1_decrement_ref_counts_fpmt(BufferPool *buffer_pool,
4914
0
                                   int ref_buffers_used_map) {
4915
0
  for (int i = 0; i < buffer_pool->num_frame_bufs; ++i) {
4916
0
    if (ref_buffers_used_map & (1 << i)) {
4917
0
      --buffer_pool->frame_bufs[i].ref_count;
4918
0
    }
4919
0
  }
4920
0
}
4921
4922
// Initialize parallel frame contexts with screen content decisions.
4923
0
void av1_init_sc_decisions(AV1_PRIMARY *const ppi) {
4924
0
  AV1_COMP *const first_cpi = ppi->cpi;
4925
0
  for (int i = 1; i < ppi->num_fp_contexts; ++i) {
4926
0
    AV1_COMP *cur_cpi = ppi->parallel_cpi[i];
4927
0
    cur_cpi->common.features.allow_screen_content_tools =
4928
0
        first_cpi->common.features.allow_screen_content_tools;
4929
0
    cur_cpi->common.features.allow_intrabc =
4930
0
        first_cpi->common.features.allow_intrabc;
4931
0
    cur_cpi->use_screen_content_tools = first_cpi->use_screen_content_tools;
4932
0
    cur_cpi->is_screen_content_type = first_cpi->is_screen_content_type;
4933
0
  }
4934
0
}
4935
4936
AV1_COMP *av1_get_parallel_frame_enc_data(AV1_PRIMARY *const ppi,
4937
0
                                          AV1_COMP_DATA *const first_cpi_data) {
4938
0
  int cpi_idx = 0;
4939
4940
  // Loop over parallel_cpi to find the cpi that processed the current
4941
  // gf_frame_index ahead of time.
4942
0
  for (int i = 1; i < ppi->num_fp_contexts; i++) {
4943
0
    if (ppi->cpi->gf_frame_index == ppi->parallel_cpi[i]->gf_frame_index) {
4944
0
      cpi_idx = i;
4945
0
      break;
4946
0
    }
4947
0
  }
4948
4949
0
  assert(cpi_idx > 0);
4950
0
  assert(!ppi->parallel_cpi[cpi_idx]->common.show_existing_frame);
4951
4952
  // Release the previously-used frame-buffer.
4953
0
  if (ppi->cpi->common.cur_frame != NULL) {
4954
0
    --ppi->cpi->common.cur_frame->ref_count;
4955
0
    ppi->cpi->common.cur_frame = NULL;
4956
0
  }
4957
4958
  // Swap the appropriate parallel_cpi with the parallel_cpi[0].
4959
0
  ppi->cpi = ppi->parallel_cpi[cpi_idx];
4960
0
  ppi->parallel_cpi[cpi_idx] = ppi->parallel_cpi[0];
4961
0
  ppi->parallel_cpi[0] = ppi->cpi;
4962
4963
  // Copy appropriate parallel_frames_data to local data.
4964
0
  {
4965
0
    AV1_COMP_DATA *data = &ppi->parallel_frames_data[cpi_idx - 1];
4966
0
    assert(data->frame_size > 0);
4967
0
    if (data->frame_size > first_cpi_data->cx_data_sz) {
4968
0
      aom_internal_error(&ppi->error, AOM_CODEC_ERROR,
4969
0
                         "first_cpi_data->cx_data buffer full");
4970
0
    }
4971
4972
0
    first_cpi_data->lib_flags = data->lib_flags;
4973
0
    first_cpi_data->ts_frame_start = data->ts_frame_start;
4974
0
    first_cpi_data->ts_frame_end = data->ts_frame_end;
4975
0
    memcpy(first_cpi_data->cx_data, data->cx_data, data->frame_size);
4976
0
    first_cpi_data->frame_size = data->frame_size;
4977
0
    if (ppi->cpi->common.show_frame) {
4978
0
      first_cpi_data->pop_lookahead = 1;
4979
0
    }
4980
0
  }
4981
4982
0
  return ppi->cpi;
4983
0
}
4984
4985
// Initialises frames belonging to a parallel encode set.
4986
int av1_init_parallel_frame_context(const AV1_COMP_DATA *const first_cpi_data,
4987
                                    AV1_PRIMARY *const ppi,
4988
0
                                    int *ref_buffers_used_map) {
4989
0
  AV1_COMP *const first_cpi = ppi->cpi;
4990
0
  GF_GROUP *const gf_group = &ppi->gf_group;
4991
0
  int gf_index_start = first_cpi->gf_frame_index;
4992
0
  assert(gf_group->frame_parallel_level[gf_index_start] == 1);
4993
0
  int parallel_frame_count = 0;
4994
0
  int cur_frame_num = first_cpi->common.current_frame.frame_number;
4995
0
  int show_frame_count = first_cpi->frame_index_set.show_frame_count;
4996
0
  int frames_since_key = first_cpi->rc.frames_since_key;
4997
0
  int frames_to_key = first_cpi->rc.frames_to_key;
4998
0
  int frames_to_fwd_kf = first_cpi->rc.frames_to_fwd_kf;
4999
0
  int cur_frame_disp = cur_frame_num + gf_group->arf_src_offset[gf_index_start];
5000
0
  const FIRSTPASS_STATS *stats_in = first_cpi->twopass_frame.stats_in;
5001
5002
0
  assert(*ref_buffers_used_map == 0);
5003
5004
  // Release the previously used frame-buffer by a frame_parallel_level 1 frame.
5005
0
  if (first_cpi->common.cur_frame != NULL) {
5006
0
    --first_cpi->common.cur_frame->ref_count;
5007
0
    first_cpi->common.cur_frame = NULL;
5008
0
  }
5009
5010
0
  RefFrameMapPair ref_frame_map_pairs[REF_FRAMES];
5011
0
  RefFrameMapPair first_ref_frame_map_pairs[REF_FRAMES];
5012
0
  init_ref_map_pair(first_cpi, first_ref_frame_map_pairs);
5013
0
  memcpy(ref_frame_map_pairs, first_ref_frame_map_pairs,
5014
0
         sizeof(RefFrameMapPair) * REF_FRAMES);
5015
5016
  // Store the reference refresh index of frame_parallel_level 1 frame in a
5017
  // parallel encode set of lower layer frames.
5018
0
  if (gf_group->update_type[gf_index_start] == INTNL_ARF_UPDATE) {
5019
0
    first_cpi->ref_refresh_index = av1_calc_refresh_idx_for_intnl_arf(
5020
0
        first_cpi, ref_frame_map_pairs, gf_index_start);
5021
0
    assert(first_cpi->ref_refresh_index != INVALID_IDX &&
5022
0
           first_cpi->ref_refresh_index < REF_FRAMES);
5023
0
    first_cpi->refresh_idx_available = true;
5024
    // Update ref_frame_map_pairs.
5025
0
    ref_frame_map_pairs[first_cpi->ref_refresh_index].disp_order =
5026
0
        gf_group->display_idx[gf_index_start];
5027
0
    ref_frame_map_pairs[first_cpi->ref_refresh_index].pyr_level =
5028
0
        gf_group->layer_depth[gf_index_start];
5029
0
  }
5030
5031
  // Set do_frame_data_update flag as false for frame_parallel_level 1 frame.
5032
0
  first_cpi->do_frame_data_update = false;
5033
0
  if (gf_group->arf_src_offset[gf_index_start] == 0) {
5034
0
    first_cpi->time_stamps.prev_ts_start = ppi->ts_start_last_show_frame;
5035
0
    first_cpi->time_stamps.prev_ts_end = ppi->ts_end_last_show_frame;
5036
0
  }
5037
5038
0
  av1_get_ref_frames(first_ref_frame_map_pairs, cur_frame_disp, first_cpi,
5039
0
                     gf_index_start, 1, first_cpi->common.remapped_ref_idx);
5040
5041
0
  scale_references_fpmt(first_cpi, ref_buffers_used_map);
5042
0
  parallel_frame_count++;
5043
5044
  // Iterate through the GF_GROUP to find the remaining frame_parallel_level 2
5045
  // frames which are part of the current parallel encode set and initialize the
5046
  // required cpi elements.
5047
0
  for (int i = gf_index_start + 1; i < gf_group->size; i++) {
5048
    // Update frame counters if previous frame was show frame or show existing
5049
    // frame.
5050
0
    if (gf_group->arf_src_offset[i - 1] == 0) {
5051
0
      cur_frame_num++;
5052
0
      show_frame_count++;
5053
0
      if (frames_to_fwd_kf <= 0)
5054
0
        frames_to_fwd_kf = first_cpi->oxcf.kf_cfg.fwd_kf_dist;
5055
0
      if (frames_to_key) {
5056
0
        frames_since_key++;
5057
0
        frames_to_key--;
5058
0
        frames_to_fwd_kf--;
5059
0
      }
5060
0
      stats_in++;
5061
0
    }
5062
0
    cur_frame_disp = cur_frame_num + gf_group->arf_src_offset[i];
5063
0
    if (gf_group->frame_parallel_level[i] == 2) {
5064
0
      AV1_COMP *cur_cpi = ppi->parallel_cpi[parallel_frame_count];
5065
0
      AV1_COMP_DATA *cur_cpi_data =
5066
0
          &ppi->parallel_frames_data[parallel_frame_count - 1];
5067
0
      cur_cpi->gf_frame_index = i;
5068
0
      cur_cpi->framerate = first_cpi->framerate;
5069
0
      cur_cpi->common.current_frame.frame_number = cur_frame_num;
5070
0
      cur_cpi->common.current_frame.frame_type = gf_group->frame_type[i];
5071
0
      cur_cpi->frame_index_set.show_frame_count = show_frame_count;
5072
0
      cur_cpi->rc.frames_since_key = frames_since_key;
5073
0
      cur_cpi->rc.frames_to_key = frames_to_key;
5074
0
      cur_cpi->rc.frames_to_fwd_kf = frames_to_fwd_kf;
5075
0
      cur_cpi->rc.active_worst_quality = first_cpi->rc.active_worst_quality;
5076
0
      cur_cpi->rc.avg_frame_bandwidth = first_cpi->rc.avg_frame_bandwidth;
5077
0
      cur_cpi->rc.max_frame_bandwidth = first_cpi->rc.max_frame_bandwidth;
5078
0
      cur_cpi->rc.min_frame_bandwidth = first_cpi->rc.min_frame_bandwidth;
5079
0
      cur_cpi->rc.intervals_till_gf_calculate_due =
5080
0
          first_cpi->rc.intervals_till_gf_calculate_due;
5081
0
      cur_cpi->mv_search_params.max_mv_magnitude =
5082
0
          first_cpi->mv_search_params.max_mv_magnitude;
5083
0
      if (gf_group->update_type[cur_cpi->gf_frame_index] == INTNL_ARF_UPDATE) {
5084
0
        cur_cpi->common.lf.mode_ref_delta_enabled = 1;
5085
0
      }
5086
0
      cur_cpi->do_frame_data_update = false;
5087
      // Initialize prev_ts_start and prev_ts_end for show frame(s) and show
5088
      // existing frame(s).
5089
0
      if (gf_group->arf_src_offset[i] == 0) {
5090
        // Choose source of prev frame.
5091
0
        int src_index = gf_group->src_offset[i];
5092
0
        struct lookahead_entry *prev_source = av1_lookahead_peek(
5093
0
            ppi->lookahead, src_index - 1, cur_cpi->compressor_stage);
5094
        // Save timestamps of prev frame.
5095
0
        cur_cpi->time_stamps.prev_ts_start = prev_source->ts_start;
5096
0
        cur_cpi->time_stamps.prev_ts_end = prev_source->ts_end;
5097
0
      }
5098
0
      cur_cpi->time_stamps.first_ts_start =
5099
0
          first_cpi->time_stamps.first_ts_start;
5100
5101
0
      memcpy(cur_cpi->common.ref_frame_map, first_cpi->common.ref_frame_map,
5102
0
             sizeof(first_cpi->common.ref_frame_map));
5103
0
      cur_cpi_data->lib_flags = 0;
5104
0
      cur_cpi_data->timestamp_ratio = first_cpi_data->timestamp_ratio;
5105
0
      cur_cpi_data->flush = first_cpi_data->flush;
5106
0
      cur_cpi_data->frame_size = 0;
5107
0
      if (gf_group->update_type[gf_index_start] == INTNL_ARF_UPDATE) {
5108
        // If the first frame in a parallel encode set is INTNL_ARF_UPDATE
5109
        // frame, initialize lib_flags of frame_parallel_level 2 frame in the
5110
        // set with that of frame_parallel_level 1 frame.
5111
0
        cur_cpi_data->lib_flags = first_cpi_data->lib_flags;
5112
        // Store the reference refresh index of frame_parallel_level 2 frame in
5113
        // a parallel encode set of lower layer frames.
5114
0
        cur_cpi->ref_refresh_index =
5115
0
            av1_calc_refresh_idx_for_intnl_arf(cur_cpi, ref_frame_map_pairs, i);
5116
0
        cur_cpi->refresh_idx_available = true;
5117
        // Skip the reference frame which will be refreshed by
5118
        // frame_parallel_level 1 frame in a parallel encode set of lower layer
5119
        // frames.
5120
0
        cur_cpi->ref_idx_to_skip = first_cpi->ref_refresh_index;
5121
0
      } else {
5122
0
        cur_cpi->ref_idx_to_skip = INVALID_IDX;
5123
0
        cur_cpi->ref_refresh_index = INVALID_IDX;
5124
0
        cur_cpi->refresh_idx_available = false;
5125
0
      }
5126
0
      cur_cpi->twopass_frame.stats_in = stats_in;
5127
5128
0
      av1_get_ref_frames(first_ref_frame_map_pairs, cur_frame_disp, cur_cpi, i,
5129
0
                         1, cur_cpi->common.remapped_ref_idx);
5130
0
      scale_references_fpmt(cur_cpi, ref_buffers_used_map);
5131
0
      parallel_frame_count++;
5132
0
    }
5133
5134
    // Set do_frame_data_update to true for the last frame_parallel_level 2
5135
    // frame in the current parallel encode set.
5136
0
    if (i == (gf_group->size - 1) ||
5137
0
        (gf_group->frame_parallel_level[i + 1] == 0 &&
5138
0
         (gf_group->update_type[i + 1] == ARF_UPDATE ||
5139
0
          gf_group->update_type[i + 1] == INTNL_ARF_UPDATE)) ||
5140
0
        gf_group->frame_parallel_level[i + 1] == 1) {
5141
0
      ppi->parallel_cpi[parallel_frame_count - 1]->do_frame_data_update = true;
5142
0
      break;
5143
0
    }
5144
0
  }
5145
5146
0
  increment_scaled_ref_counts_fpmt(first_cpi->common.buffer_pool,
5147
0
                                   *ref_buffers_used_map);
5148
5149
  // Return the number of frames in the parallel encode set.
5150
0
  return parallel_frame_count;
5151
0
}
5152
5153
0
int av1_get_preview_raw_frame(AV1_COMP *cpi, YV12_BUFFER_CONFIG *dest) {
5154
0
  AV1_COMMON *cm = &cpi->common;
5155
0
  if (!cm->show_frame) {
5156
0
    return -1;
5157
0
  } else {
5158
0
    int ret;
5159
0
    if (cm->cur_frame != NULL && !cpi->oxcf.algo_cfg.skip_postproc_filtering) {
5160
0
      *dest = cm->cur_frame->buf;
5161
0
      dest->y_width = cm->width;
5162
0
      dest->y_height = cm->height;
5163
0
      dest->uv_width = cm->width >> cm->seq_params->subsampling_x;
5164
0
      dest->uv_height = cm->height >> cm->seq_params->subsampling_y;
5165
0
      ret = 0;
5166
0
    } else {
5167
0
      ret = -1;
5168
0
    }
5169
0
    return ret;
5170
0
  }
5171
0
}
5172
5173
0
int av1_get_last_show_frame(AV1_COMP *cpi, YV12_BUFFER_CONFIG *frame) {
5174
0
  if (cpi->last_show_frame_buf == NULL ||
5175
0
      cpi->oxcf.algo_cfg.skip_postproc_filtering)
5176
0
    return -1;
5177
5178
0
  *frame = cpi->last_show_frame_buf->buf;
5179
0
  return 0;
5180
0
}
5181
5182
aom_codec_err_t av1_copy_new_frame_enc(AV1_COMMON *cm,
5183
                                       YV12_BUFFER_CONFIG *new_frame,
5184
0
                                       YV12_BUFFER_CONFIG *sd) {
5185
0
  const int num_planes = av1_num_planes(cm);
5186
0
  if (!equal_dimensions_and_border(new_frame, sd))
5187
0
    aom_internal_error(cm->error, AOM_CODEC_ERROR,
5188
0
                       "Incorrect buffer dimensions");
5189
0
  else
5190
0
    aom_yv12_copy_frame(new_frame, sd, num_planes);
5191
5192
0
  return cm->error->error_code;
5193
0
}
5194
5195
int av1_set_internal_size(AV1EncoderConfig *const oxcf,
5196
                          ResizePendingParams *resize_pending_params,
5197
                          AOM_SCALING_MODE horiz_mode,
5198
0
                          AOM_SCALING_MODE vert_mode) {
5199
0
  int hr = 0, hs = 0, vr = 0, vs = 0;
5200
5201
  // Checks for invalid AOM_SCALING_MODE values.
5202
0
  if (horiz_mode > AOME_ONETHREE || vert_mode > AOME_ONETHREE) return -1;
5203
5204
0
  Scale2Ratio(horiz_mode, &hr, &hs);
5205
0
  Scale2Ratio(vert_mode, &vr, &vs);
5206
5207
  // always go to the next whole number
5208
0
  resize_pending_params->width = (hs - 1 + oxcf->frm_dim_cfg.width * hr) / hs;
5209
0
  resize_pending_params->height = (vs - 1 + oxcf->frm_dim_cfg.height * vr) / vs;
5210
5211
0
  if (horiz_mode != AOME_NORMAL || vert_mode != AOME_NORMAL) {
5212
0
    oxcf->resize_cfg.resize_mode = RESIZE_FIXED;
5213
0
    oxcf->algo_cfg.enable_tpl_model = 0;
5214
0
  }
5215
0
  return 0;
5216
0
}
5217
5218
0
int av1_get_quantizer(AV1_COMP *cpi) {
5219
0
  return cpi->common.quant_params.base_qindex;
5220
0
}
5221
5222
int av1_convert_sect5obus_to_annexb(uint8_t *buffer, size_t buffer_size,
5223
0
                                    size_t *frame_size) {
5224
0
  assert(*frame_size <= buffer_size);
5225
0
  size_t output_size = 0;
5226
0
  size_t remaining_size = *frame_size;
5227
0
  uint8_t *buff_ptr = buffer;
5228
5229
  // go through each OBUs
5230
0
  while (remaining_size > 0) {
5231
0
    uint8_t saved_obu_header[2];
5232
0
    uint64_t obu_payload_size;
5233
0
    size_t length_of_payload_size;
5234
0
    size_t length_of_obu_size;
5235
0
    const uint32_t obu_header_size = (buff_ptr[0] >> 2) & 0x1 ? 2 : 1;
5236
0
    size_t obu_bytes_read = obu_header_size;  // bytes read for current obu
5237
5238
    // save the obu header (1 or 2 bytes)
5239
0
    memcpy(saved_obu_header, buff_ptr, obu_header_size);
5240
    // clear the obu_has_size_field
5241
0
    saved_obu_header[0] &= ~0x2;
5242
5243
    // get the payload_size and length of payload_size
5244
0
    if (aom_uleb_decode(buff_ptr + obu_header_size,
5245
0
                        remaining_size - obu_header_size, &obu_payload_size,
5246
0
                        &length_of_payload_size) != 0) {
5247
0
      return AOM_CODEC_ERROR;
5248
0
    }
5249
0
    obu_bytes_read += length_of_payload_size;
5250
5251
    // calculate the length of size of the obu header plus payload
5252
0
    const uint64_t obu_size = obu_header_size + obu_payload_size;
5253
0
    length_of_obu_size = aom_uleb_size_in_bytes(obu_size);
5254
5255
0
    if (length_of_obu_size + obu_header_size >
5256
0
        buffer_size - output_size - (remaining_size - obu_bytes_read)) {
5257
0
      return AOM_CODEC_ERROR;
5258
0
    }
5259
    // move the rest of data to new location
5260
0
    memmove(buff_ptr + length_of_obu_size + obu_header_size,
5261
0
            buff_ptr + obu_bytes_read, remaining_size - obu_bytes_read);
5262
0
    obu_bytes_read += (size_t)obu_payload_size;
5263
5264
    // write the new obu size
5265
0
    size_t coded_obu_size;
5266
0
    if (aom_uleb_encode(obu_size, length_of_obu_size, buff_ptr,
5267
0
                        &coded_obu_size) != 0 ||
5268
0
        coded_obu_size != length_of_obu_size) {
5269
0
      return AOM_CODEC_ERROR;
5270
0
    }
5271
5272
    // write the saved (modified) obu_header following obu size
5273
0
    memcpy(buff_ptr + length_of_obu_size, saved_obu_header, obu_header_size);
5274
5275
0
    remaining_size -= obu_bytes_read;
5276
0
    buff_ptr += length_of_obu_size + (size_t)obu_size;
5277
0
    output_size += length_of_obu_size + (size_t)obu_size;
5278
0
  }
5279
5280
0
  *frame_size = output_size;
5281
0
  return AOM_CODEC_OK;
5282
0
}
5283
5284
static void rtc_set_updates_ref_frame_config(
5285
    ExtRefreshFrameFlagsInfo *const ext_refresh_frame_flags,
5286
0
    RTC_REF *const rtc_ref) {
5287
0
  ext_refresh_frame_flags->update_pending = 1;
5288
0
  ext_refresh_frame_flags->last_frame = rtc_ref->refresh[rtc_ref->ref_idx[0]];
5289
0
  ext_refresh_frame_flags->golden_frame = rtc_ref->refresh[rtc_ref->ref_idx[3]];
5290
0
  ext_refresh_frame_flags->bwd_ref_frame =
5291
0
      rtc_ref->refresh[rtc_ref->ref_idx[4]];
5292
0
  ext_refresh_frame_flags->alt2_ref_frame =
5293
0
      rtc_ref->refresh[rtc_ref->ref_idx[5]];
5294
0
  ext_refresh_frame_flags->alt_ref_frame =
5295
0
      rtc_ref->refresh[rtc_ref->ref_idx[6]];
5296
0
  rtc_ref->non_reference_frame = 1;
5297
0
  for (int i = 0; i < REF_FRAMES; i++) {
5298
0
    if (rtc_ref->refresh[i] == 1) {
5299
0
      rtc_ref->non_reference_frame = 0;
5300
0
      break;
5301
0
    }
5302
0
  }
5303
0
}
5304
5305
0
static int rtc_set_references_external_ref_frame_config(AV1_COMP *cpi) {
5306
  // LAST_FRAME (0), LAST2_FRAME(1), LAST3_FRAME(2), GOLDEN_FRAME(3),
5307
  // BWDREF_FRAME(4), ALTREF2_FRAME(5), ALTREF_FRAME(6).
5308
0
  int ref = AOM_REFFRAME_ALL;
5309
0
  for (int i = 0; i < INTER_REFS_PER_FRAME; i++) {
5310
0
    if (!cpi->ppi->rtc_ref.reference[i]) ref ^= (1 << i);
5311
0
  }
5312
0
  return ref;
5313
0
}
5314
5315
0
void av1_apply_encoding_flags(AV1_COMP *cpi, aom_enc_frame_flags_t flags) {
5316
  // TODO(yunqingwang): For what references to use, external encoding flags
5317
  // should be consistent with internal reference frame selection. Need to
5318
  // ensure that there is not conflict between the two. In AV1 encoder, the
5319
  // priority rank for 7 reference frames are: LAST, ALTREF, LAST2, LAST3,
5320
  // GOLDEN, BWDREF, ALTREF2.
5321
5322
0
  ExternalFlags *const ext_flags = &cpi->ext_flags;
5323
0
  ExtRefreshFrameFlagsInfo *const ext_refresh_frame_flags =
5324
0
      &ext_flags->refresh_frame;
5325
0
  ext_flags->ref_frame_flags = AOM_REFFRAME_ALL;
5326
0
  if (flags &
5327
0
      (AOM_EFLAG_NO_REF_LAST | AOM_EFLAG_NO_REF_LAST2 | AOM_EFLAG_NO_REF_LAST3 |
5328
0
       AOM_EFLAG_NO_REF_GF | AOM_EFLAG_NO_REF_ARF | AOM_EFLAG_NO_REF_BWD |
5329
0
       AOM_EFLAG_NO_REF_ARF2)) {
5330
0
    int ref = AOM_REFFRAME_ALL;
5331
5332
0
    if (flags & AOM_EFLAG_NO_REF_LAST) ref ^= AOM_LAST_FLAG;
5333
0
    if (flags & AOM_EFLAG_NO_REF_LAST2) ref ^= AOM_LAST2_FLAG;
5334
0
    if (flags & AOM_EFLAG_NO_REF_LAST3) ref ^= AOM_LAST3_FLAG;
5335
5336
0
    if (flags & AOM_EFLAG_NO_REF_GF) ref ^= AOM_GOLD_FLAG;
5337
5338
0
    if (flags & AOM_EFLAG_NO_REF_ARF) {
5339
0
      ref ^= AOM_ALT_FLAG;
5340
0
      ref ^= AOM_BWD_FLAG;
5341
0
      ref ^= AOM_ALT2_FLAG;
5342
0
    } else {
5343
0
      if (flags & AOM_EFLAG_NO_REF_BWD) ref ^= AOM_BWD_FLAG;
5344
0
      if (flags & AOM_EFLAG_NO_REF_ARF2) ref ^= AOM_ALT2_FLAG;
5345
0
    }
5346
5347
0
    av1_use_as_reference(&ext_flags->ref_frame_flags, ref);
5348
0
  } else {
5349
0
    if (cpi->ppi->rtc_ref.set_ref_frame_config) {
5350
0
      int ref = rtc_set_references_external_ref_frame_config(cpi);
5351
0
      av1_use_as_reference(&ext_flags->ref_frame_flags, ref);
5352
0
    }
5353
0
  }
5354
5355
0
  if (flags &
5356
0
      (AOM_EFLAG_NO_UPD_LAST | AOM_EFLAG_NO_UPD_GF | AOM_EFLAG_NO_UPD_ARF)) {
5357
0
    int upd = AOM_REFFRAME_ALL;
5358
5359
    // Refreshing LAST/LAST2/LAST3 is handled by 1 common flag.
5360
0
    if (flags & AOM_EFLAG_NO_UPD_LAST) upd ^= AOM_LAST_FLAG;
5361
5362
0
    if (flags & AOM_EFLAG_NO_UPD_GF) upd ^= AOM_GOLD_FLAG;
5363
5364
0
    if (flags & AOM_EFLAG_NO_UPD_ARF) {
5365
0
      upd ^= AOM_ALT_FLAG;
5366
0
      upd ^= AOM_BWD_FLAG;
5367
0
      upd ^= AOM_ALT2_FLAG;
5368
0
    }
5369
5370
0
    ext_refresh_frame_flags->last_frame = (upd & AOM_LAST_FLAG) != 0;
5371
0
    ext_refresh_frame_flags->golden_frame = (upd & AOM_GOLD_FLAG) != 0;
5372
0
    ext_refresh_frame_flags->alt_ref_frame = (upd & AOM_ALT_FLAG) != 0;
5373
0
    ext_refresh_frame_flags->bwd_ref_frame = (upd & AOM_BWD_FLAG) != 0;
5374
0
    ext_refresh_frame_flags->alt2_ref_frame = (upd & AOM_ALT2_FLAG) != 0;
5375
0
    ext_refresh_frame_flags->update_pending = 1;
5376
0
  } else {
5377
0
    if (cpi->ppi->rtc_ref.set_ref_frame_config)
5378
0
      rtc_set_updates_ref_frame_config(ext_refresh_frame_flags,
5379
0
                                       &cpi->ppi->rtc_ref);
5380
0
    else
5381
0
      ext_refresh_frame_flags->update_pending = 0;
5382
0
  }
5383
5384
0
  ext_flags->use_ref_frame_mvs = cpi->oxcf.tool_cfg.enable_ref_frame_mvs &
5385
0
                                 ((flags & AOM_EFLAG_NO_REF_FRAME_MVS) == 0);
5386
0
  ext_flags->use_error_resilient = cpi->oxcf.tool_cfg.error_resilient_mode |
5387
0
                                   ((flags & AOM_EFLAG_ERROR_RESILIENT) != 0);
5388
0
  ext_flags->use_s_frame =
5389
0
      cpi->oxcf.kf_cfg.enable_sframe | ((flags & AOM_EFLAG_SET_S_FRAME) != 0);
5390
0
  ext_flags->use_primary_ref_none =
5391
0
      (flags & AOM_EFLAG_SET_PRIMARY_REF_NONE) != 0;
5392
5393
0
  if (flags & AOM_EFLAG_NO_UPD_ENTROPY) {
5394
0
    update_entropy(&ext_flags->refresh_frame_context,
5395
0
                   &ext_flags->refresh_frame_context_pending, 0);
5396
0
  }
5397
0
}
5398
5399
0
aom_fixed_buf_t *av1_get_global_headers(AV1_PRIMARY *ppi) {
5400
0
  if (!ppi) return NULL;
5401
5402
0
  uint8_t header_buf[512] = { 0 };
5403
0
  const uint32_t sequence_header_size = av1_write_sequence_header_obu(
5404
0
      &ppi->seq_params, &header_buf[0], sizeof(header_buf));
5405
0
  assert(sequence_header_size <= sizeof(header_buf));
5406
0
  if (sequence_header_size == 0) return NULL;
5407
5408
0
  const size_t obu_header_size = 1;
5409
0
  const size_t size_field_size = aom_uleb_size_in_bytes(sequence_header_size);
5410
0
  const size_t payload_offset = obu_header_size + size_field_size;
5411
5412
0
  if (payload_offset + sequence_header_size > sizeof(header_buf)) return NULL;
5413
0
  memmove(&header_buf[payload_offset], &header_buf[0], sequence_header_size);
5414
5415
0
  if (av1_write_obu_header(&ppi->level_params, &ppi->cpi->frame_header_count,
5416
0
                           OBU_SEQUENCE_HEADER,
5417
0
                           ppi->seq_params.has_nonzero_operating_point_idc,
5418
                           /*is_layer_specific_obu=*/false, 0,
5419
0
                           &header_buf[0]) != obu_header_size) {
5420
0
    return NULL;
5421
0
  }
5422
5423
0
  size_t coded_size_field_size = 0;
5424
0
  if (aom_uleb_encode(sequence_header_size, size_field_size,
5425
0
                      &header_buf[obu_header_size],
5426
0
                      &coded_size_field_size) != 0) {
5427
0
    return NULL;
5428
0
  }
5429
0
  assert(coded_size_field_size == size_field_size);
5430
5431
0
  aom_fixed_buf_t *global_headers =
5432
0
      (aom_fixed_buf_t *)malloc(sizeof(*global_headers));
5433
0
  if (!global_headers) return NULL;
5434
5435
0
  const size_t global_header_buf_size =
5436
0
      obu_header_size + size_field_size + sequence_header_size;
5437
5438
0
  global_headers->buf = malloc(global_header_buf_size);
5439
0
  if (!global_headers->buf) {
5440
0
    free(global_headers);
5441
0
    return NULL;
5442
0
  }
5443
5444
0
  memcpy(global_headers->buf, &header_buf[0], global_header_buf_size);
5445
0
  global_headers->sz = global_header_buf_size;
5446
0
  return global_headers;
5447
0
}