Coverage Report

Created: 2026-08-31 07:01

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
303k
    bool refresh_arf) {
50
303k
  refresh_frame->golden_frame = refresh_gf;
51
303k
  refresh_frame->bwd_ref_frame = refresh_bwdref;
52
303k
  refresh_frame->alt_ref_frame = refresh_arf;
53
303k
}
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
174k
                                  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
174k
  const ExtRefreshFrameFlagsInfo *const ext_refresh_frame_flags =
63
174k
      &cpi->ext_flags.refresh_frame;
64
174k
  cpi->rc.is_src_frame_alt_ref = 0;
65
66
174k
  switch (type) {
67
137k
    case KF_UPDATE:
68
137k
      set_refresh_frame_flags(refresh_frame, true, true, true);
69
137k
      break;
70
71
30.0k
    case LF_UPDATE:
72
30.0k
      set_refresh_frame_flags(refresh_frame, false, false, false);
73
30.0k
      break;
74
75
4
    case GF_UPDATE:
76
4
      set_refresh_frame_flags(refresh_frame, true, false, false);
77
4
      break;
78
79
3.23k
    case OVERLAY_UPDATE:
80
3.23k
      if (refbuf_state == REFBUF_RESET)
81
0
        set_refresh_frame_flags(refresh_frame, true, true, true);
82
3.23k
      else
83
3.23k
        set_refresh_frame_flags(refresh_frame, true, false, false);
84
85
3.23k
      cpi->rc.is_src_frame_alt_ref = 1;
86
3.23k
      break;
87
88
3.23k
    case ARF_UPDATE:
89
      // NOTE: BWDREF does not get updated along with ALTREF_FRAME.
90
3.23k
      if (refbuf_state == REFBUF_RESET)
91
0
        set_refresh_frame_flags(refresh_frame, true, true, true);
92
3.23k
      else
93
3.23k
        set_refresh_frame_flags(refresh_frame, false, false, true);
94
95
3.23k
      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
174k
  }
108
109
174k
  if (ext_refresh_frame_flags->update_pending &&
110
20.3k
      (!is_stat_generation_stage(cpi))) {
111
20.3k
    set_refresh_frame_flags(refresh_frame,
112
20.3k
                            ext_refresh_frame_flags->golden_frame,
113
20.3k
                            ext_refresh_frame_flags->bwd_ref_frame,
114
20.3k
                            ext_refresh_frame_flags->alt_ref_frame);
115
20.3k
    GF_GROUP *gf_group = &cpi->ppi->gf_group;
116
20.3k
    if (ext_refresh_frame_flags->golden_frame)
117
4
      gf_group->update_type[cpi->gf_frame_index] = GF_UPDATE;
118
20.3k
    if (ext_refresh_frame_flags->alt_ref_frame)
119
0
      gf_group->update_type[cpi->gf_frame_index] = ARF_UPDATE;
120
20.3k
    if (ext_refresh_frame_flags->bwd_ref_frame)
121
0
      gf_group->update_type[cpi->gf_frame_index] = INTNL_ARF_UPDATE;
122
20.3k
  }
123
124
174k
  if (force_refresh_all)
125
109k
    set_refresh_frame_flags(refresh_frame, true, true, true);
126
174k
}
127
128
static void set_additional_frame_flags(const AV1_COMMON *const cm,
129
127k
                                       unsigned int *const frame_flags) {
130
127k
  if (frame_is_intra_only(cm)) {
131
101k
    *frame_flags |= FRAMEFLAGS_INTRAONLY;
132
101k
  }
133
127k
  if (frame_is_sframe(cm)) {
134
0
    *frame_flags |= FRAMEFLAGS_SWITCH;
135
0
  }
136
127k
  if (cm->features.error_resilient_mode) {
137
0
    *frame_flags |= FRAMEFLAGS_ERROR_RESILIENT;
138
0
  }
139
127k
}
140
141
static void set_ext_overrides(AV1_COMMON *const cm,
142
                              EncodeFrameParams *const frame_params,
143
127k
                              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
127k
  if (ext_flags->use_s_frame) {
150
0
    frame_params->frame_type = S_FRAME;
151
0
  }
152
153
127k
  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
127k
  cm->features.allow_ref_frame_mvs = ext_flags->use_ref_frame_mvs;
158
159
127k
  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
127k
  frame_params->error_resilient_mode &= frame_params->frame_type != KEY_FRAME;
164
  // For bitstream conformance, s-frames must be error-resilient
165
127k
  frame_params->error_resilient_mode |= frame_params->frame_type == S_FRAME;
166
127k
}
167
168
static int choose_primary_ref_frame(
169
127k
    AV1_COMP *const cpi, const EncodeFrameParams *const frame_params) {
170
127k
  const AV1_COMMON *const cm = &cpi->common;
171
172
127k
  const int intra_only = frame_params->frame_type == KEY_FRAME ||
173
26.3k
                         frame_params->frame_type == INTRA_ONLY_FRAME;
174
127k
  if (intra_only || frame_params->error_resilient_mode ||
175
101k
      cpi->ext_flags.use_primary_ref_none) {
176
101k
    return PRIMARY_REF_NONE;
177
101k
  }
178
179
26.3k
#if !CONFIG_REALTIME_ONLY
180
26.3k
  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
26.3k
#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
26.3k
  if (cm->tiles.large_scale) return (LAST_FRAME - LAST_FRAME);
196
197
26.3k
  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
26.3k
  const int current_ref_type = get_current_frame_ref_type(cpi);
203
26.3k
  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
26.3k
  int primary_ref_frame = PRIMARY_REF_NONE;
224
211k
  for (int ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
225
184k
    if (get_ref_frame_map_idx(cm, ref_frame) == wanted_fb) {
226
21.1k
      primary_ref_frame = ref_frame - LAST_FRAME;
227
21.1k
    }
228
184k
  }
229
230
26.3k
  return primary_ref_frame;
231
26.3k
}
232
233
143k
static void adjust_frame_rate(AV1_COMP *cpi, int64_t ts_start, int64_t ts_end) {
234
143k
  TimeStamps *time_stamps = &cpi->time_stamps;
235
143k
  int64_t this_duration;
236
143k
  int step = 0;
237
238
  // Clear down mmx registers
239
240
143k
  if (is_one_pass_rt_params(cpi) ||
241
123k
      (cpi->ppi->use_svc && cpi->ppi->rtc_ref.set_ref_frame_config &&
242
20.3k
       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
20.3k
    this_duration = ts_end - ts_start;
252
20.3k
    if (this_duration > 0) {
253
20.3k
      cpi->new_framerate = 10000000.0 / this_duration;
254
20.3k
      av1_new_framerate(cpi, cpi->new_framerate);
255
20.3k
      time_stamps->prev_ts_start = ts_start;
256
20.3k
      time_stamps->prev_ts_end = ts_end;
257
20.3k
      return;
258
20.3k
    }
259
20.3k
  }
260
261
123k
  if (ts_start == time_stamps->first_ts_start) {
262
123k
    this_duration = ts_end - ts_start;
263
123k
    step = 1;
264
123k
  } 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
123k
  if (this_duration) {
276
123k
    if (step) {
277
123k
      cpi->new_framerate = 10000000.0 / this_duration;
278
123k
      av1_new_framerate(cpi, cpi->new_framerate);
279
123k
    } 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
123k
  }
298
299
123k
  time_stamps->prev_ts_start = ts_start;
300
123k
  time_stamps->prev_ts_end = ts_end;
301
123k
}
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
208k
                               const COMPRESSOR_STAGE compressor_stage) {
307
436k
  for (int i = 0; i <= up_to_index; i++) {
308
434k
    const struct lookahead_entry *e =
309
434k
        av1_lookahead_peek(lookahead, i, compressor_stage);
310
434k
    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
184k
      return -1;
314
250k
    } else if (e->flags == AOM_EFLAG_FORCE_KF) {
315
22.8k
      return i;
316
227k
    } else {
317
227k
      continue;
318
227k
    }
319
434k
  }
320
1.61k
  return -1;  // Never reached
321
208k
}
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
145k
    struct lookahead_entry **last_source, int *const show_frame) {
330
145k
  AV1_COMMON *const cm = &cpi->common;
331
145k
  const GF_GROUP *const gf_group = &cpi->ppi->gf_group;
332
145k
  struct lookahead_entry *source = NULL;
333
334
  // Source index in lookahead buffer.
335
145k
  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
145k
  if (src_index &&
339
1.61k
      (is_forced_keyframe_pending(cpi->ppi->lookahead, src_index,
340
1.61k
                                  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
145k
  *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
145k
  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
145k
  if (is_stat_generation_stage(cpi)) {
367
17.9k
    *pop_lookahead = 1;
368
17.9k
    src_index = 0;
369
17.9k
  }
370
371
145k
  *show_frame = *pop_lookahead;
372
373
#if CONFIG_FPMT_TEST
374
  if (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_ENCODE) {
375
#else
376
145k
  {
377
145k
#endif  // CONFIG_FPMT_TEST
378
    // Future frame in parallel encode set
379
145k
    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
145k
  }
383
145k
  if (*show_frame) {
384
    // show frame, pop from buffer
385
    // Get last frame source.
386
143k
    if (cm->current_frame.frame_number > 0) {
387
47.4k
      *last_source = av1_lookahead_peek(cpi->ppi->lookahead, src_index - 1,
388
47.4k
                                        cpi->compressor_stage);
389
47.4k
    }
390
    // Read in the source frame.
391
143k
    source = av1_lookahead_peek(cpi->ppi->lookahead, src_index,
392
143k
                                cpi->compressor_stage);
393
143k
  } else {
394
    // no show frames are arf frames
395
1.61k
    source = av1_lookahead_peek(cpi->ppi->lookahead, src_index,
396
1.61k
                                cpi->compressor_stage);
397
1.61k
    if (source != NULL) {
398
1.61k
      cm->showable_frame = 1;
399
1.61k
    }
400
1.61k
  }
401
145k
  return source;
402
145k
}
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
127k
                               unsigned int frame_flags) {
409
127k
  if (cpi->common.current_frame.frame_number == 0) return 0;
410
411
37.3k
  const struct lookahead_entry *lookahead_src =
412
37.3k
      av1_lookahead_peek(cpi->ppi->lookahead, 0, cpi->compressor_stage);
413
37.3k
  if (lookahead_src == NULL) return 1;
414
415
37.3k
  const int is_error_resilient =
416
37.3k
      cpi->oxcf.tool_cfg.error_resilient_mode ||
417
37.3k
      (lookahead_src->flags & AOM_EFLAG_ERROR_RESILIENT);
418
37.3k
  const int is_s_frame = cpi->oxcf.kf_cfg.enable_sframe ||
419
37.3k
                         (lookahead_src->flags & AOM_EFLAG_SET_S_FRAME);
420
37.3k
  const int is_key_frame =
421
37.3k
      (cpi->rc.frames_to_key == 0) || (frame_flags & FRAMEFLAGS_KEY);
422
37.3k
  return !(is_error_resilient || is_s_frame) || is_key_frame;
423
37.3k
}
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
127k
                               unsigned int *frame_flags) {
430
127k
  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
127k
  if (refresh_frame->golden_frame) {
439
102k
    *frame_flags |= FRAMEFLAGS_GOLDEN;
440
102k
  } else {
441
24.7k
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_GOLDEN;
442
24.7k
  }
443
444
127k
  if (refresh_frame->alt_ref_frame) {
445
102k
    *frame_flags |= FRAMEFLAGS_ALTREF;
446
102k
  } else {
447
24.7k
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_ALTREF;
448
24.7k
  }
449
450
127k
  if (refresh_frame->bwd_ref_frame) {
451
101k
    *frame_flags |= FRAMEFLAGS_BWDREF;
452
101k
  } else {
453
26.3k
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_BWDREF;
454
26.3k
  }
455
456
127k
  if (cm->current_frame.frame_type == KEY_FRAME) {
457
101k
    *frame_flags |= FRAMEFLAGS_KEY;
458
101k
  } else {
459
26.3k
    *frame_flags &= ~(uint32_t)FRAMEFLAGS_KEY;
460
26.3k
  }
461
127k
}
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
19.6k
int av1_get_refresh_ref_frame_map(int refresh_frame_flags) {
516
19.6k
  int ref_map_index;
517
518
46.9k
  for (ref_map_index = 0; ref_map_index < REF_FRAMES; ++ref_map_index)
519
45.2k
    if ((refresh_frame_flags >> ref_map_index) & 1) break;
520
521
19.6k
  if (ref_map_index == REF_FRAMES) ref_map_index = INVALID_IDX;
522
19.6k
  return ref_map_index;
523
19.6k
}
524
525
25.2k
static int get_free_ref_map_index(RefFrameMapPair ref_map_pairs[REF_FRAMES]) {
526
71.1k
  for (int idx = 0; idx < REF_FRAMES; ++idx)
527
71.1k
    if (ref_map_pairs[idx].disp_order == -1) return idx;
528
0
  return INVALID_IDX;
529
25.2k
}
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
0
static int get_new_fb_map_idx_rc(int new_fb_map_idx) {
615
0
  if (new_fb_map_idx == INVALID_IDX) return 0;
616
0
  return 1 << new_fb_map_idx;
617
0
}
618
619
int av1_get_refresh_frame_flags(
620
    const AV1_COMP *const cpi, const EncodeFrameParams *const frame_params,
621
    FRAME_UPDATE_TYPE frame_update_type, int gf_index, int cur_disp_order,
622
147k
    RefFrameMapPair ref_frame_map_pairs[REF_FRAMES]) {
623
147k
  const AV1_COMMON *const cm = &cpi->common;
624
147k
  const ExtRefreshFrameFlagsInfo *const ext_refresh_frame_flags =
625
147k
      &cpi->ext_flags.refresh_frame;
626
627
147k
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
628
147k
  if (gf_group->refbuf_state[gf_index] == REFBUF_RESET)
629
110k
    return SELECT_ALL_BUF_SLOTS;
630
631
  // TODO(jingning): Deprecate the following operations.
632
  // Switch frames and shown key-frames overwrite all reference slots
633
36.5k
  if (frame_params->frame_type == S_FRAME) return SELECT_ALL_BUF_SLOTS;
634
635
  // show_existing_frames don't actually send refresh_frame_flags so set the
636
  // flags to 0 to keep things consistent.
637
36.5k
  if (frame_params->show_existing_frame) return 0;
638
639
34.9k
  const RTC_REF *const rtc_ref = &cpi->ppi->rtc_ref;
640
34.9k
  if (is_frame_droppable(rtc_ref, ext_refresh_frame_flags)) return 0;
641
642
34.9k
#if !CONFIG_REALTIME_ONLY
643
34.9k
  if (cpi->use_ducky_encode &&
644
0
      cpi->ducky_encode_info.frame_info.gop_mode == DUCKY_ENCODE_GOP_MODE_RCL) {
645
0
    return get_new_fb_map_idx_rc(gf_group->update_ref_idx[gf_index]);
646
0
  }
647
34.9k
#endif  // !CONFIG_REALTIME_ONLY
648
649
34.9k
  if (cpi->ext_ratectrl.ready &&
650
0
      (cpi->ext_ratectrl.funcs.rc_type & AOM_RC_GOP) != 0 &&
651
0
      cpi->ext_ratectrl.funcs.get_gop_decision != NULL) {
652
0
    return get_new_fb_map_idx_rc(gf_group->update_ref_idx[gf_index]);
653
0
  }
654
655
34.9k
  int refresh_mask = 0;
656
34.9k
  if (ext_refresh_frame_flags->update_pending) {
657
9.69k
    if (rtc_ref->set_ref_frame_config ||
658
9.69k
        use_rtc_reference_structure_one_layer(cpi)) {
659
77.5k
      for (unsigned int i = 0; i < INTER_REFS_PER_FRAME; i++) {
660
67.8k
        int ref_frame_map_idx = rtc_ref->ref_idx[i];
661
67.8k
        refresh_mask |= rtc_ref->refresh[ref_frame_map_idx]
662
67.8k
                        << ref_frame_map_idx;
663
67.8k
      }
664
9.69k
      return refresh_mask;
665
9.69k
    }
666
    // Unfortunately the encoder interface reflects the old refresh_*_frame
667
    // flags so we have to replicate the old refresh_frame_flags logic here in
668
    // order to preserve the behaviour of the flag overrides.
669
0
    int ref_frame_map_idx = get_ref_frame_map_idx(cm, LAST_FRAME);
670
0
    if (ref_frame_map_idx != INVALID_IDX)
671
0
      refresh_mask |= ext_refresh_frame_flags->last_frame << ref_frame_map_idx;
672
673
0
    ref_frame_map_idx = get_ref_frame_map_idx(cm, EXTREF_FRAME);
674
0
    if (ref_frame_map_idx != INVALID_IDX)
675
0
      refresh_mask |= ext_refresh_frame_flags->bwd_ref_frame
676
0
                      << ref_frame_map_idx;
677
678
0
    ref_frame_map_idx = get_ref_frame_map_idx(cm, ALTREF2_FRAME);
679
0
    if (ref_frame_map_idx != INVALID_IDX)
680
0
      refresh_mask |= ext_refresh_frame_flags->alt2_ref_frame
681
0
                      << ref_frame_map_idx;
682
683
0
    if (frame_update_type == OVERLAY_UPDATE) {
684
0
      ref_frame_map_idx = get_ref_frame_map_idx(cm, ALTREF_FRAME);
685
0
      if (ref_frame_map_idx != INVALID_IDX)
686
0
        refresh_mask |= ext_refresh_frame_flags->golden_frame
687
0
                        << ref_frame_map_idx;
688
0
    } else {
689
0
      ref_frame_map_idx = get_ref_frame_map_idx(cm, GOLDEN_FRAME);
690
0
      if (ref_frame_map_idx != INVALID_IDX)
691
0
        refresh_mask |= ext_refresh_frame_flags->golden_frame
692
0
                        << ref_frame_map_idx;
693
694
0
      ref_frame_map_idx = get_ref_frame_map_idx(cm, ALTREF_FRAME);
695
0
      if (ref_frame_map_idx != INVALID_IDX)
696
0
        refresh_mask |= ext_refresh_frame_flags->alt_ref_frame
697
0
                        << ref_frame_map_idx;
698
0
    }
699
0
    return refresh_mask;
700
9.69k
  }
701
702
  // Search for the open slot to store the current frame.
703
25.2k
  int free_fb_index = get_free_ref_map_index(ref_frame_map_pairs);
704
705
  // No refresh necessary for these frame types.
706
25.2k
  if (frame_update_type == OVERLAY_UPDATE ||
707
23.5k
      frame_update_type == INTNL_OVERLAY_UPDATE)
708
1.61k
    return refresh_mask;
709
710
  // If there is an open slot, refresh that one instead of replacing a
711
  // reference.
712
23.5k
  if (free_fb_index != INVALID_IDX) {
713
23.5k
    refresh_mask = 1 << free_fb_index;
714
23.5k
    return refresh_mask;
715
23.5k
  }
716
0
  const int enable_refresh_skip = !is_one_pass_rt_params(cpi);
717
0
  const int update_arf = frame_update_type == ARF_UPDATE;
718
0
  const int refresh_idx =
719
0
      get_refresh_idx(ref_frame_map_pairs, update_arf, &cpi->ppi->gf_group,
720
0
                      gf_index, enable_refresh_skip, cur_disp_order);
721
0
  return 1 << refresh_idx;
722
23.5k
}
723
724
#if !CONFIG_REALTIME_ONLY
725
// Apply temporal filtering to source frames and encode the filtered frame.
726
// If the current frame does not require filtering, this function is identical
727
// to av1_encode() except that tpl is not performed.
728
static int denoise_and_encode(AV1_COMP *const cpi, uint8_t *const dest,
729
                              size_t dest_size,
730
                              EncodeFrameInput *const frame_input,
731
                              const EncodeFrameParams *const frame_params,
732
125k
                              size_t *const frame_size) {
733
#if CONFIG_COLLECT_COMPONENT_TIMING
734
  if (cpi->oxcf.pass == 2) start_timing(cpi, denoise_and_encode_time);
735
#endif
736
125k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
737
125k
  AV1_COMMON *const cm = &cpi->common;
738
739
125k
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
740
125k
  FRAME_UPDATE_TYPE update_type =
741
125k
      get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
742
125k
  const int is_second_arf =
743
125k
      av1_gop_is_second_arf(gf_group, cpi->gf_frame_index);
744
745
  // Decide whether to apply temporal filtering to the source frame.
746
125k
  int apply_filtering =
747
125k
      av1_is_temporal_filter_on(oxcf) && !is_stat_generation_stage(cpi);
748
125k
  if (update_type != KF_UPDATE && update_type != ARF_UPDATE && !is_second_arf) {
749
15.0k
    apply_filtering = 0;
750
15.0k
  }
751
125k
  if (apply_filtering) {
752
11.0k
    if (frame_params->frame_type == KEY_FRAME) {
753
      // TODO(angiebird): Move the noise level check to av1_tf_info_filtering.
754
      // Decide whether it is allowed to perform key frame filtering
755
9.47k
      int allow_kf_filtering = oxcf->kf_cfg.enable_keyframe_filtering &&
756
9.47k
                               !frame_params->show_existing_frame &&
757
9.47k
                               !is_lossless_requested(&oxcf->rc_cfg);
758
9.47k
      if (allow_kf_filtering) {
759
9.17k
        double y_noise_level = 0.0;
760
9.17k
        av1_estimate_noise_level(
761
9.17k
            frame_input->source, &y_noise_level, AOM_PLANE_Y, AOM_PLANE_Y,
762
9.17k
            cm->seq_params->bit_depth, NOISE_ESTIMATION_EDGE_THRESHOLD);
763
9.17k
        apply_filtering = y_noise_level > 0;
764
9.17k
      } else {
765
293
        apply_filtering = 0;
766
293
      }
767
      // If we are doing kf filtering, set up a few things.
768
9.47k
      if (apply_filtering) {
769
1.61k
        av1_setup_past_independence(cm);
770
1.61k
      }
771
9.47k
    } else if (is_second_arf) {
772
0
      apply_filtering = cpi->sf.hl_sf.second_alt_ref_filtering;
773
0
    }
774
11.0k
  }
775
776
#if CONFIG_COLLECT_COMPONENT_TIMING
777
  if (cpi->oxcf.pass == 2) start_timing(cpi, apply_filtering_time);
778
#endif
779
  // Save the pointer to the original source image.
780
125k
  YV12_BUFFER_CONFIG *source_buffer = frame_input->source;
781
782
  // Set cm->current_frame.frame_type and cpi->rc.this_frame_target
783
  // so that the call to av1_rc_pick_q_and_bounds() below returns the
784
  // correct q_index.
785
125k
  cm->current_frame.frame_type = frame_params->frame_type;
786
125k
  av1_set_frame_size(cpi, cm->width, cm->height);
787
788
  // apply filtering to frame
789
125k
  if (apply_filtering) {
790
3.23k
    int show_existing_alt_ref = 0;
791
3.23k
    FRAME_DIFF frame_diff;
792
3.23k
    int top_index = 0;
793
3.23k
    int bottom_index = 0;
794
3.23k
    const int q_index = av1_rc_pick_q_and_bounds(
795
3.23k
        cpi, cpi->oxcf.frm_dim_cfg.width, cpi->oxcf.frm_dim_cfg.height,
796
3.23k
        cpi->gf_frame_index, &bottom_index, &top_index);
797
798
3.23k
    if (update_type == KF_UPDATE || update_type == ARF_UPDATE) {
799
3.23k
      YV12_BUFFER_CONFIG *tf_buf = av1_tf_info_get_filtered_buf(
800
3.23k
          &cpi->ppi->tf_info, cpi->gf_frame_index, &frame_diff);
801
3.23k
      if (tf_buf != NULL) {
802
3.23k
        frame_input->source = tf_buf;
803
3.23k
        show_existing_alt_ref = av1_check_show_filtered_frame(
804
3.23k
            tf_buf, &frame_diff, q_index, cm->seq_params->bit_depth,
805
3.23k
            cpi->oxcf.algo_cfg.enable_overlay, 0);
806
3.23k
        if (show_existing_alt_ref) {
807
258
          cpi->common.showable_frame |= 1;
808
2.97k
        } else {
809
2.97k
          cpi->common.showable_frame = 0;
810
2.97k
        }
811
3.23k
      }
812
3.23k
      if (gf_group->frame_type[cpi->gf_frame_index] != KEY_FRAME) {
813
1.61k
        cpi->ppi->show_existing_alt_ref = show_existing_alt_ref;
814
1.61k
      }
815
3.23k
    }
816
817
3.23k
    if (is_second_arf) {
818
      // Allocate the memory for tf_buf_second_arf buffer, only when it is
819
      // required.
820
0
      int ret = aom_realloc_frame_buffer(
821
0
          &cpi->ppi->tf_info.tf_buf_second_arf, oxcf->frm_dim_cfg.width,
822
0
          oxcf->frm_dim_cfg.height, cm->seq_params->subsampling_x,
823
0
          cm->seq_params->subsampling_y, cm->seq_params->use_highbitdepth,
824
0
          cpi->oxcf.border_in_pixels, cm->features.byte_alignment, NULL, NULL,
825
0
          NULL, cpi->alloc_pyramid, 0);
826
0
      if (ret)
827
0
        aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
828
0
                           "Failed to allocate tf_buf_second_arf");
829
830
0
      YV12_BUFFER_CONFIG *tf_buf_second_arf =
831
0
          &cpi->ppi->tf_info.tf_buf_second_arf;
832
      // We didn't apply temporal filtering for second arf ahead in
833
      // av1_tf_info_filtering().
834
0
      const int arf_src_index = gf_group->arf_src_offset[cpi->gf_frame_index];
835
      // Right now, we are still using tf_buf_second_arf due to
836
      // implementation complexity.
837
      // TODO(angiebird): Reuse tf_info->tf_buf here.
838
0
      av1_temporal_filter(cpi, arf_src_index, cpi->gf_frame_index, &frame_diff,
839
0
                          tf_buf_second_arf);
840
0
      show_existing_alt_ref =
841
0
          av1_check_show_filtered_frame(tf_buf_second_arf, &frame_diff, q_index,
842
0
                                        cm->seq_params->bit_depth, 1, 1);
843
0
      if (show_existing_alt_ref) {
844
0
        aom_extend_frame_borders(tf_buf_second_arf, av1_num_planes(cm));
845
0
        frame_input->source = tf_buf_second_arf;
846
0
      }
847
      // Currently INTNL_ARF_UPDATE only do show_existing.
848
0
      cpi->common.showable_frame |= 1;
849
0
    }
850
851
    // Copy source metadata to the temporal filtered frame
852
3.23k
    if (source_buffer->metadata &&
853
0
        aom_copy_metadata_to_frame_buffer(frame_input->source,
854
0
                                          source_buffer->metadata)) {
855
0
      aom_internal_error(
856
0
          cm->error, AOM_CODEC_MEM_ERROR,
857
0
          "Failed to copy source metadata to the temporal filtered frame");
858
0
    }
859
3.23k
  }
860
#if CONFIG_COLLECT_COMPONENT_TIMING
861
  if (cpi->oxcf.pass == 2) end_timing(cpi, apply_filtering_time);
862
#endif
863
864
125k
  int set_mv_params = frame_params->frame_type == KEY_FRAME ||
865
26.5k
                      update_type == ARF_UPDATE || update_type == GF_UPDATE;
866
125k
  cm->show_frame = frame_params->show_frame;
867
125k
  if (set_mv_params) av1_set_mv_search_params(cpi);
868
869
#if CONFIG_RD_COMMAND
870
  if (frame_params->frame_type == KEY_FRAME) {
871
    char filepath[] = "rd_command.txt";
872
    av1_read_rd_command(filepath, &cpi->rd_command);
873
  }
874
#endif  // CONFIG_RD_COMMAND
875
125k
  if (cpi->gf_frame_index == 0 && !is_stat_generation_stage(cpi)) {
876
    // perform tpl after filtering
877
90.4k
    int allow_tpl =
878
90.4k
        oxcf->gf_cfg.lag_in_frames > 1 && oxcf->algo_cfg.enable_tpl_model;
879
90.4k
    if (gf_group->size > MAX_LENGTH_TPL_FRAME_STATS) {
880
0
      allow_tpl = 0;
881
0
    }
882
90.4k
    if (frame_params->frame_type != KEY_FRAME) {
883
      // In rare case, it's possible to have non ARF/GF update_type here.
884
      // We should set allow_tpl to zero in the situation
885
0
      bool frame_type_allow_tpl =
886
0
          update_type == ARF_UPDATE || update_type == GF_UPDATE;
887
      // When external rate control is used, sometimes the sequence ends with
888
      // a GOP with only 1 frame which is a leaf frame. TPL stats needs to be
889
      // calculated for it as well.
890
0
      if (av1_use_tpl_for_extrc(&cpi->ext_ratectrl)) {
891
0
        frame_type_allow_tpl |= update_type == LF_UPDATE;
892
0
      }
893
0
      allow_tpl = allow_tpl && (frame_type_allow_tpl ||
894
0
                                (cpi->use_ducky_encode &&
895
0
                                 cpi->ducky_encode_info.frame_info.gop_mode ==
896
0
                                     DUCKY_ENCODE_GOP_MODE_RCL));
897
0
    }
898
899
90.4k
    if (allow_tpl) {
900
9.47k
      if (!cpi->skip_tpl_setup_stats) {
901
9.47k
        av1_tpl_preload_rc_estimate(cpi, frame_params);
902
9.47k
        av1_tpl_setup_stats(cpi, 0, frame_params);
903
#if CONFIG_BITRATE_ACCURACY && !CONFIG_THREE_PASS
904
        assert(cpi->gf_frame_index == 0);
905
        av1_vbr_rc_update_q_index_list(&cpi->vbr_rc_info, &cpi->ppi->tpl_data,
906
                                       gf_group, cm->seq_params->bit_depth);
907
#endif
908
9.47k
      }
909
80.9k
    } else {
910
80.9k
      av1_init_tpl_stats(&cpi->ppi->tpl_data);
911
80.9k
    }
912
#if CONFIG_BITRATE_ACCURACY && CONFIG_THREE_PASS
913
    if (cpi->oxcf.pass == AOM_RC_SECOND_PASS &&
914
        cpi->second_pass_log_stream != NULL) {
915
      TPL_INFO *tpl_info;
916
      AOM_CHECK_MEM_ERROR(cm->error, tpl_info, aom_malloc(sizeof(*tpl_info)));
917
      av1_pack_tpl_info(tpl_info, gf_group, &cpi->ppi->tpl_data);
918
      av1_write_tpl_info(tpl_info, cpi->second_pass_log_stream,
919
                         cpi->common.error);
920
      aom_free(tpl_info);
921
    }
922
#endif  // CONFIG_BITRATE_ACCURACY && CONFIG_THREE_PASS
923
90.4k
  }
924
925
125k
  if (av1_encode(cpi, dest, dest_size, frame_input, frame_params, frame_size) !=
926
125k
      AOM_CODEC_OK) {
927
0
    return AOM_CODEC_ERROR;
928
0
  }
929
930
  // Set frame_input source to true source for psnr calculation.
931
125k
  if (apply_filtering && is_psnr_calc_enabled(cpi)) {
932
0
    cpi->source = av1_realloc_and_scale_if_required(
933
0
        cm, source_buffer, &cpi->scaled_source, cm->features.interp_filter, 0,
934
0
        false, true, cpi->oxcf.border_in_pixels, cpi->alloc_pyramid);
935
0
    cpi->unscaled_source = source_buffer;
936
0
  }
937
#if CONFIG_COLLECT_COMPONENT_TIMING
938
  if (cpi->oxcf.pass == 2) end_timing(cpi, denoise_and_encode_time);
939
#endif
940
125k
  return AOM_CODEC_OK;
941
125k
}
942
#endif  // !CONFIG_REALTIME_ONLY
943
944
/*!\cond */
945
// Struct to keep track of relevant reference frame data.
946
typedef struct {
947
  int map_idx;
948
  int disp_order;
949
  int pyr_level;
950
  int used;
951
} RefBufMapData;
952
/*!\endcond */
953
954
// Comparison function to sort reference frames in ascending display order.
955
32.0k
static int compare_map_idx_pair_asc(const void *a, const void *b) {
956
32.0k
  if (((RefBufMapData *)a)->disp_order == ((RefBufMapData *)b)->disp_order) {
957
0
    return 0;
958
32.0k
  } else if (((const RefBufMapData *)a)->disp_order >
959
32.0k
             ((const RefBufMapData *)b)->disp_order) {
960
9.71k
    return 1;
961
22.2k
  } else {
962
22.2k
    return -1;
963
22.2k
  }
964
32.0k
}
965
966
// Checks to see if a particular reference frame is already in the reference
967
// frame map.
968
52.3k
static int is_in_ref_map(RefBufMapData *map, int disp_order, int n_frames) {
969
91.9k
  for (int i = 0; i < n_frames; i++) {
970
39.5k
    if (disp_order == map[i].disp_order) return 1;
971
39.5k
  }
972
52.3k
  return 0;
973
52.3k
}
974
975
// Add a reference buffer index to a named reference slot.
976
static void add_ref_to_slot(RefBufMapData *ref, int *const remapped_ref_idx,
977
52.3k
                            int frame) {
978
52.3k
  remapped_ref_idx[frame - LAST_FRAME] = ref->map_idx;
979
52.3k
  ref->used = 1;
980
52.3k
}
981
982
// Threshold dictating when we are allowed to start considering
983
// leaving lowest level frames unmapped.
984
0
#define LOW_LEVEL_FRAMES_TR 5
985
986
// Find which reference buffer should be left out of the named mapping.
987
// This is because there are 8 reference buffers and only 7 named slots.
988
static void set_unmapped_ref(RefBufMapData *buffer_map, int n_bufs,
989
                             int n_min_level_refs, int min_level,
990
126k
                             int cur_frame_disp) {
991
126k
  int max_dist = 0;
992
126k
  int unmapped_idx = -1;
993
126k
  if (n_bufs <= ALTREF_FRAME) return;
994
0
  for (int i = 0; i < n_bufs; i++) {
995
0
    if (buffer_map[i].used) continue;
996
0
    if (buffer_map[i].pyr_level != min_level ||
997
0
        n_min_level_refs >= LOW_LEVEL_FRAMES_TR) {
998
0
      int dist = abs(cur_frame_disp - buffer_map[i].disp_order);
999
0
      if (dist > max_dist) {
1000
0
        max_dist = dist;
1001
0
        unmapped_idx = i;
1002
0
      }
1003
0
    }
1004
0
  }
1005
0
  assert(unmapped_idx >= 0 && "Unmapped reference not found");
1006
0
  buffer_map[unmapped_idx].used = 1;
1007
0
}
1008
1009
void av1_get_ref_frames(RefFrameMapPair ref_frame_map_pairs[REF_FRAMES],
1010
                        int cur_frame_disp, const AV1_COMP *cpi, int gf_index,
1011
                        int is_parallel_encode,
1012
126k
                        int remapped_ref_idx[REF_FRAMES]) {
1013
126k
  int buf_map_idx = 0;
1014
1015
  // Initialize reference frame mappings.
1016
1.14M
  for (int i = 0; i < REF_FRAMES; ++i) remapped_ref_idx[i] = INVALID_IDX;
1017
1018
126k
  if (cpi->ppi->gf_group.use_ext_ref_frame_map[gf_index]) {
1019
0
    for (int rf = LAST_FRAME; rf < REF_FRAMES; ++rf) {
1020
0
      if (cpi->ppi->gf_group.ref_frame_list[gf_index][rf] != INVALID_IDX) {
1021
0
        remapped_ref_idx[rf - LAST_FRAME] =
1022
0
            (int)cpi->ppi->gf_group.ref_frame_list[gf_index][rf];
1023
0
      }
1024
0
    }
1025
0
    for (int i = 0; i < REF_FRAMES; ++i) {
1026
0
      if (remapped_ref_idx[i] == INVALID_IDX) {
1027
0
        remapped_ref_idx[i] = 0;
1028
0
      }
1029
0
    }
1030
0
    return;
1031
0
  }
1032
1033
126k
#if !CONFIG_REALTIME_ONLY
1034
126k
  if (cpi->use_ducky_encode &&
1035
0
      cpi->ducky_encode_info.frame_info.gop_mode == DUCKY_ENCODE_GOP_MODE_RCL) {
1036
0
    for (int rf = LAST_FRAME; rf < REF_FRAMES; ++rf) {
1037
0
      if (cpi->ppi->gf_group.ref_frame_list[gf_index][rf] != INVALID_IDX) {
1038
0
        remapped_ref_idx[rf - LAST_FRAME] =
1039
0
            cpi->ppi->gf_group.ref_frame_list[gf_index][rf];
1040
0
      }
1041
0
    }
1042
1043
0
    int valid_rf_idx = 0;
1044
0
    static const int ref_frame_type_order[REF_FRAMES - LAST_FRAME] = {
1045
0
      GOLDEN_FRAME,  ALTREF_FRAME, LAST_FRAME, BWDREF_FRAME,
1046
0
      ALTREF2_FRAME, LAST2_FRAME,  LAST3_FRAME
1047
0
    };
1048
0
    for (int i = 0; i < REF_FRAMES - LAST_FRAME; i++) {
1049
0
      int rf = ref_frame_type_order[i];
1050
0
      if (remapped_ref_idx[rf - LAST_FRAME] != INVALID_IDX) {
1051
0
        valid_rf_idx = remapped_ref_idx[rf - LAST_FRAME];
1052
0
        break;
1053
0
      }
1054
0
    }
1055
1056
0
    for (int i = 0; i < REF_FRAMES; ++i) {
1057
0
      if (remapped_ref_idx[i] == INVALID_IDX) {
1058
0
        remapped_ref_idx[i] = valid_rf_idx;
1059
0
      }
1060
0
    }
1061
1062
0
    return;
1063
0
  }
1064
126k
#endif  // !CONFIG_REALTIME_ONLY
1065
1066
126k
  RefBufMapData buffer_map[REF_FRAMES];
1067
126k
  int n_bufs = 0;
1068
126k
  memset(buffer_map, 0, REF_FRAMES * sizeof(buffer_map[0]));
1069
126k
  int min_level = MAX_ARF_LAYERS;
1070
126k
  int max_level = 0;
1071
126k
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
1072
126k
  int skip_ref_unmapping = 0;
1073
126k
  int is_one_pass_rt = is_one_pass_rt_params(cpi);
1074
1075
  // Go through current reference buffers and store display order, pyr level,
1076
  // and map index.
1077
1.14M
  for (int map_idx = 0; map_idx < REF_FRAMES; map_idx++) {
1078
    // Get reference frame buffer.
1079
1.01M
    RefFrameMapPair ref_pair = ref_frame_map_pairs[map_idx];
1080
1.01M
    if (ref_pair.disp_order == -1) continue;
1081
52.3k
    const int frame_order = ref_pair.disp_order;
1082
    // Avoid duplicates.
1083
52.3k
    if (is_in_ref_map(buffer_map, frame_order, n_bufs)) continue;
1084
52.3k
    const int reference_frame_level = ref_pair.pyr_level;
1085
1086
    // Keep track of the lowest and highest levels that currently exist.
1087
52.3k
    if (reference_frame_level < min_level) min_level = reference_frame_level;
1088
52.3k
    if (reference_frame_level > max_level) max_level = reference_frame_level;
1089
1090
52.3k
    buffer_map[n_bufs].map_idx = map_idx;
1091
52.3k
    buffer_map[n_bufs].disp_order = frame_order;
1092
52.3k
    buffer_map[n_bufs].pyr_level = reference_frame_level;
1093
52.3k
    buffer_map[n_bufs].used = 0;
1094
52.3k
    n_bufs++;
1095
52.3k
  }
1096
1097
  // Sort frames in ascending display order.
1098
126k
  qsort(buffer_map, n_bufs, sizeof(buffer_map[0]), compare_map_idx_pair_asc);
1099
1100
126k
  int n_min_level_refs = 0;
1101
126k
  int closest_past_ref = -1;
1102
126k
  int golden_idx = -1;
1103
126k
  int altref_idx = -1;
1104
1105
  // Find the GOLDEN_FRAME and BWDREF_FRAME.
1106
  // Also collect various stats about the reference frames for the remaining
1107
  // mappings.
1108
179k
  for (int i = n_bufs - 1; i >= 0; i--) {
1109
52.3k
    if (buffer_map[i].pyr_level == min_level) {
1110
      // Keep track of the number of lowest level frames.
1111
36.5k
      n_min_level_refs++;
1112
36.5k
      if (buffer_map[i].disp_order < cur_frame_disp && golden_idx == -1 &&
1113
26.8k
          remapped_ref_idx[GOLDEN_FRAME - LAST_FRAME] == INVALID_IDX) {
1114
        // Save index for GOLDEN.
1115
26.8k
        golden_idx = i;
1116
26.8k
      } else if (buffer_map[i].disp_order > cur_frame_disp &&
1117
6.47k
                 altref_idx == -1 &&
1118
6.47k
                 remapped_ref_idx[ALTREF_FRAME - LAST_FRAME] == INVALID_IDX) {
1119
        // Save index for ALTREF.
1120
6.47k
        altref_idx = i;
1121
6.47k
      }
1122
36.5k
    } else if (buffer_map[i].disp_order == cur_frame_disp) {
1123
      // Map the BWDREF_FRAME if this is the show_existing_frame.
1124
0
      add_ref_to_slot(&buffer_map[i], remapped_ref_idx, BWDREF_FRAME);
1125
0
    }
1126
1127
    // During parallel encodes of lower layer frames, exclude the first frame
1128
    // (frame_parallel_level 1) from being used for the reference assignment of
1129
    // the second frame (frame_parallel_level 2).
1130
52.3k
    if (!is_one_pass_rt && gf_group->frame_parallel_level[gf_index] == 2 &&
1131
0
        gf_group->frame_parallel_level[gf_index - 1] == 1 &&
1132
0
        gf_group->update_type[gf_index - 1] == INTNL_ARF_UPDATE) {
1133
0
      assert(gf_group->update_type[gf_index] == INTNL_ARF_UPDATE);
1134
#if CONFIG_FPMT_TEST
1135
      is_parallel_encode = (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_ENCODE)
1136
                               ? is_parallel_encode
1137
                               : 0;
1138
#endif  // CONFIG_FPMT_TEST
1139
      // If parallel cpis are active, use ref_idx_to_skip, else, use display
1140
      // index.
1141
0
      assert(IMPLIES(is_parallel_encode, cpi->ref_idx_to_skip != INVALID_IDX));
1142
0
      assert(IMPLIES(!is_parallel_encode,
1143
0
                     gf_group->skip_frame_as_ref[gf_index] != INVALID_IDX));
1144
0
      buffer_map[i].used = is_parallel_encode
1145
0
                               ? (buffer_map[i].map_idx == cpi->ref_idx_to_skip)
1146
0
                               : (buffer_map[i].disp_order ==
1147
0
                                  gf_group->skip_frame_as_ref[gf_index]);
1148
      // In case a ref frame is excluded from being used during assignment,
1149
      // skip the call to set_unmapped_ref(). Applicable in steady state.
1150
0
      if (buffer_map[i].used) skip_ref_unmapping = 1;
1151
0
    }
1152
1153
    // Keep track of where the frames change from being past frames to future
1154
    // frames.
1155
52.3k
    if (buffer_map[i].disp_order < cur_frame_disp && closest_past_ref < 0)
1156
26.8k
      closest_past_ref = i;
1157
52.3k
  }
1158
1159
  // Do not map GOLDEN and ALTREF based on their pyramid level if all reference
1160
  // frames have the same level.
1161
126k
  if (n_min_level_refs < n_bufs) {
1162
    // Map the GOLDEN_FRAME.
1163
11.5k
    if (golden_idx > -1)
1164
11.5k
      add_ref_to_slot(&buffer_map[golden_idx], remapped_ref_idx, GOLDEN_FRAME);
1165
    // Map the ALTREF_FRAME.
1166
11.5k
    if (altref_idx > -1)
1167
3.23k
      add_ref_to_slot(&buffer_map[altref_idx], remapped_ref_idx, ALTREF_FRAME);
1168
11.5k
  }
1169
1170
  // Find the buffer to be excluded from the mapping.
1171
126k
  if (!skip_ref_unmapping)
1172
126k
    set_unmapped_ref(buffer_map, n_bufs, n_min_level_refs, min_level,
1173
126k
                     cur_frame_disp);
1174
1175
  // Place past frames in LAST_FRAME, LAST2_FRAME, and LAST3_FRAME.
1176
157k
  for (int frame = LAST_FRAME; frame < GOLDEN_FRAME; frame++) {
1177
    // Continue if the current ref slot is already full.
1178
157k
    if (remapped_ref_idx[frame - LAST_FRAME] != INVALID_IDX) continue;
1179
    // Find the next unmapped reference buffer
1180
    // in decreasing output order relative to current picture.
1181
157k
    int next_buf_max = -1;
1182
157k
    int next_disp_order = INT_MIN;
1183
278k
    for (buf_map_idx = n_bufs - 1; buf_map_idx >= 0; buf_map_idx--) {
1184
120k
      if (!buffer_map[buf_map_idx].used &&
1185
51.6k
          buffer_map[buf_map_idx].disp_order < cur_frame_disp &&
1186
35.4k
          buffer_map[buf_map_idx].disp_order > next_disp_order) {
1187
31.1k
        next_disp_order = buffer_map[buf_map_idx].disp_order;
1188
31.1k
        next_buf_max = buf_map_idx;
1189
31.1k
      }
1190
120k
    }
1191
157k
    buf_map_idx = next_buf_max;
1192
157k
    if (buf_map_idx < 0) break;
1193
31.1k
    if (buffer_map[buf_map_idx].used) break;
1194
31.1k
    add_ref_to_slot(&buffer_map[buf_map_idx], remapped_ref_idx, frame);
1195
31.1k
  }
1196
1197
  // Place future frames (if there are any) in BWDREF_FRAME and ALTREF2_FRAME.
1198
129k
  for (int frame = BWDREF_FRAME; frame < REF_FRAMES; frame++) {
1199
    // Continue if the current ref slot is already full.
1200
129k
    if (remapped_ref_idx[frame - LAST_FRAME] != INVALID_IDX) continue;
1201
    // Find the next unmapped reference buffer
1202
    // in increasing output order relative to current picture.
1203
129k
    int next_buf_max = -1;
1204
129k
    int next_disp_order = INT_MAX;
1205
188k
    for (buf_map_idx = n_bufs - 1; buf_map_idx >= 0; buf_map_idx--) {
1206
58.8k
      if (!buffer_map[buf_map_idx].used &&
1207
6.47k
          buffer_map[buf_map_idx].disp_order > cur_frame_disp &&
1208
3.23k
          buffer_map[buf_map_idx].disp_order < next_disp_order) {
1209
3.23k
        next_disp_order = buffer_map[buf_map_idx].disp_order;
1210
3.23k
        next_buf_max = buf_map_idx;
1211
3.23k
      }
1212
58.8k
    }
1213
129k
    buf_map_idx = next_buf_max;
1214
129k
    if (buf_map_idx < 0) break;
1215
3.23k
    if (buffer_map[buf_map_idx].used) break;
1216
3.23k
    add_ref_to_slot(&buffer_map[buf_map_idx], remapped_ref_idx, frame);
1217
3.23k
  }
1218
1219
  // Place remaining past frames.
1220
126k
  buf_map_idx = closest_past_ref;
1221
157k
  for (int frame = LAST_FRAME; frame < REF_FRAMES; frame++) {
1222
    // Continue if the current ref slot is already full.
1223
157k
    if (remapped_ref_idx[frame - LAST_FRAME] != INVALID_IDX) continue;
1224
    // Find the next unmapped reference buffer.
1225
169k
    for (; buf_map_idx >= 0; buf_map_idx--) {
1226
42.6k
      if (!buffer_map[buf_map_idx].used) break;
1227
42.6k
    }
1228
126k
    if (buf_map_idx < 0) break;
1229
0
    if (buffer_map[buf_map_idx].used) break;
1230
0
    add_ref_to_slot(&buffer_map[buf_map_idx], remapped_ref_idx, frame);
1231
0
  }
1232
1233
  // Place remaining future frames.
1234
126k
  buf_map_idx = n_bufs - 1;
1235
133k
  for (int frame = ALTREF_FRAME; frame >= LAST_FRAME; frame--) {
1236
    // Continue if the current ref slot is already full.
1237
133k
    if (remapped_ref_idx[frame - LAST_FRAME] != INVALID_IDX) continue;
1238
    // Find the next unmapped reference buffer.
1239
139k
    for (; buf_map_idx > closest_past_ref; buf_map_idx--) {
1240
12.9k
      if (!buffer_map[buf_map_idx].used) break;
1241
12.9k
    }
1242
129k
    if (buf_map_idx < 0) break;
1243
30.0k
    if (buffer_map[buf_map_idx].used) break;
1244
3.23k
    add_ref_to_slot(&buffer_map[buf_map_idx], remapped_ref_idx, frame);
1245
3.23k
  }
1246
1247
  // Fill any slots that are empty (should only happen for the first 7 frames).
1248
1.14M
  for (int i = 0; i < REF_FRAMES; ++i)
1249
1.01M
    if (remapped_ref_idx[i] == INVALID_IDX) remapped_ref_idx[i] = 0;
1250
126k
}
1251
1252
int av1_encode_strategy(AV1_COMP *const cpi, size_t *const size,
1253
                        uint8_t *const dest, size_t dest_size,
1254
                        unsigned int *frame_flags, int64_t *const time_stamp,
1255
                        int64_t *const time_end,
1256
                        const aom_rational64_t *const timestamp_ratio,
1257
277k
                        int *const pop_lookahead, int flush) {
1258
277k
  AV1EncoderConfig *const oxcf = &cpi->oxcf;
1259
277k
  AV1_COMMON *const cm = &cpi->common;
1260
277k
  GF_GROUP *gf_group = &cpi->ppi->gf_group;
1261
277k
  ExternalFlags *const ext_flags = &cpi->ext_flags;
1262
277k
  GFConfig *const gf_cfg = &oxcf->gf_cfg;
1263
1264
277k
  EncodeFrameInput frame_input;
1265
277k
  EncodeFrameParams frame_params;
1266
277k
  size_t frame_size;
1267
277k
  memset(&frame_input, 0, sizeof(frame_input));
1268
277k
  memset(&frame_params, 0, sizeof(frame_params));
1269
277k
  frame_size = 0;
1270
1271
#if CONFIG_BITRATE_ACCURACY && CONFIG_THREE_PASS
1272
  VBR_RATECTRL_INFO *vbr_rc_info = &cpi->vbr_rc_info;
1273
  if (oxcf->pass == AOM_RC_THIRD_PASS && vbr_rc_info->ready == 0) {
1274
    THIRD_PASS_FRAME_INFO frame_info[MAX_THIRD_PASS_BUF];
1275
    av1_open_second_pass_log(cpi, 1);
1276
    FILE *second_pass_log_stream = cpi->second_pass_log_stream;
1277
    fseek(second_pass_log_stream, 0, SEEK_END);
1278
    size_t file_size = ftell(second_pass_log_stream);
1279
    rewind(second_pass_log_stream);
1280
    size_t read_size = 0;
1281
    while (read_size < file_size) {
1282
      THIRD_PASS_GOP_INFO gop_info;
1283
      struct aom_internal_error_info *error = cpi->common.error;
1284
      // Read in GOP information from the second pass file.
1285
      av1_read_second_pass_gop_info(second_pass_log_stream, &gop_info, error);
1286
      TPL_INFO *tpl_info;
1287
      AOM_CHECK_MEM_ERROR(cm->error, tpl_info, aom_malloc(sizeof(*tpl_info)));
1288
      av1_read_tpl_info(tpl_info, second_pass_log_stream, error);
1289
      // Read in per-frame info from second-pass encoding
1290
      av1_read_second_pass_per_frame_info(second_pass_log_stream, frame_info,
1291
                                          gop_info.num_frames, error);
1292
      av1_vbr_rc_append_tpl_info(vbr_rc_info, tpl_info);
1293
      read_size = ftell(second_pass_log_stream);
1294
      aom_free(tpl_info);
1295
    }
1296
    av1_close_second_pass_log(cpi);
1297
    if (cpi->oxcf.rc_cfg.mode == AOM_Q) {
1298
      vbr_rc_info->base_q_index = cpi->oxcf.rc_cfg.cq_level;
1299
      av1_vbr_rc_compute_q_indices(
1300
          vbr_rc_info->base_q_index, vbr_rc_info->total_frame_count,
1301
          vbr_rc_info->qstep_ratio_list, cm->seq_params->bit_depth,
1302
          vbr_rc_info->q_index_list);
1303
    } else {
1304
      vbr_rc_info->base_q_index = av1_vbr_rc_info_estimate_base_q(
1305
          vbr_rc_info->total_bit_budget, cm->seq_params->bit_depth,
1306
          vbr_rc_info->scale_factors, vbr_rc_info->total_frame_count,
1307
          vbr_rc_info->update_type_list, vbr_rc_info->qstep_ratio_list,
1308
          vbr_rc_info->txfm_stats_list, vbr_rc_info->q_index_list, NULL);
1309
    }
1310
    vbr_rc_info->ready = 1;
1311
#if CONFIG_RATECTRL_LOG
1312
    rc_log_record_chunk_info(&cpi->rc_log, vbr_rc_info->base_q_index,
1313
                             vbr_rc_info->total_frame_count);
1314
#endif  // CONFIG_RATECTRL_LOG
1315
  }
1316
#endif  // CONFIG_BITRATE_ACCURACY && CONFIG_THREE_PASS
1317
1318
  // Check if we need to stuff more src frames
1319
277k
  if (flush == 0) {
1320
143k
    int srcbuf_size =
1321
143k
        av1_lookahead_depth(cpi->ppi->lookahead, cpi->compressor_stage);
1322
143k
    int pop_size =
1323
143k
        av1_lookahead_pop_sz(cpi->ppi->lookahead, cpi->compressor_stage);
1324
1325
    // Continue buffering look ahead buffer.
1326
143k
    if (srcbuf_size < pop_size) return -1;
1327
143k
  }
1328
1329
259k
  if (!av1_lookahead_peek(cpi->ppi->lookahead, 0, cpi->compressor_stage)) {
1330
114k
#if !CONFIG_REALTIME_ONLY
1331
114k
    if (flush && oxcf->pass == AOM_RC_FIRST_PASS &&
1332
0
        !cpi->ppi->twopass.first_pass_done) {
1333
0
      av1_end_first_pass(cpi); /* get last stats packet */
1334
0
      cpi->ppi->twopass.first_pass_done = 1;
1335
0
    }
1336
114k
#endif
1337
114k
    return -1;
1338
114k
  }
1339
1340
145k
  if (has_no_stats_stage(cpi) && !is_one_pass_rt_lag_params(cpi)) {
1341
107k
    gf_cfg->gf_max_pyr_height =
1342
107k
        AOMMIN(gf_cfg->gf_max_pyr_height, USE_ALTREF_FOR_ONE_PASS);
1343
107k
    gf_cfg->gf_min_pyr_height =
1344
107k
        AOMMIN(gf_cfg->gf_min_pyr_height, gf_cfg->gf_max_pyr_height);
1345
107k
  }
1346
1347
  // Allocation of mi buffers.
1348
145k
  alloc_mb_mode_info_buffers(cpi);
1349
1350
145k
  cpi->cb_delta_rdmult_enabled = 0;
1351
1352
145k
  cpi->skip_tpl_setup_stats = 0;
1353
145k
#if !CONFIG_REALTIME_ONLY
1354
145k
  if (oxcf->pass != AOM_RC_FIRST_PASS) {
1355
145k
    TplParams *const tpl_data = &cpi->ppi->tpl_data;
1356
145k
    if (tpl_data->tpl_stats_pool[0] == NULL) {
1357
132k
      av1_setup_tpl_buffers(cpi->ppi, &cm->mi_params, oxcf->frm_dim_cfg.width,
1358
132k
                            oxcf->frm_dim_cfg.height, 0,
1359
132k
                            oxcf->gf_cfg.lag_in_frames);
1360
132k
    }
1361
145k
  }
1362
145k
  cpi->twopass_frame.this_frame = NULL;
1363
145k
  const int use_one_pass_rt_params = is_one_pass_rt_params(cpi);
1364
145k
  if (!use_one_pass_rt_params && !is_stat_generation_stage(cpi)) {
1365
#if CONFIG_COLLECT_COMPONENT_TIMING
1366
    start_timing(cpi, av1_get_second_pass_params_time);
1367
#endif
1368
1369
    // Initialise frame_level_rate_correction_factors with value previous
1370
    // to the parallel frames.
1371
107k
    if (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
1372
0
      for (int i = 0; i < RATE_FACTOR_LEVELS; i++) {
1373
0
        cpi->rc.frame_level_rate_correction_factors[i] =
1374
#if CONFIG_FPMT_TEST
1375
            (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE)
1376
                ? cpi->ppi->p_rc.temp_rate_correction_factors[i]
1377
                :
1378
#endif  // CONFIG_FPMT_TEST
1379
0
                cpi->ppi->p_rc.rate_correction_factors[i];
1380
0
      }
1381
0
    }
1382
1383
    // copy mv_stats from ppi to frame_level cpi.
1384
107k
    cpi->mv_stats = cpi->ppi->mv_stats;
1385
107k
    av1_get_second_pass_params(cpi, &frame_params, *frame_flags);
1386
#if CONFIG_COLLECT_COMPONENT_TIMING
1387
    end_timing(cpi, av1_get_second_pass_params_time);
1388
#endif
1389
107k
  }
1390
145k
#endif
1391
1392
145k
  if (!is_stat_generation_stage(cpi)) {
1393
    // TODO(jingning): fwd key frame always uses show existing frame?
1394
127k
    if (gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE &&
1395
1.61k
        gf_group->refbuf_state[cpi->gf_frame_index] == REFBUF_RESET) {
1396
0
      frame_params.show_existing_frame = 1;
1397
127k
    } else {
1398
127k
      frame_params.show_existing_frame =
1399
127k
          (cpi->ppi->show_existing_alt_ref &&
1400
0
           gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE) ||
1401
127k
          gf_group->update_type[cpi->gf_frame_index] == INTNL_OVERLAY_UPDATE;
1402
127k
    }
1403
127k
    frame_params.show_existing_frame &= allow_show_existing(cpi, *frame_flags);
1404
1405
    // Special handling to reset 'show_existing_frame' in case of dropped
1406
    // frames.
1407
127k
    if (oxcf->rc_cfg.drop_frames_water_mark &&
1408
0
        (gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE ||
1409
0
         gf_group->update_type[cpi->gf_frame_index] == INTNL_OVERLAY_UPDATE)) {
1410
      // During the encode of an OVERLAY_UPDATE/INTNL_OVERLAY_UPDATE frame, loop
1411
      // over the gf group to check if the corresponding
1412
      // ARF_UPDATE/INTNL_ARF_UPDATE frame was dropped.
1413
0
      int cur_disp_idx = gf_group->display_idx[cpi->gf_frame_index];
1414
0
      for (int idx = 0; idx < cpi->gf_frame_index; idx++) {
1415
0
        if (cur_disp_idx == gf_group->display_idx[idx]) {
1416
0
          assert(IMPLIES(
1417
0
              gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE,
1418
0
              gf_group->update_type[idx] == ARF_UPDATE));
1419
0
          assert(IMPLIES(gf_group->update_type[cpi->gf_frame_index] ==
1420
0
                             INTNL_OVERLAY_UPDATE,
1421
0
                         gf_group->update_type[idx] == INTNL_ARF_UPDATE));
1422
          // Reset show_existing_frame and set cpi->is_dropped_frame to true if
1423
          // the frame was dropped during its first encode.
1424
0
          if (gf_group->is_frame_dropped[idx]) {
1425
0
            frame_params.show_existing_frame = 0;
1426
0
            assert(!cpi->is_dropped_frame);
1427
0
            cpi->is_dropped_frame = true;
1428
0
          }
1429
0
          break;
1430
0
        }
1431
0
      }
1432
0
    }
1433
1434
    // Reset show_existing_alt_ref decision to 0 after it is used.
1435
127k
    if (gf_group->update_type[cpi->gf_frame_index] == OVERLAY_UPDATE) {
1436
1.61k
      cpi->ppi->show_existing_alt_ref = 0;
1437
1.61k
    }
1438
127k
  } else {
1439
17.9k
    frame_params.show_existing_frame = 0;
1440
17.9k
  }
1441
1442
145k
  struct lookahead_entry *source = NULL;
1443
145k
  struct lookahead_entry *last_source = NULL;
1444
145k
  if (frame_params.show_existing_frame) {
1445
0
    source = av1_lookahead_peek(cpi->ppi->lookahead, 0, cpi->compressor_stage);
1446
0
    *pop_lookahead = 1;
1447
0
    frame_params.show_frame = 1;
1448
145k
  } else {
1449
145k
    source = choose_frame_source(cpi, &flush, pop_lookahead, &last_source,
1450
145k
                                 &frame_params.show_frame);
1451
145k
  }
1452
1453
145k
  if (source == NULL) {  // If no source was found, we can't encode a frame.
1454
0
#if !CONFIG_REALTIME_ONLY
1455
0
    if (flush && oxcf->pass == AOM_RC_FIRST_PASS &&
1456
0
        !cpi->ppi->twopass.first_pass_done) {
1457
0
      av1_end_first_pass(cpi); /* get last stats packet */
1458
0
      cpi->ppi->twopass.first_pass_done = 1;
1459
0
    }
1460
0
#endif
1461
0
    return -1;
1462
0
  }
1463
1464
  // reset src_offset to allow actual encode call for this frame to get its
1465
  // source.
1466
145k
  gf_group->src_offset[cpi->gf_frame_index] = 0;
1467
1468
  // Source may be changed if temporal filtered later.
1469
145k
  frame_input.source = &source->img;
1470
145k
  if ((cpi->ppi->use_svc || cpi->rc.prev_frame_is_dropped) &&
1471
0
      last_source != NULL)
1472
0
    av1_svc_set_last_source(cpi, &frame_input, &last_source->img);
1473
145k
  else
1474
145k
    frame_input.last_source = last_source != NULL ? &last_source->img : NULL;
1475
145k
  frame_input.ts_duration = source->ts_end - source->ts_start;
1476
  // Save unfiltered source. It is used in av1_get_second_pass_params().
1477
145k
  cpi->unfiltered_source = frame_input.source;
1478
1479
145k
  *time_stamp = source->ts_start;
1480
145k
  *time_end = source->ts_end;
1481
145k
  if (source->ts_start < cpi->time_stamps.first_ts_start) {
1482
96.3k
    cpi->time_stamps.first_ts_start = source->ts_start;
1483
96.3k
    cpi->time_stamps.prev_ts_end = source->ts_start;
1484
96.3k
  }
1485
1486
145k
  av1_apply_encoding_flags(cpi, source->flags);
1487
145k
  *frame_flags = (source->flags & AOM_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
1488
1489
#if CONFIG_FPMT_TEST
1490
  if (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) {
1491
    if (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
1492
      cpi->framerate = cpi->temp_framerate;
1493
    }
1494
  }
1495
#endif  // CONFIG_FPMT_TEST
1496
1497
  // Shown frames and arf-overlay frames need frame-rate considering
1498
145k
  if (frame_params.show_frame)
1499
143k
    adjust_frame_rate(cpi, source->ts_start, source->ts_end);
1500
1501
145k
  if (!frame_params.show_existing_frame) {
1502
145k
#if !CONFIG_REALTIME_ONLY
1503
145k
    if (cpi->film_grain_table) {
1504
0
      cm->cur_frame->film_grain_params_present = aom_film_grain_table_lookup(
1505
0
          cpi->film_grain_table, *time_stamp, *time_end, 0 /* =erase */,
1506
0
          &cm->film_grain_params);
1507
145k
    } else {
1508
145k
      cm->cur_frame->film_grain_params_present =
1509
145k
          cm->seq_params->film_grain_params_present;
1510
145k
    }
1511
145k
#endif
1512
    // only one operating point supported now
1513
145k
    const int64_t pts64 = ticks_to_timebase_units(timestamp_ratio, *time_stamp);
1514
145k
    if (pts64 < 0 || pts64 > UINT32_MAX) return AOM_CODEC_ERROR;
1515
1516
145k
    cm->frame_presentation_time = (uint32_t)pts64;
1517
145k
  }
1518
1519
#if CONFIG_COLLECT_COMPONENT_TIMING
1520
  start_timing(cpi, av1_get_one_pass_rt_params_time);
1521
#endif
1522
#if CONFIG_REALTIME_ONLY
1523
  av1_get_one_pass_rt_params(cpi, &frame_params.frame_type, &frame_input,
1524
                             *frame_flags);
1525
  if (use_rtc_reference_structure_one_layer(cpi))
1526
    av1_set_rtc_reference_structure_one_layer(cpi, cpi->gf_frame_index == 0);
1527
#else
1528
145k
  if (use_one_pass_rt_params) {
1529
20.3k
    av1_get_one_pass_rt_params(cpi, &frame_params.frame_type, &frame_input,
1530
20.3k
                               *frame_flags);
1531
20.3k
    if (use_rtc_reference_structure_one_layer(cpi))
1532
20.3k
      av1_set_rtc_reference_structure_one_layer(cpi, cpi->gf_frame_index == 0);
1533
125k
  } else if (is_one_pass_rt_lag_params(cpi) && oxcf->rc_cfg.mode == AOM_CBR) {
1534
    // For realtime mode with lookahead in CBR: the current frame buffer_level
1535
    // is used to update the frame target_bandwidth, so we need to call
1536
    // av1_calc_i/pframe_target_size_one_pass_cbr() here for every frame.
1537
0
    int target;
1538
0
    const FRAME_UPDATE_TYPE cur_update_type =
1539
0
        gf_group->update_type[cpi->gf_frame_index];
1540
0
    if (cur_update_type == KF_UPDATE) {
1541
0
      target = av1_calc_iframe_target_size_one_pass_cbr(cpi);
1542
0
    } else {
1543
0
      target = av1_calc_pframe_target_size_one_pass_cbr(cpi, cur_update_type);
1544
0
    }
1545
0
    gf_group->bit_allocation[cpi->gf_frame_index] = target;
1546
0
    av1_rc_set_frame_target(cpi, target, cm->width, cm->height);
1547
0
    cpi->rc.base_frame_target = target;
1548
0
  }
1549
145k
#endif
1550
#if CONFIG_COLLECT_COMPONENT_TIMING
1551
  end_timing(cpi, av1_get_one_pass_rt_params_time);
1552
#endif
1553
1554
145k
  FRAME_UPDATE_TYPE frame_update_type =
1555
145k
      get_frame_update_type(gf_group, cpi->gf_frame_index);
1556
1557
145k
  if (frame_params.show_existing_frame &&
1558
0
      frame_params.frame_type != KEY_FRAME) {
1559
    // Force show-existing frames to be INTER, except forward keyframes
1560
0
    frame_params.frame_type = INTER_FRAME;
1561
0
  }
1562
1563
  // Per-frame encode speed.  In theory this can vary, but things may have
1564
  // been written assuming speed-level will not change within a sequence, so
1565
  // this parameter should be used with caution.
1566
145k
  frame_params.speed = oxcf->speed;
1567
1568
145k
#if !CONFIG_REALTIME_ONLY
1569
  // Set forced key frames when necessary. For two-pass encoding / lap mode,
1570
  // this is already handled by av1_get_second_pass_params. However when no
1571
  // stats are available, we still need to check if the new frame is a keyframe.
1572
  // For one pass rt, this is already checked in av1_get_one_pass_rt_params.
1573
145k
  if (!use_one_pass_rt_params &&
1574
125k
      (is_stat_generation_stage(cpi) || has_no_stats_stage(cpi))) {
1575
    // Current frame is coded as a key-frame for any of the following cases:
1576
    // 1) First frame of a video
1577
    // 2) For all-intra frame encoding
1578
    // 3) When a key-frame is forced
1579
105k
    const int kf_requested =
1580
105k
        (cm->current_frame.frame_number == 0 ||
1581
22.2k
         oxcf->kf_cfg.key_freq_max == 0 || (*frame_flags & FRAMEFLAGS_KEY));
1582
105k
    if (kf_requested && frame_update_type != OVERLAY_UPDATE &&
1583
88.0k
        frame_update_type != INTNL_OVERLAY_UPDATE) {
1584
88.0k
      frame_params.frame_type = KEY_FRAME;
1585
88.0k
    } else if (is_stat_generation_stage(cpi)) {
1586
      // For stats generation, set the frame type to inter here.
1587
9.87k
      frame_params.frame_type = INTER_FRAME;
1588
9.87k
    }
1589
105k
  }
1590
145k
#endif
1591
1592
  // Work out some encoding parameters specific to the pass:
1593
145k
  if (has_no_stats_stage(cpi) && oxcf->q_cfg.aq_mode == CYCLIC_REFRESH_AQ) {
1594
0
    av1_cyclic_refresh_update_parameters(cpi);
1595
145k
  } else if (is_stat_generation_stage(cpi)) {
1596
17.9k
    cpi->td.mb.e_mbd.lossless[0] = is_lossless_requested(&oxcf->rc_cfg);
1597
127k
  } else if (is_stat_consumption_stage(cpi)) {
1598
#if CONFIG_MISMATCH_DEBUG
1599
    mismatch_move_frame_idx_w();
1600
#endif
1601
#if TXCOEFF_COST_TIMER
1602
    cm->txcoeff_cost_timer = 0;
1603
    cm->txcoeff_cost_count = 0;
1604
#endif
1605
19.6k
  }
1606
1607
145k
  if (!is_stat_generation_stage(cpi))
1608
127k
    set_ext_overrides(cm, &frame_params, ext_flags);
1609
1610
  // Shown keyframes and S frames refresh all reference buffers
1611
145k
  const int force_refresh_all =
1612
145k
      ((frame_params.frame_type == KEY_FRAME && frame_params.show_frame) ||
1613
36.2k
       frame_params.frame_type == S_FRAME) &&
1614
109k
      !frame_params.show_existing_frame;
1615
1616
145k
  av1_configure_buffer_updates(
1617
145k
      cpi, &frame_params.refresh_frame, frame_update_type,
1618
145k
      gf_group->refbuf_state[cpi->gf_frame_index], force_refresh_all);
1619
1620
145k
  if (!is_stat_generation_stage(cpi)) {
1621
127k
    const YV12_BUFFER_CONFIG *ref_frame_buf[INTER_REFS_PER_FRAME];
1622
1623
127k
    RefFrameMapPair ref_frame_map_pairs[REF_FRAMES];
1624
127k
    init_ref_map_pair(cpi, ref_frame_map_pairs);
1625
127k
    const int order_offset = gf_group->arf_src_offset[cpi->gf_frame_index];
1626
127k
    const int cur_frame_disp =
1627
127k
        cpi->common.current_frame.frame_number + order_offset;
1628
1629
127k
    int get_ref_frames = 0;
1630
#if CONFIG_FPMT_TEST
1631
    get_ref_frames =
1632
        (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) ? 1 : 0;
1633
#endif  // CONFIG_FPMT_TEST
1634
127k
    if (get_ref_frames ||
1635
127k
        gf_group->frame_parallel_level[cpi->gf_frame_index] == 0) {
1636
127k
      if (!ext_flags->refresh_frame.update_pending) {
1637
107k
        av1_get_ref_frames(ref_frame_map_pairs, cur_frame_disp, cpi,
1638
107k
                           cpi->gf_frame_index, 1, cm->remapped_ref_idx);
1639
107k
      } else if (cpi->ppi->rtc_ref.set_ref_frame_config ||
1640
20.3k
                 use_rtc_reference_structure_one_layer(cpi)) {
1641
162k
        for (unsigned int i = 0; i < INTER_REFS_PER_FRAME; i++)
1642
142k
          cm->remapped_ref_idx[i] = cpi->ppi->rtc_ref.ref_idx[i];
1643
20.3k
      }
1644
127k
    }
1645
1646
    // Get the reference frames
1647
127k
    bool has_ref_frames = false;
1648
1.01M
    for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
1649
891k
      const RefCntBuffer *ref_frame =
1650
891k
          get_ref_frame_buf(cm, ref_frame_priority_order[i]);
1651
891k
      ref_frame_buf[i] = ref_frame != NULL ? &ref_frame->buf : NULL;
1652
891k
      if (ref_frame != NULL) has_ref_frames = true;
1653
891k
    }
1654
127k
    if (!has_ref_frames && (frame_params.frame_type == INTER_FRAME ||
1655
90.0k
                            frame_params.frame_type == S_FRAME)) {
1656
0
      return AOM_CODEC_ERROR;
1657
0
    }
1658
1659
    // Work out which reference frame slots may be used.
1660
127k
    frame_params.ref_frame_flags =
1661
127k
        get_ref_frame_flags(&cpi->sf, is_one_pass_rt_params(cpi), ref_frame_buf,
1662
127k
                            ext_flags->ref_frame_flags);
1663
1664
    // Set primary_ref_frame of non-reference frames as PRIMARY_REF_NONE.
1665
127k
    if (cpi->ppi->gf_group.is_frame_non_ref[cpi->gf_frame_index]) {
1666
0
      frame_params.primary_ref_frame = PRIMARY_REF_NONE;
1667
127k
    } else {
1668
127k
      frame_params.primary_ref_frame =
1669
127k
          choose_primary_ref_frame(cpi, &frame_params);
1670
127k
    }
1671
1672
127k
    frame_params.order_offset = gf_group->arf_src_offset[cpi->gf_frame_index];
1673
1674
    // Call av1_get_refresh_frame_flags() if refresh index not available.
1675
127k
    if (!cpi->refresh_idx_available) {
1676
127k
      frame_params.refresh_frame_flags = av1_get_refresh_frame_flags(
1677
127k
          cpi, &frame_params, frame_update_type, cpi->gf_frame_index,
1678
127k
          cur_frame_disp, ref_frame_map_pairs);
1679
127k
    } else {
1680
0
      assert(cpi->ref_refresh_index != INVALID_IDX);
1681
0
      frame_params.refresh_frame_flags = (1 << cpi->ref_refresh_index);
1682
0
    }
1683
1684
    // Make the frames marked as is_frame_non_ref to non-reference frames.
1685
127k
    if (gf_group->is_frame_non_ref[cpi->gf_frame_index])
1686
0
      frame_params.refresh_frame_flags = 0;
1687
1688
127k
    frame_params.existing_fb_idx_to_show = INVALID_IDX;
1689
    // Find the frame buffer to show based on display order.
1690
127k
    if (frame_params.show_existing_frame) {
1691
0
      for (int frame = 0; frame < REF_FRAMES; frame++) {
1692
0
        const RefCntBuffer *const buf = cm->ref_frame_map[frame];
1693
0
        if (buf == NULL) continue;
1694
0
        const int frame_order = (int)buf->display_order_hint;
1695
0
        if (frame_order == cur_frame_disp)
1696
0
          frame_params.existing_fb_idx_to_show = frame;
1697
0
      }
1698
0
    }
1699
127k
  }
1700
1701
  // The way frame_params->remapped_ref_idx is setup is a placeholder.
1702
  // Currently, reference buffer assignment is done by update_ref_frame_map()
1703
  // which is called by high-level strategy AFTER encoding a frame.  It
1704
  // modifies cm->remapped_ref_idx.  If you want to use an alternative method
1705
  // to determine reference buffer assignment, just put your assignments into
1706
  // frame_params->remapped_ref_idx here and they will be used when encoding
1707
  // this frame.  If frame_params->remapped_ref_idx is setup independently of
1708
  // cm->remapped_ref_idx then update_ref_frame_map() will have no effect.
1709
145k
  memcpy(frame_params.remapped_ref_idx, cm->remapped_ref_idx,
1710
145k
         REF_FRAMES * sizeof(*cm->remapped_ref_idx));
1711
1712
145k
  cpi->td.mb.rdmult_delta_qindex = cpi->td.mb.delta_qindex = 0;
1713
1714
145k
  if (!frame_params.show_existing_frame) {
1715
145k
    cm->quant_params.using_qmatrix = oxcf->q_cfg.using_qm;
1716
145k
  }
1717
1718
145k
  const int is_intra_frame = frame_params.frame_type == KEY_FRAME ||
1719
36.2k
                             frame_params.frame_type == INTRA_ONLY_FRAME;
1720
145k
  FeatureFlags *const features = &cm->features;
1721
145k
  if (!is_stat_generation_stage(cpi) &&
1722
127k
      (oxcf->pass == AOM_RC_ONE_PASS || oxcf->pass >= AOM_RC_SECOND_PASS) &&
1723
127k
      is_intra_frame) {
1724
101k
    av1_set_screen_content_options(cpi, features);
1725
101k
  }
1726
1727
#if CONFIG_REALTIME_ONLY
1728
  if (av1_encode(cpi, dest, dest_size, &frame_input, &frame_params,
1729
                 &frame_size) != AOM_CODEC_OK) {
1730
    return AOM_CODEC_ERROR;
1731
  }
1732
#else
1733
145k
  if (has_no_stats_stage(cpi) && oxcf->mode == REALTIME &&
1734
20.3k
      gf_cfg->lag_in_frames == 0) {
1735
20.3k
    if (av1_encode(cpi, dest, dest_size, &frame_input, &frame_params,
1736
20.3k
                   &frame_size) != AOM_CODEC_OK) {
1737
0
      return AOM_CODEC_ERROR;
1738
0
    }
1739
125k
  } else if (denoise_and_encode(cpi, dest, dest_size, &frame_input,
1740
125k
                                &frame_params, &frame_size) != AOM_CODEC_OK) {
1741
0
    return AOM_CODEC_ERROR;
1742
0
  }
1743
145k
#endif  // CONFIG_REALTIME_ONLY
1744
1745
  // This is used in rtc temporal filter case. Use true source in the PSNR
1746
  // calculation.
1747
145k
  if (is_psnr_calc_enabled(cpi) && cpi->sf.rt_sf.use_rtc_tf) {
1748
0
    assert(cpi->orig_source.buffer_alloc_sz > 0);
1749
0
    cpi->source = &cpi->orig_source;
1750
0
  }
1751
1752
145k
  if (!is_stat_generation_stage(cpi)) {
1753
    // First pass doesn't modify reference buffer assignment or produce frame
1754
    // flags
1755
127k
    update_frame_flags(&cpi->common, &cpi->refresh_frame, frame_flags);
1756
127k
    set_additional_frame_flags(cm, frame_flags);
1757
127k
  }
1758
1759
145k
#if !CONFIG_REALTIME_ONLY
1760
#if TXCOEFF_COST_TIMER
1761
  if (!is_stat_generation_stage(cpi)) {
1762
    cm->cum_txcoeff_cost_timer += cm->txcoeff_cost_timer;
1763
    fprintf(stderr,
1764
            "\ntxb coeff cost block number: %ld, frame time: %ld, cum time %ld "
1765
            "in us\n",
1766
            cm->txcoeff_cost_count, cm->txcoeff_cost_timer,
1767
            cm->cum_txcoeff_cost_timer);
1768
  }
1769
#endif
1770
145k
#endif  // !CONFIG_REALTIME_ONLY
1771
1772
#if CONFIG_TUNE_VMAF
1773
  if (!is_stat_generation_stage(cpi) &&
1774
      (oxcf->tune_cfg.tuning >= AOM_TUNE_VMAF_WITH_PREPROCESSING &&
1775
       oxcf->tune_cfg.tuning <= AOM_TUNE_VMAF_NEG_MAX_GAIN)) {
1776
    av1_update_vmaf_curve(cpi);
1777
  }
1778
#endif
1779
1780
145k
  *size = frame_size;
1781
1782
  // Leave a signal for a higher level caller about if this frame is droppable
1783
145k
  if (*size > 0) {
1784
127k
    cpi->droppable =
1785
127k
        is_frame_droppable(&cpi->ppi->rtc_ref, &ext_flags->refresh_frame);
1786
127k
  }
1787
1788
  // For SVC, or when frame-dropper is enabled:
1789
  // keep track of the (unscaled) source corresponding to the refresh of LAST
1790
  // reference (base temporal layer - TL0). Copy only for the
1791
  // top spatial enhancement layer so all spatial layers of the next
1792
  // superframe have last_source to be aligned with previous TL0 superframe.
1793
  // Avoid cases where resolution changes for unscaled source (top spatial
1794
  // layer). Only needs to be done for frame that are encoded (size > 0).
1795
145k
  if (*size > 0 &&
1796
127k
      (cpi->ppi->use_svc || cpi->oxcf.rc_cfg.drop_frames_water_mark > 0) &&
1797
0
      cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1798
0
      cpi->svc.temporal_layer_id == 0 &&
1799
0
      cpi->unscaled_source->y_width == cpi->svc.source_last_TL0.y_width &&
1800
0
      cpi->unscaled_source->y_height == cpi->svc.source_last_TL0.y_height) {
1801
0
    aom_yv12_copy_y(cpi->unscaled_source, &cpi->svc.source_last_TL0, 1);
1802
0
    aom_yv12_copy_u(cpi->unscaled_source, &cpi->svc.source_last_TL0, 1);
1803
0
    aom_yv12_copy_v(cpi->unscaled_source, &cpi->svc.source_last_TL0, 1);
1804
0
  }
1805
1806
145k
  return AOM_CODEC_OK;
1807
145k
}