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