Coverage Report

Created: 2025-10-28 07:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libavif/ext/aom/av1/encoder/encode_strategy.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2019, 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 <stdint.h>
13
14
#include "av1/common/blockd.h"
15
#include "config/aom_config.h"
16
#include "config/aom_scale_rtcd.h"
17
18
#include "aom/aom_codec.h"
19
#include "aom/aom_encoder.h"
20
21
#if CONFIG_MISMATCH_DEBUG
22
#include "aom_util/debug_util.h"
23
#endif  // CONFIG_MISMATCH_DEBUG
24
25
#include "av1/common/av1_common_int.h"
26
#include "av1/common/reconinter.h"
27
28
#include "av1/encoder/encoder.h"
29
#include "av1/encoder/encode_strategy.h"
30
#include "av1/encoder/encodeframe.h"
31
#include "av1/encoder/encoder_alloc.h"
32
#include "av1/encoder/firstpass.h"
33
#include "av1/encoder/gop_structure.h"
34
#include "av1/encoder/pass2_strategy.h"
35
#include "av1/encoder/temporal_filter.h"
36
#if CONFIG_THREE_PASS
37
#include "av1/encoder/thirdpass.h"
38
#endif  // CONFIG_THREE_PASS
39
#include "av1/encoder/tpl_model.h"
40
41
#if CONFIG_TUNE_VMAF
42
#include "av1/encoder/tune_vmaf.h"
43
#endif
44
45
#define TEMPORAL_FILTER_KEY_FRAME (CONFIG_REALTIME_ONLY ? 0 : 1)
46
47
static inline void set_refresh_frame_flags(
48
    RefreshFrameInfo *const refresh_frame, bool refresh_gf, bool refresh_bwdref,
49
273k
    bool refresh_arf) {
50
273k
  refresh_frame->golden_frame = refresh_gf;
51
273k
  refresh_frame->bwd_ref_frame = refresh_bwdref;
52
273k
  refresh_frame->alt_ref_frame = refresh_arf;
53
273k
}
54
55
void av1_configure_buffer_updates(AV1_COMP *const cpi,
56
                                  RefreshFrameInfo *const refresh_frame,
57
                                  const FRAME_UPDATE_TYPE type,
58
                                  const REFBUF_STATE refbuf_state,
59
159k
                                  int force_refresh_all) {
60
  // NOTE(weitinglin): Should we define another function to take care of
61
  // cpi->rc.is_$Source_Type to make this function as it is in the comment?
62
159k
  const ExtRefreshFrameFlagsInfo *const ext_refresh_frame_flags =
63
159k
      &cpi->ext_flags.refresh_frame;
64
159k
  cpi->rc.is_src_frame_alt_ref = 0;
65
66
159k
  switch (type) {
67
124k
    case KF_UPDATE:
68
124k
      set_refresh_frame_flags(refresh_frame, true, true, true);
69
124k
      break;
70
71
25.2k
    case LF_UPDATE:
72
25.2k
      set_refresh_frame_flags(refresh_frame, false, false, false);
73
25.2k
      break;
74
75
9.73k
    case GF_UPDATE:
76
9.73k
      set_refresh_frame_flags(refresh_frame, true, false, false);
77
9.73k
      break;
78
79
0
    case OVERLAY_UPDATE:
80
0
      if (refbuf_state == REFBUF_RESET)
81
0
        set_refresh_frame_flags(refresh_frame, true, true, true);
82
0
      else
83
0
        set_refresh_frame_flags(refresh_frame, true, false, false);
84
85
0
      cpi->rc.is_src_frame_alt_ref = 1;
86
0
      break;
87
88
0
    case ARF_UPDATE:
89
      // NOTE: BWDREF does not get updated along with ALTREF_FRAME.
90
0
      if (refbuf_state == REFBUF_RESET)
91
0
        set_refresh_frame_flags(refresh_frame, true, true, true);
92
0
      else
93
0
        set_refresh_frame_flags(refresh_frame, false, false, true);
94
95
0
      break;
96
97
0
    case INTNL_OVERLAY_UPDATE:
98
0
      set_refresh_frame_flags(refresh_frame, false, false, false);
99
0
      cpi->rc.is_src_frame_alt_ref = 1;
100
0
      break;
101
102
0
    case INTNL_ARF_UPDATE:
103
0
      set_refresh_frame_flags(refresh_frame, false, true, false);
104
0
      break;
105
106
0
    default: assert(0); break;
107
159k
  }
108
109
159k
  if (ext_refresh_frame_flags->update_pending &&
110
21.8k
      (!is_stat_generation_stage(cpi))) {
111
21.8k
    set_refresh_frame_flags(refresh_frame,
112
21.8k
                            ext_refresh_frame_flags->golden_frame,
113
21.8k
                            ext_refresh_frame_flags->bwd_ref_frame,
114
21.8k
                            ext_refresh_frame_flags->alt_ref_frame);
115
21.8k
    GF_GROUP *gf_group = &cpi->ppi->gf_group;
116
21.8k
    if (ext_refresh_frame_flags->golden_frame)
117
0
      gf_group->update_type[cpi->gf_frame_index] = GF_UPDATE;
118
21.8k
    if (ext_refresh_frame_flags->alt_ref_frame)
119
0
      gf_group->update_type[cpi->gf_frame_index] = ARF_UPDATE;
120
21.8k
    if (ext_refresh_frame_flags->bwd_ref_frame)
121
0
      gf_group->update_type[cpi->gf_frame_index] = INTNL_ARF_UPDATE;
122
21.8k
  }
123
124
159k
  if (force_refresh_all)
125
92.1k
    set_refresh_frame_flags(refresh_frame, true, true, true);
126
159k
}
127
128
static void set_additional_frame_flags(const AV1_COMMON *const cm,
129
110k
                                       unsigned int *const frame_flags) {
130
110k
  if (frame_is_intra_only(cm)) {
131
82.5k
    *frame_flags |= FRAMEFLAGS_INTRAONLY;
132
82.5k
  }
133
110k
  if (frame_is_sframe(cm)) {
134
0
    *frame_flags |= FRAMEFLAGS_SWITCH;
135
0
  }
136
110k
  if (cm->features.error_resilient_mode) {
137
0
    *frame_flags |= FRAMEFLAGS_ERROR_RESILIENT;
138
0
  }
139
110k
}
140
141
static void set_ext_overrides(AV1_COMMON *const cm,
142
                              EncodeFrameParams *const frame_params,
143
110k
                              ExternalFlags *const ext_flags) {
144
  // Overrides the defaults with the externally supplied values with
145
  // av1_update_reference() and av1_update_entropy() calls
146
  // Note: The overrides are valid only for the next frame passed
147
  // to av1_encode_lowlevel()
148
149
110k
  if (ext_flags->use_s_frame) {
150
0
    frame_params->frame_type = S_FRAME;
151
0
  }
152
153
110k
  if (ext_flags->refresh_frame_context_pending) {
154
0
    cm->features.refresh_frame_context = ext_flags->refresh_frame_context;
155
0
    ext_flags->refresh_frame_context_pending = 0;
156
0
  }
157
110k
  cm->features.allow_ref_frame_mvs = ext_flags->use_ref_frame_mvs;
158
159
110k
  frame_params->error_resilient_mode = ext_flags->use_error_resilient;
160
  // A keyframe is already error resilient and keyframes with
161
  // error_resilient_mode interferes with the use of show_existing_frame
162
  // when forward reference keyframes are enabled.
163
110k
  frame_params->error_resilient_mode &= frame_params->frame_type != KEY_FRAME;
164
  // For bitstream conformance, s-frames must be error-resilient
165
110k
  frame_params->error_resilient_mode |= frame_params->frame_type == S_FRAME;
166
110k
}
167
168
static int choose_primary_ref_frame(
169
110k
    AV1_COMP *const cpi, const EncodeFrameParams *const frame_params) {
170
110k
  const AV1_COMMON *const cm = &cpi->common;
171
172
110k
  const int intra_only = frame_params->frame_type == KEY_FRAME ||
173
27.5k
                         frame_params->frame_type == INTRA_ONLY_FRAME;
174
110k
  if (intra_only || frame_params->error_resilient_mode ||
175
82.5k
      cpi->ext_flags.use_primary_ref_none) {
176
82.5k
    return PRIMARY_REF_NONE;
177
82.5k
  }
178
179
27.5k
#if !CONFIG_REALTIME_ONLY
180
27.5k
  if (cpi->use_ducky_encode) {
181
0
    int wanted_fb = cpi->ppi->gf_group.primary_ref_idx[cpi->gf_frame_index];
182
0
    for (int ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
183
0
      if (get_ref_frame_map_idx(cm, ref_frame) == wanted_fb)
184
0
        return ref_frame - LAST_FRAME;
185
0
    }
186
187
0
    return PRIMARY_REF_NONE;
188
0
  }
189
27.5k
#endif  // !CONFIG_REALTIME_ONLY
190
191
  // In large scale case, always use Last frame's frame contexts.
192
  // Note(yunqing): In other cases, primary_ref_frame is chosen based on
193
  // cpi->ppi->gf_group.layer_depth[cpi->gf_frame_index], which also controls
194
  // frame bit allocation.
195
27.5k
  if (cm->tiles.large_scale) return (LAST_FRAME - LAST_FRAME);
196
197
27.5k
  if (cpi->ppi->use_svc || cpi->ppi->rtc_ref.set_ref_frame_config)
198
0
    return av1_svc_primary_ref_frame(cpi);
199
200
  // Find the most recent reference frame with the same reference type as the
201
  // current frame
202
27.5k
  const int current_ref_type = get_current_frame_ref_type(cpi);
203
27.5k
  int wanted_fb = cpi->ppi->fb_of_context_type[current_ref_type];
204
#if CONFIG_FPMT_TEST
205
  if (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) {
206
    GF_GROUP *const gf_group = &cpi->ppi->gf_group;
207
    if (gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE) {
208
      int frame_level = gf_group->frame_parallel_level[cpi->gf_frame_index];
209
      // Book keep wanted_fb of frame_parallel_level 1 frame in an FP2 set.
210
      if (frame_level == 1) {
211
        cpi->wanted_fb = wanted_fb;
212
      }
213
      // Use the wanted_fb of level 1 frame in an FP2 for a level 2 frame in the
214
      // set.
215
      if (frame_level == 2 &&
216
          gf_group->update_type[cpi->gf_frame_index - 1] == INTNL_ARF_UPDATE) {
217
        assert(gf_group->frame_parallel_level[cpi->gf_frame_index - 1] == 1);
218
        wanted_fb = cpi->wanted_fb;
219
      }
220
    }
221
  }
222
#endif  // CONFIG_FPMT_TEST
223
27.5k
  int primary_ref_frame = PRIMARY_REF_NONE;
224
220k
  for (int ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
225
192k
    if (get_ref_frame_map_idx(cm, ref_frame) == wanted_fb) {
226
57.9k
      primary_ref_frame = ref_frame - LAST_FRAME;
227
57.9k
    }
228
192k
  }
229
230
27.5k
  return primary_ref_frame;
231
27.5k
}
232
233
129k
static void adjust_frame_rate(AV1_COMP *cpi, int64_t ts_start, int64_t ts_end) {
234
129k
  TimeStamps *time_stamps = &cpi->time_stamps;
235
129k
  int64_t this_duration;
236
129k
  int step = 0;
237
238
  // Clear down mmx registers
239
240
129k
  if (is_one_pass_rt_params(cpi) ||
241
107k
      (cpi->ppi->use_svc && cpi->ppi->rtc_ref.set_ref_frame_config &&
242
21.8k
       cpi->svc.number_spatial_layers > 1)) {
243
    // ts_start is the timestamp for the current frame and ts_end is the
244
    // expected next timestamp given the duration passed into codec_encode().
245
    // See the setting in encoder_encode() in av1_cx_iface.c:
246
    // ts_start = timebase_units_to_ticks(cpi_data.timestamp_ratio, ptsvol),
247
    // ts_end = timebase_units_to_ticks(cpi_data.timestamp_ratio, ptsvol +
248
    // duration). So the difference ts_end - ts_start is the duration passed
249
    // in by the user. For RTC or spatial layers SVC set the framerate based
250
    // directly on the duration, and bypass the adjustments below.
251
21.8k
    this_duration = ts_end - ts_start;
252
21.8k
    if (this_duration > 0) {
253
21.8k
      cpi->new_framerate = 10000000.0 / this_duration;
254
21.8k
      av1_new_framerate(cpi, cpi->new_framerate);
255
21.8k
      time_stamps->prev_ts_start = ts_start;
256
21.8k
      time_stamps->prev_ts_end = ts_end;
257
21.8k
      return;
258
21.8k
    }
259
21.8k
  }
260
261
107k
  if (ts_start == time_stamps->first_ts_start) {
262
107k
    this_duration = ts_end - ts_start;
263
107k
    step = 1;
264
107k
  } else {
265
0
    int64_t last_duration =
266
0
        time_stamps->prev_ts_end - time_stamps->prev_ts_start;
267
268
0
    this_duration = ts_end - time_stamps->prev_ts_end;
269
270
    // do a step update if the duration changes by 10%
271
0
    if (last_duration)
272
0
      step = (int)((this_duration - last_duration) * 10 / last_duration);
273
0
  }
274
275
107k
  if (this_duration) {
276
107k
    if (step) {
277
107k
      cpi->new_framerate = 10000000.0 / this_duration;
278
107k
      av1_new_framerate(cpi, cpi->new_framerate);
279
107k
    } else {
280
      // Average this frame's rate into the last second's average
281
      // frame rate. If we haven't seen 1 second yet, then average
282
      // over the whole interval seen.
283
0
      const double interval =
284
0
          AOMMIN((double)(ts_end - time_stamps->first_ts_start), 10000000.0);
285
0
      double avg_duration = 10000000.0 / cpi->framerate;
286
0
      avg_duration *= (interval - avg_duration + this_duration);
287
0
      avg_duration /= interval;
288
0
      cpi->new_framerate = (10000000.0 / avg_duration);
289
      // For parallel frames update cpi->framerate with new_framerate
290
      // during av1_post_encode_updates()
291
0
      double framerate =
292
0
          (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)
293
0
              ? cpi->framerate
294
0
              : cpi->new_framerate;
295
0
      av1_new_framerate(cpi, framerate);
296
0
    }
297
107k
  }
298
299
107k
  time_stamps->prev_ts_start = ts_start;
300
107k
  time_stamps->prev_ts_end = ts_end;
301
107k
}
302
303
// Determine whether there is a forced keyframe pending in the lookahead buffer
304
int is_forced_keyframe_pending(struct lookahead_ctx *lookahead,
305
                               const int up_to_index,
306
170k
                               const COMPRESSOR_STAGE compressor_stage) {
307
340k
  for (int i = 0; i <= up_to_index; i++) {
308
340k
    const struct lookahead_entry *e =
309
340k
        av1_lookahead_peek(lookahead, i, compressor_stage);
310
340k
    if (e == NULL) {
311
      // We have reached the end of the lookahead buffer and not early-returned
312
      // so there isn't a forced key-frame pending.
313
137k
      return -1;
314
203k
    } else if (e->flags == AOM_EFLAG_FORCE_KF) {
315
33.2k
      return i;
316
170k
    } else {
317
170k
      continue;
318
170k
    }
319
340k
  }
320
0
  return -1;  // Never reached
321
170k
}
322
323
// Check if we should encode an ARF or internal ARF.  If not, try a LAST
324
// Do some setup associated with the chosen source
325
// temporal_filtered, flush, and frame_update_type are outputs.
326
// Return the frame source, or NULL if we couldn't find one
327
static struct lookahead_entry *choose_frame_source(
328
    AV1_COMP *const cpi, int *const flush, int *pop_lookahead,
329
129k
    struct lookahead_entry **last_source, int *const show_frame) {
330
129k
  AV1_COMMON *const cm = &cpi->common;
331
129k
  const GF_GROUP *const gf_group = &cpi->ppi->gf_group;
332
129k
  struct lookahead_entry *source = NULL;
333
334
  // Source index in lookahead buffer.
335
129k
  int src_index = gf_group->arf_src_offset[cpi->gf_frame_index];
336
337
  // TODO(Aasaipriya): Forced key frames need to be fixed when rc_mode != AOM_Q
338
129k
  if (src_index &&
339
0
      (is_forced_keyframe_pending(cpi->ppi->lookahead, src_index,
340
0
                                  cpi->compressor_stage) != -1) &&
341
0
      cpi->oxcf.rc_cfg.mode != AOM_Q && !is_stat_generation_stage(cpi)) {
342
0
    src_index = 0;
343
0
    *flush = 1;
344
0
  }
345
346
  // If the current frame is arf, then we should not pop from the lookahead
347
  // buffer. If the current frame is not arf, then pop it. This assumes the
348
  // first frame in the GF group is not arf. May need to change if it is not
349
  // true.
350
129k
  *pop_lookahead = (src_index == 0);
351
  // If this is a key frame and keyframe filtering is enabled with overlay,
352
  // then do not pop.
353
129k
  if (*pop_lookahead && cpi->oxcf.kf_cfg.enable_keyframe_filtering > 1 &&
354
0
      gf_group->update_type[cpi->gf_frame_index] == ARF_UPDATE &&
355
0
      !is_stat_generation_stage(cpi) && cpi->ppi->lookahead) {
356
0
    if (cpi->ppi->lookahead->read_ctxs[cpi->compressor_stage].sz &&
357
0
        (*flush ||
358
0
         cpi->ppi->lookahead->read_ctxs[cpi->compressor_stage].sz ==
359
0
             cpi->ppi->lookahead->read_ctxs[cpi->compressor_stage].pop_sz)) {
360
0
      *pop_lookahead = 0;
361
0
    }
362
0
  }
363
364
  // LAP stage does not have ARFs or forward key-frames,
365
  // hence, always pop_lookahead here.
366
129k
  if (is_stat_generation_stage(cpi)) {
367
18.9k
    *pop_lookahead = 1;
368
18.9k
    src_index = 0;
369
18.9k
  }
370
371
129k
  *show_frame = *pop_lookahead;
372
373
#if CONFIG_FPMT_TEST
374
  if (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_ENCODE) {
375
#else
376
129k
  {
377
129k
#endif  // CONFIG_FPMT_TEST
378
    // Future frame in parallel encode set
379
129k
    if (gf_group->src_offset[cpi->gf_frame_index] != 0 &&
380
0
        !is_stat_generation_stage(cpi))
381
0
      src_index = gf_group->src_offset[cpi->gf_frame_index];
382
129k
  }
383
129k
  if (*show_frame) {
384
    // show frame, pop from buffer
385
    // Get last frame source.
386
129k
    if (cm->current_frame.frame_number > 0) {
387
54.1k
      *last_source = av1_lookahead_peek(cpi->ppi->lookahead, src_index - 1,
388
54.1k
                                        cpi->compressor_stage);
389
54.1k
    }
390
    // Read in the source frame.
391
129k
    source = av1_lookahead_peek(cpi->ppi->lookahead, src_index,
392
129k
                                cpi->compressor_stage);
393
129k
  } else {
394
    // no show frames are arf frames
395
0
    source = av1_lookahead_peek(cpi->ppi->lookahead, src_index,
396
0
                                cpi->compressor_stage);
397
0
    if (source != NULL) {
398
0
      cm->showable_frame = 1;
399
0
    }
400
0
  }
401
129k
  return source;
402
129k
}
403
404
// Don't allow a show_existing_frame to coincide with an error resilient or
405
// S-Frame. An exception can be made in the case of a keyframe, since it does
406
// not depend on any previous frames.
407
static int allow_show_existing(const AV1_COMP *const cpi,
408
110k
                               unsigned int frame_flags) {
409
110k
  if (cpi->common.current_frame.frame_number == 0) return 0;
410
411
42.2k
  const struct lookahead_entry *lookahead_src =
412
42.2k
      av1_lookahead_peek(cpi->ppi->lookahead, 0, cpi->compressor_stage);
413
42.2k
  if (lookahead_src == NULL) return 1;
414
415
42.2k
  const int is_error_resilient =
416
42.2k
      cpi->oxcf.tool_cfg.error_resilient_mode ||
417
42.2k
      (lookahead_src->flags & AOM_EFLAG_ERROR_RESILIENT);
418
42.2k
  const int is_s_frame = cpi->oxcf.kf_cfg.enable_sframe ||
419
42.2k
                         (lookahead_src->flags & AOM_EFLAG_SET_S_FRAME);
420
42.2k
  const int is_key_frame =
421
42.2k
      (cpi->rc.frames_to_key == 0) || (frame_flags & FRAMEFLAGS_KEY);
422
42.2k
  return !(is_error_resilient || is_s_frame) || is_key_frame;
423
42.2k
}
424
425
// Update frame_flags to tell the encoder's caller what sort of frame was
426
// encoded.
427
static void update_frame_flags(const AV1_COMMON *const cm,
428
                               const RefreshFrameInfo *const refresh_frame,
429
110k
                               unsigned int *frame_flags) {
430
110k
  if (encode_show_existing_frame(cm)) {
431
0
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_GOLDEN;
432
0
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_BWDREF;
433
0
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_ALTREF;
434
0
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_KEY;
435
0
    return;
436
0
  }
437
438
110k
  if (refresh_frame->golden_frame) {
439
92.2k
    *frame_flags |= FRAMEFLAGS_GOLDEN;
440
92.2k
  } else {
441
17.8k
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_GOLDEN;
442
17.8k
  }
443
444
110k
  if (refresh_frame->alt_ref_frame) {
445
82.5k
    *frame_flags |= FRAMEFLAGS_ALTREF;
446
82.5k
  } else {
447
27.5k
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_ALTREF;
448
27.5k
  }
449
450
110k
  if (refresh_frame->bwd_ref_frame) {
451
82.5k
    *frame_flags |= FRAMEFLAGS_BWDREF;
452
82.5k
  } else {
453
27.5k
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_BWDREF;
454
27.5k
  }
455
456
110k
  if (cm->current_frame.frame_type == KEY_FRAME) {
457
82.5k
    *frame_flags |= FRAMEFLAGS_KEY;
458
82.5k
  } else {
459
27.5k
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_KEY;
460
27.5k
  }
461
110k
}
462
463
#define DUMP_REF_FRAME_IMAGES 0
464
465
#if DUMP_REF_FRAME_IMAGES == 1
466
static int dump_one_image(AV1_COMMON *cm,
467
                          const YV12_BUFFER_CONFIG *const ref_buf,
468
                          char *file_name) {
469
  int h;
470
  FILE *f_ref = NULL;
471
472
  if (ref_buf == NULL) {
473
    printf("Frame data buffer is NULL.\n");
474
    return AOM_CODEC_MEM_ERROR;
475
  }
476
477
  if ((f_ref = fopen(file_name, "wb")) == NULL) {
478
    printf("Unable to open file %s to write.\n", file_name);
479
    return AOM_CODEC_MEM_ERROR;
480
  }
481
482
  // --- Y ---
483
  for (h = 0; h < cm->height; ++h) {
484
    fwrite(&ref_buf->y_buffer[h * ref_buf->y_stride], 1, cm->width, f_ref);
485
  }
486
  // --- U ---
487
  for (h = 0; h < (cm->height >> 1); ++h) {
488
    fwrite(&ref_buf->u_buffer[h * ref_buf->uv_stride], 1, (cm->width >> 1),
489
           f_ref);
490
  }
491
  // --- V ---
492
  for (h = 0; h < (cm->height >> 1); ++h) {
493
    fwrite(&ref_buf->v_buffer[h * ref_buf->uv_stride], 1, (cm->width >> 1),
494
           f_ref);
495
  }
496
497
  fclose(f_ref);
498
499
  return AOM_CODEC_OK;
500
}
501
502
static void dump_ref_frame_images(AV1_COMP *cpi) {
503
  AV1_COMMON *const cm = &cpi->common;
504
  MV_REFERENCE_FRAME ref_frame;
505
506
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
507
    char file_name[256] = "";
508
    snprintf(file_name, sizeof(file_name), "/tmp/enc_F%d_ref_%d.yuv",
509
             cm->current_frame.frame_number, ref_frame);
510
    dump_one_image(cm, get_ref_frame_yv12_buf(cpi, ref_frame), file_name);
511
  }
512
}
513
#endif  // DUMP_REF_FRAME_IMAGES == 1
514
515
18.9k
int av1_get_refresh_ref_frame_map(int refresh_frame_flags) {
516
18.9k
  int ref_map_index;
517
518
30.4k
  for (ref_map_index = 0; ref_map_index < REF_FRAMES; ++ref_map_index)
519
30.4k
    if ((refresh_frame_flags >> ref_map_index) & 1) break;
520
521
18.9k
  if (ref_map_index == REF_FRAMES) ref_map_index = INVALID_IDX;
522
18.9k
  return ref_map_index;
523
18.9k
}
524
525
24.6k
static int get_free_ref_map_index(RefFrameMapPair ref_map_pairs[REF_FRAMES]) {
526
63.5k
  for (int idx = 0; idx < REF_FRAMES; ++idx)
527
63.5k
    if (ref_map_pairs[idx].disp_order == -1) return idx;
528
0
  return INVALID_IDX;
529
24.6k
}
530
531
static int get_refresh_idx(RefFrameMapPair ref_frame_map_pairs[REF_FRAMES],
532
                           int update_arf, GF_GROUP *gf_group, int gf_index,
533
0
                           int enable_refresh_skip, int cur_frame_disp) {
534
0
  int arf_count = 0;
535
0
  int oldest_arf_order = INT32_MAX;
536
0
  int oldest_arf_idx = -1;
537
538
0
  int oldest_frame_order = INT32_MAX;
539
0
  int oldest_idx = -1;
540
541
0
  for (int map_idx = 0; map_idx < REF_FRAMES; map_idx++) {
542
0
    RefFrameMapPair ref_pair = ref_frame_map_pairs[map_idx];
543
0
    if (ref_pair.disp_order == -1) continue;
544
0
    const int frame_order = ref_pair.disp_order;
545
0
    const int reference_frame_level = ref_pair.pyr_level;
546
    // Keep future frames and three closest previous frames in output order.
547
0
    if (frame_order > cur_frame_disp - 3) continue;
548
549
0
    if (enable_refresh_skip) {
550
0
      int skip_frame = 0;
551
      // Prevent refreshing a frame in gf_group->skip_frame_refresh.
552
0
      for (int i = 0; i < REF_FRAMES; i++) {
553
0
        int frame_to_skip = gf_group->skip_frame_refresh[gf_index][i];
554
0
        if (frame_to_skip == INVALID_IDX) break;
555
0
        if (frame_order == frame_to_skip) {
556
0
          skip_frame = 1;
557
0
          break;
558
0
        }
559
0
      }
560
0
      if (skip_frame) continue;
561
0
    }
562
563
    // Keep track of the oldest level 1 frame if the current frame is also level
564
    // 1.
565
0
    if (reference_frame_level == 1) {
566
      // If there are more than 2 level 1 frames in the reference list,
567
      // discard the oldest.
568
0
      if (frame_order < oldest_arf_order) {
569
0
        oldest_arf_order = frame_order;
570
0
        oldest_arf_idx = map_idx;
571
0
      }
572
0
      arf_count++;
573
0
      continue;
574
0
    }
575
576
    // Update the overall oldest reference frame.
577
0
    if (frame_order < oldest_frame_order) {
578
0
      oldest_frame_order = frame_order;
579
0
      oldest_idx = map_idx;
580
0
    }
581
0
  }
582
0
  if (update_arf && arf_count > 2) return oldest_arf_idx;
583
0
  if (oldest_idx >= 0) return oldest_idx;
584
0
  if (oldest_arf_idx >= 0) return oldest_arf_idx;
585
0
  if (oldest_idx == -1) {
586
0
    assert(arf_count > 2 && enable_refresh_skip);
587
0
    return oldest_arf_idx;
588
0
  }
589
0
  assert(0 && "No valid refresh index found");
590
0
  return -1;
591
0
}
592
593
// Computes the reference refresh index for INTNL_ARF_UPDATE frame.
594
int av1_calc_refresh_idx_for_intnl_arf(
595
    AV1_COMP *cpi, RefFrameMapPair ref_frame_map_pairs[REF_FRAMES],
596
0
    int gf_index) {
597
0
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
598
599
  // Search for the open slot to store the current frame.
600
0
  int free_fb_index = get_free_ref_map_index(ref_frame_map_pairs);
601
602
  // Use a free slot if available.
603
0
  if (free_fb_index != INVALID_IDX) {
604
0
    return free_fb_index;
605
0
  } else {
606
0
    int enable_refresh_skip = !is_one_pass_rt_params(cpi);
607
0
    int refresh_idx =
608
0
        get_refresh_idx(ref_frame_map_pairs, 0, gf_group, gf_index,
609
0
                        enable_refresh_skip, gf_group->display_idx[gf_index]);
610
0
    return refresh_idx;
611
0
  }
612
0
}
613
614
int av1_get_refresh_frame_flags(
615
    const AV1_COMP *const cpi, const EncodeFrameParams *const frame_params,
616
    FRAME_UPDATE_TYPE frame_update_type, int gf_index, int cur_disp_order,
617
129k
    RefFrameMapPair ref_frame_map_pairs[REF_FRAMES]) {
618
129k
  const AV1_COMMON *const cm = &cpi->common;
619
129k
  const ExtRefreshFrameFlagsInfo *const ext_refresh_frame_flags =
620
129k
      &cpi->ext_flags.refresh_frame;
621
622
129k
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
623
129k
  if (gf_group->refbuf_state[gf_index] == REFBUF_RESET)
624
94.0k
    return SELECT_ALL_BUF_SLOTS;
625
626
  // TODO(jingning): Deprecate the following operations.
627
  // Switch frames and shown key-frames overwrite all reference slots
628
35.0k
  if (frame_params->frame_type == S_FRAME) return SELECT_ALL_BUF_SLOTS;
629
630
  // show_existing_frames don't actually send refresh_frame_flags so set the
631
  // flags to 0 to keep things consistent.
632
35.0k
  if (frame_params->show_existing_frame) return 0;
633
634
35.0k
  const RTC_REF *const rtc_ref = &cpi->ppi->rtc_ref;
635
35.0k
  if (is_frame_droppable(rtc_ref, ext_refresh_frame_flags)) return 0;
636
637
35.0k
#if !CONFIG_REALTIME_ONLY
638
35.0k
  if (cpi->use_ducky_encode &&
639
0
      cpi->ducky_encode_info.frame_info.gop_mode == DUCKY_ENCODE_GOP_MODE_RCL) {
640
0
    int new_fb_map_idx = cpi->ppi->gf_group.update_ref_idx[gf_index];
641
0
    if (new_fb_map_idx == INVALID_IDX) return 0;
642
0
    return 1 << new_fb_map_idx;
643
0
  }
644
35.0k
#endif  // !CONFIG_REALTIME_ONLY
645
646
35.0k
  int refresh_mask = 0;
647
35.0k
  if (ext_refresh_frame_flags->update_pending) {
648
10.3k
    if (rtc_ref->set_ref_frame_config ||
649
10.3k
        use_rtc_reference_structure_one_layer(cpi)) {
650
82.6k
      for (unsigned int i = 0; i < INTER_REFS_PER_FRAME; i++) {
651
72.3k
        int ref_frame_map_idx = rtc_ref->ref_idx[i];
652
72.3k
        refresh_mask |= rtc_ref->refresh[ref_frame_map_idx]
653
72.3k
                        << ref_frame_map_idx;
654
72.3k
      }
655
10.3k
      return refresh_mask;
656
10.3k
    }
657
    // Unfortunately the encoder interface reflects the old refresh_*_frame
658
    // flags so we have to replicate the old refresh_frame_flags logic here in
659
    // order to preserve the behaviour of the flag overrides.
660
0
    int ref_frame_map_idx = get_ref_frame_map_idx(cm, LAST_FRAME);
661
0
    if (ref_frame_map_idx != INVALID_IDX)
662
0
      refresh_mask |= ext_refresh_frame_flags->last_frame << ref_frame_map_idx;
663
664
0
    ref_frame_map_idx = get_ref_frame_map_idx(cm, EXTREF_FRAME);
665
0
    if (ref_frame_map_idx != INVALID_IDX)
666
0
      refresh_mask |= ext_refresh_frame_flags->bwd_ref_frame
667
0
                      << ref_frame_map_idx;
668
669
0
    ref_frame_map_idx = get_ref_frame_map_idx(cm, ALTREF2_FRAME);
670
0
    if (ref_frame_map_idx != INVALID_IDX)
671
0
      refresh_mask |= ext_refresh_frame_flags->alt2_ref_frame
672
0
                      << ref_frame_map_idx;
673
674
0
    if (frame_update_type == OVERLAY_UPDATE) {
675
0
      ref_frame_map_idx = get_ref_frame_map_idx(cm, ALTREF_FRAME);
676
0
      if (ref_frame_map_idx != INVALID_IDX)
677
0
        refresh_mask |= ext_refresh_frame_flags->golden_frame
678
0
                        << ref_frame_map_idx;
679
0
    } else {
680
0
      ref_frame_map_idx = get_ref_frame_map_idx(cm, GOLDEN_FRAME);
681
0
      if (ref_frame_map_idx != INVALID_IDX)
682
0
        refresh_mask |= ext_refresh_frame_flags->golden_frame
683
0
                        << ref_frame_map_idx;
684
685
0
      ref_frame_map_idx = get_ref_frame_map_idx(cm, ALTREF_FRAME);
686
0
      if (ref_frame_map_idx != INVALID_IDX)
687
0
        refresh_mask |= ext_refresh_frame_flags->alt_ref_frame
688
0
                        << ref_frame_map_idx;
689
0
    }
690
0
    return refresh_mask;
691
10.3k
  }
692
693
  // Search for the open slot to store the current frame.
694
24.6k
  int free_fb_index = get_free_ref_map_index(ref_frame_map_pairs);
695
696
  // No refresh necessary for these frame types.
697
24.6k
  if (frame_update_type == OVERLAY_UPDATE ||
698
24.6k
      frame_update_type == INTNL_OVERLAY_UPDATE)
699
0
    return refresh_mask;
700
701
  // If there is an open slot, refresh that one instead of replacing a
702
  // reference.
703
24.6k
  if (free_fb_index != INVALID_IDX) {
704
24.6k
    refresh_mask = 1 << free_fb_index;
705
24.6k
    return refresh_mask;
706
24.6k
  }
707
0
  const int enable_refresh_skip = !is_one_pass_rt_params(cpi);
708
0
  const int update_arf = frame_update_type == ARF_UPDATE;
709
0
  const int refresh_idx =
710
0
      get_refresh_idx(ref_frame_map_pairs, update_arf, &cpi->ppi->gf_group,
711
0
                      gf_index, enable_refresh_skip, cur_disp_order);
712
0
  return 1 << refresh_idx;
713
24.6k
}
714
715
#if !CONFIG_REALTIME_ONLY
716
// Apply temporal filtering to source frames and encode the filtered frame.
717
// If the current frame does not require filtering, this function is identical
718
// to av1_encode() except that tpl is not performed.
719
static int denoise_and_encode(AV1_COMP *const cpi, uint8_t *const dest,
720
                              size_t dest_size,
721
                              EncodeFrameInput *const frame_input,
722
                              const EncodeFrameParams *const frame_params,
723
107k
                              size_t *const frame_size) {
724
#if CONFIG_COLLECT_COMPONENT_TIMING
725
  if (cpi->oxcf.pass == 2) start_timing(cpi, denoise_and_encode_time);
726
#endif
727
107k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
728
107k
  AV1_COMMON *const cm = &cpi->common;
729
730
107k
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
731
107k
  FRAME_UPDATE_TYPE update_type =
732
107k
      get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
733
107k
  const int is_second_arf =
734
107k
      av1_gop_is_second_arf(gf_group, cpi->gf_frame_index);
735
736
  // Decide whether to apply temporal filtering to the source frame.
737
107k
  int apply_filtering =
738
107k
      av1_is_temporal_filter_on(oxcf) && !is_stat_generation_stage(cpi);
739
107k
  if (update_type != KF_UPDATE && update_type != ARF_UPDATE && !is_second_arf) {
740
17.2k
    apply_filtering = 0;
741
17.2k
  }
742
107k
  if (apply_filtering) {
743
11.4k
    if (frame_params->frame_type == KEY_FRAME) {
744
      // TODO(angiebird): Move the noise level check to av1_tf_info_filtering.
745
      // Decide whether it is allowed to perform key frame filtering
746
11.4k
      int allow_kf_filtering = oxcf->kf_cfg.enable_keyframe_filtering &&
747
11.4k
                               !frame_params->show_existing_frame &&
748
11.4k
                               !is_lossless_requested(&oxcf->rc_cfg);
749
11.4k
      if (allow_kf_filtering) {
750
11.2k
        double y_noise_level = 0.0;
751
11.2k
        av1_estimate_noise_level(
752
11.2k
            frame_input->source, &y_noise_level, AOM_PLANE_Y, AOM_PLANE_Y,
753
11.2k
            cm->seq_params->bit_depth, NOISE_ESTIMATION_EDGE_THRESHOLD);
754
11.2k
        apply_filtering = y_noise_level > 0;
755
11.2k
      } else {
756
249
        apply_filtering = 0;
757
249
      }
758
      // If we are doing kf filtering, set up a few things.
759
11.4k
      if (apply_filtering) {
760
1.67k
        av1_setup_past_independence(cm);
761
1.67k
      }
762
11.4k
    } else if (is_second_arf) {
763
0
      apply_filtering = cpi->sf.hl_sf.second_alt_ref_filtering;
764
0
    }
765
11.4k
  }
766
767
#if CONFIG_COLLECT_COMPONENT_TIMING
768
  if (cpi->oxcf.pass == 2) start_timing(cpi, apply_filtering_time);
769
#endif
770
  // Save the pointer to the original source image.
771
107k
  YV12_BUFFER_CONFIG *source_buffer = frame_input->source;
772
  // apply filtering to frame
773
107k
  if (apply_filtering) {
774
1.67k
    int show_existing_alt_ref = 0;
775
1.67k
    FRAME_DIFF frame_diff;
776
1.67k
    int top_index = 0;
777
1.67k
    int bottom_index = 0;
778
1.67k
    const int q_index = av1_rc_pick_q_and_bounds(
779
1.67k
        cpi, cpi->oxcf.frm_dim_cfg.width, cpi->oxcf.frm_dim_cfg.height,
780
1.67k
        cpi->gf_frame_index, &bottom_index, &top_index);
781
782
    // TODO(bohanli): figure out why we need frame_type in cm here.
783
1.67k
    cm->current_frame.frame_type = frame_params->frame_type;
784
1.67k
    if (update_type == KF_UPDATE || update_type == ARF_UPDATE) {
785
1.67k
      YV12_BUFFER_CONFIG *tf_buf = av1_tf_info_get_filtered_buf(
786
1.67k
          &cpi->ppi->tf_info, cpi->gf_frame_index, &frame_diff);
787
1.67k
      if (tf_buf != NULL) {
788
1.67k
        frame_input->source = tf_buf;
789
1.67k
        show_existing_alt_ref = av1_check_show_filtered_frame(
790
1.67k
            tf_buf, &frame_diff, q_index, cm->seq_params->bit_depth);
791
1.67k
        if (show_existing_alt_ref) {
792
217
          cpi->common.showable_frame |= 1;
793
1.45k
        } else {
794
1.45k
          cpi->common.showable_frame = 0;
795
1.45k
        }
796
1.67k
      }
797
1.67k
      if (gf_group->frame_type[cpi->gf_frame_index] != KEY_FRAME) {
798
0
        cpi->ppi->show_existing_alt_ref = show_existing_alt_ref;
799
0
      }
800
1.67k
    }
801
802
1.67k
    if (is_second_arf) {
803
      // Allocate the memory for tf_buf_second_arf buffer, only when it is
804
      // required.
805
0
      int ret = aom_realloc_frame_buffer(
806
0
          &cpi->ppi->tf_info.tf_buf_second_arf, oxcf->frm_dim_cfg.width,
807
0
          oxcf->frm_dim_cfg.height, cm->seq_params->subsampling_x,
808
0
          cm->seq_params->subsampling_y, cm->seq_params->use_highbitdepth,
809
0
          cpi->oxcf.border_in_pixels, cm->features.byte_alignment, NULL, NULL,
810
0
          NULL, cpi->alloc_pyramid, 0);
811
0
      if (ret)
812
0
        aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
813
0
                           "Failed to allocate tf_buf_second_arf");
814
815
0
      YV12_BUFFER_CONFIG *tf_buf_second_arf =
816
0
          &cpi->ppi->tf_info.tf_buf_second_arf;
817
      // We didn't apply temporal filtering for second arf ahead in
818
      // av1_tf_info_filtering().
819
0
      const int arf_src_index = gf_group->arf_src_offset[cpi->gf_frame_index];
820
      // Right now, we are still using tf_buf_second_arf due to
821
      // implementation complexity.
822
      // TODO(angiebird): Reuse tf_info->tf_buf here.
823
0
      av1_temporal_filter(cpi, arf_src_index, cpi->gf_frame_index, &frame_diff,
824
0
                          tf_buf_second_arf);
825
0
      show_existing_alt_ref = av1_check_show_filtered_frame(
826
0
          tf_buf_second_arf, &frame_diff, q_index, cm->seq_params->bit_depth);
827
0
      if (show_existing_alt_ref) {
828
0
        aom_extend_frame_borders(tf_buf_second_arf, av1_num_planes(cm));
829
0
        frame_input->source = tf_buf_second_arf;
830
0
      }
831
      // Currently INTNL_ARF_UPDATE only do show_existing.
832
0
      cpi->common.showable_frame |= 1;
833
0
    }
834
835
    // Copy source metadata to the temporal filtered frame
836
1.67k
    if (source_buffer->metadata &&
837
0
        aom_copy_metadata_to_frame_buffer(frame_input->source,
838
0
                                          source_buffer->metadata)) {
839
0
      aom_internal_error(
840
0
          cm->error, AOM_CODEC_MEM_ERROR,
841
0
          "Failed to copy source metadata to the temporal filtered frame");
842
0
    }
843
1.67k
  }
844
#if CONFIG_COLLECT_COMPONENT_TIMING
845
  if (cpi->oxcf.pass == 2) end_timing(cpi, apply_filtering_time);
846
#endif
847
848
107k
  int set_mv_params = frame_params->frame_type == KEY_FRAME ||
849
26.5k
                      update_type == ARF_UPDATE || update_type == GF_UPDATE;
850
107k
  cm->show_frame = frame_params->show_frame;
851
107k
  cm->current_frame.frame_type = frame_params->frame_type;
852
  // TODO(bohanli): Why is this? what part of it is necessary?
853
107k
  av1_set_frame_size(cpi, cm->width, cm->height);
854
107k
  if (set_mv_params) av1_set_mv_search_params(cpi);
855
856
#if CONFIG_RD_COMMAND
857
  if (frame_params->frame_type == KEY_FRAME) {
858
    char filepath[] = "rd_command.txt";
859
    av1_read_rd_command(filepath, &cpi->rd_command);
860
  }
861
#endif  // CONFIG_RD_COMMAND
862
107k
  if (cpi->gf_frame_index == 0 && !is_stat_generation_stage(cpi)) {
863
    // perform tpl after filtering
864
80.7k
    int allow_tpl =
865
80.7k
        oxcf->gf_cfg.lag_in_frames > 1 && oxcf->algo_cfg.enable_tpl_model;
866
80.7k
    if (gf_group->size > MAX_LENGTH_TPL_FRAME_STATS) {
867
0
      allow_tpl = 0;
868
0
    }
869
80.7k
    if (frame_params->frame_type != KEY_FRAME) {
870
      // In rare case, it's possible to have non ARF/GF update_type here.
871
      // We should set allow_tpl to zero in the situation
872
9.73k
      allow_tpl =
873
9.73k
          allow_tpl && (update_type == ARF_UPDATE || update_type == GF_UPDATE ||
874
0
                        (cpi->use_ducky_encode &&
875
0
                         cpi->ducky_encode_info.frame_info.gop_mode ==
876
0
                             DUCKY_ENCODE_GOP_MODE_RCL));
877
9.73k
    }
878
879
80.7k
    if (allow_tpl) {
880
11.4k
      if (!cpi->skip_tpl_setup_stats) {
881
11.4k
        av1_tpl_preload_rc_estimate(cpi, frame_params);
882
11.4k
        av1_tpl_setup_stats(cpi, 0, frame_params);
883
#if CONFIG_BITRATE_ACCURACY && !CONFIG_THREE_PASS
884
        assert(cpi->gf_frame_index == 0);
885
        av1_vbr_rc_update_q_index_list(&cpi->vbr_rc_info, &cpi->ppi->tpl_data,
886
                                       gf_group, cm->seq_params->bit_depth);
887
#endif
888
11.4k
      }
889
69.3k
    } else {
890
69.3k
      av1_init_tpl_stats(&cpi->ppi->tpl_data);
891
69.3k
    }
892
#if CONFIG_BITRATE_ACCURACY && CONFIG_THREE_PASS
893
    if (cpi->oxcf.pass == AOM_RC_SECOND_PASS &&
894
        cpi->second_pass_log_stream != NULL) {
895
      TPL_INFO *tpl_info;
896
      AOM_CHECK_MEM_ERROR(cm->error, tpl_info, aom_malloc(sizeof(*tpl_info)));
897
      av1_pack_tpl_info(tpl_info, gf_group, &cpi->ppi->tpl_data);
898
      av1_write_tpl_info(tpl_info, cpi->second_pass_log_stream,
899
                         cpi->common.error);
900
      aom_free(tpl_info);
901
    }
902
#endif  // CONFIG_BITRATE_ACCURACY && CONFIG_THREE_PASS
903
80.7k
  }
904
905
107k
  if (av1_encode(cpi, dest, dest_size, frame_input, frame_params, frame_size) !=
906
107k
      AOM_CODEC_OK) {
907
0
    return AOM_CODEC_ERROR;
908
0
  }
909
910
  // Set frame_input source to true source for psnr calculation.
911
107k
  if (apply_filtering && is_psnr_calc_enabled(cpi)) {
912
0
    cpi->source = av1_realloc_and_scale_if_required(
913
0
        cm, source_buffer, &cpi->scaled_source, cm->features.interp_filter, 0,
914
0
        false, true, cpi->oxcf.border_in_pixels, cpi->alloc_pyramid);
915
0
    cpi->unscaled_source = source_buffer;
916
0
  }
917
#if CONFIG_COLLECT_COMPONENT_TIMING
918
  if (cpi->oxcf.pass == 2) end_timing(cpi, denoise_and_encode_time);
919
#endif
920
107k
  return AOM_CODEC_OK;
921
107k
}
922
#endif  // !CONFIG_REALTIME_ONLY
923
924
/*!\cond */
925
// Struct to keep track of relevant reference frame data.
926
typedef struct {
927
  int map_idx;
928
  int disp_order;
929
  int pyr_level;
930
  int used;
931
} RefBufMapData;
932
/*!\endcond */
933
934
// Comparison function to sort reference frames in ascending display order.
935
14.2k
static int compare_map_idx_pair_asc(const void *a, const void *b) {
936
14.2k
  if (((RefBufMapData *)a)->disp_order == ((RefBufMapData *)b)->disp_order) {
937
0
    return 0;
938
14.2k
  } else if (((const RefBufMapData *)a)->disp_order >
939
14.2k
             ((const RefBufMapData *)b)->disp_order) {
940
0
    return 1;
941
14.2k
  } else {
942
14.2k
    return -1;
943
14.2k
  }
944
14.2k
}
945
946
// Checks to see if a particular reference frame is already in the reference
947
// frame map.
948
38.8k
static int is_in_ref_map(RefBufMapData *map, int disp_order, int n_frames) {
949
56.4k
  for (int i = 0; i < n_frames; i++) {
950
17.6k
    if (disp_order == map[i].disp_order) return 1;
951
17.6k
  }
952
38.8k
  return 0;
953
38.8k
}
954
955
// Add a reference buffer index to a named reference slot.
956
static void add_ref_to_slot(RefBufMapData *ref, int *const remapped_ref_idx,
957
121k
                            int frame) {
958
121k
  remapped_ref_idx[frame - LAST_FRAME] = ref->map_idx;
959
121k
  ref->used = 1;
960
121k
}
961
962
// Threshold dictating when we are allowed to start considering
963
// leaving lowest level frames unmapped.
964
0
#define LOW_LEVEL_FRAMES_TR 5
965
966
// Find which reference buffer should be left out of the named mapping.
967
// This is because there are 8 reference buffers and only 7 named slots.
968
static void set_unmapped_ref(RefBufMapData *buffer_map, int n_bufs,
969
                             int n_min_level_refs, int min_level,
970
107k
                             int cur_frame_disp) {
971
107k
  int max_dist = 0;
972
107k
  int unmapped_idx = -1;
973
107k
  if (n_bufs <= ALTREF_FRAME) return;
974
0
  for (int i = 0; i < n_bufs; i++) {
975
0
    if (buffer_map[i].used) continue;
976
0
    if (buffer_map[i].pyr_level != min_level ||
977
0
        n_min_level_refs >= LOW_LEVEL_FRAMES_TR) {
978
0
      int dist = abs(cur_frame_disp - buffer_map[i].disp_order);
979
0
      if (dist > max_dist) {
980
0
        max_dist = dist;
981
0
        unmapped_idx = i;
982
0
      }
983
0
    }
984
0
  }
985
0
  assert(unmapped_idx >= 0 && "Unmapped reference not found");
986
0
  buffer_map[unmapped_idx].used = 1;
987
0
}
988
989
void av1_get_ref_frames(RefFrameMapPair ref_frame_map_pairs[REF_FRAMES],
990
                        int cur_frame_disp, const AV1_COMP *cpi, int gf_index,
991
                        int is_parallel_encode,
992
107k
                        int remapped_ref_idx[REF_FRAMES]) {
993
107k
  int buf_map_idx = 0;
994
995
  // Initialize reference frame mappings.
996
964k
  for (int i = 0; i < REF_FRAMES; ++i) remapped_ref_idx[i] = INVALID_IDX;
997
998
107k
#if !CONFIG_REALTIME_ONLY
999
107k
  if (cpi->use_ducky_encode &&
1000
0
      cpi->ducky_encode_info.frame_info.gop_mode == DUCKY_ENCODE_GOP_MODE_RCL) {
1001
0
    for (int rf = LAST_FRAME; rf < REF_FRAMES; ++rf) {
1002
0
      if (cpi->ppi->gf_group.ref_frame_list[gf_index][rf] != INVALID_IDX) {
1003
0
        remapped_ref_idx[rf - LAST_FRAME] =
1004
0
            cpi->ppi->gf_group.ref_frame_list[gf_index][rf];
1005
0
      }
1006
0
    }
1007
1008
0
    int valid_rf_idx = 0;
1009
0
    static const int ref_frame_type_order[REF_FRAMES - LAST_FRAME] = {
1010
0
      GOLDEN_FRAME,  ALTREF_FRAME, LAST_FRAME, BWDREF_FRAME,
1011
0
      ALTREF2_FRAME, LAST2_FRAME,  LAST3_FRAME
1012
0
    };
1013
0
    for (int i = 0; i < REF_FRAMES - LAST_FRAME; i++) {
1014
0
      int rf = ref_frame_type_order[i];
1015
0
      if (remapped_ref_idx[rf - LAST_FRAME] != INVALID_IDX) {
1016
0
        valid_rf_idx = remapped_ref_idx[rf - LAST_FRAME];
1017
0
        break;
1018
0
      }
1019
0
    }
1020
1021
0
    for (int i = 0; i < REF_FRAMES; ++i) {
1022
0
      if (remapped_ref_idx[i] == INVALID_IDX) {
1023
0
        remapped_ref_idx[i] = valid_rf_idx;
1024
0
      }
1025
0
    }
1026
1027
0
    return;
1028
0
  }
1029
107k
#endif  // !CONFIG_REALTIME_ONLY
1030
1031
107k
  RefBufMapData buffer_map[REF_FRAMES];
1032
107k
  int n_bufs = 0;
1033
107k
  memset(buffer_map, 0, REF_FRAMES * sizeof(buffer_map[0]));
1034
107k
  int min_level = MAX_ARF_LAYERS;
1035
107k
  int max_level = 0;
1036
107k
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
1037
107k
  int skip_ref_unmapping = 0;
1038
107k
  int is_one_pass_rt = is_one_pass_rt_params(cpi);
1039
1040
  // Go through current reference buffers and store display order, pyr level,
1041
  // and map index.
1042
964k
  for (int map_idx = 0; map_idx < REF_FRAMES; map_idx++) {
1043
    // Get reference frame buffer.
1044
857k
    RefFrameMapPair ref_pair = ref_frame_map_pairs[map_idx];
1045
857k
    if (ref_pair.disp_order == -1) continue;
1046
38.8k
    const int frame_order = ref_pair.disp_order;
1047
    // Avoid duplicates.
1048
38.8k
    if (is_in_ref_map(buffer_map, frame_order, n_bufs)) continue;
1049
38.8k
    const int reference_frame_level = ref_pair.pyr_level;
1050
1051
    // Keep track of the lowest and highest levels that currently exist.
1052
38.8k
    if (reference_frame_level < min_level) min_level = reference_frame_level;
1053
38.8k
    if (reference_frame_level > max_level) max_level = reference_frame_level;
1054
1055
38.8k
    buffer_map[n_bufs].map_idx = map_idx;
1056
38.8k
    buffer_map[n_bufs].disp_order = frame_order;
1057
38.8k
    buffer_map[n_bufs].pyr_level = reference_frame_level;
1058
38.8k
    buffer_map[n_bufs].used = 0;
1059
38.8k
    n_bufs++;
1060
38.8k
  }
1061
1062
  // Sort frames in ascending display order.
1063
107k
  qsort(buffer_map, n_bufs, sizeof(buffer_map[0]), compare_map_idx_pair_asc);
1064
1065
107k
  int n_min_level_refs = 0;
1066
107k
  int closest_past_ref = -1;
1067
107k
  int golden_idx = -1;
1068
107k
  int altref_idx = -1;
1069
1070
  // Find the GOLDEN_FRAME and BWDREF_FRAME.
1071
  // Also collect various stats about the reference frames for the remaining
1072
  // mappings.
1073
146k
  for (int i = n_bufs - 1; i >= 0; i--) {
1074
38.8k
    if (buffer_map[i].pyr_level == min_level) {
1075
      // Keep track of the number of lowest level frames.
1076
32.5k
      n_min_level_refs++;
1077
32.5k
      if (buffer_map[i].disp_order < cur_frame_disp && golden_idx == -1 &&
1078
24.6k
          remapped_ref_idx[GOLDEN_FRAME - LAST_FRAME] == INVALID_IDX) {
1079
        // Save index for GOLDEN.
1080
24.6k
        golden_idx = i;
1081
24.6k
      } else if (buffer_map[i].disp_order > cur_frame_disp &&
1082
0
                 altref_idx == -1 &&
1083
0
                 remapped_ref_idx[ALTREF_FRAME - LAST_FRAME] == INVALID_IDX) {
1084
        // Save index for ALTREF.
1085
0
        altref_idx = i;
1086
0
      }
1087
32.5k
    } else if (buffer_map[i].disp_order == cur_frame_disp) {
1088
      // Map the BWDREF_FRAME if this is the show_existing_frame.
1089
0
      add_ref_to_slot(&buffer_map[i], remapped_ref_idx, BWDREF_FRAME);
1090
0
    }
1091
1092
    // During parallel encodes of lower layer frames, exclude the first frame
1093
    // (frame_parallel_level 1) from being used for the reference assignment of
1094
    // the second frame (frame_parallel_level 2).
1095
38.8k
    if (!is_one_pass_rt && gf_group->frame_parallel_level[gf_index] == 2 &&
1096
0
        gf_group->frame_parallel_level[gf_index - 1] == 1 &&
1097
0
        gf_group->update_type[gf_index - 1] == INTNL_ARF_UPDATE) {
1098
0
      assert(gf_group->update_type[gf_index] == INTNL_ARF_UPDATE);
1099
#if CONFIG_FPMT_TEST
1100
      is_parallel_encode = (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_ENCODE)
1101
                               ? is_parallel_encode
1102
                               : 0;
1103
#endif  // CONFIG_FPMT_TEST
1104
      // If parallel cpis are active, use ref_idx_to_skip, else, use display
1105
      // index.
1106
0
      assert(IMPLIES(is_parallel_encode, cpi->ref_idx_to_skip != INVALID_IDX));
1107
0
      assert(IMPLIES(!is_parallel_encode,
1108
0
                     gf_group->skip_frame_as_ref[gf_index] != INVALID_IDX));
1109
0
      buffer_map[i].used = is_parallel_encode
1110
0
                               ? (buffer_map[i].map_idx == cpi->ref_idx_to_skip)
1111
0
                               : (buffer_map[i].disp_order ==
1112
0
                                  gf_group->skip_frame_as_ref[gf_index]);
1113
      // In case a ref frame is excluded from being used during assignment,
1114
      // skip the call to set_unmapped_ref(). Applicable in steady state.
1115
0
      if (buffer_map[i].used) skip_ref_unmapping = 1;
1116
0
    }
1117
1118
    // Keep track of where the frames change from being past frames to future
1119
    // frames.
1120
38.8k
    if (buffer_map[i].disp_order < cur_frame_disp && closest_past_ref < 0)
1121
24.6k
      closest_past_ref = i;
1122
38.8k
  }
1123
1124
  // Do not map GOLDEN and ALTREF based on their pyramid level if all reference
1125
  // frames have the same level.
1126
107k
  if (n_min_level_refs <= n_bufs) {
1127
    // Map the GOLDEN_FRAME.
1128
107k
    if (golden_idx > -1)
1129
24.6k
      add_ref_to_slot(&buffer_map[golden_idx], remapped_ref_idx, GOLDEN_FRAME);
1130
    // Map the ALTREF_FRAME.
1131
107k
    if (altref_idx > -1)
1132
0
      add_ref_to_slot(&buffer_map[altref_idx], remapped_ref_idx, ALTREF_FRAME);
1133
107k
  }
1134
1135
  // Find the buffer to be excluded from the mapping.
1136
107k
  if (!skip_ref_unmapping)
1137
107k
    set_unmapped_ref(buffer_map, n_bufs, n_min_level_refs, min_level,
1138
107k
                     cur_frame_disp);
1139
1140
  // Place past frames in LAST_FRAME, LAST2_FRAME, and LAST3_FRAME.
1141
203k
  for (int frame = LAST_FRAME; frame < GOLDEN_FRAME; frame++) {
1142
    // Continue if the current ref slot is already full.
1143
203k
    if (remapped_ref_idx[frame - LAST_FRAME] != INVALID_IDX) continue;
1144
    // Find the next unmapped reference buffer
1145
    // in decreasing ouptut order relative to current picture.
1146
203k
    int next_buf_max = 0;
1147
203k
    int next_disp_order = INT_MIN;
1148
278k
    for (buf_map_idx = n_bufs - 1; buf_map_idx >= 0; buf_map_idx--) {
1149
74.1k
      if (!buffer_map[buf_map_idx].used &&
1150
17.6k
          buffer_map[buf_map_idx].disp_order < cur_frame_disp &&
1151
17.6k
          buffer_map[buf_map_idx].disp_order > next_disp_order) {
1152
14.2k
        next_disp_order = buffer_map[buf_map_idx].disp_order;
1153
14.2k
        next_buf_max = buf_map_idx;
1154
14.2k
      }
1155
74.1k
    }
1156
203k
    buf_map_idx = next_buf_max;
1157
203k
    if (buf_map_idx < 0) break;
1158
203k
    if (buffer_map[buf_map_idx].used) break;
1159
96.7k
    add_ref_to_slot(&buffer_map[buf_map_idx], remapped_ref_idx, frame);
1160
96.7k
  }
1161
1162
  // Place future frames (if there are any) in BWDREF_FRAME and ALTREF2_FRAME.
1163
107k
  for (int frame = BWDREF_FRAME; frame < REF_FRAMES; frame++) {
1164
    // Continue if the current ref slot is already full.
1165
107k
    if (remapped_ref_idx[frame - LAST_FRAME] != INVALID_IDX) continue;
1166
    // Find the next unmapped reference buffer
1167
    // in increasing ouptut order relative to current picture.
1168
107k
    int next_buf_max = 0;
1169
107k
    int next_disp_order = INT_MAX;
1170
146k
    for (buf_map_idx = n_bufs - 1; buf_map_idx >= 0; buf_map_idx--) {
1171
38.8k
      if (!buffer_map[buf_map_idx].used &&
1172
0
          buffer_map[buf_map_idx].disp_order > cur_frame_disp &&
1173
0
          buffer_map[buf_map_idx].disp_order < next_disp_order) {
1174
0
        next_disp_order = buffer_map[buf_map_idx].disp_order;
1175
0
        next_buf_max = buf_map_idx;
1176
0
      }
1177
38.8k
    }
1178
107k
    buf_map_idx = next_buf_max;
1179
107k
    if (buf_map_idx < 0) break;
1180
107k
    if (buffer_map[buf_map_idx].used) break;
1181
0
    add_ref_to_slot(&buffer_map[buf_map_idx], remapped_ref_idx, frame);
1182
0
  }
1183
1184
  // Place remaining past frames.
1185
107k
  buf_map_idx = closest_past_ref;
1186
203k
  for (int frame = LAST_FRAME; frame < REF_FRAMES; frame++) {
1187
    // Continue if the current ref slot is already full.
1188
203k
    if (remapped_ref_idx[frame - LAST_FRAME] != INVALID_IDX) continue;
1189
    // Find the next unmapped reference buffer.
1190
146k
    for (; buf_map_idx >= 0; buf_map_idx--) {
1191
38.8k
      if (!buffer_map[buf_map_idx].used) break;
1192
38.8k
    }
1193
107k
    if (buf_map_idx < 0) break;
1194
0
    if (buffer_map[buf_map_idx].used) break;
1195
0
    add_ref_to_slot(&buffer_map[buf_map_idx], remapped_ref_idx, frame);
1196
0
  }
1197
1198
  // Place remaining future frames.
1199
107k
  buf_map_idx = n_bufs - 1;
1200
107k
  for (int frame = ALTREF_FRAME; frame >= LAST_FRAME; frame--) {
1201
    // Continue if the current ref slot is already full.
1202
107k
    if (remapped_ref_idx[frame - LAST_FRAME] != INVALID_IDX) continue;
1203
    // Find the next unmapped reference buffer.
1204
107k
    for (; buf_map_idx > closest_past_ref; buf_map_idx--) {
1205
0
      if (!buffer_map[buf_map_idx].used) break;
1206
0
    }
1207
107k
    if (buf_map_idx < 0) break;
1208
24.6k
    if (buffer_map[buf_map_idx].used) break;
1209
0
    add_ref_to_slot(&buffer_map[buf_map_idx], remapped_ref_idx, frame);
1210
0
  }
1211
1212
  // Fill any slots that are empty (should only happen for the first 7 frames).
1213
964k
  for (int i = 0; i < REF_FRAMES; ++i)
1214
857k
    if (remapped_ref_idx[i] == INVALID_IDX) remapped_ref_idx[i] = 0;
1215
107k
}
1216
1217
int av1_encode_strategy(AV1_COMP *const cpi, size_t *const size,
1218
                        uint8_t *const dest, size_t dest_size,
1219
                        unsigned int *frame_flags, int64_t *const time_stamp,
1220
                        int64_t *const time_end,
1221
                        const aom_rational64_t *const timestamp_ratio,
1222
241k
                        int *const pop_lookahead, int flush) {
1223
241k
  AV1EncoderConfig *const oxcf = &cpi->oxcf;
1224
241k
  AV1_COMMON *const cm = &cpi->common;
1225
241k
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
1226
241k
  ExternalFlags *const ext_flags = &cpi->ext_flags;
1227
241k
  GFConfig *const gf_cfg = &oxcf->gf_cfg;
1228
1229
241k
  EncodeFrameInput frame_input;
1230
241k
  EncodeFrameParams frame_params;
1231
241k
  size_t frame_size;
1232
241k
  memset(&frame_input, 0, sizeof(frame_input));
1233
241k
  memset(&frame_params, 0, sizeof(frame_params));
1234
241k
  frame_size = 0;
1235
1236
#if CONFIG_BITRATE_ACCURACY && CONFIG_THREE_PASS
1237
  VBR_RATECTRL_INFO *vbr_rc_info = &cpi->vbr_rc_info;
1238
  if (oxcf->pass == AOM_RC_THIRD_PASS && vbr_rc_info->ready == 0) {
1239
    THIRD_PASS_FRAME_INFO frame_info[MAX_THIRD_PASS_BUF];
1240
    av1_open_second_pass_log(cpi, 1);
1241
    FILE *second_pass_log_stream = cpi->second_pass_log_stream;
1242
    fseek(second_pass_log_stream, 0, SEEK_END);
1243
    size_t file_size = ftell(second_pass_log_stream);
1244
    rewind(second_pass_log_stream);
1245
    size_t read_size = 0;
1246
    while (read_size < file_size) {
1247
      THIRD_PASS_GOP_INFO gop_info;
1248
      struct aom_internal_error_info *error = cpi->common.error;
1249
      // Read in GOP information from the second pass file.
1250
      av1_read_second_pass_gop_info(second_pass_log_stream, &gop_info, error);
1251
      TPL_INFO *tpl_info;
1252
      AOM_CHECK_MEM_ERROR(cm->error, tpl_info, aom_malloc(sizeof(*tpl_info)));
1253
      av1_read_tpl_info(tpl_info, second_pass_log_stream, error);
1254
      // Read in per-frame info from second-pass encoding
1255
      av1_read_second_pass_per_frame_info(second_pass_log_stream, frame_info,
1256
                                          gop_info.num_frames, error);
1257
      av1_vbr_rc_append_tpl_info(vbr_rc_info, tpl_info);
1258
      read_size = ftell(second_pass_log_stream);
1259
      aom_free(tpl_info);
1260
    }
1261
    av1_close_second_pass_log(cpi);
1262
    if (cpi->oxcf.rc_cfg.mode == AOM_Q) {
1263
      vbr_rc_info->base_q_index = cpi->oxcf.rc_cfg.cq_level;
1264
      av1_vbr_rc_compute_q_indices(
1265
          vbr_rc_info->base_q_index, vbr_rc_info->total_frame_count,
1266
          vbr_rc_info->qstep_ratio_list, cm->seq_params->bit_depth,
1267
          vbr_rc_info->q_index_list);
1268
    } else {
1269
      vbr_rc_info->base_q_index = av1_vbr_rc_info_estimate_base_q(
1270
          vbr_rc_info->total_bit_budget, cm->seq_params->bit_depth,
1271
          vbr_rc_info->scale_factors, vbr_rc_info->total_frame_count,
1272
          vbr_rc_info->update_type_list, vbr_rc_info->qstep_ratio_list,
1273
          vbr_rc_info->txfm_stats_list, vbr_rc_info->q_index_list, NULL);
1274
    }
1275
    vbr_rc_info->ready = 1;
1276
#if CONFIG_RATECTRL_LOG
1277
    rc_log_record_chunk_info(&cpi->rc_log, vbr_rc_info->base_q_index,
1278
                             vbr_rc_info->total_frame_count);
1279
#endif  // CONFIG_RATECTRL_LOG
1280
  }
1281
#endif  // CONFIG_BITRATE_ACCURACY && CONFIG_THREE_PASS
1282
1283
  // Check if we need to stuff more src frames
1284
241k
  if (flush == 0) {
1285
129k
    int srcbuf_size =
1286
129k
        av1_lookahead_depth(cpi->ppi->lookahead, cpi->compressor_stage);
1287
129k
    int pop_size =
1288
129k
        av1_lookahead_pop_sz(cpi->ppi->lookahead, cpi->compressor_stage);
1289
1290
    // Continue buffering look ahead buffer.
1291
129k
    if (srcbuf_size < pop_size) return -1;
1292
129k
  }
1293
1294
222k
  if (!av1_lookahead_peek(cpi->ppi->lookahead, 0, cpi->compressor_stage)) {
1295
93.7k
#if !CONFIG_REALTIME_ONLY
1296
93.7k
    if (flush && oxcf->pass == AOM_RC_FIRST_PASS &&
1297
0
        !cpi->ppi->twopass.first_pass_done) {
1298
0
      av1_end_first_pass(cpi); /* get last stats packet */
1299
0
      cpi->ppi->twopass.first_pass_done = 1;
1300
0
    }
1301
93.7k
#endif
1302
93.7k
    return -1;
1303
93.7k
  }
1304
1305
  // TODO(sarahparker) finish bit allocation for one pass pyramid
1306
129k
  if (has_no_stats_stage(cpi)) {
1307
91.1k
    gf_cfg->gf_max_pyr_height =
1308
91.1k
        AOMMIN(gf_cfg->gf_max_pyr_height, USE_ALTREF_FOR_ONE_PASS);
1309
91.1k
    gf_cfg->gf_min_pyr_height =
1310
91.1k
        AOMMIN(gf_cfg->gf_min_pyr_height, gf_cfg->gf_max_pyr_height);
1311
91.1k
  }
1312
1313
  // Allocation of mi buffers.
1314
129k
  alloc_mb_mode_info_buffers(cpi);
1315
1316
129k
  cpi->skip_tpl_setup_stats = 0;
1317
129k
#if !CONFIG_REALTIME_ONLY
1318
129k
  if (oxcf->pass != AOM_RC_FIRST_PASS) {
1319
129k
    TplParams *const tpl_data = &cpi->ppi->tpl_data;
1320
129k
    if (tpl_data->tpl_stats_pool[0] == NULL) {
1321
117k
      av1_setup_tpl_buffers(cpi->ppi, &cm->mi_params, oxcf->frm_dim_cfg.width,
1322
117k
                            oxcf->frm_dim_cfg.height, 0,
1323
117k
                            oxcf->gf_cfg.lag_in_frames);
1324
117k
    }
1325
129k
  }
1326
129k
  cpi->twopass_frame.this_frame = NULL;
1327
129k
  const int use_one_pass_rt_params = is_one_pass_rt_params(cpi);
1328
129k
  if (!use_one_pass_rt_params && !is_stat_generation_stage(cpi)) {
1329
#if CONFIG_COLLECT_COMPONENT_TIMING
1330
    start_timing(cpi, av1_get_second_pass_params_time);
1331
#endif
1332
1333
    // Initialise frame_level_rate_correction_factors with value previous
1334
    // to the parallel frames.
1335
88.2k
    if (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
1336
0
      for (int i = 0; i < RATE_FACTOR_LEVELS; i++) {
1337
0
        cpi->rc.frame_level_rate_correction_factors[i] =
1338
#if CONFIG_FPMT_TEST
1339
            (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE)
1340
                ? cpi->ppi->p_rc.temp_rate_correction_factors[i]
1341
                :
1342
#endif  // CONFIG_FPMT_TEST
1343
0
                cpi->ppi->p_rc.rate_correction_factors[i];
1344
0
      }
1345
0
    }
1346
1347
    // copy mv_stats from ppi to frame_level cpi.
1348
88.2k
    cpi->mv_stats = cpi->ppi->mv_stats;
1349
88.2k
    av1_get_second_pass_params(cpi, &frame_params, *frame_flags);
1350
#if CONFIG_COLLECT_COMPONENT_TIMING
1351
    end_timing(cpi, av1_get_second_pass_params_time);
1352
#endif
1353
88.2k
  }
1354
129k
#endif
1355
1356
129k
  if (!is_stat_generation_stage(cpi)) {
1357
    // TODO(jingning): fwd key frame always uses show existing frame?
1358
110k
    if (gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE &&
1359
0
        gf_group->refbuf_state[cpi->gf_frame_index] == REFBUF_RESET) {
1360
0
      frame_params.show_existing_frame = 1;
1361
110k
    } else {
1362
110k
      frame_params.show_existing_frame =
1363
110k
          (cpi->ppi->show_existing_alt_ref &&
1364
0
           gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE) ||
1365
110k
          gf_group->update_type[cpi->gf_frame_index] == INTNL_OVERLAY_UPDATE;
1366
110k
    }
1367
110k
    frame_params.show_existing_frame &= allow_show_existing(cpi, *frame_flags);
1368
1369
    // Special handling to reset 'show_existing_frame' in case of dropped
1370
    // frames.
1371
110k
    if (oxcf->rc_cfg.drop_frames_water_mark &&
1372
0
        (gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE ||
1373
0
         gf_group->update_type[cpi->gf_frame_index] == INTNL_OVERLAY_UPDATE)) {
1374
      // During the encode of an OVERLAY_UPDATE/INTNL_OVERLAY_UPDATE frame, loop
1375
      // over the gf group to check if the corresponding
1376
      // ARF_UPDATE/INTNL_ARF_UPDATE frame was dropped.
1377
0
      int cur_disp_idx = gf_group->display_idx[cpi->gf_frame_index];
1378
0
      for (int idx = 0; idx < cpi->gf_frame_index; idx++) {
1379
0
        if (cur_disp_idx == gf_group->display_idx[idx]) {
1380
0
          assert(IMPLIES(
1381
0
              gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE,
1382
0
              gf_group->update_type[idx] == ARF_UPDATE));
1383
0
          assert(IMPLIES(gf_group->update_type[cpi->gf_frame_index] ==
1384
0
                             INTNL_OVERLAY_UPDATE,
1385
0
                         gf_group->update_type[idx] == INTNL_ARF_UPDATE));
1386
          // Reset show_existing_frame and set cpi->is_dropped_frame to true if
1387
          // the frame was dropped during its first encode.
1388
0
          if (gf_group->is_frame_dropped[idx]) {
1389
0
            frame_params.show_existing_frame = 0;
1390
0
            assert(!cpi->is_dropped_frame);
1391
0
            cpi->is_dropped_frame = true;
1392
0
          }
1393
0
          break;
1394
0
        }
1395
0
      }
1396
0
    }
1397
1398
    // Reset show_existing_alt_ref decision to 0 after it is used.
1399
110k
    if (gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE) {
1400
0
      cpi->ppi->show_existing_alt_ref = 0;
1401
0
    }
1402
110k
  } else {
1403
18.9k
    frame_params.show_existing_frame = 0;
1404
18.9k
  }
1405
1406
129k
  struct lookahead_entry *source = NULL;
1407
129k
  struct lookahead_entry *last_source = NULL;
1408
129k
  if (frame_params.show_existing_frame) {
1409
0
    source = av1_lookahead_peek(cpi->ppi->lookahead, 0, cpi->compressor_stage);
1410
0
    *pop_lookahead = 1;
1411
0
    frame_params.show_frame = 1;
1412
129k
  } else {
1413
129k
    source = choose_frame_source(cpi, &flush, pop_lookahead, &last_source,
1414
129k
                                 &frame_params.show_frame);
1415
129k
  }
1416
1417
129k
  if (source == NULL) {  // If no source was found, we can't encode a frame.
1418
0
#if !CONFIG_REALTIME_ONLY
1419
0
    if (flush && oxcf->pass == AOM_RC_FIRST_PASS &&
1420
0
        !cpi->ppi->twopass.first_pass_done) {
1421
0
      av1_end_first_pass(cpi); /* get last stats packet */
1422
0
      cpi->ppi->twopass.first_pass_done = 1;
1423
0
    }
1424
0
#endif
1425
0
    return -1;
1426
0
  }
1427
1428
  // reset src_offset to allow actual encode call for this frame to get its
1429
  // source.
1430
129k
  gf_group->src_offset[cpi->gf_frame_index] = 0;
1431
1432
  // Source may be changed if temporal filtered later.
1433
129k
  frame_input.source = &source->img;
1434
129k
  if ((cpi->ppi->use_svc || cpi->rc.prev_frame_is_dropped) &&
1435
0
      last_source != NULL)
1436
0
    av1_svc_set_last_source(cpi, &frame_input, &last_source->img);
1437
129k
  else
1438
129k
    frame_input.last_source = last_source != NULL ? &last_source->img : NULL;
1439
129k
  frame_input.ts_duration = source->ts_end - source->ts_start;
1440
  // Save unfiltered source. It is used in av1_get_second_pass_params().
1441
129k
  cpi->unfiltered_source = frame_input.source;
1442
1443
129k
  *time_stamp = source->ts_start;
1444
129k
  *time_end = source->ts_end;
1445
129k
  if (source->ts_start < cpi->time_stamps.first_ts_start) {
1446
74.8k
    cpi->time_stamps.first_ts_start = source->ts_start;
1447
74.8k
    cpi->time_stamps.prev_ts_end = source->ts_start;
1448
74.8k
  }
1449
1450
129k
  av1_apply_encoding_flags(cpi, source->flags);
1451
129k
  *frame_flags = (source->flags & AOM_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
1452
1453
#if CONFIG_FPMT_TEST
1454
  if (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) {
1455
    if (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
1456
      cpi->framerate = cpi->temp_framerate;
1457
    }
1458
  }
1459
#endif  // CONFIG_FPMT_TEST
1460
1461
  // Shown frames and arf-overlay frames need frame-rate considering
1462
129k
  if (frame_params.show_frame)
1463
129k
    adjust_frame_rate(cpi, source->ts_start, source->ts_end);
1464
1465
129k
  if (!frame_params.show_existing_frame) {
1466
129k
#if !CONFIG_REALTIME_ONLY
1467
129k
    if (cpi->film_grain_table) {
1468
0
      cm->cur_frame->film_grain_params_present = aom_film_grain_table_lookup(
1469
0
          cpi->film_grain_table, *time_stamp, *time_end, 0 /* =erase */,
1470
0
          &cm->film_grain_params);
1471
129k
    } else {
1472
129k
      cm->cur_frame->film_grain_params_present =
1473
129k
          cm->seq_params->film_grain_params_present;
1474
129k
    }
1475
129k
#endif
1476
    // only one operating point supported now
1477
129k
    const int64_t pts64 = ticks_to_timebase_units(timestamp_ratio, *time_stamp);
1478
129k
    if (pts64 < 0 || pts64 > UINT32_MAX) return AOM_CODEC_ERROR;
1479
1480
129k
    cm->frame_presentation_time = (uint32_t)pts64;
1481
129k
  }
1482
1483
#if CONFIG_COLLECT_COMPONENT_TIMING
1484
  start_timing(cpi, av1_get_one_pass_rt_params_time);
1485
#endif
1486
#if CONFIG_REALTIME_ONLY
1487
  av1_get_one_pass_rt_params(cpi, &frame_params.frame_type, &frame_input,
1488
                             *frame_flags);
1489
  if (use_rtc_reference_structure_one_layer(cpi))
1490
    av1_set_rtc_reference_structure_one_layer(cpi, cpi->gf_frame_index == 0);
1491
#else
1492
129k
  if (use_one_pass_rt_params) {
1493
21.8k
    av1_get_one_pass_rt_params(cpi, &frame_params.frame_type, &frame_input,
1494
21.8k
                               *frame_flags);
1495
21.8k
    if (use_rtc_reference_structure_one_layer(cpi))
1496
21.8k
      av1_set_rtc_reference_structure_one_layer(cpi, cpi->gf_frame_index == 0);
1497
21.8k
  }
1498
129k
#endif
1499
#if CONFIG_COLLECT_COMPONENT_TIMING
1500
  end_timing(cpi, av1_get_one_pass_rt_params_time);
1501
#endif
1502
1503
129k
  FRAME_UPDATE_TYPE frame_update_type =
1504
129k
      get_frame_update_type(gf_group, cpi->gf_frame_index);
1505
1506
129k
  if (frame_params.show_existing_frame &&
1507
0
      frame_params.frame_type != KEY_FRAME) {
1508
    // Force show-existing frames to be INTER, except forward keyframes
1509
0
    frame_params.frame_type = INTER_FRAME;
1510
0
  }
1511
1512
  // Per-frame encode speed.  In theory this can vary, but things may have
1513
  // been written assuming speed-level will not change within a sequence, so
1514
  // this parameter should be used with caution.
1515
129k
  frame_params.speed = oxcf->speed;
1516
1517
129k
#if !CONFIG_REALTIME_ONLY
1518
  // Set forced key frames when necessary. For two-pass encoding / lap mode,
1519
  // this is already handled by av1_get_second_pass_params. However when no
1520
  // stats are available, we still need to check if the new frame is a keyframe.
1521
  // For one pass rt, this is already checked in av1_get_one_pass_rt_params.
1522
129k
  if (!use_one_pass_rt_params &&
1523
107k
      (is_stat_generation_stage(cpi) || has_no_stats_stage(cpi))) {
1524
    // Current frame is coded as a key-frame for any of the following cases:
1525
    // 1) First frame of a video
1526
    // 2) For all-intra frame encoding
1527
    // 3) When a key-frame is forced
1528
88.2k
    const int kf_requested =
1529
88.2k
        (cm->current_frame.frame_number == 0 ||
1530
27.7k
         oxcf->kf_cfg.key_freq_max == 0 || (*frame_flags & FRAMEFLAGS_KEY));
1531
88.2k
    if (kf_requested && frame_update_type != OVERLAY_UPDATE &&
1532
67.6k
        frame_update_type != INTNL_OVERLAY_UPDATE) {
1533
67.6k
      frame_params.frame_type = KEY_FRAME;
1534
67.6k
    } else if (is_stat_generation_stage(cpi)) {
1535
      // For stats generation, set the frame type to inter here.
1536
9.31k
      frame_params.frame_type = INTER_FRAME;
1537
9.31k
    }
1538
88.2k
  }
1539
129k
#endif
1540
1541
  // Work out some encoding parameters specific to the pass:
1542
129k
  if (has_no_stats_stage(cpi) && oxcf->q_cfg.aq_mode == CYCLIC_REFRESH_AQ) {
1543
0
    av1_cyclic_refresh_update_parameters(cpi);
1544
129k
  } else if (is_stat_generation_stage(cpi)) {
1545
18.9k
    cpi->td.mb.e_mbd.lossless[0] = is_lossless_requested(&oxcf->rc_cfg);
1546
110k
  } else if (is_stat_consumption_stage(cpi)) {
1547
#if CONFIG_MISMATCH_DEBUG
1548
    mismatch_move_frame_idx_w();
1549
#endif
1550
#if TXCOEFF_COST_TIMER
1551
    cm->txcoeff_cost_timer = 0;
1552
    cm->txcoeff_cost_count = 0;
1553
#endif
1554
18.9k
  }
1555
1556
129k
  if (!is_stat_generation_stage(cpi))
1557
110k
    set_ext_overrides(cm, &frame_params, ext_flags);
1558
1559
  // Shown keyframes and S frames refresh all reference buffers
1560
129k
  const int force_refresh_all =
1561
129k
      ((frame_params.frame_type == KEY_FRAME && frame_params.show_frame) ||
1562
36.8k
       frame_params.frame_type == S_FRAME) &&
1563
92.1k
      !frame_params.show_existing_frame;
1564
1565
129k
  av1_configure_buffer_updates(
1566
129k
      cpi, &frame_params.refresh_frame, frame_update_type,
1567
129k
      gf_group->refbuf_state[cpi->gf_frame_index], force_refresh_all);
1568
1569
129k
  if (!is_stat_generation_stage(cpi)) {
1570
110k
    const YV12_BUFFER_CONFIG *ref_frame_buf[INTER_REFS_PER_FRAME];
1571
1572
110k
    RefFrameMapPair ref_frame_map_pairs[REF_FRAMES];
1573
110k
    init_ref_map_pair(cpi, ref_frame_map_pairs);
1574
110k
    const int order_offset = gf_group->arf_src_offset[cpi->gf_frame_index];
1575
110k
    const int cur_frame_disp =
1576
110k
        cpi->common.current_frame.frame_number + order_offset;
1577
1578
110k
    int get_ref_frames = 0;
1579
#if CONFIG_FPMT_TEST
1580
    get_ref_frames =
1581
        (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) ? 1 : 0;
1582
#endif  // CONFIG_FPMT_TEST
1583
110k
    if (get_ref_frames ||
1584
110k
        gf_group->frame_parallel_level[cpi->gf_frame_index] == 0) {
1585
110k
      if (!ext_flags->refresh_frame.update_pending) {
1586
88.2k
        av1_get_ref_frames(ref_frame_map_pairs, cur_frame_disp, cpi,
1587
88.2k
                           cpi->gf_frame_index, 1, cm->remapped_ref_idx);
1588
88.2k
      } else if (cpi->ppi->rtc_ref.set_ref_frame_config ||
1589
21.8k
                 use_rtc_reference_structure_one_layer(cpi)) {
1590
174k
        for (unsigned int i = 0; i < INTER_REFS_PER_FRAME; i++)
1591
152k
          cm->remapped_ref_idx[i] = cpi->ppi->rtc_ref.ref_idx[i];
1592
21.8k
      }
1593
110k
    }
1594
1595
    // Get the reference frames
1596
110k
    bool has_ref_frames = false;
1597
880k
    for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
1598
770k
      const RefCntBuffer *ref_frame =
1599
770k
          get_ref_frame_buf(cm, ref_frame_priority_order[i]);
1600
770k
      ref_frame_buf[i] = ref_frame != NULL ? &ref_frame->buf : NULL;
1601
770k
      if (ref_frame != NULL) has_ref_frames = true;
1602
770k
    }
1603
110k
    if (!has_ref_frames && (frame_params.frame_type == INTER_FRAME ||
1604
67.8k
                            frame_params.frame_type == S_FRAME)) {
1605
0
      return AOM_CODEC_ERROR;
1606
0
    }
1607
1608
    // Work out which reference frame slots may be used.
1609
110k
    frame_params.ref_frame_flags =
1610
110k
        get_ref_frame_flags(&cpi->sf, is_one_pass_rt_params(cpi), ref_frame_buf,
1611
110k
                            ext_flags->ref_frame_flags);
1612
1613
    // Set primary_ref_frame of non-reference frames as PRIMARY_REF_NONE.
1614
110k
    if (cpi->ppi->gf_group.is_frame_non_ref[cpi->gf_frame_index]) {
1615
0
      frame_params.primary_ref_frame = PRIMARY_REF_NONE;
1616
110k
    } else {
1617
110k
      frame_params.primary_ref_frame =
1618
110k
          choose_primary_ref_frame(cpi, &frame_params);
1619
110k
    }
1620
1621
110k
    frame_params.order_offset = gf_group->arf_src_offset[cpi->gf_frame_index];
1622
1623
    // Call av1_get_refresh_frame_flags() if refresh index not available.
1624
110k
    if (!cpi->refresh_idx_available) {
1625
110k
      frame_params.refresh_frame_flags = av1_get_refresh_frame_flags(
1626
110k
          cpi, &frame_params, frame_update_type, cpi->gf_frame_index,
1627
110k
          cur_frame_disp, ref_frame_map_pairs);
1628
110k
    } else {
1629
0
      assert(cpi->ref_refresh_index != INVALID_IDX);
1630
0
      frame_params.refresh_frame_flags = (1 << cpi->ref_refresh_index);
1631
0
    }
1632
1633
    // Make the frames marked as is_frame_non_ref to non-reference frames.
1634
110k
    if (gf_group->is_frame_non_ref[cpi->gf_frame_index])
1635
0
      frame_params.refresh_frame_flags = 0;
1636
1637
110k
    frame_params.existing_fb_idx_to_show = INVALID_IDX;
1638
    // Find the frame buffer to show based on display order.
1639
110k
    if (frame_params.show_existing_frame) {
1640
0
      for (int frame = 0; frame < REF_FRAMES; frame++) {
1641
0
        const RefCntBuffer *const buf = cm->ref_frame_map[frame];
1642
0
        if (buf == NULL) continue;
1643
0
        const int frame_order = (int)buf->display_order_hint;
1644
0
        if (frame_order == cur_frame_disp)
1645
0
          frame_params.existing_fb_idx_to_show = frame;
1646
0
      }
1647
0
    }
1648
110k
  }
1649
1650
  // The way frame_params->remapped_ref_idx is setup is a placeholder.
1651
  // Currently, reference buffer assignment is done by update_ref_frame_map()
1652
  // which is called by high-level strategy AFTER encoding a frame.  It
1653
  // modifies cm->remapped_ref_idx.  If you want to use an alternative method
1654
  // to determine reference buffer assignment, just put your assignments into
1655
  // frame_params->remapped_ref_idx here and they will be used when encoding
1656
  // this frame.  If frame_params->remapped_ref_idx is setup independently of
1657
  // cm->remapped_ref_idx then update_ref_frame_map() will have no effect.
1658
129k
  memcpy(frame_params.remapped_ref_idx, cm->remapped_ref_idx,
1659
129k
         REF_FRAMES * sizeof(*cm->remapped_ref_idx));
1660
1661
129k
  cpi->td.mb.rdmult_delta_qindex = cpi->td.mb.delta_qindex = 0;
1662
1663
129k
  if (!frame_params.show_existing_frame) {
1664
129k
    cm->quant_params.using_qmatrix = oxcf->q_cfg.using_qm;
1665
129k
  }
1666
1667
129k
  const int is_intra_frame = frame_params.frame_type == KEY_FRAME ||
1668
36.8k
                             frame_params.frame_type == INTRA_ONLY_FRAME;
1669
129k
  FeatureFlags *const features = &cm->features;
1670
129k
  if (!is_stat_generation_stage(cpi) &&
1671
110k
      (oxcf->pass == AOM_RC_ONE_PASS || oxcf->pass >= AOM_RC_SECOND_PASS) &&
1672
110k
      is_intra_frame) {
1673
82.5k
    av1_set_screen_content_options(cpi, features);
1674
82.5k
  }
1675
1676
#if CONFIG_REALTIME_ONLY
1677
  if (av1_encode(cpi, dest, dest_size, &frame_input, &frame_params,
1678
                 &frame_size) != AOM_CODEC_OK) {
1679
    return AOM_CODEC_ERROR;
1680
  }
1681
#else
1682
129k
  if (has_no_stats_stage(cpi) && oxcf->mode == REALTIME &&
1683
21.8k
      gf_cfg->lag_in_frames == 0) {
1684
21.8k
    if (av1_encode(cpi, dest, dest_size, &frame_input, &frame_params,
1685
21.8k
                   &frame_size) != AOM_CODEC_OK) {
1686
0
      return AOM_CODEC_ERROR;
1687
0
    }
1688
107k
  } else if (denoise_and_encode(cpi, dest, dest_size, &frame_input,
1689
107k
                                &frame_params, &frame_size) != AOM_CODEC_OK) {
1690
0
    return AOM_CODEC_ERROR;
1691
0
  }
1692
129k
#endif  // CONFIG_REALTIME_ONLY
1693
1694
  // This is used in rtc temporal filter case. Use true source in the PSNR
1695
  // calculation.
1696
129k
  if (is_psnr_calc_enabled(cpi) && cpi->sf.rt_sf.use_rtc_tf) {
1697
0
    assert(cpi->orig_source.buffer_alloc_sz > 0);
1698
0
    cpi->source = &cpi->orig_source;
1699
0
  }
1700
1701
129k
  if (!is_stat_generation_stage(cpi)) {
1702
    // First pass doesn't modify reference buffer assignment or produce frame
1703
    // flags
1704
110k
    update_frame_flags(&cpi->common, &cpi->refresh_frame, frame_flags);
1705
110k
    set_additional_frame_flags(cm, frame_flags);
1706
110k
  }
1707
1708
129k
#if !CONFIG_REALTIME_ONLY
1709
#if TXCOEFF_COST_TIMER
1710
  if (!is_stat_generation_stage(cpi)) {
1711
    cm->cum_txcoeff_cost_timer += cm->txcoeff_cost_timer;
1712
    fprintf(stderr,
1713
            "\ntxb coeff cost block number: %ld, frame time: %ld, cum time %ld "
1714
            "in us\n",
1715
            cm->txcoeff_cost_count, cm->txcoeff_cost_timer,
1716
            cm->cum_txcoeff_cost_timer);
1717
  }
1718
#endif
1719
129k
#endif  // !CONFIG_REALTIME_ONLY
1720
1721
#if CONFIG_TUNE_VMAF
1722
  if (!is_stat_generation_stage(cpi) &&
1723
      (oxcf->tune_cfg.tuning >= AOM_TUNE_VMAF_WITH_PREPROCESSING &&
1724
       oxcf->tune_cfg.tuning <= AOM_TUNE_VMAF_NEG_MAX_GAIN)) {
1725
    av1_update_vmaf_curve(cpi);
1726
  }
1727
#endif
1728
1729
129k
  *size = frame_size;
1730
1731
  // Leave a signal for a higher level caller about if this frame is droppable
1732
129k
  if (*size > 0) {
1733
110k
    cpi->droppable =
1734
110k
        is_frame_droppable(&cpi->ppi->rtc_ref, &ext_flags->refresh_frame);
1735
110k
  }
1736
1737
  // For SVC, or when frame-dropper is enabled:
1738
  // keep track of the (unscaled) source corresponding to the refresh of LAST
1739
  // reference (base temporal layer - TL0). Copy only for the
1740
  // top spatial enhancement layer so all spatial layers of the next
1741
  // superframe have last_source to be aligned with previous TL0 superframe.
1742
  // Avoid cases where resolution changes for unscaled source (top spatial
1743
  // layer). Only needs to be done for frame that are encoded (size > 0).
1744
129k
  if (*size > 0 &&
1745
110k
      (cpi->ppi->use_svc || cpi->oxcf.rc_cfg.drop_frames_water_mark > 0) &&
1746
0
      cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1747
0
      cpi->svc.temporal_layer_id == 0 &&
1748
0
      cpi->unscaled_source->y_width == cpi->svc.source_last_TL0.y_width &&
1749
0
      cpi->unscaled_source->y_height == cpi->svc.source_last_TL0.y_height) {
1750
0
    aom_yv12_copy_y(cpi->unscaled_source, &cpi->svc.source_last_TL0, 1);
1751
0
    aom_yv12_copy_u(cpi->unscaled_source, &cpi->svc.source_last_TL0, 1);
1752
0
    aom_yv12_copy_v(cpi->unscaled_source, &cpi->svc.source_last_TL0, 1);
1753
0
  }
1754
1755
129k
  return AOM_CODEC_OK;
1756
129k
}