xref: /aosp_15_r20/external/libaom/av1/common/mvref_common.c (revision 77c1e3ccc04c968bd2bc212e87364f250e820521)
1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved.
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include <stdlib.h>
13 
14 #include "av1/common/mvref_common.h"
15 #include "av1/common/warped_motion.h"
16 
17 // Although we assign 32 bit integers, all the values are strictly under 14
18 // bits.
19 static int div_mult[32] = { 0,    16384, 8192, 5461, 4096, 3276, 2730, 2340,
20                             2048, 1820,  1638, 1489, 1365, 1260, 1170, 1092,
21                             1024, 963,   910,  862,  819,  780,  744,  712,
22                             682,  655,   630,  606,  585,  564,  546,  528 };
23 
24 // TODO(jingning): Consider the use of lookup table for (num / den)
25 // altogether.
get_mv_projection(MV * output,MV ref,int num,int den)26 static inline void get_mv_projection(MV *output, MV ref, int num, int den) {
27   den = AOMMIN(den, MAX_FRAME_DISTANCE);
28   num = num > 0 ? AOMMIN(num, MAX_FRAME_DISTANCE)
29                 : AOMMAX(num, -MAX_FRAME_DISTANCE);
30   const int mv_row =
31       ROUND_POWER_OF_TWO_SIGNED(ref.row * num * div_mult[den], 14);
32   const int mv_col =
33       ROUND_POWER_OF_TWO_SIGNED(ref.col * num * div_mult[den], 14);
34   const int clamp_max = MV_UPP - 1;
35   const int clamp_min = MV_LOW + 1;
36   output->row = (int16_t)clamp(mv_row, clamp_min, clamp_max);
37   output->col = (int16_t)clamp(mv_col, clamp_min, clamp_max);
38 }
39 
av1_copy_frame_mvs(const AV1_COMMON * const cm,const MB_MODE_INFO * const mi,int mi_row,int mi_col,int x_mis,int y_mis)40 void av1_copy_frame_mvs(const AV1_COMMON *const cm,
41                         const MB_MODE_INFO *const mi, int mi_row, int mi_col,
42                         int x_mis, int y_mis) {
43   const int frame_mvs_stride = ROUND_POWER_OF_TWO(cm->mi_params.mi_cols, 1);
44   MV_REF *frame_mvs =
45       cm->cur_frame->mvs + (mi_row >> 1) * frame_mvs_stride + (mi_col >> 1);
46   x_mis = ROUND_POWER_OF_TWO(x_mis, 1);
47   y_mis = ROUND_POWER_OF_TWO(y_mis, 1);
48   int w, h;
49 
50   for (h = 0; h < y_mis; h++) {
51     MV_REF *mv = frame_mvs;
52     for (w = 0; w < x_mis; w++) {
53       mv->ref_frame = NONE_FRAME;
54       mv->mv.as_int = 0;
55 
56       for (int idx = 0; idx < 2; ++idx) {
57         MV_REFERENCE_FRAME ref_frame = mi->ref_frame[idx];
58         if (ref_frame > INTRA_FRAME) {
59           int8_t ref_idx = cm->ref_frame_side[ref_frame];
60           if (ref_idx) continue;
61           if ((abs(mi->mv[idx].as_mv.row) > REFMVS_LIMIT) ||
62               (abs(mi->mv[idx].as_mv.col) > REFMVS_LIMIT))
63             continue;
64           mv->ref_frame = ref_frame;
65           mv->mv.as_int = mi->mv[idx].as_int;
66         }
67       }
68       mv++;
69     }
70     frame_mvs += frame_mvs_stride;
71   }
72 }
73 
add_ref_mv_candidate(const MB_MODE_INFO * const candidate,const MV_REFERENCE_FRAME rf[2],uint8_t * refmv_count,uint8_t * ref_match_count,uint8_t * newmv_count,CANDIDATE_MV * ref_mv_stack,uint16_t * ref_mv_weight,int_mv * gm_mv_candidates,const WarpedMotionParams * gm_params,uint16_t weight)74 static inline void add_ref_mv_candidate(
75     const MB_MODE_INFO *const candidate, const MV_REFERENCE_FRAME rf[2],
76     uint8_t *refmv_count, uint8_t *ref_match_count, uint8_t *newmv_count,
77     CANDIDATE_MV *ref_mv_stack, uint16_t *ref_mv_weight,
78     int_mv *gm_mv_candidates, const WarpedMotionParams *gm_params,
79     uint16_t weight) {
80   if (!is_inter_block(candidate)) return;
81   assert(weight % 2 == 0);
82   int index, ref;
83 
84   if (rf[1] == NONE_FRAME) {
85     // single reference frame
86     for (ref = 0; ref < 2; ++ref) {
87       if (candidate->ref_frame[ref] == rf[0]) {
88         const int is_gm_block =
89             is_global_mv_block(candidate, gm_params[rf[0]].wmtype);
90         const int_mv this_refmv =
91             is_gm_block ? gm_mv_candidates[0] : get_block_mv(candidate, ref);
92         for (index = 0; index < *refmv_count; ++index) {
93           if (ref_mv_stack[index].this_mv.as_int == this_refmv.as_int) {
94             ref_mv_weight[index] += weight;
95             break;
96           }
97         }
98 
99         // Add a new item to the list.
100         if (index == *refmv_count && *refmv_count < MAX_REF_MV_STACK_SIZE) {
101           ref_mv_stack[index].this_mv = this_refmv;
102           ref_mv_weight[index] = weight;
103           ++(*refmv_count);
104         }
105         if (have_newmv_in_inter_mode(candidate->mode)) ++*newmv_count;
106         ++*ref_match_count;
107       }
108     }
109   } else {
110     // compound reference frame
111     if (candidate->ref_frame[0] == rf[0] && candidate->ref_frame[1] == rf[1]) {
112       int_mv this_refmv[2];
113 
114       for (ref = 0; ref < 2; ++ref) {
115         if (is_global_mv_block(candidate, gm_params[rf[ref]].wmtype))
116           this_refmv[ref] = gm_mv_candidates[ref];
117         else
118           this_refmv[ref] = get_block_mv(candidate, ref);
119       }
120 
121       for (index = 0; index < *refmv_count; ++index) {
122         if ((ref_mv_stack[index].this_mv.as_int == this_refmv[0].as_int) &&
123             (ref_mv_stack[index].comp_mv.as_int == this_refmv[1].as_int)) {
124           ref_mv_weight[index] += weight;
125           break;
126         }
127       }
128 
129       // Add a new item to the list.
130       if (index == *refmv_count && *refmv_count < MAX_REF_MV_STACK_SIZE) {
131         ref_mv_stack[index].this_mv = this_refmv[0];
132         ref_mv_stack[index].comp_mv = this_refmv[1];
133         ref_mv_weight[index] = weight;
134         ++(*refmv_count);
135       }
136       if (have_newmv_in_inter_mode(candidate->mode)) ++*newmv_count;
137       ++*ref_match_count;
138     }
139   }
140 }
141 
scan_row_mbmi(const AV1_COMMON * cm,const MACROBLOCKD * xd,int mi_col,const MV_REFERENCE_FRAME rf[2],int row_offset,CANDIDATE_MV * ref_mv_stack,uint16_t * ref_mv_weight,uint8_t * refmv_count,uint8_t * ref_match_count,uint8_t * newmv_count,int_mv * gm_mv_candidates,int max_row_offset,int * processed_rows)142 static inline void scan_row_mbmi(const AV1_COMMON *cm, const MACROBLOCKD *xd,
143                                  int mi_col, const MV_REFERENCE_FRAME rf[2],
144                                  int row_offset, CANDIDATE_MV *ref_mv_stack,
145                                  uint16_t *ref_mv_weight, uint8_t *refmv_count,
146                                  uint8_t *ref_match_count, uint8_t *newmv_count,
147                                  int_mv *gm_mv_candidates, int max_row_offset,
148                                  int *processed_rows) {
149   int end_mi = AOMMIN(xd->width, cm->mi_params.mi_cols - mi_col);
150   end_mi = AOMMIN(end_mi, mi_size_wide[BLOCK_64X64]);
151   const int width_8x8 = mi_size_wide[BLOCK_8X8];
152   const int width_16x16 = mi_size_wide[BLOCK_16X16];
153   int col_offset = 0;
154   // TODO(jingning): Revisit this part after cb4x4 is stable.
155   if (abs(row_offset) > 1) {
156     col_offset = 1;
157     if ((mi_col & 0x01) && xd->width < width_8x8) --col_offset;
158   }
159   const int use_step_16 = (xd->width >= 16);
160   MB_MODE_INFO **const candidate_mi0 = xd->mi + row_offset * xd->mi_stride;
161 
162   for (int i = 0; i < end_mi;) {
163     const MB_MODE_INFO *const candidate = candidate_mi0[col_offset + i];
164     const int candidate_bsize = candidate->bsize;
165     const int n4_w = mi_size_wide[candidate_bsize];
166     int len = AOMMIN(xd->width, n4_w);
167     if (use_step_16)
168       len = AOMMAX(width_16x16, len);
169     else if (abs(row_offset) > 1)
170       len = AOMMAX(len, width_8x8);
171 
172     uint16_t weight = 2;
173     if (xd->width >= width_8x8 && xd->width <= n4_w) {
174       uint16_t inc = AOMMIN(-max_row_offset + row_offset + 1,
175                             mi_size_high[candidate_bsize]);
176       // Obtain range used in weight calculation.
177       weight = AOMMAX(weight, inc);
178       // Update processed rows.
179       *processed_rows = inc - row_offset - 1;
180     }
181 
182     add_ref_mv_candidate(candidate, rf, refmv_count, ref_match_count,
183                          newmv_count, ref_mv_stack, ref_mv_weight,
184                          gm_mv_candidates, cm->global_motion, len * weight);
185 
186     i += len;
187   }
188 }
189 
scan_col_mbmi(const AV1_COMMON * cm,const MACROBLOCKD * xd,int mi_row,const MV_REFERENCE_FRAME rf[2],int col_offset,CANDIDATE_MV * ref_mv_stack,uint16_t * ref_mv_weight,uint8_t * refmv_count,uint8_t * ref_match_count,uint8_t * newmv_count,int_mv * gm_mv_candidates,int max_col_offset,int * processed_cols)190 static inline void scan_col_mbmi(const AV1_COMMON *cm, const MACROBLOCKD *xd,
191                                  int mi_row, const MV_REFERENCE_FRAME rf[2],
192                                  int col_offset, CANDIDATE_MV *ref_mv_stack,
193                                  uint16_t *ref_mv_weight, uint8_t *refmv_count,
194                                  uint8_t *ref_match_count, uint8_t *newmv_count,
195                                  int_mv *gm_mv_candidates, int max_col_offset,
196                                  int *processed_cols) {
197   int end_mi = AOMMIN(xd->height, cm->mi_params.mi_rows - mi_row);
198   end_mi = AOMMIN(end_mi, mi_size_high[BLOCK_64X64]);
199   const int n8_h_8 = mi_size_high[BLOCK_8X8];
200   const int n8_h_16 = mi_size_high[BLOCK_16X16];
201   int i;
202   int row_offset = 0;
203   if (abs(col_offset) > 1) {
204     row_offset = 1;
205     if ((mi_row & 0x01) && xd->height < n8_h_8) --row_offset;
206   }
207   const int use_step_16 = (xd->height >= 16);
208 
209   for (i = 0; i < end_mi;) {
210     const MB_MODE_INFO *const candidate =
211         xd->mi[(row_offset + i) * xd->mi_stride + col_offset];
212     const int candidate_bsize = candidate->bsize;
213     const int n4_h = mi_size_high[candidate_bsize];
214     int len = AOMMIN(xd->height, n4_h);
215     if (use_step_16)
216       len = AOMMAX(n8_h_16, len);
217     else if (abs(col_offset) > 1)
218       len = AOMMAX(len, n8_h_8);
219 
220     int weight = 2;
221     if (xd->height >= n8_h_8 && xd->height <= n4_h) {
222       int inc = AOMMIN(-max_col_offset + col_offset + 1,
223                        mi_size_wide[candidate_bsize]);
224       // Obtain range used in weight calculation.
225       weight = AOMMAX(weight, inc);
226       // Update processed cols.
227       *processed_cols = inc - col_offset - 1;
228     }
229 
230     add_ref_mv_candidate(candidate, rf, refmv_count, ref_match_count,
231                          newmv_count, ref_mv_stack, ref_mv_weight,
232                          gm_mv_candidates, cm->global_motion, len * weight);
233 
234     i += len;
235   }
236 }
237 
scan_blk_mbmi(const AV1_COMMON * cm,const MACROBLOCKD * xd,const int mi_row,const int mi_col,const MV_REFERENCE_FRAME rf[2],int row_offset,int col_offset,CANDIDATE_MV * ref_mv_stack,uint16_t * ref_mv_weight,uint8_t * ref_match_count,uint8_t * newmv_count,int_mv * gm_mv_candidates,uint8_t * refmv_count)238 static inline void scan_blk_mbmi(const AV1_COMMON *cm, const MACROBLOCKD *xd,
239                                  const int mi_row, const int mi_col,
240                                  const MV_REFERENCE_FRAME rf[2], int row_offset,
241                                  int col_offset, CANDIDATE_MV *ref_mv_stack,
242                                  uint16_t *ref_mv_weight,
243                                  uint8_t *ref_match_count, uint8_t *newmv_count,
244                                  int_mv *gm_mv_candidates,
245                                  uint8_t *refmv_count) {
246   const TileInfo *const tile = &xd->tile;
247   POSITION mi_pos;
248 
249   mi_pos.row = row_offset;
250   mi_pos.col = col_offset;
251 
252   if (is_inside(tile, mi_col, mi_row, &mi_pos)) {
253     const MB_MODE_INFO *const candidate =
254         xd->mi[mi_pos.row * xd->mi_stride + mi_pos.col];
255     const int len = mi_size_wide[BLOCK_8X8];
256 
257     add_ref_mv_candidate(candidate, rf, refmv_count, ref_match_count,
258                          newmv_count, ref_mv_stack, ref_mv_weight,
259                          gm_mv_candidates, cm->global_motion, 2 * len);
260   }  // Analyze a single 8x8 block motion information.
261 }
262 
has_top_right(const AV1_COMMON * cm,const MACROBLOCKD * xd,int mi_row,int mi_col,int bs)263 static int has_top_right(const AV1_COMMON *cm, const MACROBLOCKD *xd,
264                          int mi_row, int mi_col, int bs) {
265   const int sb_mi_size = mi_size_wide[cm->seq_params->sb_size];
266   const int mask_row = mi_row & (sb_mi_size - 1);
267   const int mask_col = mi_col & (sb_mi_size - 1);
268 
269   if (bs > mi_size_wide[BLOCK_64X64]) return 0;
270 
271   // In a split partition all apart from the bottom right has a top right
272   int has_tr = !((mask_row & bs) && (mask_col & bs));
273 
274   // bs > 0 and bs is a power of 2
275   assert(bs > 0 && !(bs & (bs - 1)));
276 
277   // For each 4x4 group of blocks, when the bottom right is decoded the blocks
278   // to the right have not been decoded therefore the bottom right does
279   // not have a top right
280   while (bs < sb_mi_size) {
281     if (mask_col & bs) {
282       if ((mask_col & (2 * bs)) && (mask_row & (2 * bs))) {
283         has_tr = 0;
284         break;
285       }
286     } else {
287       break;
288     }
289     bs <<= 1;
290   }
291 
292   // In a VERTICAL or VERTICAL_4 partition, all partition before the last one
293   // always have a top right (as the block above will have been decoded).
294   if (xd->width < xd->height) {
295     if (!xd->is_last_vertical_rect) has_tr = 1;
296   }
297 
298   // In a HORIZONTAL or HORIZONTAL_4 partition, partitions after the first one
299   // never have a top right (as the block to the right won't have been decoded).
300   if (xd->width > xd->height) {
301     if (!xd->is_first_horizontal_rect) has_tr = 0;
302   }
303 
304   // The bottom left square of a Vertical A (in the old format) does
305   // not have a top right as it is decoded before the right hand
306   // rectangle of the partition
307   if (xd->mi[0]->partition == PARTITION_VERT_A) {
308     if (xd->width == xd->height)
309       if (mask_row & bs) has_tr = 0;
310   }
311 
312   return has_tr;
313 }
314 
check_sb_border(const int mi_row,const int mi_col,const int row_offset,const int col_offset)315 static int check_sb_border(const int mi_row, const int mi_col,
316                            const int row_offset, const int col_offset) {
317   const int sb_mi_size = mi_size_wide[BLOCK_64X64];
318   const int row = mi_row & (sb_mi_size - 1);
319   const int col = mi_col & (sb_mi_size - 1);
320 
321   if (row + row_offset < 0 || row + row_offset >= sb_mi_size ||
322       col + col_offset < 0 || col + col_offset >= sb_mi_size)
323     return 0;
324 
325   return 1;
326 }
327 
add_tpl_ref_mv(const AV1_COMMON * cm,const MACROBLOCKD * xd,int mi_row,int mi_col,MV_REFERENCE_FRAME ref_frame,int blk_row,int blk_col,int_mv * gm_mv_candidates,uint8_t * const refmv_count,CANDIDATE_MV ref_mv_stack[MAX_REF_MV_STACK_SIZE],uint16_t ref_mv_weight[MAX_REF_MV_STACK_SIZE],int16_t * mode_context)328 static int add_tpl_ref_mv(const AV1_COMMON *cm, const MACROBLOCKD *xd,
329                           int mi_row, int mi_col, MV_REFERENCE_FRAME ref_frame,
330                           int blk_row, int blk_col, int_mv *gm_mv_candidates,
331                           uint8_t *const refmv_count,
332                           CANDIDATE_MV ref_mv_stack[MAX_REF_MV_STACK_SIZE],
333                           uint16_t ref_mv_weight[MAX_REF_MV_STACK_SIZE],
334                           int16_t *mode_context) {
335   POSITION mi_pos;
336   mi_pos.row = (mi_row & 0x01) ? blk_row : blk_row + 1;
337   mi_pos.col = (mi_col & 0x01) ? blk_col : blk_col + 1;
338 
339   if (!is_inside(&xd->tile, mi_col, mi_row, &mi_pos)) return 0;
340 
341   const TPL_MV_REF *prev_frame_mvs =
342       cm->tpl_mvs +
343       ((mi_row + mi_pos.row) >> 1) * (cm->mi_params.mi_stride >> 1) +
344       ((mi_col + mi_pos.col) >> 1);
345   if (prev_frame_mvs->mfmv0.as_int == INVALID_MV) return 0;
346 
347   MV_REFERENCE_FRAME rf[2];
348   av1_set_ref_frame(rf, ref_frame);
349 
350   const uint16_t weight_unit = 1;  // mi_size_wide[BLOCK_8X8];
351   const int cur_frame_index = cm->cur_frame->order_hint;
352   const RefCntBuffer *const buf_0 = get_ref_frame_buf(cm, rf[0]);
353   const int frame0_index = buf_0->order_hint;
354   const int cur_offset_0 = get_relative_dist(&cm->seq_params->order_hint_info,
355                                              cur_frame_index, frame0_index);
356   int idx;
357   const int allow_high_precision_mv = cm->features.allow_high_precision_mv;
358   const int force_integer_mv = cm->features.cur_frame_force_integer_mv;
359 
360   int_mv this_refmv;
361   get_mv_projection(&this_refmv.as_mv, prev_frame_mvs->mfmv0.as_mv,
362                     cur_offset_0, prev_frame_mvs->ref_frame_offset);
363   lower_mv_precision(&this_refmv.as_mv, allow_high_precision_mv,
364                      force_integer_mv);
365 
366   if (rf[1] == NONE_FRAME) {
367     if (blk_row == 0 && blk_col == 0) {
368       if (abs(this_refmv.as_mv.row - gm_mv_candidates[0].as_mv.row) >= 16 ||
369           abs(this_refmv.as_mv.col - gm_mv_candidates[0].as_mv.col) >= 16)
370         mode_context[ref_frame] |= (1 << GLOBALMV_OFFSET);
371     }
372 
373     for (idx = 0; idx < *refmv_count; ++idx)
374       if (this_refmv.as_int == ref_mv_stack[idx].this_mv.as_int) break;
375 
376     if (idx < *refmv_count) ref_mv_weight[idx] += 2 * weight_unit;
377 
378     if (idx == *refmv_count && *refmv_count < MAX_REF_MV_STACK_SIZE) {
379       ref_mv_stack[idx].this_mv.as_int = this_refmv.as_int;
380       ref_mv_weight[idx] = 2 * weight_unit;
381       ++(*refmv_count);
382     }
383   } else {
384     // Process compound inter mode
385     const RefCntBuffer *const buf_1 = get_ref_frame_buf(cm, rf[1]);
386     const int frame1_index = buf_1->order_hint;
387     const int cur_offset_1 = get_relative_dist(&cm->seq_params->order_hint_info,
388                                                cur_frame_index, frame1_index);
389     int_mv comp_refmv;
390     get_mv_projection(&comp_refmv.as_mv, prev_frame_mvs->mfmv0.as_mv,
391                       cur_offset_1, prev_frame_mvs->ref_frame_offset);
392     lower_mv_precision(&comp_refmv.as_mv, allow_high_precision_mv,
393                        force_integer_mv);
394 
395     if (blk_row == 0 && blk_col == 0) {
396       if (abs(this_refmv.as_mv.row - gm_mv_candidates[0].as_mv.row) >= 16 ||
397           abs(this_refmv.as_mv.col - gm_mv_candidates[0].as_mv.col) >= 16 ||
398           abs(comp_refmv.as_mv.row - gm_mv_candidates[1].as_mv.row) >= 16 ||
399           abs(comp_refmv.as_mv.col - gm_mv_candidates[1].as_mv.col) >= 16)
400         mode_context[ref_frame] |= (1 << GLOBALMV_OFFSET);
401     }
402 
403     for (idx = 0; idx < *refmv_count; ++idx) {
404       if (this_refmv.as_int == ref_mv_stack[idx].this_mv.as_int &&
405           comp_refmv.as_int == ref_mv_stack[idx].comp_mv.as_int)
406         break;
407     }
408 
409     if (idx < *refmv_count) ref_mv_weight[idx] += 2 * weight_unit;
410 
411     if (idx == *refmv_count && *refmv_count < MAX_REF_MV_STACK_SIZE) {
412       ref_mv_stack[idx].this_mv.as_int = this_refmv.as_int;
413       ref_mv_stack[idx].comp_mv.as_int = comp_refmv.as_int;
414       ref_mv_weight[idx] = 2 * weight_unit;
415       ++(*refmv_count);
416     }
417   }
418 
419   return 1;
420 }
421 
process_compound_ref_mv_candidate(const MB_MODE_INFO * const candidate,const AV1_COMMON * const cm,const MV_REFERENCE_FRAME * const rf,int_mv ref_id[2][2],int ref_id_count[2],int_mv ref_diff[2][2],int ref_diff_count[2])422 static inline void process_compound_ref_mv_candidate(
423     const MB_MODE_INFO *const candidate, const AV1_COMMON *const cm,
424     const MV_REFERENCE_FRAME *const rf, int_mv ref_id[2][2],
425     int ref_id_count[2], int_mv ref_diff[2][2], int ref_diff_count[2]) {
426   for (int rf_idx = 0; rf_idx < 2; ++rf_idx) {
427     MV_REFERENCE_FRAME can_rf = candidate->ref_frame[rf_idx];
428 
429     for (int cmp_idx = 0; cmp_idx < 2; ++cmp_idx) {
430       if (can_rf == rf[cmp_idx] && ref_id_count[cmp_idx] < 2) {
431         ref_id[cmp_idx][ref_id_count[cmp_idx]] = candidate->mv[rf_idx];
432         ++ref_id_count[cmp_idx];
433       } else if (can_rf > INTRA_FRAME && ref_diff_count[cmp_idx] < 2) {
434         int_mv this_mv = candidate->mv[rf_idx];
435         if (cm->ref_frame_sign_bias[can_rf] !=
436             cm->ref_frame_sign_bias[rf[cmp_idx]]) {
437           this_mv.as_mv.row = -this_mv.as_mv.row;
438           this_mv.as_mv.col = -this_mv.as_mv.col;
439         }
440         ref_diff[cmp_idx][ref_diff_count[cmp_idx]] = this_mv;
441         ++ref_diff_count[cmp_idx];
442       }
443     }
444   }
445 }
446 
process_single_ref_mv_candidate(const MB_MODE_INFO * const candidate,const AV1_COMMON * const cm,MV_REFERENCE_FRAME ref_frame,uint8_t * const refmv_count,CANDIDATE_MV ref_mv_stack[MAX_REF_MV_STACK_SIZE],uint16_t ref_mv_weight[MAX_REF_MV_STACK_SIZE])447 static inline void process_single_ref_mv_candidate(
448     const MB_MODE_INFO *const candidate, const AV1_COMMON *const cm,
449     MV_REFERENCE_FRAME ref_frame, uint8_t *const refmv_count,
450     CANDIDATE_MV ref_mv_stack[MAX_REF_MV_STACK_SIZE],
451     uint16_t ref_mv_weight[MAX_REF_MV_STACK_SIZE]) {
452   for (int rf_idx = 0; rf_idx < 2; ++rf_idx) {
453     if (candidate->ref_frame[rf_idx] > INTRA_FRAME) {
454       int_mv this_mv = candidate->mv[rf_idx];
455       if (cm->ref_frame_sign_bias[candidate->ref_frame[rf_idx]] !=
456           cm->ref_frame_sign_bias[ref_frame]) {
457         this_mv.as_mv.row = -this_mv.as_mv.row;
458         this_mv.as_mv.col = -this_mv.as_mv.col;
459       }
460       int stack_idx;
461       for (stack_idx = 0; stack_idx < *refmv_count; ++stack_idx) {
462         const int_mv stack_mv = ref_mv_stack[stack_idx].this_mv;
463         if (this_mv.as_int == stack_mv.as_int) break;
464       }
465 
466       if (stack_idx == *refmv_count) {
467         ref_mv_stack[stack_idx].this_mv = this_mv;
468 
469         // TODO(jingning): Set an arbitrary small number here. The weight
470         // doesn't matter as long as it is properly initialized.
471         ref_mv_weight[stack_idx] = 2;
472         ++(*refmv_count);
473       }
474     }
475   }
476 }
477 
setup_ref_mv_list(const AV1_COMMON * cm,const MACROBLOCKD * xd,MV_REFERENCE_FRAME ref_frame,uint8_t * const refmv_count,CANDIDATE_MV ref_mv_stack[MAX_REF_MV_STACK_SIZE],uint16_t ref_mv_weight[MAX_REF_MV_STACK_SIZE],int_mv mv_ref_list[MAX_MV_REF_CANDIDATES],int_mv * gm_mv_candidates,int mi_row,int mi_col,int16_t * mode_context)478 static inline void setup_ref_mv_list(
479     const AV1_COMMON *cm, const MACROBLOCKD *xd, MV_REFERENCE_FRAME ref_frame,
480     uint8_t *const refmv_count,
481     CANDIDATE_MV ref_mv_stack[MAX_REF_MV_STACK_SIZE],
482     uint16_t ref_mv_weight[MAX_REF_MV_STACK_SIZE],
483     int_mv mv_ref_list[MAX_MV_REF_CANDIDATES], int_mv *gm_mv_candidates,
484     int mi_row, int mi_col, int16_t *mode_context) {
485   const int bs = AOMMAX(xd->width, xd->height);
486   const int has_tr = has_top_right(cm, xd, mi_row, mi_col, bs);
487   MV_REFERENCE_FRAME rf[2];
488 
489   const TileInfo *const tile = &xd->tile;
490   int max_row_offset = 0, max_col_offset = 0;
491   const int row_adj = (xd->height < mi_size_high[BLOCK_8X8]) && (mi_row & 0x01);
492   const int col_adj = (xd->width < mi_size_wide[BLOCK_8X8]) && (mi_col & 0x01);
493   int processed_rows = 0;
494   int processed_cols = 0;
495 
496   av1_set_ref_frame(rf, ref_frame);
497   mode_context[ref_frame] = 0;
498   *refmv_count = 0;
499 
500   // Find valid maximum row/col offset.
501   if (xd->up_available) {
502     max_row_offset = -(MVREF_ROW_COLS << 1) + row_adj;
503 
504     if (xd->height < mi_size_high[BLOCK_8X8])
505       max_row_offset = -(2 << 1) + row_adj;
506 
507     max_row_offset = find_valid_row_offset(tile, mi_row, max_row_offset);
508   }
509 
510   if (xd->left_available) {
511     max_col_offset = -(MVREF_ROW_COLS << 1) + col_adj;
512 
513     if (xd->width < mi_size_wide[BLOCK_8X8])
514       max_col_offset = -(2 << 1) + col_adj;
515 
516     max_col_offset = find_valid_col_offset(tile, mi_col, max_col_offset);
517   }
518 
519   uint8_t col_match_count = 0;
520   uint8_t row_match_count = 0;
521   uint8_t newmv_count = 0;
522 
523   // Scan the first above row mode info. row_offset = -1;
524   if (abs(max_row_offset) >= 1)
525     scan_row_mbmi(cm, xd, mi_col, rf, -1, ref_mv_stack, ref_mv_weight,
526                   refmv_count, &row_match_count, &newmv_count, gm_mv_candidates,
527                   max_row_offset, &processed_rows);
528   // Scan the first left column mode info. col_offset = -1;
529   if (abs(max_col_offset) >= 1)
530     scan_col_mbmi(cm, xd, mi_row, rf, -1, ref_mv_stack, ref_mv_weight,
531                   refmv_count, &col_match_count, &newmv_count, gm_mv_candidates,
532                   max_col_offset, &processed_cols);
533   // Check top-right boundary
534   if (has_tr)
535     scan_blk_mbmi(cm, xd, mi_row, mi_col, rf, -1, xd->width, ref_mv_stack,
536                   ref_mv_weight, &row_match_count, &newmv_count,
537                   gm_mv_candidates, refmv_count);
538 
539   const uint8_t nearest_match = (row_match_count > 0) + (col_match_count > 0);
540   const uint8_t nearest_refmv_count = *refmv_count;
541 
542   // TODO(yunqing): for comp_search, do it for all 3 cases.
543   for (int idx = 0; idx < nearest_refmv_count; ++idx)
544     ref_mv_weight[idx] += REF_CAT_LEVEL;
545 
546   if (cm->features.allow_ref_frame_mvs) {
547     int is_available = 0;
548     const int voffset = AOMMAX(mi_size_high[BLOCK_8X8], xd->height);
549     const int hoffset = AOMMAX(mi_size_wide[BLOCK_8X8], xd->width);
550     const int blk_row_end = AOMMIN(xd->height, mi_size_high[BLOCK_64X64]);
551     const int blk_col_end = AOMMIN(xd->width, mi_size_wide[BLOCK_64X64]);
552 
553     const int tpl_sample_pos[3][2] = {
554       { voffset, -2 },
555       { voffset, hoffset },
556       { voffset - 2, hoffset },
557     };
558     const int allow_extension = (xd->height >= mi_size_high[BLOCK_8X8]) &&
559                                 (xd->height < mi_size_high[BLOCK_64X64]) &&
560                                 (xd->width >= mi_size_wide[BLOCK_8X8]) &&
561                                 (xd->width < mi_size_wide[BLOCK_64X64]);
562 
563     const int step_h = (xd->height >= mi_size_high[BLOCK_64X64])
564                            ? mi_size_high[BLOCK_16X16]
565                            : mi_size_high[BLOCK_8X8];
566     const int step_w = (xd->width >= mi_size_wide[BLOCK_64X64])
567                            ? mi_size_wide[BLOCK_16X16]
568                            : mi_size_wide[BLOCK_8X8];
569 
570     for (int blk_row = 0; blk_row < blk_row_end; blk_row += step_h) {
571       for (int blk_col = 0; blk_col < blk_col_end; blk_col += step_w) {
572         int ret = add_tpl_ref_mv(cm, xd, mi_row, mi_col, ref_frame, blk_row,
573                                  blk_col, gm_mv_candidates, refmv_count,
574                                  ref_mv_stack, ref_mv_weight, mode_context);
575         if (blk_row == 0 && blk_col == 0) is_available = ret;
576       }
577     }
578 
579     if (is_available == 0) mode_context[ref_frame] |= (1 << GLOBALMV_OFFSET);
580 
581     for (int i = 0; i < 3 && allow_extension; ++i) {
582       const int blk_row = tpl_sample_pos[i][0];
583       const int blk_col = tpl_sample_pos[i][1];
584 
585       if (!check_sb_border(mi_row, mi_col, blk_row, blk_col)) continue;
586       add_tpl_ref_mv(cm, xd, mi_row, mi_col, ref_frame, blk_row, blk_col,
587                      gm_mv_candidates, refmv_count, ref_mv_stack, ref_mv_weight,
588                      mode_context);
589     }
590   }
591 
592   uint8_t dummy_newmv_count = 0;
593 
594   // Scan the second outer area.
595   scan_blk_mbmi(cm, xd, mi_row, mi_col, rf, -1, -1, ref_mv_stack, ref_mv_weight,
596                 &row_match_count, &dummy_newmv_count, gm_mv_candidates,
597                 refmv_count);
598 
599   for (int idx = 2; idx <= MVREF_ROW_COLS; ++idx) {
600     const int row_offset = -(idx << 1) + 1 + row_adj;
601     const int col_offset = -(idx << 1) + 1 + col_adj;
602 
603     if (abs(row_offset) <= abs(max_row_offset) &&
604         abs(row_offset) > processed_rows)
605       scan_row_mbmi(cm, xd, mi_col, rf, row_offset, ref_mv_stack, ref_mv_weight,
606                     refmv_count, &row_match_count, &dummy_newmv_count,
607                     gm_mv_candidates, max_row_offset, &processed_rows);
608 
609     if (abs(col_offset) <= abs(max_col_offset) &&
610         abs(col_offset) > processed_cols)
611       scan_col_mbmi(cm, xd, mi_row, rf, col_offset, ref_mv_stack, ref_mv_weight,
612                     refmv_count, &col_match_count, &dummy_newmv_count,
613                     gm_mv_candidates, max_col_offset, &processed_cols);
614   }
615 
616   const uint8_t ref_match_count = (row_match_count > 0) + (col_match_count > 0);
617 
618   switch (nearest_match) {
619     case 0:
620       if (ref_match_count >= 1) mode_context[ref_frame] |= 1;
621       if (ref_match_count == 1)
622         mode_context[ref_frame] |= (1 << REFMV_OFFSET);
623       else if (ref_match_count >= 2)
624         mode_context[ref_frame] |= (2 << REFMV_OFFSET);
625       break;
626     case 1:
627       mode_context[ref_frame] |= (newmv_count > 0) ? 2 : 3;
628       if (ref_match_count == 1)
629         mode_context[ref_frame] |= (3 << REFMV_OFFSET);
630       else if (ref_match_count >= 2)
631         mode_context[ref_frame] |= (4 << REFMV_OFFSET);
632       break;
633     case 2:
634     default:
635       if (newmv_count >= 1)
636         mode_context[ref_frame] |= 4;
637       else
638         mode_context[ref_frame] |= 5;
639 
640       mode_context[ref_frame] |= (5 << REFMV_OFFSET);
641       break;
642   }
643 
644   // Rank the likelihood and assign nearest and near mvs.
645   int len = nearest_refmv_count;
646   while (len > 0) {
647     int nr_len = 0;
648     for (int idx = 1; idx < len; ++idx) {
649       if (ref_mv_weight[idx - 1] < ref_mv_weight[idx]) {
650         const CANDIDATE_MV tmp_mv = ref_mv_stack[idx - 1];
651         const uint16_t tmp_ref_mv_weight = ref_mv_weight[idx - 1];
652         ref_mv_stack[idx - 1] = ref_mv_stack[idx];
653         ref_mv_stack[idx] = tmp_mv;
654         ref_mv_weight[idx - 1] = ref_mv_weight[idx];
655         ref_mv_weight[idx] = tmp_ref_mv_weight;
656         nr_len = idx;
657       }
658     }
659     len = nr_len;
660   }
661 
662   len = *refmv_count;
663   while (len > nearest_refmv_count) {
664     int nr_len = nearest_refmv_count;
665     for (int idx = nearest_refmv_count + 1; idx < len; ++idx) {
666       if (ref_mv_weight[idx - 1] < ref_mv_weight[idx]) {
667         const CANDIDATE_MV tmp_mv = ref_mv_stack[idx - 1];
668         const uint16_t tmp_ref_mv_weight = ref_mv_weight[idx - 1];
669         ref_mv_stack[idx - 1] = ref_mv_stack[idx];
670         ref_mv_stack[idx] = tmp_mv;
671         ref_mv_weight[idx - 1] = ref_mv_weight[idx];
672         ref_mv_weight[idx] = tmp_ref_mv_weight;
673         nr_len = idx;
674       }
675     }
676     len = nr_len;
677   }
678 
679   int mi_width = AOMMIN(mi_size_wide[BLOCK_64X64], xd->width);
680   mi_width = AOMMIN(mi_width, cm->mi_params.mi_cols - mi_col);
681   int mi_height = AOMMIN(mi_size_high[BLOCK_64X64], xd->height);
682   mi_height = AOMMIN(mi_height, cm->mi_params.mi_rows - mi_row);
683   const int mi_size = AOMMIN(mi_width, mi_height);
684   if (rf[1] > NONE_FRAME) {
685     // TODO(jingning, yunqing): Refactor and consolidate the compound and
686     // single reference frame modes. Reduce unnecessary redundancy.
687     if (*refmv_count < MAX_MV_REF_CANDIDATES) {
688       int_mv ref_id[2][2], ref_diff[2][2];
689       int ref_id_count[2] = { 0 }, ref_diff_count[2] = { 0 };
690 
691       for (int idx = 0; abs(max_row_offset) >= 1 && idx < mi_size;) {
692         const MB_MODE_INFO *const candidate = xd->mi[-xd->mi_stride + idx];
693         process_compound_ref_mv_candidate(
694             candidate, cm, rf, ref_id, ref_id_count, ref_diff, ref_diff_count);
695         idx += mi_size_wide[candidate->bsize];
696       }
697 
698       for (int idx = 0; abs(max_col_offset) >= 1 && idx < mi_size;) {
699         const MB_MODE_INFO *const candidate = xd->mi[idx * xd->mi_stride - 1];
700         process_compound_ref_mv_candidate(
701             candidate, cm, rf, ref_id, ref_id_count, ref_diff, ref_diff_count);
702         idx += mi_size_high[candidate->bsize];
703       }
704 
705       // Build up the compound mv predictor
706       int_mv comp_list[MAX_MV_REF_CANDIDATES][2];
707 
708       for (int idx = 0; idx < 2; ++idx) {
709         int comp_idx = 0;
710         for (int list_idx = 0;
711              list_idx < ref_id_count[idx] && comp_idx < MAX_MV_REF_CANDIDATES;
712              ++list_idx, ++comp_idx)
713           comp_list[comp_idx][idx] = ref_id[idx][list_idx];
714         for (int list_idx = 0;
715              list_idx < ref_diff_count[idx] && comp_idx < MAX_MV_REF_CANDIDATES;
716              ++list_idx, ++comp_idx)
717           comp_list[comp_idx][idx] = ref_diff[idx][list_idx];
718         for (; comp_idx < MAX_MV_REF_CANDIDATES; ++comp_idx)
719           comp_list[comp_idx][idx] = gm_mv_candidates[idx];
720       }
721 
722       if (*refmv_count) {
723         assert(*refmv_count == 1);
724         if (comp_list[0][0].as_int == ref_mv_stack[0].this_mv.as_int &&
725             comp_list[0][1].as_int == ref_mv_stack[0].comp_mv.as_int) {
726           ref_mv_stack[*refmv_count].this_mv = comp_list[1][0];
727           ref_mv_stack[*refmv_count].comp_mv = comp_list[1][1];
728         } else {
729           ref_mv_stack[*refmv_count].this_mv = comp_list[0][0];
730           ref_mv_stack[*refmv_count].comp_mv = comp_list[0][1];
731         }
732         ref_mv_weight[*refmv_count] = 2;
733         ++*refmv_count;
734       } else {
735         for (int idx = 0; idx < MAX_MV_REF_CANDIDATES; ++idx) {
736           ref_mv_stack[*refmv_count].this_mv = comp_list[idx][0];
737           ref_mv_stack[*refmv_count].comp_mv = comp_list[idx][1];
738           ref_mv_weight[*refmv_count] = 2;
739           ++*refmv_count;
740         }
741       }
742     }
743 
744     assert(*refmv_count >= 2);
745 
746     for (int idx = 0; idx < *refmv_count; ++idx) {
747       clamp_mv_ref(&ref_mv_stack[idx].this_mv.as_mv, xd->width << MI_SIZE_LOG2,
748                    xd->height << MI_SIZE_LOG2, xd);
749       clamp_mv_ref(&ref_mv_stack[idx].comp_mv.as_mv, xd->width << MI_SIZE_LOG2,
750                    xd->height << MI_SIZE_LOG2, xd);
751     }
752   } else {
753     // Handle single reference frame extension
754     for (int idx = 0; abs(max_row_offset) >= 1 && idx < mi_size &&
755                       *refmv_count < MAX_MV_REF_CANDIDATES;) {
756       const MB_MODE_INFO *const candidate = xd->mi[-xd->mi_stride + idx];
757       process_single_ref_mv_candidate(candidate, cm, ref_frame, refmv_count,
758                                       ref_mv_stack, ref_mv_weight);
759       idx += mi_size_wide[candidate->bsize];
760     }
761 
762     for (int idx = 0; abs(max_col_offset) >= 1 && idx < mi_size &&
763                       *refmv_count < MAX_MV_REF_CANDIDATES;) {
764       const MB_MODE_INFO *const candidate = xd->mi[idx * xd->mi_stride - 1];
765       process_single_ref_mv_candidate(candidate, cm, ref_frame, refmv_count,
766                                       ref_mv_stack, ref_mv_weight);
767       idx += mi_size_high[candidate->bsize];
768     }
769 
770     for (int idx = 0; idx < *refmv_count; ++idx) {
771       clamp_mv_ref(&ref_mv_stack[idx].this_mv.as_mv, xd->width << MI_SIZE_LOG2,
772                    xd->height << MI_SIZE_LOG2, xd);
773     }
774 
775     if (mv_ref_list != NULL) {
776       for (int idx = *refmv_count; idx < MAX_MV_REF_CANDIDATES; ++idx)
777         mv_ref_list[idx].as_int = gm_mv_candidates[0].as_int;
778 
779       for (int idx = 0; idx < AOMMIN(MAX_MV_REF_CANDIDATES, *refmv_count);
780            ++idx) {
781         mv_ref_list[idx].as_int = ref_mv_stack[idx].this_mv.as_int;
782       }
783     }
784   }
785 }
786 
av1_find_mv_refs(const AV1_COMMON * cm,const MACROBLOCKD * xd,MB_MODE_INFO * mi,MV_REFERENCE_FRAME ref_frame,uint8_t ref_mv_count[MODE_CTX_REF_FRAMES],CANDIDATE_MV ref_mv_stack[][MAX_REF_MV_STACK_SIZE],uint16_t ref_mv_weight[][MAX_REF_MV_STACK_SIZE],int_mv mv_ref_list[][MAX_MV_REF_CANDIDATES],int_mv * global_mvs,int16_t * mode_context)787 void av1_find_mv_refs(const AV1_COMMON *cm, const MACROBLOCKD *xd,
788                       MB_MODE_INFO *mi, MV_REFERENCE_FRAME ref_frame,
789                       uint8_t ref_mv_count[MODE_CTX_REF_FRAMES],
790                       CANDIDATE_MV ref_mv_stack[][MAX_REF_MV_STACK_SIZE],
791                       uint16_t ref_mv_weight[][MAX_REF_MV_STACK_SIZE],
792                       int_mv mv_ref_list[][MAX_MV_REF_CANDIDATES],
793                       int_mv *global_mvs, int16_t *mode_context) {
794   const int mi_row = xd->mi_row;
795   const int mi_col = xd->mi_col;
796   int_mv gm_mv[2];
797 
798   if (ref_frame == INTRA_FRAME) {
799     gm_mv[0].as_int = gm_mv[1].as_int = 0;
800     if (global_mvs != NULL) {
801       global_mvs[ref_frame].as_int = INVALID_MV;
802     }
803   } else {
804     const BLOCK_SIZE bsize = mi->bsize;
805     const int allow_high_precision_mv = cm->features.allow_high_precision_mv;
806     const int force_integer_mv = cm->features.cur_frame_force_integer_mv;
807     if (ref_frame < REF_FRAMES) {
808       gm_mv[0] = gm_get_motion_vector(&cm->global_motion[ref_frame],
809                                       allow_high_precision_mv, bsize, mi_col,
810                                       mi_row, force_integer_mv);
811       gm_mv[1].as_int = 0;
812       if (global_mvs != NULL) global_mvs[ref_frame] = gm_mv[0];
813     } else {
814       MV_REFERENCE_FRAME rf[2];
815       av1_set_ref_frame(rf, ref_frame);
816       gm_mv[0] = gm_get_motion_vector(&cm->global_motion[rf[0]],
817                                       allow_high_precision_mv, bsize, mi_col,
818                                       mi_row, force_integer_mv);
819       gm_mv[1] = gm_get_motion_vector(&cm->global_motion[rf[1]],
820                                       allow_high_precision_mv, bsize, mi_col,
821                                       mi_row, force_integer_mv);
822     }
823   }
824 
825   setup_ref_mv_list(cm, xd, ref_frame, &ref_mv_count[ref_frame],
826                     ref_mv_stack[ref_frame], ref_mv_weight[ref_frame],
827                     mv_ref_list ? mv_ref_list[ref_frame] : NULL, gm_mv, mi_row,
828                     mi_col, mode_context);
829 }
830 
av1_find_best_ref_mvs(int allow_hp,int_mv * mvlist,int_mv * nearest_mv,int_mv * near_mv,int is_integer)831 void av1_find_best_ref_mvs(int allow_hp, int_mv *mvlist, int_mv *nearest_mv,
832                            int_mv *near_mv, int is_integer) {
833   int i;
834   // Make sure all the candidates are properly clamped etc
835   for (i = 0; i < MAX_MV_REF_CANDIDATES; ++i) {
836     lower_mv_precision(&mvlist[i].as_mv, allow_hp, is_integer);
837   }
838   *nearest_mv = mvlist[0];
839   *near_mv = mvlist[1];
840 }
841 
av1_setup_frame_buf_refs(AV1_COMMON * cm)842 void av1_setup_frame_buf_refs(AV1_COMMON *cm) {
843   cm->cur_frame->order_hint = cm->current_frame.order_hint;
844   cm->cur_frame->display_order_hint = cm->current_frame.display_order_hint;
845   cm->cur_frame->pyramid_level = cm->current_frame.pyramid_level;
846   MV_REFERENCE_FRAME ref_frame;
847   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
848     const RefCntBuffer *const buf = get_ref_frame_buf(cm, ref_frame);
849     if (buf != NULL) {
850       cm->cur_frame->ref_order_hints[ref_frame - LAST_FRAME] = buf->order_hint;
851       cm->cur_frame->ref_display_order_hint[ref_frame - LAST_FRAME] =
852           buf->display_order_hint;
853     }
854   }
855 }
856 
av1_setup_frame_sign_bias(AV1_COMMON * cm)857 void av1_setup_frame_sign_bias(AV1_COMMON *cm) {
858   MV_REFERENCE_FRAME ref_frame;
859   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
860     const RefCntBuffer *const buf = get_ref_frame_buf(cm, ref_frame);
861     if (cm->seq_params->order_hint_info.enable_order_hint && buf != NULL) {
862       const int ref_order_hint = buf->order_hint;
863       cm->ref_frame_sign_bias[ref_frame] =
864           (get_relative_dist(&cm->seq_params->order_hint_info, ref_order_hint,
865                              (int)cm->current_frame.order_hint) <= 0)
866               ? 0
867               : 1;
868     } else {
869       cm->ref_frame_sign_bias[ref_frame] = 0;
870     }
871   }
872 }
873 
874 #define MAX_OFFSET_WIDTH 64
875 #define MAX_OFFSET_HEIGHT 0
876 
get_block_position(AV1_COMMON * cm,int * mi_r,int * mi_c,int blk_row,int blk_col,MV mv,int sign_bias)877 static int get_block_position(AV1_COMMON *cm, int *mi_r, int *mi_c, int blk_row,
878                               int blk_col, MV mv, int sign_bias) {
879   const int base_blk_row = (blk_row >> 3) << 3;
880   const int base_blk_col = (blk_col >> 3) << 3;
881 
882   const int row_offset = (mv.row >= 0) ? (mv.row >> (4 + MI_SIZE_LOG2))
883                                        : -((-mv.row) >> (4 + MI_SIZE_LOG2));
884 
885   const int col_offset = (mv.col >= 0) ? (mv.col >> (4 + MI_SIZE_LOG2))
886                                        : -((-mv.col) >> (4 + MI_SIZE_LOG2));
887 
888   const int row =
889       (sign_bias == 1) ? blk_row - row_offset : blk_row + row_offset;
890   const int col =
891       (sign_bias == 1) ? blk_col - col_offset : blk_col + col_offset;
892 
893   if (row < 0 || row >= (cm->mi_params.mi_rows >> 1) || col < 0 ||
894       col >= (cm->mi_params.mi_cols >> 1))
895     return 0;
896 
897   if (row < base_blk_row - (MAX_OFFSET_HEIGHT >> 3) ||
898       row >= base_blk_row + 8 + (MAX_OFFSET_HEIGHT >> 3) ||
899       col < base_blk_col - (MAX_OFFSET_WIDTH >> 3) ||
900       col >= base_blk_col + 8 + (MAX_OFFSET_WIDTH >> 3))
901     return 0;
902 
903   *mi_r = row;
904   *mi_c = col;
905 
906   return 1;
907 }
908 
909 // Note: motion_filed_projection finds motion vectors of current frame's
910 // reference frame, and projects them to current frame. To make it clear,
911 // let's call current frame's reference frame as start frame.
912 // Call Start frame's reference frames as reference frames.
913 // Call ref_offset as frame distances between start frame and its reference
914 // frames.
motion_field_projection(AV1_COMMON * cm,MV_REFERENCE_FRAME start_frame,int dir)915 static int motion_field_projection(AV1_COMMON *cm,
916                                    MV_REFERENCE_FRAME start_frame, int dir) {
917   TPL_MV_REF *tpl_mvs_base = cm->tpl_mvs;
918   int ref_offset[REF_FRAMES] = { 0 };
919 
920   const RefCntBuffer *const start_frame_buf =
921       get_ref_frame_buf(cm, start_frame);
922   if (start_frame_buf == NULL) return 0;
923 
924   if (start_frame_buf->frame_type == KEY_FRAME ||
925       start_frame_buf->frame_type == INTRA_ONLY_FRAME)
926     return 0;
927 
928   if (start_frame_buf->mi_rows != cm->mi_params.mi_rows ||
929       start_frame_buf->mi_cols != cm->mi_params.mi_cols)
930     return 0;
931 
932   const int start_frame_order_hint = start_frame_buf->order_hint;
933   const unsigned int *const ref_order_hints =
934       &start_frame_buf->ref_order_hints[0];
935   const int cur_order_hint = cm->cur_frame->order_hint;
936   int start_to_current_frame_offset = get_relative_dist(
937       &cm->seq_params->order_hint_info, start_frame_order_hint, cur_order_hint);
938 
939   for (MV_REFERENCE_FRAME rf = LAST_FRAME; rf <= INTER_REFS_PER_FRAME; ++rf) {
940     ref_offset[rf] = get_relative_dist(&cm->seq_params->order_hint_info,
941                                        start_frame_order_hint,
942                                        ref_order_hints[rf - LAST_FRAME]);
943   }
944 
945   if (dir == 2) start_to_current_frame_offset = -start_to_current_frame_offset;
946 
947   MV_REF *mv_ref_base = start_frame_buf->mvs;
948   const int mvs_rows = (cm->mi_params.mi_rows + 1) >> 1;
949   const int mvs_cols = (cm->mi_params.mi_cols + 1) >> 1;
950 
951   for (int blk_row = 0; blk_row < mvs_rows; ++blk_row) {
952     for (int blk_col = 0; blk_col < mvs_cols; ++blk_col) {
953       MV_REF *mv_ref = &mv_ref_base[blk_row * mvs_cols + blk_col];
954       MV fwd_mv = mv_ref->mv.as_mv;
955 
956       if (mv_ref->ref_frame > INTRA_FRAME) {
957         int_mv this_mv;
958         int mi_r, mi_c;
959         const int ref_frame_offset = ref_offset[mv_ref->ref_frame];
960 
961         int pos_valid =
962             abs(ref_frame_offset) <= MAX_FRAME_DISTANCE &&
963             ref_frame_offset > 0 &&
964             abs(start_to_current_frame_offset) <= MAX_FRAME_DISTANCE;
965 
966         if (pos_valid) {
967           get_mv_projection(&this_mv.as_mv, fwd_mv,
968                             start_to_current_frame_offset, ref_frame_offset);
969           pos_valid = get_block_position(cm, &mi_r, &mi_c, blk_row, blk_col,
970                                          this_mv.as_mv, dir >> 1);
971         }
972 
973         if (pos_valid) {
974           const int mi_offset = mi_r * (cm->mi_params.mi_stride >> 1) + mi_c;
975 
976           tpl_mvs_base[mi_offset].mfmv0.as_mv.row = fwd_mv.row;
977           tpl_mvs_base[mi_offset].mfmv0.as_mv.col = fwd_mv.col;
978           tpl_mvs_base[mi_offset].ref_frame_offset = ref_frame_offset;
979         }
980       }
981     }
982   }
983 
984   return 1;
985 }
986 
987 // cm->ref_frame_side is calculated here, and will be used in
988 // av1_copy_frame_mvs() to affect how mvs are copied.
av1_calculate_ref_frame_side(AV1_COMMON * cm)989 void av1_calculate_ref_frame_side(AV1_COMMON *cm) {
990   const OrderHintInfo *const order_hint_info = &cm->seq_params->order_hint_info;
991 
992   memset(cm->ref_frame_side, 0, sizeof(cm->ref_frame_side));
993   if (!order_hint_info->enable_order_hint) return;
994 
995   const int cur_order_hint = cm->cur_frame->order_hint;
996 
997   for (int ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
998     const RefCntBuffer *const buf = get_ref_frame_buf(cm, ref_frame);
999     int order_hint = 0;
1000 
1001     if (buf != NULL) order_hint = buf->order_hint;
1002 
1003     if (get_relative_dist(order_hint_info, order_hint, cur_order_hint) > 0)
1004       cm->ref_frame_side[ref_frame] = 1;
1005     else if (order_hint == cur_order_hint)
1006       cm->ref_frame_side[ref_frame] = -1;
1007   }
1008 }
1009 
av1_setup_motion_field(AV1_COMMON * cm)1010 void av1_setup_motion_field(AV1_COMMON *cm) {
1011   const OrderHintInfo *const order_hint_info = &cm->seq_params->order_hint_info;
1012 
1013   if (!order_hint_info->enable_order_hint) return;
1014 
1015   TPL_MV_REF *tpl_mvs_base = cm->tpl_mvs;
1016   int size = ((cm->mi_params.mi_rows + MAX_MIB_SIZE) >> 1) *
1017              (cm->mi_params.mi_stride >> 1);
1018   for (int idx = 0; idx < size; ++idx) {
1019     tpl_mvs_base[idx].mfmv0.as_int = INVALID_MV;
1020     tpl_mvs_base[idx].ref_frame_offset = 0;
1021   }
1022 
1023   const int cur_order_hint = cm->cur_frame->order_hint;
1024   const RefCntBuffer *ref_buf[INTER_REFS_PER_FRAME];
1025   int ref_order_hint[INTER_REFS_PER_FRAME];
1026 
1027   for (int ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
1028     const int ref_idx = ref_frame - LAST_FRAME;
1029     const RefCntBuffer *const buf = get_ref_frame_buf(cm, ref_frame);
1030     int order_hint = 0;
1031 
1032     if (buf != NULL) order_hint = buf->order_hint;
1033 
1034     ref_buf[ref_idx] = buf;
1035     ref_order_hint[ref_idx] = order_hint;
1036   }
1037 
1038   int ref_stamp = MFMV_STACK_SIZE - 1;
1039 
1040   if (ref_buf[LAST_FRAME - LAST_FRAME] != NULL) {
1041     const int alt_of_lst_order_hint =
1042         ref_buf[LAST_FRAME - LAST_FRAME]
1043             ->ref_order_hints[ALTREF_FRAME - LAST_FRAME];
1044 
1045     const int is_lst_overlay =
1046         (alt_of_lst_order_hint == ref_order_hint[GOLDEN_FRAME - LAST_FRAME]);
1047     if (!is_lst_overlay) motion_field_projection(cm, LAST_FRAME, 2);
1048     --ref_stamp;
1049   }
1050 
1051   if (get_relative_dist(order_hint_info,
1052                         ref_order_hint[BWDREF_FRAME - LAST_FRAME],
1053                         cur_order_hint) > 0) {
1054     if (motion_field_projection(cm, BWDREF_FRAME, 0)) --ref_stamp;
1055   }
1056 
1057   if (get_relative_dist(order_hint_info,
1058                         ref_order_hint[ALTREF2_FRAME - LAST_FRAME],
1059                         cur_order_hint) > 0) {
1060     if (motion_field_projection(cm, ALTREF2_FRAME, 0)) --ref_stamp;
1061   }
1062 
1063   if (get_relative_dist(order_hint_info,
1064                         ref_order_hint[ALTREF_FRAME - LAST_FRAME],
1065                         cur_order_hint) > 0 &&
1066       ref_stamp >= 0)
1067     if (motion_field_projection(cm, ALTREF_FRAME, 0)) --ref_stamp;
1068 
1069   if (ref_stamp >= 0) motion_field_projection(cm, LAST2_FRAME, 2);
1070 }
1071 
record_samples(const MB_MODE_INFO * mbmi,int * pts,int * pts_inref,int row_offset,int sign_r,int col_offset,int sign_c)1072 static inline void record_samples(const MB_MODE_INFO *mbmi, int *pts,
1073                                   int *pts_inref, int row_offset, int sign_r,
1074                                   int col_offset, int sign_c) {
1075   const int bw = block_size_wide[mbmi->bsize];
1076   const int bh = block_size_high[mbmi->bsize];
1077   const int x = col_offset * MI_SIZE + sign_c * bw / 2 - 1;
1078   const int y = row_offset * MI_SIZE + sign_r * bh / 2 - 1;
1079 
1080   pts[0] = GET_MV_SUBPEL(x);
1081   pts[1] = GET_MV_SUBPEL(y);
1082   pts_inref[0] = pts[0] + mbmi->mv[0].as_mv.col;
1083   pts_inref[1] = pts[1] + mbmi->mv[0].as_mv.row;
1084 }
1085 
1086 // Select samples according to the motion vector difference.
av1_selectSamples(MV * mv,int * pts,int * pts_inref,int len,BLOCK_SIZE bsize)1087 uint8_t av1_selectSamples(MV *mv, int *pts, int *pts_inref, int len,
1088                           BLOCK_SIZE bsize) {
1089   const int bw = block_size_wide[bsize];
1090   const int bh = block_size_high[bsize];
1091   const int thresh = clamp(AOMMAX(bw, bh), 16, 112);
1092   uint8_t ret = 0;
1093   assert(len <= LEAST_SQUARES_SAMPLES_MAX);
1094 
1095   // Only keep the samples with MV differences within threshold.
1096   for (int i = 0; i < len; ++i) {
1097     const int diff = abs(pts_inref[2 * i] - pts[2 * i] - mv->col) +
1098                      abs(pts_inref[2 * i + 1] - pts[2 * i + 1] - mv->row);
1099     if (diff > thresh) continue;
1100     if (ret != i) {
1101       memcpy(pts + 2 * ret, pts + 2 * i, 2 * sizeof(pts[0]));
1102       memcpy(pts_inref + 2 * ret, pts_inref + 2 * i, 2 * sizeof(pts_inref[0]));
1103     }
1104     ++ret;
1105   }
1106   // Keep at least 1 sample.
1107   return AOMMAX(ret, 1);
1108 }
1109 
1110 // Note: Samples returned are at 1/8-pel precision
1111 // Sample are the neighbor block center point's coordinates relative to the
1112 // left-top pixel of current block.
av1_findSamples(const AV1_COMMON * cm,MACROBLOCKD * xd,int * pts,int * pts_inref)1113 uint8_t av1_findSamples(const AV1_COMMON *cm, MACROBLOCKD *xd, int *pts,
1114                         int *pts_inref) {
1115   const MB_MODE_INFO *const mbmi0 = xd->mi[0];
1116   const int ref_frame = mbmi0->ref_frame[0];
1117   const int up_available = xd->up_available;
1118   const int left_available = xd->left_available;
1119   uint8_t np = 0;
1120   int do_tl = 1;
1121   int do_tr = 1;
1122   const int mi_stride = xd->mi_stride;
1123   const int mi_row = xd->mi_row;
1124   const int mi_col = xd->mi_col;
1125 
1126   // scan the nearest above rows
1127   if (up_available) {
1128     const int mi_row_offset = -1;
1129     const MB_MODE_INFO *mbmi = xd->mi[mi_row_offset * mi_stride];
1130     uint8_t superblock_width = mi_size_wide[mbmi->bsize];
1131 
1132     if (xd->width <= superblock_width) {
1133       // Handle "current block width <= above block width" case.
1134       const int col_offset = -mi_col % superblock_width;
1135 
1136       if (col_offset < 0) do_tl = 0;
1137       if (col_offset + superblock_width > xd->width) do_tr = 0;
1138 
1139       if (mbmi->ref_frame[0] == ref_frame && mbmi->ref_frame[1] == NONE_FRAME) {
1140         record_samples(mbmi, pts, pts_inref, 0, -1, col_offset, 1);
1141         pts += 2;
1142         pts_inref += 2;
1143         if (++np >= LEAST_SQUARES_SAMPLES_MAX) return LEAST_SQUARES_SAMPLES_MAX;
1144       }
1145     } else {
1146       // Handle "current block width > above block width" case.
1147       for (int i = 0; i < AOMMIN(xd->width, cm->mi_params.mi_cols - mi_col);
1148            i += superblock_width) {
1149         mbmi = xd->mi[i + mi_row_offset * mi_stride];
1150         superblock_width = mi_size_wide[mbmi->bsize];
1151 
1152         if (mbmi->ref_frame[0] == ref_frame &&
1153             mbmi->ref_frame[1] == NONE_FRAME) {
1154           record_samples(mbmi, pts, pts_inref, 0, -1, i, 1);
1155           pts += 2;
1156           pts_inref += 2;
1157           if (++np >= LEAST_SQUARES_SAMPLES_MAX)
1158             return LEAST_SQUARES_SAMPLES_MAX;
1159         }
1160       }
1161     }
1162   }
1163   assert(np <= LEAST_SQUARES_SAMPLES_MAX);
1164 
1165   // scan the nearest left columns
1166   if (left_available) {
1167     const int mi_col_offset = -1;
1168     const MB_MODE_INFO *mbmi = xd->mi[mi_col_offset];
1169     uint8_t superblock_height = mi_size_high[mbmi->bsize];
1170 
1171     if (xd->height <= superblock_height) {
1172       // Handle "current block height <= above block height" case.
1173       const int row_offset = -mi_row % superblock_height;
1174 
1175       if (row_offset < 0) do_tl = 0;
1176 
1177       if (mbmi->ref_frame[0] == ref_frame && mbmi->ref_frame[1] == NONE_FRAME) {
1178         record_samples(mbmi, pts, pts_inref, row_offset, 1, 0, -1);
1179         pts += 2;
1180         pts_inref += 2;
1181         np++;
1182         if (np >= LEAST_SQUARES_SAMPLES_MAX) return LEAST_SQUARES_SAMPLES_MAX;
1183       }
1184     } else {
1185       // Handle "current block height > above block height" case.
1186       for (int i = 0; i < AOMMIN(xd->height, cm->mi_params.mi_rows - mi_row);
1187            i += superblock_height) {
1188         mbmi = xd->mi[mi_col_offset + i * mi_stride];
1189         superblock_height = mi_size_high[mbmi->bsize];
1190 
1191         if (mbmi->ref_frame[0] == ref_frame &&
1192             mbmi->ref_frame[1] == NONE_FRAME) {
1193           record_samples(mbmi, pts, pts_inref, i, 1, 0, -1);
1194           pts += 2;
1195           pts_inref += 2;
1196           if (++np >= LEAST_SQUARES_SAMPLES_MAX)
1197             return LEAST_SQUARES_SAMPLES_MAX;
1198         }
1199       }
1200     }
1201   }
1202   assert(np <= LEAST_SQUARES_SAMPLES_MAX);
1203 
1204   // Top-left block
1205   if (do_tl && left_available && up_available) {
1206     const int mi_row_offset = -1;
1207     const int mi_col_offset = -1;
1208     MB_MODE_INFO *mbmi = xd->mi[mi_col_offset + mi_row_offset * mi_stride];
1209 
1210     if (mbmi->ref_frame[0] == ref_frame && mbmi->ref_frame[1] == NONE_FRAME) {
1211       record_samples(mbmi, pts, pts_inref, 0, -1, 0, -1);
1212       pts += 2;
1213       pts_inref += 2;
1214       if (++np >= LEAST_SQUARES_SAMPLES_MAX) return LEAST_SQUARES_SAMPLES_MAX;
1215     }
1216   }
1217   assert(np <= LEAST_SQUARES_SAMPLES_MAX);
1218 
1219   // Top-right block
1220   if (do_tr &&
1221       has_top_right(cm, xd, mi_row, mi_col, AOMMAX(xd->width, xd->height))) {
1222     const POSITION trb_pos = { -1, xd->width };
1223     const TileInfo *const tile = &xd->tile;
1224     if (is_inside(tile, mi_col, mi_row, &trb_pos)) {
1225       const int mi_row_offset = -1;
1226       const int mi_col_offset = xd->width;
1227       const MB_MODE_INFO *mbmi =
1228           xd->mi[mi_col_offset + mi_row_offset * mi_stride];
1229 
1230       if (mbmi->ref_frame[0] == ref_frame && mbmi->ref_frame[1] == NONE_FRAME) {
1231         record_samples(mbmi, pts, pts_inref, 0, -1, xd->width, 1);
1232         if (++np >= LEAST_SQUARES_SAMPLES_MAX) return LEAST_SQUARES_SAMPLES_MAX;
1233       }
1234     }
1235   }
1236   assert(np <= LEAST_SQUARES_SAMPLES_MAX);
1237 
1238   return np;
1239 }
1240 
av1_setup_skip_mode_allowed(AV1_COMMON * cm)1241 void av1_setup_skip_mode_allowed(AV1_COMMON *cm) {
1242   const OrderHintInfo *const order_hint_info = &cm->seq_params->order_hint_info;
1243   SkipModeInfo *const skip_mode_info = &cm->current_frame.skip_mode_info;
1244 
1245   skip_mode_info->skip_mode_allowed = 0;
1246   skip_mode_info->ref_frame_idx_0 = INVALID_IDX;
1247   skip_mode_info->ref_frame_idx_1 = INVALID_IDX;
1248 
1249   if (!order_hint_info->enable_order_hint || frame_is_intra_only(cm) ||
1250       cm->current_frame.reference_mode == SINGLE_REFERENCE)
1251     return;
1252 
1253   const int cur_order_hint = cm->current_frame.order_hint;
1254   int ref_order_hints[2] = { -1, INT_MAX };
1255   int ref_idx[2] = { INVALID_IDX, INVALID_IDX };
1256 
1257   // Identify the nearest forward and backward references.
1258   for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
1259     const RefCntBuffer *const buf = get_ref_frame_buf(cm, LAST_FRAME + i);
1260     if (buf == NULL) continue;
1261 
1262     const int ref_order_hint = buf->order_hint;
1263     if (get_relative_dist(order_hint_info, ref_order_hint, cur_order_hint) <
1264         0) {
1265       // Forward reference
1266       if (ref_order_hints[0] == -1 ||
1267           get_relative_dist(order_hint_info, ref_order_hint,
1268                             ref_order_hints[0]) > 0) {
1269         ref_order_hints[0] = ref_order_hint;
1270         ref_idx[0] = i;
1271       }
1272     } else if (get_relative_dist(order_hint_info, ref_order_hint,
1273                                  cur_order_hint) > 0) {
1274       // Backward reference
1275       if (ref_order_hints[1] == INT_MAX ||
1276           get_relative_dist(order_hint_info, ref_order_hint,
1277                             ref_order_hints[1]) < 0) {
1278         ref_order_hints[1] = ref_order_hint;
1279         ref_idx[1] = i;
1280       }
1281     }
1282   }
1283 
1284   if (ref_idx[0] != INVALID_IDX && ref_idx[1] != INVALID_IDX) {
1285     // == Bi-directional prediction ==
1286     skip_mode_info->skip_mode_allowed = 1;
1287     skip_mode_info->ref_frame_idx_0 = AOMMIN(ref_idx[0], ref_idx[1]);
1288     skip_mode_info->ref_frame_idx_1 = AOMMAX(ref_idx[0], ref_idx[1]);
1289   } else if (ref_idx[0] != INVALID_IDX && ref_idx[1] == INVALID_IDX) {
1290     // == Forward prediction only ==
1291     // Identify the second nearest forward reference.
1292     ref_order_hints[1] = -1;
1293     for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
1294       const RefCntBuffer *const buf = get_ref_frame_buf(cm, LAST_FRAME + i);
1295       if (buf == NULL) continue;
1296 
1297       const int ref_order_hint = buf->order_hint;
1298       if ((ref_order_hints[0] != -1 &&
1299            get_relative_dist(order_hint_info, ref_order_hint,
1300                              ref_order_hints[0]) < 0) &&
1301           (ref_order_hints[1] == -1 ||
1302            get_relative_dist(order_hint_info, ref_order_hint,
1303                              ref_order_hints[1]) > 0)) {
1304         // Second closest forward reference
1305         ref_order_hints[1] = ref_order_hint;
1306         ref_idx[1] = i;
1307       }
1308     }
1309     if (ref_order_hints[1] != -1) {
1310       skip_mode_info->skip_mode_allowed = 1;
1311       skip_mode_info->ref_frame_idx_0 = AOMMIN(ref_idx[0], ref_idx[1]);
1312       skip_mode_info->ref_frame_idx_1 = AOMMAX(ref_idx[0], ref_idx[1]);
1313     }
1314   }
1315 }
1316 
1317 typedef struct {
1318   int map_idx;        // frame map index
1319   RefCntBuffer *buf;  // frame buffer
1320   int sort_idx;       // index based on the offset to be used for sorting
1321 } REF_FRAME_INFO;
1322 
1323 // Compares the sort_idx fields. If they are equal, then compares the map_idx
1324 // fields to break the tie. This ensures a stable sort.
compare_ref_frame_info(const void * arg_a,const void * arg_b)1325 static int compare_ref_frame_info(const void *arg_a, const void *arg_b) {
1326   const REF_FRAME_INFO *info_a = (REF_FRAME_INFO *)arg_a;
1327   const REF_FRAME_INFO *info_b = (REF_FRAME_INFO *)arg_b;
1328 
1329   const int sort_idx_diff = info_a->sort_idx - info_b->sort_idx;
1330   if (sort_idx_diff != 0) return sort_idx_diff;
1331   return info_a->map_idx - info_b->map_idx;
1332 }
1333 
set_ref_frame_info(int * remapped_ref_idx,int frame_idx,REF_FRAME_INFO * ref_info)1334 static inline void set_ref_frame_info(int *remapped_ref_idx, int frame_idx,
1335                                       REF_FRAME_INFO *ref_info) {
1336   assert(frame_idx >= 0 && frame_idx < INTER_REFS_PER_FRAME);
1337 
1338   remapped_ref_idx[frame_idx] = ref_info->map_idx;
1339 }
1340 
av1_set_frame_refs(AV1_COMMON * const cm,int * remapped_ref_idx,int lst_map_idx,int gld_map_idx)1341 void av1_set_frame_refs(AV1_COMMON *const cm, int *remapped_ref_idx,
1342                         int lst_map_idx, int gld_map_idx) {
1343   int lst_frame_sort_idx = -1;
1344   int gld_frame_sort_idx = -1;
1345 
1346   assert(cm->seq_params->order_hint_info.enable_order_hint);
1347   assert(cm->seq_params->order_hint_info.order_hint_bits_minus_1 >= 0);
1348   const int cur_order_hint = (int)cm->current_frame.order_hint;
1349   const int cur_frame_sort_idx =
1350       1 << cm->seq_params->order_hint_info.order_hint_bits_minus_1;
1351 
1352   REF_FRAME_INFO ref_frame_info[REF_FRAMES];
1353   int ref_flag_list[INTER_REFS_PER_FRAME] = { 0, 0, 0, 0, 0, 0, 0 };
1354 
1355   for (int i = 0; i < REF_FRAMES; ++i) {
1356     const int map_idx = i;
1357 
1358     ref_frame_info[i].map_idx = map_idx;
1359     ref_frame_info[i].sort_idx = -1;
1360 
1361     RefCntBuffer *const buf = cm->ref_frame_map[map_idx];
1362     ref_frame_info[i].buf = buf;
1363 
1364     if (buf == NULL) continue;
1365     // If this assertion fails, there is a reference leak.
1366     assert(buf->ref_count > 0);
1367 
1368     const int offset = (int)buf->order_hint;
1369     ref_frame_info[i].sort_idx =
1370         (offset == -1) ? -1
1371                        : cur_frame_sort_idx +
1372                              get_relative_dist(&cm->seq_params->order_hint_info,
1373                                                offset, cur_order_hint);
1374     assert(ref_frame_info[i].sort_idx >= -1);
1375 
1376     if (map_idx == lst_map_idx) lst_frame_sort_idx = ref_frame_info[i].sort_idx;
1377     if (map_idx == gld_map_idx) gld_frame_sort_idx = ref_frame_info[i].sort_idx;
1378   }
1379 
1380   // Confirm both LAST_FRAME and GOLDEN_FRAME are valid forward reference
1381   // frames.
1382   if (lst_frame_sort_idx == -1 || lst_frame_sort_idx >= cur_frame_sort_idx) {
1383     aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
1384                        "Inter frame requests a look-ahead frame as LAST");
1385   }
1386   if (gld_frame_sort_idx == -1 || gld_frame_sort_idx >= cur_frame_sort_idx) {
1387     aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
1388                        "Inter frame requests a look-ahead frame as GOLDEN");
1389   }
1390 
1391   // Sort ref frames based on their frame_offset values.
1392   qsort(ref_frame_info, REF_FRAMES, sizeof(REF_FRAME_INFO),
1393         compare_ref_frame_info);
1394 
1395   // Identify forward and backward reference frames.
1396   // Forward  reference: offset < order_hint
1397   // Backward reference: offset >= order_hint
1398   int fwd_start_idx = 0, fwd_end_idx = REF_FRAMES - 1;
1399 
1400   for (int i = 0; i < REF_FRAMES; i++) {
1401     if (ref_frame_info[i].sort_idx == -1) {
1402       fwd_start_idx++;
1403       continue;
1404     }
1405 
1406     if (ref_frame_info[i].sort_idx >= cur_frame_sort_idx) {
1407       fwd_end_idx = i - 1;
1408       break;
1409     }
1410   }
1411 
1412   int bwd_start_idx = fwd_end_idx + 1;
1413   int bwd_end_idx = REF_FRAMES - 1;
1414 
1415   // === Backward Reference Frames ===
1416 
1417   // == ALTREF_FRAME ==
1418   if (bwd_start_idx <= bwd_end_idx) {
1419     set_ref_frame_info(remapped_ref_idx, ALTREF_FRAME - LAST_FRAME,
1420                        &ref_frame_info[bwd_end_idx]);
1421     ref_flag_list[ALTREF_FRAME - LAST_FRAME] = 1;
1422     bwd_end_idx--;
1423   }
1424 
1425   // == BWDREF_FRAME ==
1426   if (bwd_start_idx <= bwd_end_idx) {
1427     set_ref_frame_info(remapped_ref_idx, BWDREF_FRAME - LAST_FRAME,
1428                        &ref_frame_info[bwd_start_idx]);
1429     ref_flag_list[BWDREF_FRAME - LAST_FRAME] = 1;
1430     bwd_start_idx++;
1431   }
1432 
1433   // == ALTREF2_FRAME ==
1434   if (bwd_start_idx <= bwd_end_idx) {
1435     set_ref_frame_info(remapped_ref_idx, ALTREF2_FRAME - LAST_FRAME,
1436                        &ref_frame_info[bwd_start_idx]);
1437     ref_flag_list[ALTREF2_FRAME - LAST_FRAME] = 1;
1438   }
1439 
1440   // === Forward Reference Frames ===
1441 
1442   for (int i = fwd_start_idx; i <= fwd_end_idx; ++i) {
1443     // == LAST_FRAME ==
1444     if (ref_frame_info[i].map_idx == lst_map_idx) {
1445       set_ref_frame_info(remapped_ref_idx, LAST_FRAME - LAST_FRAME,
1446                          &ref_frame_info[i]);
1447       ref_flag_list[LAST_FRAME - LAST_FRAME] = 1;
1448     }
1449 
1450     // == GOLDEN_FRAME ==
1451     if (ref_frame_info[i].map_idx == gld_map_idx) {
1452       set_ref_frame_info(remapped_ref_idx, GOLDEN_FRAME - LAST_FRAME,
1453                          &ref_frame_info[i]);
1454       ref_flag_list[GOLDEN_FRAME - LAST_FRAME] = 1;
1455     }
1456   }
1457 
1458   assert(ref_flag_list[LAST_FRAME - LAST_FRAME] == 1 &&
1459          ref_flag_list[GOLDEN_FRAME - LAST_FRAME] == 1);
1460 
1461   // == LAST2_FRAME ==
1462   // == LAST3_FRAME ==
1463   // == BWDREF_FRAME ==
1464   // == ALTREF2_FRAME ==
1465   // == ALTREF_FRAME ==
1466 
1467   // Set up the reference frames in the anti-chronological order.
1468   static const MV_REFERENCE_FRAME ref_frame_list[INTER_REFS_PER_FRAME - 2] = {
1469     LAST2_FRAME, LAST3_FRAME, BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME
1470   };
1471 
1472   int ref_idx;
1473   for (ref_idx = 0; ref_idx < (INTER_REFS_PER_FRAME - 2); ref_idx++) {
1474     const MV_REFERENCE_FRAME ref_frame = ref_frame_list[ref_idx];
1475 
1476     if (ref_flag_list[ref_frame - LAST_FRAME] == 1) continue;
1477 
1478     while (fwd_start_idx <= fwd_end_idx &&
1479            (ref_frame_info[fwd_end_idx].map_idx == lst_map_idx ||
1480             ref_frame_info[fwd_end_idx].map_idx == gld_map_idx)) {
1481       fwd_end_idx--;
1482     }
1483     if (fwd_start_idx > fwd_end_idx) break;
1484 
1485     set_ref_frame_info(remapped_ref_idx, ref_frame - LAST_FRAME,
1486                        &ref_frame_info[fwd_end_idx]);
1487     ref_flag_list[ref_frame - LAST_FRAME] = 1;
1488 
1489     fwd_end_idx--;
1490   }
1491 
1492   // Assign all the remaining frame(s), if any, to the earliest reference
1493   // frame.
1494   for (; ref_idx < (INTER_REFS_PER_FRAME - 2); ref_idx++) {
1495     const MV_REFERENCE_FRAME ref_frame = ref_frame_list[ref_idx];
1496     if (ref_flag_list[ref_frame - LAST_FRAME] == 1) continue;
1497     set_ref_frame_info(remapped_ref_idx, ref_frame - LAST_FRAME,
1498                        &ref_frame_info[fwd_start_idx]);
1499     ref_flag_list[ref_frame - LAST_FRAME] = 1;
1500   }
1501 
1502   for (int i = 0; i < INTER_REFS_PER_FRAME; i++) {
1503     assert(ref_flag_list[i] == 1);
1504   }
1505 }
1506