Coverage Report

Created: 2026-10-28 07:26

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