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