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