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