1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include <assert.h>
12 #include <math.h>
13 
14 #include "./vp9_rtcd.h"
15 
16 #include "vpx_mem/vpx_mem.h"
17 
18 #include "vp9/common/vp9_common.h"
19 #include "vp9/common/vp9_entropy.h"
20 #include "vp9/common/vp9_entropymode.h"
21 #include "vp9/common/vp9_idct.h"
22 #include "vp9/common/vp9_mvref_common.h"
23 #include "vp9/common/vp9_pred_common.h"
24 #include "vp9/common/vp9_quant_common.h"
25 #include "vp9/common/vp9_reconinter.h"
26 #include "vp9/common/vp9_reconintra.h"
27 #include "vp9/common/vp9_seg_common.h"
28 #include "vp9/common/vp9_systemdependent.h"
29 
30 #include "vp9/encoder/vp9_cost.h"
31 #include "vp9/encoder/vp9_encodemb.h"
32 #include "vp9/encoder/vp9_encodemv.h"
33 #include "vp9/encoder/vp9_encoder.h"
34 #include "vp9/encoder/vp9_mcomp.h"
35 #include "vp9/encoder/vp9_quantize.h"
36 #include "vp9/encoder/vp9_ratectrl.h"
37 #include "vp9/encoder/vp9_rd.h"
38 #include "vp9/encoder/vp9_rdopt.h"
39 #include "vp9/encoder/vp9_variance.h"
40 
41 #define RD_THRESH_MAX_FACT 64
42 #define RD_THRESH_INC      1
43 
44 #define LAST_FRAME_MODE_MASK    0xFFEDCD60
45 #define GOLDEN_FRAME_MODE_MASK  0xFFDA3BB0
46 #define ALT_REF_MODE_MASK       0xFFC648D0
47 
48 #define MIN_EARLY_TERM_INDEX    3
49 
50 typedef struct {
51   PREDICTION_MODE mode;
52   MV_REFERENCE_FRAME ref_frame[2];
53 } MODE_DEFINITION;
54 
55 typedef struct {
56   MV_REFERENCE_FRAME ref_frame[2];
57 } REF_DEFINITION;
58 
59 struct rdcost_block_args {
60   MACROBLOCK *x;
61   ENTROPY_CONTEXT t_above[16];
62   ENTROPY_CONTEXT t_left[16];
63   int rate;
64   int64_t dist;
65   int64_t sse;
66   int this_rate;
67   int64_t this_dist;
68   int64_t this_sse;
69   int64_t this_rd;
70   int64_t best_rd;
71   int skip;
72   int use_fast_coef_costing;
73   const scan_order *so;
74 };
75 
76 static const MODE_DEFINITION vp9_mode_order[MAX_MODES] = {
77   {NEARESTMV, {LAST_FRAME,   NONE}},
78   {NEARESTMV, {ALTREF_FRAME, NONE}},
79   {NEARESTMV, {GOLDEN_FRAME, NONE}},
80 
81   {DC_PRED,   {INTRA_FRAME,  NONE}},
82 
83   {NEWMV,     {LAST_FRAME,   NONE}},
84   {NEWMV,     {ALTREF_FRAME, NONE}},
85   {NEWMV,     {GOLDEN_FRAME, NONE}},
86 
87   {NEARMV,    {LAST_FRAME,   NONE}},
88   {NEARMV,    {ALTREF_FRAME, NONE}},
89   {NEARESTMV, {LAST_FRAME,   ALTREF_FRAME}},
90   {NEARESTMV, {GOLDEN_FRAME, ALTREF_FRAME}},
91 
92   {TM_PRED,   {INTRA_FRAME,  NONE}},
93 
94   {NEARMV,    {LAST_FRAME,   ALTREF_FRAME}},
95   {NEWMV,     {LAST_FRAME,   ALTREF_FRAME}},
96   {NEARMV,    {GOLDEN_FRAME, NONE}},
97   {NEARMV,    {GOLDEN_FRAME, ALTREF_FRAME}},
98   {NEWMV,     {GOLDEN_FRAME, ALTREF_FRAME}},
99 
100   {ZEROMV,    {LAST_FRAME,   NONE}},
101   {ZEROMV,    {GOLDEN_FRAME, NONE}},
102   {ZEROMV,    {ALTREF_FRAME, NONE}},
103   {ZEROMV,    {LAST_FRAME,   ALTREF_FRAME}},
104   {ZEROMV,    {GOLDEN_FRAME, ALTREF_FRAME}},
105 
106   {H_PRED,    {INTRA_FRAME,  NONE}},
107   {V_PRED,    {INTRA_FRAME,  NONE}},
108   {D135_PRED, {INTRA_FRAME,  NONE}},
109   {D207_PRED, {INTRA_FRAME,  NONE}},
110   {D153_PRED, {INTRA_FRAME,  NONE}},
111   {D63_PRED,  {INTRA_FRAME,  NONE}},
112   {D117_PRED, {INTRA_FRAME,  NONE}},
113   {D45_PRED,  {INTRA_FRAME,  NONE}},
114 };
115 
116 static const REF_DEFINITION vp9_ref_order[MAX_REFS] = {
117   {{LAST_FRAME,   NONE}},
118   {{GOLDEN_FRAME, NONE}},
119   {{ALTREF_FRAME, NONE}},
120   {{LAST_FRAME,   ALTREF_FRAME}},
121   {{GOLDEN_FRAME, ALTREF_FRAME}},
122   {{INTRA_FRAME,  NONE}},
123 };
124 
raster_block_offset(BLOCK_SIZE plane_bsize,int raster_block,int stride)125 static int raster_block_offset(BLOCK_SIZE plane_bsize,
126                                int raster_block, int stride) {
127   const int bw = b_width_log2(plane_bsize);
128   const int y = 4 * (raster_block >> bw);
129   const int x = 4 * (raster_block & ((1 << bw) - 1));
130   return y * stride + x;
131 }
raster_block_offset_int16(BLOCK_SIZE plane_bsize,int raster_block,int16_t * base)132 static int16_t* raster_block_offset_int16(BLOCK_SIZE plane_bsize,
133                                           int raster_block, int16_t *base) {
134   const int stride = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
135   return base + raster_block_offset(plane_bsize, raster_block, stride);
136 }
137 
swap_block_ptr(MACROBLOCK * x,PICK_MODE_CONTEXT * ctx,int m,int n,int min_plane,int max_plane)138 static void swap_block_ptr(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx,
139                            int m, int n, int min_plane, int max_plane) {
140   int i;
141 
142   for (i = min_plane; i < max_plane; ++i) {
143     struct macroblock_plane *const p = &x->plane[i];
144     struct macroblockd_plane *const pd = &x->e_mbd.plane[i];
145 
146     p->coeff    = ctx->coeff_pbuf[i][m];
147     p->qcoeff   = ctx->qcoeff_pbuf[i][m];
148     pd->dqcoeff = ctx->dqcoeff_pbuf[i][m];
149     p->eobs     = ctx->eobs_pbuf[i][m];
150 
151     ctx->coeff_pbuf[i][m]   = ctx->coeff_pbuf[i][n];
152     ctx->qcoeff_pbuf[i][m]  = ctx->qcoeff_pbuf[i][n];
153     ctx->dqcoeff_pbuf[i][m] = ctx->dqcoeff_pbuf[i][n];
154     ctx->eobs_pbuf[i][m]    = ctx->eobs_pbuf[i][n];
155 
156     ctx->coeff_pbuf[i][n]   = p->coeff;
157     ctx->qcoeff_pbuf[i][n]  = p->qcoeff;
158     ctx->dqcoeff_pbuf[i][n] = pd->dqcoeff;
159     ctx->eobs_pbuf[i][n]    = p->eobs;
160   }
161 }
162 
model_rd_for_sb(VP9_COMP * cpi,BLOCK_SIZE bsize,MACROBLOCK * x,MACROBLOCKD * xd,int * out_rate_sum,int64_t * out_dist_sum)163 static void model_rd_for_sb(VP9_COMP *cpi, BLOCK_SIZE bsize,
164                             MACROBLOCK *x, MACROBLOCKD *xd,
165                             int *out_rate_sum, int64_t *out_dist_sum) {
166   // Note our transform coeffs are 8 times an orthogonal transform.
167   // Hence quantizer step is also 8 times. To get effective quantizer
168   // we need to divide by 8 before sending to modeling function.
169   int i;
170   int64_t rate_sum = 0;
171   int64_t dist_sum = 0;
172   const int ref = xd->mi[0]->mbmi.ref_frame[0];
173   unsigned int sse;
174   const int shift = 8;
175 
176   for (i = 0; i < MAX_MB_PLANE; ++i) {
177     struct macroblock_plane *const p = &x->plane[i];
178     struct macroblockd_plane *const pd = &xd->plane[i];
179     const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
180 
181     const unsigned int var = cpi->fn_ptr[bs].vf(p->src.buf, p->src.stride,
182                                                 pd->dst.buf, pd->dst.stride,
183                                                 &sse);
184 
185     if (!x->select_tx_size) {
186       if (sse < p->quant_thred[0] >> shift)
187         x->skip_txfm[i] = 1;
188       else if (var < p->quant_thred[1] >> shift)
189         x->skip_txfm[i] = 2;
190       else
191         x->skip_txfm[i] = 0;
192     }
193 
194     x->bsse[i] = sse;
195     if (i == 0)
196       x->pred_sse[ref] = sse;
197 
198     // Fast approximate the modelling function.
199     if (cpi->oxcf.speed > 4) {
200       int64_t rate;
201       int64_t dist;
202       int64_t square_error = sse;
203       int quantizer = (pd->dequant[1] >> 3);
204 
205       if (quantizer < 120)
206         rate = (square_error * (280 - quantizer)) >> 8;
207       else
208         rate = 0;
209       dist = (square_error * quantizer) >> 8;
210       rate_sum += rate;
211       dist_sum += dist;
212     } else {
213       int rate;
214       int64_t dist;
215       vp9_model_rd_from_var_lapndz(sse, 1 << num_pels_log2_lookup[bs],
216                                    pd->dequant[1] >> 3, &rate, &dist);
217       rate_sum += rate;
218       dist_sum += dist;
219     }
220   }
221 
222   *out_rate_sum = (int)rate_sum;
223   *out_dist_sum = dist_sum << 4;
224 }
225 
vp9_block_error_c(const int16_t * coeff,const int16_t * dqcoeff,intptr_t block_size,int64_t * ssz)226 int64_t vp9_block_error_c(const int16_t *coeff, const int16_t *dqcoeff,
227                           intptr_t block_size, int64_t *ssz) {
228   int i;
229   int64_t error = 0, sqcoeff = 0;
230 
231   for (i = 0; i < block_size; i++) {
232     const int diff = coeff[i] - dqcoeff[i];
233     error +=  diff * diff;
234     sqcoeff += coeff[i] * coeff[i];
235   }
236 
237   *ssz = sqcoeff;
238   return error;
239 }
240 
241 /* The trailing '0' is a terminator which is used inside cost_coeffs() to
242  * decide whether to include cost of a trailing EOB node or not (i.e. we
243  * can skip this if the last coefficient in this transform block, e.g. the
244  * 16th coefficient in a 4x4 block or the 64th coefficient in a 8x8 block,
245  * were non-zero). */
246 static const int16_t band_counts[TX_SIZES][8] = {
247   { 1, 2, 3, 4,  3,   16 - 13, 0 },
248   { 1, 2, 3, 4, 11,   64 - 21, 0 },
249   { 1, 2, 3, 4, 11,  256 - 21, 0 },
250   { 1, 2, 3, 4, 11, 1024 - 21, 0 },
251 };
cost_coeffs(MACROBLOCK * x,int plane,int block,ENTROPY_CONTEXT * A,ENTROPY_CONTEXT * L,TX_SIZE tx_size,const int16_t * scan,const int16_t * nb,int use_fast_coef_costing)252 static INLINE int cost_coeffs(MACROBLOCK *x,
253                               int plane, int block,
254                               ENTROPY_CONTEXT *A, ENTROPY_CONTEXT *L,
255                               TX_SIZE tx_size,
256                               const int16_t *scan, const int16_t *nb,
257                               int use_fast_coef_costing) {
258   MACROBLOCKD *const xd = &x->e_mbd;
259   MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
260   const struct macroblock_plane *p = &x->plane[plane];
261   const struct macroblockd_plane *pd = &xd->plane[plane];
262   const PLANE_TYPE type = pd->plane_type;
263   const int16_t *band_count = &band_counts[tx_size][1];
264   const int eob = p->eobs[block];
265   const int16_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
266   unsigned int (*token_costs)[2][COEFF_CONTEXTS][ENTROPY_TOKENS] =
267                    x->token_costs[tx_size][type][is_inter_block(mbmi)];
268   uint8_t token_cache[32 * 32];
269   int pt = combine_entropy_contexts(*A, *L);
270   int c, cost;
271   // Check for consistency of tx_size with mode info
272   assert(type == PLANE_TYPE_Y ? mbmi->tx_size == tx_size
273                               : get_uv_tx_size(mbmi, pd) == tx_size);
274 
275   if (eob == 0) {
276     // single eob token
277     cost = token_costs[0][0][pt][EOB_TOKEN];
278     c = 0;
279   } else {
280     int band_left = *band_count++;
281 
282     // dc token
283     int v = qcoeff[0];
284     int prev_t = vp9_dct_value_tokens_ptr[v].token;
285     cost = (*token_costs)[0][pt][prev_t] + vp9_dct_value_cost_ptr[v];
286     token_cache[0] = vp9_pt_energy_class[prev_t];
287     ++token_costs;
288 
289     // ac tokens
290     for (c = 1; c < eob; c++) {
291       const int rc = scan[c];
292       int t;
293 
294       v = qcoeff[rc];
295       t = vp9_dct_value_tokens_ptr[v].token;
296       if (use_fast_coef_costing) {
297         cost += (*token_costs)[!prev_t][!prev_t][t] + vp9_dct_value_cost_ptr[v];
298       } else {
299         pt = get_coef_context(nb, token_cache, c);
300         cost += (*token_costs)[!prev_t][pt][t] + vp9_dct_value_cost_ptr[v];
301         token_cache[rc] = vp9_pt_energy_class[t];
302       }
303       prev_t = t;
304       if (!--band_left) {
305         band_left = *band_count++;
306         ++token_costs;
307       }
308     }
309 
310     // eob token
311     if (band_left) {
312       if (use_fast_coef_costing) {
313         cost += (*token_costs)[0][!prev_t][EOB_TOKEN];
314       } else {
315         pt = get_coef_context(nb, token_cache, c);
316         cost += (*token_costs)[0][pt][EOB_TOKEN];
317       }
318     }
319   }
320 
321   // is eob first coefficient;
322   *A = *L = (c > 0);
323 
324   return cost;
325 }
dist_block(int plane,int block,TX_SIZE tx_size,struct rdcost_block_args * args)326 static void dist_block(int plane, int block, TX_SIZE tx_size,
327                        struct rdcost_block_args* args) {
328   const int ss_txfrm_size = tx_size << 1;
329   MACROBLOCK* const x = args->x;
330   MACROBLOCKD* const xd = &x->e_mbd;
331   const struct macroblock_plane *const p = &x->plane[plane];
332   const struct macroblockd_plane *const pd = &xd->plane[plane];
333   int64_t this_sse;
334   int shift = tx_size == TX_32X32 ? 0 : 2;
335   int16_t *const coeff = BLOCK_OFFSET(p->coeff, block);
336   int16_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
337   args->dist = vp9_block_error(coeff, dqcoeff, 16 << ss_txfrm_size,
338                                &this_sse) >> shift;
339   args->sse  = this_sse >> shift;
340 
341   if (x->skip_encode && !is_inter_block(&xd->mi[0]->mbmi)) {
342     // TODO(jingning): tune the model to better capture the distortion.
343     int64_t p = (pd->dequant[1] * pd->dequant[1] *
344                     (1 << ss_txfrm_size)) >> (shift + 2);
345     args->dist += (p >> 4);
346     args->sse  += p;
347   }
348 }
349 
rate_block(int plane,int block,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,struct rdcost_block_args * args)350 static void rate_block(int plane, int block, BLOCK_SIZE plane_bsize,
351                        TX_SIZE tx_size, struct rdcost_block_args* args) {
352   int x_idx, y_idx;
353   txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x_idx, &y_idx);
354 
355   args->rate = cost_coeffs(args->x, plane, block, args->t_above + x_idx,
356                            args->t_left + y_idx, tx_size,
357                            args->so->scan, args->so->neighbors,
358                            args->use_fast_coef_costing);
359 }
360 
block_rd_txfm(int plane,int block,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg)361 static void block_rd_txfm(int plane, int block, BLOCK_SIZE plane_bsize,
362                           TX_SIZE tx_size, void *arg) {
363   struct rdcost_block_args *args = arg;
364   MACROBLOCK *const x = args->x;
365   MACROBLOCKD *const xd = &x->e_mbd;
366   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
367   int64_t rd1, rd2, rd;
368 
369   if (args->skip)
370     return;
371 
372   if (!is_inter_block(mbmi)) {
373     vp9_encode_block_intra(x, plane, block, plane_bsize, tx_size, &mbmi->skip);
374     dist_block(plane, block, tx_size, args);
375   } else {
376     if (x->skip_txfm[plane] == 0) {
377       // full forward transform and quantization
378       vp9_xform_quant(x, plane, block, plane_bsize, tx_size);
379       dist_block(plane, block, tx_size, args);
380     } else if (x->skip_txfm[plane] == 2) {
381       // compute DC coefficient
382       int16_t *const coeff   = BLOCK_OFFSET(x->plane[plane].coeff, block);
383       int16_t *const dqcoeff = BLOCK_OFFSET(xd->plane[plane].dqcoeff, block);
384       vp9_xform_quant_dc(x, plane, block, plane_bsize, tx_size);
385       args->sse  = x->bsse[plane] << 4;
386       args->dist = args->sse;
387       if (!x->plane[plane].eobs[block])
388         args->dist = args->sse - ((coeff[0] * coeff[0] -
389             (coeff[0] - dqcoeff[0]) * (coeff[0] - dqcoeff[0])) >> 2);
390     } else {
391       // skip forward transform
392       x->plane[plane].eobs[block] = 0;
393       args->sse  = x->bsse[plane] << 4;
394       args->dist = args->sse;
395     }
396   }
397 
398   rate_block(plane, block, plane_bsize, tx_size, args);
399   rd1 = RDCOST(x->rdmult, x->rddiv, args->rate, args->dist);
400   rd2 = RDCOST(x->rdmult, x->rddiv, 0, args->sse);
401 
402   // TODO(jingning): temporarily enabled only for luma component
403   rd = MIN(rd1, rd2);
404   if (plane == 0)
405     x->zcoeff_blk[tx_size][block] = !x->plane[plane].eobs[block] ||
406                                     (rd1 > rd2 && !xd->lossless);
407 
408   args->this_rate += args->rate;
409   args->this_dist += args->dist;
410   args->this_sse  += args->sse;
411   args->this_rd += rd;
412 
413   if (args->this_rd > args->best_rd) {
414     args->skip = 1;
415     return;
416   }
417 }
418 
txfm_rd_in_plane(MACROBLOCK * x,int * rate,int64_t * distortion,int * skippable,int64_t * sse,int64_t ref_best_rd,int plane,BLOCK_SIZE bsize,TX_SIZE tx_size,int use_fast_coef_casting)419 static void txfm_rd_in_plane(MACROBLOCK *x,
420                              int *rate, int64_t *distortion,
421                              int *skippable, int64_t *sse,
422                              int64_t ref_best_rd, int plane,
423                              BLOCK_SIZE bsize, TX_SIZE tx_size,
424                              int use_fast_coef_casting) {
425   MACROBLOCKD *const xd = &x->e_mbd;
426   const struct macroblockd_plane *const pd = &xd->plane[plane];
427   struct rdcost_block_args args;
428   vp9_zero(args);
429   args.x = x;
430   args.best_rd = ref_best_rd;
431   args.use_fast_coef_costing = use_fast_coef_casting;
432 
433   if (plane == 0)
434     xd->mi[0]->mbmi.tx_size = tx_size;
435 
436   vp9_get_entropy_contexts(bsize, tx_size, pd, args.t_above, args.t_left);
437 
438   args.so = get_scan(xd, tx_size, pd->plane_type, 0);
439 
440   vp9_foreach_transformed_block_in_plane(xd, bsize, plane,
441                                          block_rd_txfm, &args);
442   if (args.skip) {
443     *rate       = INT_MAX;
444     *distortion = INT64_MAX;
445     *sse        = INT64_MAX;
446     *skippable  = 0;
447   } else {
448     *distortion = args.this_dist;
449     *rate       = args.this_rate;
450     *sse        = args.this_sse;
451     *skippable  = vp9_is_skippable_in_plane(x, bsize, plane);
452   }
453 }
454 
choose_largest_tx_size(VP9_COMP * cpi,MACROBLOCK * x,int * rate,int64_t * distortion,int * skip,int64_t * sse,int64_t ref_best_rd,BLOCK_SIZE bs)455 static void choose_largest_tx_size(VP9_COMP *cpi, MACROBLOCK *x,
456                                    int *rate, int64_t *distortion,
457                                    int *skip, int64_t *sse,
458                                    int64_t ref_best_rd,
459                                    BLOCK_SIZE bs) {
460   const TX_SIZE max_tx_size = max_txsize_lookup[bs];
461   VP9_COMMON *const cm = &cpi->common;
462   const TX_SIZE largest_tx_size = tx_mode_to_biggest_tx_size[cm->tx_mode];
463   MACROBLOCKD *const xd = &x->e_mbd;
464   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
465 
466   mbmi->tx_size = MIN(max_tx_size, largest_tx_size);
467 
468   txfm_rd_in_plane(x, rate, distortion, skip,
469                    sse, ref_best_rd, 0, bs,
470                    mbmi->tx_size, cpi->sf.use_fast_coef_costing);
471   cpi->tx_stepdown_count[0]++;
472 }
473 
choose_tx_size_from_rd(VP9_COMP * cpi,MACROBLOCK * x,int * rate,int64_t * distortion,int * skip,int64_t * psse,int64_t tx_cache[TX_MODES],int64_t ref_best_rd,BLOCK_SIZE bs)474 static void choose_tx_size_from_rd(VP9_COMP *cpi, MACROBLOCK *x,
475                                    int *rate,
476                                    int64_t *distortion,
477                                    int *skip,
478                                    int64_t *psse,
479                                    int64_t tx_cache[TX_MODES],
480                                    int64_t ref_best_rd,
481                                    BLOCK_SIZE bs) {
482   const TX_SIZE max_tx_size = max_txsize_lookup[bs];
483   VP9_COMMON *const cm = &cpi->common;
484   MACROBLOCKD *const xd = &x->e_mbd;
485   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
486   vp9_prob skip_prob = vp9_get_skip_prob(cm, xd);
487   int r[TX_SIZES][2], s[TX_SIZES];
488   int64_t d[TX_SIZES], sse[TX_SIZES];
489   int64_t rd[TX_SIZES][2] = {{INT64_MAX, INT64_MAX},
490                              {INT64_MAX, INT64_MAX},
491                              {INT64_MAX, INT64_MAX},
492                              {INT64_MAX, INT64_MAX}};
493   TX_SIZE n, m;
494   int s0, s1;
495   const TX_SIZE max_mode_tx_size = tx_mode_to_biggest_tx_size[cm->tx_mode];
496   int64_t best_rd = INT64_MAX;
497   TX_SIZE best_tx = TX_4X4;
498 
499   const vp9_prob *tx_probs = get_tx_probs2(max_tx_size, xd, &cm->fc.tx_probs);
500   assert(skip_prob > 0);
501   s0 = vp9_cost_bit(skip_prob, 0);
502   s1 = vp9_cost_bit(skip_prob, 1);
503 
504   for (n = TX_4X4; n <= max_tx_size; n++) {
505     txfm_rd_in_plane(x, &r[n][0], &d[n], &s[n],
506                      &sse[n], ref_best_rd, 0, bs, n,
507                      cpi->sf.use_fast_coef_costing);
508     r[n][1] = r[n][0];
509     if (r[n][0] < INT_MAX) {
510       for (m = 0; m <= n - (n == max_tx_size); m++) {
511         if (m == n)
512           r[n][1] += vp9_cost_zero(tx_probs[m]);
513         else
514           r[n][1] += vp9_cost_one(tx_probs[m]);
515       }
516     }
517     if (d[n] == INT64_MAX) {
518       rd[n][0] = rd[n][1] = INT64_MAX;
519     } else if (s[n]) {
520       rd[n][0] = rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1, d[n]);
521     } else {
522       rd[n][0] = RDCOST(x->rdmult, x->rddiv, r[n][0] + s0, d[n]);
523       rd[n][1] = RDCOST(x->rdmult, x->rddiv, r[n][1] + s0, d[n]);
524     }
525 
526     if (rd[n][1] < best_rd) {
527       best_tx = n;
528       best_rd = rd[n][1];
529     }
530   }
531   mbmi->tx_size = cm->tx_mode == TX_MODE_SELECT ?
532                       best_tx : MIN(max_tx_size, max_mode_tx_size);
533 
534 
535   *distortion = d[mbmi->tx_size];
536   *rate       = r[mbmi->tx_size][cm->tx_mode == TX_MODE_SELECT];
537   *skip       = s[mbmi->tx_size];
538   *psse       = sse[mbmi->tx_size];
539 
540   tx_cache[ONLY_4X4] = rd[TX_4X4][0];
541   tx_cache[ALLOW_8X8] = rd[TX_8X8][0];
542   tx_cache[ALLOW_16X16] = rd[MIN(max_tx_size, TX_16X16)][0];
543   tx_cache[ALLOW_32X32] = rd[MIN(max_tx_size, TX_32X32)][0];
544 
545   if (max_tx_size == TX_32X32 && best_tx == TX_32X32) {
546     tx_cache[TX_MODE_SELECT] = rd[TX_32X32][1];
547     cpi->tx_stepdown_count[0]++;
548   } else if (max_tx_size >= TX_16X16 && best_tx == TX_16X16) {
549     tx_cache[TX_MODE_SELECT] = rd[TX_16X16][1];
550     cpi->tx_stepdown_count[max_tx_size - TX_16X16]++;
551   } else if (rd[TX_8X8][1] < rd[TX_4X4][1]) {
552     tx_cache[TX_MODE_SELECT] = rd[TX_8X8][1];
553     cpi->tx_stepdown_count[max_tx_size - TX_8X8]++;
554   } else {
555     tx_cache[TX_MODE_SELECT] = rd[TX_4X4][1];
556     cpi->tx_stepdown_count[max_tx_size - TX_4X4]++;
557   }
558 }
559 
inter_super_block_yrd(VP9_COMP * cpi,MACROBLOCK * x,int * rate,int64_t * distortion,int * skip,int64_t * psse,BLOCK_SIZE bs,int64_t txfm_cache[TX_MODES],int64_t ref_best_rd)560 static void inter_super_block_yrd(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
561                                   int64_t *distortion, int *skip,
562                                   int64_t *psse, BLOCK_SIZE bs,
563                                   int64_t txfm_cache[TX_MODES],
564                                   int64_t ref_best_rd) {
565   MACROBLOCKD *xd = &x->e_mbd;
566 
567   assert(bs == xd->mi[0]->mbmi.sb_type);
568 
569   vp9_subtract_plane(x, bs, 0);
570 
571   if (cpi->sf.tx_size_search_method == USE_LARGESTALL || xd->lossless) {
572     vpx_memset(txfm_cache, 0, TX_MODES * sizeof(int64_t));
573     choose_largest_tx_size(cpi, x, rate, distortion, skip, psse, ref_best_rd,
574                            bs);
575   } else {
576     choose_tx_size_from_rd(cpi, x, rate, distortion, skip, psse,
577                            txfm_cache, ref_best_rd, bs);
578   }
579 }
580 
intra_super_block_yrd(VP9_COMP * cpi,MACROBLOCK * x,int * rate,int64_t * distortion,int * skip,BLOCK_SIZE bs,int64_t txfm_cache[TX_MODES],int64_t ref_best_rd)581 static void intra_super_block_yrd(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
582                                   int64_t *distortion, int *skip,
583                                   BLOCK_SIZE bs,
584                                   int64_t txfm_cache[TX_MODES],
585                                   int64_t ref_best_rd) {
586   MACROBLOCKD *xd = &x->e_mbd;
587   int64_t sse;
588 
589   assert(bs == xd->mi[0]->mbmi.sb_type);
590   if (cpi->sf.tx_size_search_method != USE_FULL_RD || xd->lossless) {
591     vpx_memset(txfm_cache, 0, TX_MODES * sizeof(int64_t));
592     choose_largest_tx_size(cpi, x, rate, distortion, skip, &sse, ref_best_rd,
593                            bs);
594   } else {
595     choose_tx_size_from_rd(cpi, x, rate, distortion, skip, &sse,
596                            txfm_cache, ref_best_rd, bs);
597   }
598 }
599 
600 
conditional_skipintra(PREDICTION_MODE mode,PREDICTION_MODE best_intra_mode)601 static int conditional_skipintra(PREDICTION_MODE mode,
602                                  PREDICTION_MODE best_intra_mode) {
603   if (mode == D117_PRED &&
604       best_intra_mode != V_PRED &&
605       best_intra_mode != D135_PRED)
606     return 1;
607   if (mode == D63_PRED &&
608       best_intra_mode != V_PRED &&
609       best_intra_mode != D45_PRED)
610     return 1;
611   if (mode == D207_PRED &&
612       best_intra_mode != H_PRED &&
613       best_intra_mode != D45_PRED)
614     return 1;
615   if (mode == D153_PRED &&
616       best_intra_mode != H_PRED &&
617       best_intra_mode != D135_PRED)
618     return 1;
619   return 0;
620 }
621 
rd_pick_intra4x4block(VP9_COMP * cpi,MACROBLOCK * x,int ib,PREDICTION_MODE * best_mode,const int * bmode_costs,ENTROPY_CONTEXT * a,ENTROPY_CONTEXT * l,int * bestrate,int * bestratey,int64_t * bestdistortion,BLOCK_SIZE bsize,int64_t rd_thresh)622 static int64_t rd_pick_intra4x4block(VP9_COMP *cpi, MACROBLOCK *x, int ib,
623                                      PREDICTION_MODE *best_mode,
624                                      const int *bmode_costs,
625                                      ENTROPY_CONTEXT *a, ENTROPY_CONTEXT *l,
626                                      int *bestrate, int *bestratey,
627                                      int64_t *bestdistortion,
628                                      BLOCK_SIZE bsize, int64_t rd_thresh) {
629   PREDICTION_MODE mode;
630   MACROBLOCKD *const xd = &x->e_mbd;
631   int64_t best_rd = rd_thresh;
632 
633   struct macroblock_plane *p = &x->plane[0];
634   struct macroblockd_plane *pd = &xd->plane[0];
635   const int src_stride = p->src.stride;
636   const int dst_stride = pd->dst.stride;
637   const uint8_t *src_init = &p->src.buf[raster_block_offset(BLOCK_8X8, ib,
638                                                             src_stride)];
639   uint8_t *dst_init = &pd->dst.buf[raster_block_offset(BLOCK_8X8, ib,
640                                                        dst_stride)];
641   ENTROPY_CONTEXT ta[2], tempa[2];
642   ENTROPY_CONTEXT tl[2], templ[2];
643 
644   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
645   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
646   int idx, idy;
647   uint8_t best_dst[8 * 8];
648 
649   assert(ib < 4);
650 
651   vpx_memcpy(ta, a, sizeof(ta));
652   vpx_memcpy(tl, l, sizeof(tl));
653   xd->mi[0]->mbmi.tx_size = TX_4X4;
654 
655   for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
656     int64_t this_rd;
657     int ratey = 0;
658     int64_t distortion = 0;
659     int rate = bmode_costs[mode];
660 
661     if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode)))
662       continue;
663 
664     // Only do the oblique modes if the best so far is
665     // one of the neighboring directional modes
666     if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
667       if (conditional_skipintra(mode, *best_mode))
668           continue;
669     }
670 
671     vpx_memcpy(tempa, ta, sizeof(ta));
672     vpx_memcpy(templ, tl, sizeof(tl));
673 
674     for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
675       for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
676         const int block = ib + idy * 2 + idx;
677         const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
678         uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
679         int16_t *const src_diff = raster_block_offset_int16(BLOCK_8X8, block,
680                                                             p->src_diff);
681         int16_t *const coeff = BLOCK_OFFSET(x->plane[0].coeff, block);
682         xd->mi[0]->bmi[block].as_mode = mode;
683         vp9_predict_intra_block(xd, block, 1,
684                                 TX_4X4, mode,
685                                 x->skip_encode ? src : dst,
686                                 x->skip_encode ? src_stride : dst_stride,
687                                 dst, dst_stride, idx, idy, 0);
688         vp9_subtract_block(4, 4, src_diff, 8, src, src_stride, dst, dst_stride);
689 
690         if (xd->lossless) {
691           const scan_order *so = &vp9_default_scan_orders[TX_4X4];
692           vp9_fwht4x4(src_diff, coeff, 8);
693           vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
694           ratey += cost_coeffs(x, 0, block, tempa + idx, templ + idy, TX_4X4,
695                                so->scan, so->neighbors,
696                                cpi->sf.use_fast_coef_costing);
697           if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
698             goto next;
699           vp9_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst, dst_stride,
700                           p->eobs[block]);
701         } else {
702           int64_t unused;
703           const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
704           const scan_order *so = &vp9_scan_orders[TX_4X4][tx_type];
705           vp9_fht4x4(src_diff, coeff, 8, tx_type);
706           vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
707           ratey += cost_coeffs(x, 0, block, tempa + idx, templ + idy, TX_4X4,
708                              so->scan, so->neighbors,
709                              cpi->sf.use_fast_coef_costing);
710           distortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, block),
711                                         16, &unused) >> 2;
712           if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
713             goto next;
714           vp9_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block),
715                          dst, dst_stride, p->eobs[block]);
716         }
717       }
718     }
719 
720     rate += ratey;
721     this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
722 
723     if (this_rd < best_rd) {
724       *bestrate = rate;
725       *bestratey = ratey;
726       *bestdistortion = distortion;
727       best_rd = this_rd;
728       *best_mode = mode;
729       vpx_memcpy(a, tempa, sizeof(tempa));
730       vpx_memcpy(l, templ, sizeof(templ));
731       for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
732         vpx_memcpy(best_dst + idy * 8, dst_init + idy * dst_stride,
733                    num_4x4_blocks_wide * 4);
734     }
735   next:
736     {}
737   }
738 
739   if (best_rd >= rd_thresh || x->skip_encode)
740     return best_rd;
741 
742   for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
743     vpx_memcpy(dst_init + idy * dst_stride, best_dst + idy * 8,
744                num_4x4_blocks_wide * 4);
745 
746   return best_rd;
747 }
748 
rd_pick_intra_sub_8x8_y_mode(VP9_COMP * cpi,MACROBLOCK * mb,int * rate,int * rate_y,int64_t * distortion,int64_t best_rd)749 static int64_t rd_pick_intra_sub_8x8_y_mode(VP9_COMP *cpi, MACROBLOCK *mb,
750                                             int *rate, int *rate_y,
751                                             int64_t *distortion,
752                                             int64_t best_rd) {
753   int i, j;
754   const MACROBLOCKD *const xd = &mb->e_mbd;
755   MODE_INFO *const mic = xd->mi[0];
756   const MODE_INFO *above_mi = xd->mi[-xd->mi_stride];
757   const MODE_INFO *left_mi = xd->left_available ? xd->mi[-1] : NULL;
758   const BLOCK_SIZE bsize = xd->mi[0]->mbmi.sb_type;
759   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
760   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
761   int idx, idy;
762   int cost = 0;
763   int64_t total_distortion = 0;
764   int tot_rate_y = 0;
765   int64_t total_rd = 0;
766   ENTROPY_CONTEXT t_above[4], t_left[4];
767   const int *bmode_costs = cpi->mbmode_cost;
768 
769   vpx_memcpy(t_above, xd->plane[0].above_context, sizeof(t_above));
770   vpx_memcpy(t_left, xd->plane[0].left_context, sizeof(t_left));
771 
772   // Pick modes for each sub-block (of size 4x4, 4x8, or 8x4) in an 8x8 block.
773   for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
774     for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
775       PREDICTION_MODE best_mode = DC_PRED;
776       int r = INT_MAX, ry = INT_MAX;
777       int64_t d = INT64_MAX, this_rd = INT64_MAX;
778       i = idy * 2 + idx;
779       if (cpi->common.frame_type == KEY_FRAME) {
780         const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, i);
781         const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, i);
782 
783         bmode_costs  = cpi->y_mode_costs[A][L];
784       }
785 
786       this_rd = rd_pick_intra4x4block(cpi, mb, i, &best_mode, bmode_costs,
787                                       t_above + idx, t_left + idy, &r, &ry, &d,
788                                       bsize, best_rd - total_rd);
789       if (this_rd >= best_rd - total_rd)
790         return INT64_MAX;
791 
792       total_rd += this_rd;
793       cost += r;
794       total_distortion += d;
795       tot_rate_y += ry;
796 
797       mic->bmi[i].as_mode = best_mode;
798       for (j = 1; j < num_4x4_blocks_high; ++j)
799         mic->bmi[i + j * 2].as_mode = best_mode;
800       for (j = 1; j < num_4x4_blocks_wide; ++j)
801         mic->bmi[i + j].as_mode = best_mode;
802 
803       if (total_rd >= best_rd)
804         return INT64_MAX;
805     }
806   }
807 
808   *rate = cost;
809   *rate_y = tot_rate_y;
810   *distortion = total_distortion;
811   mic->mbmi.mode = mic->bmi[3].as_mode;
812 
813   return RDCOST(mb->rdmult, mb->rddiv, cost, total_distortion);
814 }
815 
rd_pick_intra_sby_mode(VP9_COMP * cpi,MACROBLOCK * x,int * rate,int * rate_tokenonly,int64_t * distortion,int * skippable,BLOCK_SIZE bsize,int64_t tx_cache[TX_MODES],int64_t best_rd)816 static int64_t rd_pick_intra_sby_mode(VP9_COMP *cpi, MACROBLOCK *x,
817                                       int *rate, int *rate_tokenonly,
818                                       int64_t *distortion, int *skippable,
819                                       BLOCK_SIZE bsize,
820                                       int64_t tx_cache[TX_MODES],
821                                       int64_t best_rd) {
822   PREDICTION_MODE mode;
823   PREDICTION_MODE mode_selected = DC_PRED;
824   MACROBLOCKD *const xd = &x->e_mbd;
825   MODE_INFO *const mic = xd->mi[0];
826   int this_rate, this_rate_tokenonly, s;
827   int64_t this_distortion, this_rd;
828   TX_SIZE best_tx = TX_4X4;
829   int i;
830   int *bmode_costs = cpi->mbmode_cost;
831 
832   if (cpi->sf.tx_size_search_method == USE_FULL_RD)
833     for (i = 0; i < TX_MODES; i++)
834       tx_cache[i] = INT64_MAX;
835 
836   /* Y Search for intra prediction mode */
837   for (mode = DC_PRED; mode <= TM_PRED; mode++) {
838     int64_t local_tx_cache[TX_MODES];
839     MODE_INFO *above_mi = xd->mi[-xd->mi_stride];
840     MODE_INFO *left_mi = xd->left_available ? xd->mi[-1] : NULL;
841 
842     if (cpi->common.frame_type == KEY_FRAME) {
843       const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0);
844       const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
845 
846       bmode_costs = cpi->y_mode_costs[A][L];
847     }
848     mic->mbmi.mode = mode;
849 
850     intra_super_block_yrd(cpi, x, &this_rate_tokenonly, &this_distortion,
851         &s, bsize, local_tx_cache, best_rd);
852 
853     if (this_rate_tokenonly == INT_MAX)
854       continue;
855 
856     this_rate = this_rate_tokenonly + bmode_costs[mode];
857     this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
858 
859     if (this_rd < best_rd) {
860       mode_selected   = mode;
861       best_rd         = this_rd;
862       best_tx         = mic->mbmi.tx_size;
863       *rate           = this_rate;
864       *rate_tokenonly = this_rate_tokenonly;
865       *distortion     = this_distortion;
866       *skippable      = s;
867     }
868 
869     if (cpi->sf.tx_size_search_method == USE_FULL_RD && this_rd < INT64_MAX) {
870       for (i = 0; i < TX_MODES && local_tx_cache[i] < INT64_MAX; i++) {
871         const int64_t adj_rd = this_rd + local_tx_cache[i] -
872             local_tx_cache[cpi->common.tx_mode];
873         if (adj_rd < tx_cache[i]) {
874           tx_cache[i] = adj_rd;
875         }
876       }
877     }
878   }
879 
880   mic->mbmi.mode = mode_selected;
881   mic->mbmi.tx_size = best_tx;
882 
883   return best_rd;
884 }
885 
super_block_uvrd(const VP9_COMP * cpi,MACROBLOCK * x,int * rate,int64_t * distortion,int * skippable,int64_t * sse,BLOCK_SIZE bsize,int64_t ref_best_rd)886 static void super_block_uvrd(const VP9_COMP *cpi, MACROBLOCK *x,
887                              int *rate, int64_t *distortion, int *skippable,
888                              int64_t *sse, BLOCK_SIZE bsize,
889                              int64_t ref_best_rd) {
890   MACROBLOCKD *const xd = &x->e_mbd;
891   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
892   const TX_SIZE uv_tx_size = get_uv_tx_size(mbmi, &xd->plane[1]);
893   int plane;
894   int pnrate = 0, pnskip = 1;
895   int64_t pndist = 0, pnsse = 0;
896 
897   if (ref_best_rd < 0)
898     goto term;
899 
900   if (is_inter_block(mbmi)) {
901     int plane;
902     for (plane = 1; plane < MAX_MB_PLANE; ++plane)
903       vp9_subtract_plane(x, bsize, plane);
904   }
905 
906   *rate = 0;
907   *distortion = 0;
908   *sse = 0;
909   *skippable = 1;
910 
911   for (plane = 1; plane < MAX_MB_PLANE; ++plane) {
912     txfm_rd_in_plane(x, &pnrate, &pndist, &pnskip, &pnsse,
913                      ref_best_rd, plane, bsize, uv_tx_size,
914                      cpi->sf.use_fast_coef_costing);
915     if (pnrate == INT_MAX)
916       goto term;
917     *rate += pnrate;
918     *distortion += pndist;
919     *sse += pnsse;
920     *skippable &= pnskip;
921   }
922   return;
923 
924   term:
925   *rate = INT_MAX;
926   *distortion = INT64_MAX;
927   *sse = INT64_MAX;
928   *skippable = 0;
929   return;
930 }
931 
rd_pick_intra_sbuv_mode(VP9_COMP * cpi,MACROBLOCK * x,PICK_MODE_CONTEXT * ctx,int * rate,int * rate_tokenonly,int64_t * distortion,int * skippable,BLOCK_SIZE bsize,TX_SIZE max_tx_size)932 static int64_t rd_pick_intra_sbuv_mode(VP9_COMP *cpi, MACROBLOCK *x,
933                                        PICK_MODE_CONTEXT *ctx,
934                                        int *rate, int *rate_tokenonly,
935                                        int64_t *distortion, int *skippable,
936                                        BLOCK_SIZE bsize, TX_SIZE max_tx_size) {
937   MACROBLOCKD *xd = &x->e_mbd;
938   PREDICTION_MODE mode;
939   PREDICTION_MODE mode_selected = DC_PRED;
940   int64_t best_rd = INT64_MAX, this_rd;
941   int this_rate_tokenonly, this_rate, s;
942   int64_t this_distortion, this_sse;
943 
944   for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
945     if (!(cpi->sf.intra_uv_mode_mask[max_tx_size] & (1 << mode)))
946       continue;
947 
948     xd->mi[0]->mbmi.uv_mode = mode;
949 
950     super_block_uvrd(cpi, x, &this_rate_tokenonly,
951                      &this_distortion, &s, &this_sse, bsize, best_rd);
952     if (this_rate_tokenonly == INT_MAX)
953       continue;
954     this_rate = this_rate_tokenonly +
955                 cpi->intra_uv_mode_cost[cpi->common.frame_type][mode];
956     this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
957 
958     if (this_rd < best_rd) {
959       mode_selected   = mode;
960       best_rd         = this_rd;
961       *rate           = this_rate;
962       *rate_tokenonly = this_rate_tokenonly;
963       *distortion     = this_distortion;
964       *skippable      = s;
965       if (!x->select_tx_size)
966         swap_block_ptr(x, ctx, 2, 0, 1, MAX_MB_PLANE);
967     }
968   }
969 
970   xd->mi[0]->mbmi.uv_mode = mode_selected;
971   return best_rd;
972 }
973 
rd_sbuv_dcpred(const VP9_COMP * cpi,MACROBLOCK * x,int * rate,int * rate_tokenonly,int64_t * distortion,int * skippable,BLOCK_SIZE bsize)974 static int64_t rd_sbuv_dcpred(const VP9_COMP *cpi, MACROBLOCK *x,
975                               int *rate, int *rate_tokenonly,
976                               int64_t *distortion, int *skippable,
977                               BLOCK_SIZE bsize) {
978   const VP9_COMMON *cm = &cpi->common;
979   int64_t unused;
980 
981   x->e_mbd.mi[0]->mbmi.uv_mode = DC_PRED;
982   super_block_uvrd(cpi, x, rate_tokenonly, distortion,
983                    skippable, &unused, bsize, INT64_MAX);
984   *rate = *rate_tokenonly + cpi->intra_uv_mode_cost[cm->frame_type][DC_PRED];
985   return RDCOST(x->rdmult, x->rddiv, *rate, *distortion);
986 }
987 
choose_intra_uv_mode(VP9_COMP * cpi,PICK_MODE_CONTEXT * ctx,BLOCK_SIZE bsize,TX_SIZE max_tx_size,int * rate_uv,int * rate_uv_tokenonly,int64_t * dist_uv,int * skip_uv,PREDICTION_MODE * mode_uv)988 static void choose_intra_uv_mode(VP9_COMP *cpi, PICK_MODE_CONTEXT *ctx,
989                                  BLOCK_SIZE bsize, TX_SIZE max_tx_size,
990                                  int *rate_uv, int *rate_uv_tokenonly,
991                                  int64_t *dist_uv, int *skip_uv,
992                                  PREDICTION_MODE *mode_uv) {
993   MACROBLOCK *const x = &cpi->mb;
994 
995   // Use an estimated rd for uv_intra based on DC_PRED if the
996   // appropriate speed flag is set.
997   if (cpi->sf.use_uv_intra_rd_estimate) {
998     rd_sbuv_dcpred(cpi, x, rate_uv, rate_uv_tokenonly, dist_uv,
999                    skip_uv, bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize);
1000   // Else do a proper rd search for each possible transform size that may
1001   // be considered in the main rd loop.
1002   } else {
1003     rd_pick_intra_sbuv_mode(cpi, x, ctx,
1004                             rate_uv, rate_uv_tokenonly, dist_uv, skip_uv,
1005                             bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize, max_tx_size);
1006   }
1007   *mode_uv = x->e_mbd.mi[0]->mbmi.uv_mode;
1008 }
1009 
cost_mv_ref(const VP9_COMP * cpi,PREDICTION_MODE mode,int mode_context)1010 static int cost_mv_ref(const VP9_COMP *cpi, PREDICTION_MODE mode,
1011                        int mode_context) {
1012   assert(is_inter_mode(mode));
1013   return cpi->inter_mode_cost[mode_context][INTER_OFFSET(mode)];
1014 }
1015 
1016 static void joint_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
1017                                 BLOCK_SIZE bsize,
1018                                 int_mv *frame_mv,
1019                                 int mi_row, int mi_col,
1020                                 int_mv single_newmv[MAX_REF_FRAMES],
1021                                 int *rate_mv);
1022 
set_and_cost_bmi_mvs(VP9_COMP * cpi,MACROBLOCKD * xd,int i,PREDICTION_MODE mode,int_mv this_mv[2],int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],int_mv seg_mvs[MAX_REF_FRAMES],int_mv * best_ref_mv[2],const int * mvjcost,int * mvcost[2])1023 static int set_and_cost_bmi_mvs(VP9_COMP *cpi, MACROBLOCKD *xd, int i,
1024                                 PREDICTION_MODE mode, int_mv this_mv[2],
1025                                 int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1026                                 int_mv seg_mvs[MAX_REF_FRAMES],
1027                                 int_mv *best_ref_mv[2], const int *mvjcost,
1028                                 int *mvcost[2]) {
1029   MODE_INFO *const mic = xd->mi[0];
1030   const MB_MODE_INFO *const mbmi = &mic->mbmi;
1031   int thismvcost = 0;
1032   int idx, idy;
1033   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[mbmi->sb_type];
1034   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[mbmi->sb_type];
1035   const int is_compound = has_second_ref(mbmi);
1036 
1037   switch (mode) {
1038     case NEWMV:
1039       this_mv[0].as_int = seg_mvs[mbmi->ref_frame[0]].as_int;
1040       thismvcost += vp9_mv_bit_cost(&this_mv[0].as_mv, &best_ref_mv[0]->as_mv,
1041                                     mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1042       if (is_compound) {
1043         this_mv[1].as_int = seg_mvs[mbmi->ref_frame[1]].as_int;
1044         thismvcost += vp9_mv_bit_cost(&this_mv[1].as_mv, &best_ref_mv[1]->as_mv,
1045                                       mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1046       }
1047       break;
1048     case NEARMV:
1049     case NEARESTMV:
1050       this_mv[0].as_int = frame_mv[mode][mbmi->ref_frame[0]].as_int;
1051       if (is_compound)
1052         this_mv[1].as_int = frame_mv[mode][mbmi->ref_frame[1]].as_int;
1053       break;
1054     case ZEROMV:
1055       this_mv[0].as_int = 0;
1056       if (is_compound)
1057         this_mv[1].as_int = 0;
1058       break;
1059     default:
1060       break;
1061   }
1062 
1063   mic->bmi[i].as_mv[0].as_int = this_mv[0].as_int;
1064   if (is_compound)
1065     mic->bmi[i].as_mv[1].as_int = this_mv[1].as_int;
1066 
1067   mic->bmi[i].as_mode = mode;
1068 
1069   for (idy = 0; idy < num_4x4_blocks_high; ++idy)
1070     for (idx = 0; idx < num_4x4_blocks_wide; ++idx)
1071       vpx_memcpy(&mic->bmi[i + idy * 2 + idx],
1072                  &mic->bmi[i], sizeof(mic->bmi[i]));
1073 
1074   return cost_mv_ref(cpi, mode, mbmi->mode_context[mbmi->ref_frame[0]]) +
1075             thismvcost;
1076 }
1077 
encode_inter_mb_segment(VP9_COMP * cpi,MACROBLOCK * x,int64_t best_yrd,int i,int * labelyrate,int64_t * distortion,int64_t * sse,ENTROPY_CONTEXT * ta,ENTROPY_CONTEXT * tl,int mi_row,int mi_col)1078 static int64_t encode_inter_mb_segment(VP9_COMP *cpi,
1079                                        MACROBLOCK *x,
1080                                        int64_t best_yrd,
1081                                        int i,
1082                                        int *labelyrate,
1083                                        int64_t *distortion, int64_t *sse,
1084                                        ENTROPY_CONTEXT *ta,
1085                                        ENTROPY_CONTEXT *tl,
1086                                        int mi_row, int mi_col) {
1087   int k;
1088   MACROBLOCKD *xd = &x->e_mbd;
1089   struct macroblockd_plane *const pd = &xd->plane[0];
1090   struct macroblock_plane *const p = &x->plane[0];
1091   MODE_INFO *const mi = xd->mi[0];
1092   const BLOCK_SIZE plane_bsize = get_plane_block_size(mi->mbmi.sb_type, pd);
1093   const int width = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
1094   const int height = 4 * num_4x4_blocks_high_lookup[plane_bsize];
1095   int idx, idy;
1096 
1097   const uint8_t *const src = &p->src.buf[raster_block_offset(BLOCK_8X8, i,
1098                                                              p->src.stride)];
1099   uint8_t *const dst = &pd->dst.buf[raster_block_offset(BLOCK_8X8, i,
1100                                                         pd->dst.stride)];
1101   int64_t thisdistortion = 0, thissse = 0;
1102   int thisrate = 0, ref;
1103   const scan_order *so = &vp9_default_scan_orders[TX_4X4];
1104   const int is_compound = has_second_ref(&mi->mbmi);
1105   const InterpKernel *kernel = vp9_get_interp_kernel(mi->mbmi.interp_filter);
1106 
1107   for (ref = 0; ref < 1 + is_compound; ++ref) {
1108     const uint8_t *pre = &pd->pre[ref].buf[raster_block_offset(BLOCK_8X8, i,
1109                                                pd->pre[ref].stride)];
1110     vp9_build_inter_predictor(pre, pd->pre[ref].stride,
1111                               dst, pd->dst.stride,
1112                               &mi->bmi[i].as_mv[ref].as_mv,
1113                               &xd->block_refs[ref]->sf, width, height, ref,
1114                               kernel, MV_PRECISION_Q3,
1115                               mi_col * MI_SIZE + 4 * (i % 2),
1116                               mi_row * MI_SIZE + 4 * (i / 2));
1117   }
1118 
1119   vp9_subtract_block(height, width,
1120                      raster_block_offset_int16(BLOCK_8X8, i, p->src_diff), 8,
1121                      src, p->src.stride,
1122                      dst, pd->dst.stride);
1123 
1124   k = i;
1125   for (idy = 0; idy < height / 4; ++idy) {
1126     for (idx = 0; idx < width / 4; ++idx) {
1127       int64_t ssz, rd, rd1, rd2;
1128       int16_t* coeff;
1129 
1130       k += (idy * 2 + idx);
1131       coeff = BLOCK_OFFSET(p->coeff, k);
1132       x->fwd_txm4x4(raster_block_offset_int16(BLOCK_8X8, k, p->src_diff),
1133                     coeff, 8);
1134       vp9_regular_quantize_b_4x4(x, 0, k, so->scan, so->iscan);
1135       thisdistortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, k),
1136                                         16, &ssz);
1137       thissse += ssz;
1138       thisrate += cost_coeffs(x, 0, k, ta + (k & 1), tl + (k >> 1), TX_4X4,
1139                               so->scan, so->neighbors,
1140                               cpi->sf.use_fast_coef_costing);
1141       rd1 = RDCOST(x->rdmult, x->rddiv, thisrate, thisdistortion >> 2);
1142       rd2 = RDCOST(x->rdmult, x->rddiv, 0, thissse >> 2);
1143       rd = MIN(rd1, rd2);
1144       if (rd >= best_yrd)
1145         return INT64_MAX;
1146     }
1147   }
1148 
1149   *distortion = thisdistortion >> 2;
1150   *labelyrate = thisrate;
1151   *sse = thissse >> 2;
1152 
1153   return RDCOST(x->rdmult, x->rddiv, *labelyrate, *distortion);
1154 }
1155 
1156 typedef struct {
1157   int eobs;
1158   int brate;
1159   int byrate;
1160   int64_t bdist;
1161   int64_t bsse;
1162   int64_t brdcost;
1163   int_mv mvs[2];
1164   ENTROPY_CONTEXT ta[2];
1165   ENTROPY_CONTEXT tl[2];
1166 } SEG_RDSTAT;
1167 
1168 typedef struct {
1169   int_mv *ref_mv[2];
1170   int_mv mvp;
1171 
1172   int64_t segment_rd;
1173   int r;
1174   int64_t d;
1175   int64_t sse;
1176   int segment_yrate;
1177   PREDICTION_MODE modes[4];
1178   SEG_RDSTAT rdstat[4][INTER_MODES];
1179   int mvthresh;
1180 } BEST_SEG_INFO;
1181 
mv_check_bounds(const MACROBLOCK * x,const MV * mv)1182 static INLINE int mv_check_bounds(const MACROBLOCK *x, const MV *mv) {
1183   return (mv->row >> 3) < x->mv_row_min ||
1184          (mv->row >> 3) > x->mv_row_max ||
1185          (mv->col >> 3) < x->mv_col_min ||
1186          (mv->col >> 3) > x->mv_col_max;
1187 }
1188 
mi_buf_shift(MACROBLOCK * x,int i)1189 static INLINE void mi_buf_shift(MACROBLOCK *x, int i) {
1190   MB_MODE_INFO *const mbmi = &x->e_mbd.mi[0]->mbmi;
1191   struct macroblock_plane *const p = &x->plane[0];
1192   struct macroblockd_plane *const pd = &x->e_mbd.plane[0];
1193 
1194   p->src.buf = &p->src.buf[raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1195   assert(((intptr_t)pd->pre[0].buf & 0x7) == 0);
1196   pd->pre[0].buf = &pd->pre[0].buf[raster_block_offset(BLOCK_8X8, i,
1197                                                        pd->pre[0].stride)];
1198   if (has_second_ref(mbmi))
1199     pd->pre[1].buf = &pd->pre[1].buf[raster_block_offset(BLOCK_8X8, i,
1200                                                          pd->pre[1].stride)];
1201 }
1202 
mi_buf_restore(MACROBLOCK * x,struct buf_2d orig_src,struct buf_2d orig_pre[2])1203 static INLINE void mi_buf_restore(MACROBLOCK *x, struct buf_2d orig_src,
1204                                   struct buf_2d orig_pre[2]) {
1205   MB_MODE_INFO *mbmi = &x->e_mbd.mi[0]->mbmi;
1206   x->plane[0].src = orig_src;
1207   x->e_mbd.plane[0].pre[0] = orig_pre[0];
1208   if (has_second_ref(mbmi))
1209     x->e_mbd.plane[0].pre[1] = orig_pre[1];
1210 }
1211 
mv_has_subpel(const MV * mv)1212 static INLINE int mv_has_subpel(const MV *mv) {
1213   return (mv->row & 0x0F) || (mv->col & 0x0F);
1214 }
1215 
1216 // Check if NEARESTMV/NEARMV/ZEROMV is the cheapest way encode zero motion.
1217 // TODO(aconverse): Find out if this is still productive then clean up or remove
check_best_zero_mv(const VP9_COMP * cpi,const uint8_t mode_context[MAX_REF_FRAMES],int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],int inter_mode_mask,int this_mode,const MV_REFERENCE_FRAME ref_frames[2])1218 static int check_best_zero_mv(
1219     const VP9_COMP *cpi, const uint8_t mode_context[MAX_REF_FRAMES],
1220     int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1221     int inter_mode_mask, int this_mode,
1222     const MV_REFERENCE_FRAME ref_frames[2]) {
1223   if ((inter_mode_mask & (1 << ZEROMV)) &&
1224       (this_mode == NEARMV || this_mode == NEARESTMV || this_mode == ZEROMV) &&
1225       frame_mv[this_mode][ref_frames[0]].as_int == 0 &&
1226       (ref_frames[1] == NONE ||
1227        frame_mv[this_mode][ref_frames[1]].as_int == 0)) {
1228     int rfc = mode_context[ref_frames[0]];
1229     int c1 = cost_mv_ref(cpi, NEARMV, rfc);
1230     int c2 = cost_mv_ref(cpi, NEARESTMV, rfc);
1231     int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
1232 
1233     if (this_mode == NEARMV) {
1234       if (c1 > c3) return 0;
1235     } else if (this_mode == NEARESTMV) {
1236       if (c2 > c3) return 0;
1237     } else {
1238       assert(this_mode == ZEROMV);
1239       if (ref_frames[1] == NONE) {
1240         if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0) ||
1241             (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0))
1242           return 0;
1243       } else {
1244         if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0 &&
1245              frame_mv[NEARESTMV][ref_frames[1]].as_int == 0) ||
1246             (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0 &&
1247              frame_mv[NEARMV][ref_frames[1]].as_int == 0))
1248           return 0;
1249       }
1250     }
1251   }
1252   return 1;
1253 }
1254 
rd_pick_best_sub8x8_mode(VP9_COMP * cpi,MACROBLOCK * x,const TileInfo * const tile,int_mv * best_ref_mv,int_mv * second_best_ref_mv,int64_t best_rd,int * returntotrate,int * returnyrate,int64_t * returndistortion,int * skippable,int64_t * psse,int mvthresh,int_mv seg_mvs[4][MAX_REF_FRAMES],BEST_SEG_INFO * bsi_buf,int filter_idx,int mi_row,int mi_col)1255 static int64_t rd_pick_best_sub8x8_mode(VP9_COMP *cpi, MACROBLOCK *x,
1256                                         const TileInfo * const tile,
1257                                         int_mv *best_ref_mv,
1258                                         int_mv *second_best_ref_mv,
1259                                         int64_t best_rd, int *returntotrate,
1260                                         int *returnyrate,
1261                                         int64_t *returndistortion,
1262                                         int *skippable, int64_t *psse,
1263                                         int mvthresh,
1264                                         int_mv seg_mvs[4][MAX_REF_FRAMES],
1265                                         BEST_SEG_INFO *bsi_buf, int filter_idx,
1266                                         int mi_row, int mi_col) {
1267   int i;
1268   BEST_SEG_INFO *bsi = bsi_buf + filter_idx;
1269   MACROBLOCKD *xd = &x->e_mbd;
1270   MODE_INFO *mi = xd->mi[0];
1271   MB_MODE_INFO *mbmi = &mi->mbmi;
1272   int mode_idx;
1273   int k, br = 0, idx, idy;
1274   int64_t bd = 0, block_sse = 0;
1275   PREDICTION_MODE this_mode;
1276   VP9_COMMON *cm = &cpi->common;
1277   struct macroblock_plane *const p = &x->plane[0];
1278   struct macroblockd_plane *const pd = &xd->plane[0];
1279   const int label_count = 4;
1280   int64_t this_segment_rd = 0;
1281   int label_mv_thresh;
1282   int segmentyrate = 0;
1283   const BLOCK_SIZE bsize = mbmi->sb_type;
1284   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1285   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1286   ENTROPY_CONTEXT t_above[2], t_left[2];
1287   int subpelmv = 1, have_ref = 0;
1288   const int has_second_rf = has_second_ref(mbmi);
1289   const int inter_mode_mask = cpi->sf.inter_mode_mask[bsize];
1290 
1291   vp9_zero(*bsi);
1292 
1293   bsi->segment_rd = best_rd;
1294   bsi->ref_mv[0] = best_ref_mv;
1295   bsi->ref_mv[1] = second_best_ref_mv;
1296   bsi->mvp.as_int = best_ref_mv->as_int;
1297   bsi->mvthresh = mvthresh;
1298 
1299   for (i = 0; i < 4; i++)
1300     bsi->modes[i] = ZEROMV;
1301 
1302   vpx_memcpy(t_above, pd->above_context, sizeof(t_above));
1303   vpx_memcpy(t_left, pd->left_context, sizeof(t_left));
1304 
1305   // 64 makes this threshold really big effectively
1306   // making it so that we very rarely check mvs on
1307   // segments.   setting this to 1 would make mv thresh
1308   // roughly equal to what it is for macroblocks
1309   label_mv_thresh = 1 * bsi->mvthresh / label_count;
1310 
1311   // Segmentation method overheads
1312   for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
1313     for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
1314       // TODO(jingning,rbultje): rewrite the rate-distortion optimization
1315       // loop for 4x4/4x8/8x4 block coding. to be replaced with new rd loop
1316       int_mv mode_mv[MB_MODE_COUNT][2];
1317       int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
1318       PREDICTION_MODE mode_selected = ZEROMV;
1319       int64_t best_rd = INT64_MAX;
1320       const int i = idy * 2 + idx;
1321       int ref;
1322 
1323       for (ref = 0; ref < 1 + has_second_rf; ++ref) {
1324         const MV_REFERENCE_FRAME frame = mbmi->ref_frame[ref];
1325         frame_mv[ZEROMV][frame].as_int = 0;
1326         vp9_append_sub8x8_mvs_for_idx(cm, xd, tile, i, ref, mi_row, mi_col,
1327                                       &frame_mv[NEARESTMV][frame],
1328                                       &frame_mv[NEARMV][frame]);
1329       }
1330 
1331       // search for the best motion vector on this segment
1332       for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
1333         const struct buf_2d orig_src = x->plane[0].src;
1334         struct buf_2d orig_pre[2];
1335 
1336         mode_idx = INTER_OFFSET(this_mode);
1337         bsi->rdstat[i][mode_idx].brdcost = INT64_MAX;
1338         if (!(inter_mode_mask & (1 << this_mode)))
1339           continue;
1340 
1341         if (!check_best_zero_mv(cpi, mbmi->mode_context, frame_mv,
1342                                 inter_mode_mask,
1343                                 this_mode, mbmi->ref_frame))
1344           continue;
1345 
1346         vpx_memcpy(orig_pre, pd->pre, sizeof(orig_pre));
1347         vpx_memcpy(bsi->rdstat[i][mode_idx].ta, t_above,
1348                    sizeof(bsi->rdstat[i][mode_idx].ta));
1349         vpx_memcpy(bsi->rdstat[i][mode_idx].tl, t_left,
1350                    sizeof(bsi->rdstat[i][mode_idx].tl));
1351 
1352         // motion search for newmv (single predictor case only)
1353         if (!has_second_rf && this_mode == NEWMV &&
1354             seg_mvs[i][mbmi->ref_frame[0]].as_int == INVALID_MV) {
1355           MV *const new_mv = &mode_mv[NEWMV][0].as_mv;
1356           int step_param = 0;
1357           int thissme, bestsme = INT_MAX;
1358           int sadpb = x->sadperbit4;
1359           MV mvp_full;
1360           int max_mv;
1361 
1362           /* Is the best so far sufficiently good that we cant justify doing
1363            * and new motion search. */
1364           if (best_rd < label_mv_thresh)
1365             break;
1366 
1367           if (!is_best_mode(cpi->oxcf.mode)) {
1368             // use previous block's result as next block's MV predictor.
1369             if (i > 0) {
1370               bsi->mvp.as_int = mi->bmi[i - 1].as_mv[0].as_int;
1371               if (i == 2)
1372                 bsi->mvp.as_int = mi->bmi[i - 2].as_mv[0].as_int;
1373             }
1374           }
1375           if (i == 0)
1376             max_mv = x->max_mv_context[mbmi->ref_frame[0]];
1377           else
1378             max_mv = MAX(abs(bsi->mvp.as_mv.row), abs(bsi->mvp.as_mv.col)) >> 3;
1379 
1380           if (cpi->sf.mv.auto_mv_step_size && cm->show_frame) {
1381             // Take wtd average of the step_params based on the last frame's
1382             // max mv magnitude and the best ref mvs of the current block for
1383             // the given reference.
1384             step_param = (vp9_init_search_range(max_mv) +
1385                               cpi->mv_step_param) / 2;
1386           } else {
1387             step_param = cpi->mv_step_param;
1388           }
1389 
1390           mvp_full.row = bsi->mvp.as_mv.row >> 3;
1391           mvp_full.col = bsi->mvp.as_mv.col >> 3;
1392 
1393           if (cpi->sf.adaptive_motion_search && cm->show_frame) {
1394             mvp_full.row = x->pred_mv[mbmi->ref_frame[0]].row >> 3;
1395             mvp_full.col = x->pred_mv[mbmi->ref_frame[0]].col >> 3;
1396             step_param = MAX(step_param, 8);
1397           }
1398 
1399           // adjust src pointer for this block
1400           mi_buf_shift(x, i);
1401 
1402           vp9_set_mv_search_range(x, &bsi->ref_mv[0]->as_mv);
1403 
1404           bestsme = vp9_full_pixel_search(cpi, x, bsize, &mvp_full, step_param,
1405                                           sadpb, &bsi->ref_mv[0]->as_mv, new_mv,
1406                                           INT_MAX, 1);
1407 
1408           // Should we do a full search (best quality only)
1409           if (is_best_mode(cpi->oxcf.mode)) {
1410             int_mv *const best_mv = &mi->bmi[i].as_mv[0];
1411             /* Check if mvp_full is within the range. */
1412             clamp_mv(&mvp_full, x->mv_col_min, x->mv_col_max,
1413                      x->mv_row_min, x->mv_row_max);
1414             thissme = cpi->full_search_sad(x, &mvp_full,
1415                                            sadpb, 16, &cpi->fn_ptr[bsize],
1416                                            &bsi->ref_mv[0]->as_mv,
1417                                            &best_mv->as_mv);
1418             if (thissme < bestsme) {
1419               bestsme = thissme;
1420               *new_mv = best_mv->as_mv;
1421             } else {
1422               // The full search result is actually worse so re-instate the
1423               // previous best vector
1424               best_mv->as_mv = *new_mv;
1425             }
1426           }
1427 
1428           if (bestsme < INT_MAX) {
1429             int distortion;
1430             cpi->find_fractional_mv_step(x,
1431                                          new_mv,
1432                                          &bsi->ref_mv[0]->as_mv,
1433                                          cm->allow_high_precision_mv,
1434                                          x->errorperbit, &cpi->fn_ptr[bsize],
1435                                          cpi->sf.mv.subpel_force_stop,
1436                                          cpi->sf.mv.subpel_iters_per_step,
1437                                          x->nmvjointcost, x->mvcost,
1438                                          &distortion,
1439                                          &x->pred_sse[mbmi->ref_frame[0]],
1440                                          NULL, 0, 0);
1441 
1442             // save motion search result for use in compound prediction
1443             seg_mvs[i][mbmi->ref_frame[0]].as_mv = *new_mv;
1444           }
1445 
1446           if (cpi->sf.adaptive_motion_search)
1447             x->pred_mv[mbmi->ref_frame[0]] = *new_mv;
1448 
1449           // restore src pointers
1450           mi_buf_restore(x, orig_src, orig_pre);
1451         }
1452 
1453         if (has_second_rf) {
1454           if (seg_mvs[i][mbmi->ref_frame[1]].as_int == INVALID_MV ||
1455               seg_mvs[i][mbmi->ref_frame[0]].as_int == INVALID_MV)
1456             continue;
1457         }
1458 
1459         if (has_second_rf && this_mode == NEWMV &&
1460             mbmi->interp_filter == EIGHTTAP) {
1461           // adjust src pointers
1462           mi_buf_shift(x, i);
1463           if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
1464             int rate_mv;
1465             joint_motion_search(cpi, x, bsize, frame_mv[this_mode],
1466                                 mi_row, mi_col, seg_mvs[i],
1467                                 &rate_mv);
1468             seg_mvs[i][mbmi->ref_frame[0]].as_int =
1469                 frame_mv[this_mode][mbmi->ref_frame[0]].as_int;
1470             seg_mvs[i][mbmi->ref_frame[1]].as_int =
1471                 frame_mv[this_mode][mbmi->ref_frame[1]].as_int;
1472           }
1473           // restore src pointers
1474           mi_buf_restore(x, orig_src, orig_pre);
1475         }
1476 
1477         bsi->rdstat[i][mode_idx].brate =
1478             set_and_cost_bmi_mvs(cpi, xd, i, this_mode, mode_mv[this_mode],
1479                                  frame_mv, seg_mvs[i], bsi->ref_mv,
1480                                  x->nmvjointcost, x->mvcost);
1481 
1482         for (ref = 0; ref < 1 + has_second_rf; ++ref) {
1483           bsi->rdstat[i][mode_idx].mvs[ref].as_int =
1484               mode_mv[this_mode][ref].as_int;
1485           if (num_4x4_blocks_wide > 1)
1486             bsi->rdstat[i + 1][mode_idx].mvs[ref].as_int =
1487                 mode_mv[this_mode][ref].as_int;
1488           if (num_4x4_blocks_high > 1)
1489             bsi->rdstat[i + 2][mode_idx].mvs[ref].as_int =
1490                 mode_mv[this_mode][ref].as_int;
1491         }
1492 
1493         // Trap vectors that reach beyond the UMV borders
1494         if (mv_check_bounds(x, &mode_mv[this_mode][0].as_mv) ||
1495             (has_second_rf &&
1496              mv_check_bounds(x, &mode_mv[this_mode][1].as_mv)))
1497           continue;
1498 
1499         if (filter_idx > 0) {
1500           BEST_SEG_INFO *ref_bsi = bsi_buf;
1501           subpelmv = 0;
1502           have_ref = 1;
1503 
1504           for (ref = 0; ref < 1 + has_second_rf; ++ref) {
1505             subpelmv |= mv_has_subpel(&mode_mv[this_mode][ref].as_mv);
1506             have_ref &= mode_mv[this_mode][ref].as_int ==
1507                 ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
1508           }
1509 
1510           if (filter_idx > 1 && !subpelmv && !have_ref) {
1511             ref_bsi = bsi_buf + 1;
1512             have_ref = 1;
1513             for (ref = 0; ref < 1 + has_second_rf; ++ref)
1514               have_ref &= mode_mv[this_mode][ref].as_int ==
1515                   ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
1516           }
1517 
1518           if (!subpelmv && have_ref &&
1519               ref_bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
1520             vpx_memcpy(&bsi->rdstat[i][mode_idx], &ref_bsi->rdstat[i][mode_idx],
1521                        sizeof(SEG_RDSTAT));
1522             if (num_4x4_blocks_wide > 1)
1523               bsi->rdstat[i + 1][mode_idx].eobs =
1524                   ref_bsi->rdstat[i + 1][mode_idx].eobs;
1525             if (num_4x4_blocks_high > 1)
1526               bsi->rdstat[i + 2][mode_idx].eobs =
1527                   ref_bsi->rdstat[i + 2][mode_idx].eobs;
1528 
1529             if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
1530               mode_selected = this_mode;
1531               best_rd = bsi->rdstat[i][mode_idx].brdcost;
1532             }
1533             continue;
1534           }
1535         }
1536 
1537         bsi->rdstat[i][mode_idx].brdcost =
1538             encode_inter_mb_segment(cpi, x,
1539                                     bsi->segment_rd - this_segment_rd, i,
1540                                     &bsi->rdstat[i][mode_idx].byrate,
1541                                     &bsi->rdstat[i][mode_idx].bdist,
1542                                     &bsi->rdstat[i][mode_idx].bsse,
1543                                     bsi->rdstat[i][mode_idx].ta,
1544                                     bsi->rdstat[i][mode_idx].tl,
1545                                     mi_row, mi_col);
1546         if (bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
1547           bsi->rdstat[i][mode_idx].brdcost += RDCOST(x->rdmult, x->rddiv,
1548                                             bsi->rdstat[i][mode_idx].brate, 0);
1549           bsi->rdstat[i][mode_idx].brate += bsi->rdstat[i][mode_idx].byrate;
1550           bsi->rdstat[i][mode_idx].eobs = p->eobs[i];
1551           if (num_4x4_blocks_wide > 1)
1552             bsi->rdstat[i + 1][mode_idx].eobs = p->eobs[i + 1];
1553           if (num_4x4_blocks_high > 1)
1554             bsi->rdstat[i + 2][mode_idx].eobs = p->eobs[i + 2];
1555         }
1556 
1557         if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
1558           mode_selected = this_mode;
1559           best_rd = bsi->rdstat[i][mode_idx].brdcost;
1560         }
1561       } /*for each 4x4 mode*/
1562 
1563       if (best_rd == INT64_MAX) {
1564         int iy, midx;
1565         for (iy = i + 1; iy < 4; ++iy)
1566           for (midx = 0; midx < INTER_MODES; ++midx)
1567             bsi->rdstat[iy][midx].brdcost = INT64_MAX;
1568         bsi->segment_rd = INT64_MAX;
1569         return INT64_MAX;;
1570       }
1571 
1572       mode_idx = INTER_OFFSET(mode_selected);
1573       vpx_memcpy(t_above, bsi->rdstat[i][mode_idx].ta, sizeof(t_above));
1574       vpx_memcpy(t_left, bsi->rdstat[i][mode_idx].tl, sizeof(t_left));
1575 
1576       set_and_cost_bmi_mvs(cpi, xd, i, mode_selected, mode_mv[mode_selected],
1577                            frame_mv, seg_mvs[i], bsi->ref_mv, x->nmvjointcost,
1578                            x->mvcost);
1579 
1580       br += bsi->rdstat[i][mode_idx].brate;
1581       bd += bsi->rdstat[i][mode_idx].bdist;
1582       block_sse += bsi->rdstat[i][mode_idx].bsse;
1583       segmentyrate += bsi->rdstat[i][mode_idx].byrate;
1584       this_segment_rd += bsi->rdstat[i][mode_idx].brdcost;
1585 
1586       if (this_segment_rd > bsi->segment_rd) {
1587         int iy, midx;
1588         for (iy = i + 1; iy < 4; ++iy)
1589           for (midx = 0; midx < INTER_MODES; ++midx)
1590             bsi->rdstat[iy][midx].brdcost = INT64_MAX;
1591         bsi->segment_rd = INT64_MAX;
1592         return INT64_MAX;;
1593       }
1594     }
1595   } /* for each label */
1596 
1597   bsi->r = br;
1598   bsi->d = bd;
1599   bsi->segment_yrate = segmentyrate;
1600   bsi->segment_rd = this_segment_rd;
1601   bsi->sse = block_sse;
1602 
1603   // update the coding decisions
1604   for (k = 0; k < 4; ++k)
1605     bsi->modes[k] = mi->bmi[k].as_mode;
1606 
1607   if (bsi->segment_rd > best_rd)
1608     return INT64_MAX;
1609   /* set it to the best */
1610   for (i = 0; i < 4; i++) {
1611     mode_idx = INTER_OFFSET(bsi->modes[i]);
1612     mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int;
1613     if (has_second_ref(mbmi))
1614       mi->bmi[i].as_mv[1].as_int = bsi->rdstat[i][mode_idx].mvs[1].as_int;
1615     x->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
1616     mi->bmi[i].as_mode = bsi->modes[i];
1617   }
1618 
1619   /*
1620    * used to set mbmi->mv.as_int
1621    */
1622   *returntotrate = bsi->r;
1623   *returndistortion = bsi->d;
1624   *returnyrate = bsi->segment_yrate;
1625   *skippable = vp9_is_skippable_in_plane(x, BLOCK_8X8, 0);
1626   *psse = bsi->sse;
1627   mbmi->mode = bsi->modes[3];
1628 
1629   return bsi->segment_rd;
1630 }
1631 
estimate_ref_frame_costs(const VP9_COMMON * cm,const MACROBLOCKD * xd,int segment_id,unsigned int * ref_costs_single,unsigned int * ref_costs_comp,vp9_prob * comp_mode_p)1632 static void estimate_ref_frame_costs(const VP9_COMMON *cm,
1633                                      const MACROBLOCKD *xd,
1634                                      int segment_id,
1635                                      unsigned int *ref_costs_single,
1636                                      unsigned int *ref_costs_comp,
1637                                      vp9_prob *comp_mode_p) {
1638   int seg_ref_active = vp9_segfeature_active(&cm->seg, segment_id,
1639                                              SEG_LVL_REF_FRAME);
1640   if (seg_ref_active) {
1641     vpx_memset(ref_costs_single, 0, MAX_REF_FRAMES * sizeof(*ref_costs_single));
1642     vpx_memset(ref_costs_comp,   0, MAX_REF_FRAMES * sizeof(*ref_costs_comp));
1643     *comp_mode_p = 128;
1644   } else {
1645     vp9_prob intra_inter_p = vp9_get_intra_inter_prob(cm, xd);
1646     vp9_prob comp_inter_p = 128;
1647 
1648     if (cm->reference_mode == REFERENCE_MODE_SELECT) {
1649       comp_inter_p = vp9_get_reference_mode_prob(cm, xd);
1650       *comp_mode_p = comp_inter_p;
1651     } else {
1652       *comp_mode_p = 128;
1653     }
1654 
1655     ref_costs_single[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
1656 
1657     if (cm->reference_mode != COMPOUND_REFERENCE) {
1658       vp9_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
1659       vp9_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
1660       unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
1661 
1662       if (cm->reference_mode == REFERENCE_MODE_SELECT)
1663         base_cost += vp9_cost_bit(comp_inter_p, 0);
1664 
1665       ref_costs_single[LAST_FRAME] = ref_costs_single[GOLDEN_FRAME] =
1666           ref_costs_single[ALTREF_FRAME] = base_cost;
1667       ref_costs_single[LAST_FRAME]   += vp9_cost_bit(ref_single_p1, 0);
1668       ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
1669       ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
1670       ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
1671       ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
1672     } else {
1673       ref_costs_single[LAST_FRAME]   = 512;
1674       ref_costs_single[GOLDEN_FRAME] = 512;
1675       ref_costs_single[ALTREF_FRAME] = 512;
1676     }
1677     if (cm->reference_mode != SINGLE_REFERENCE) {
1678       vp9_prob ref_comp_p = vp9_get_pred_prob_comp_ref_p(cm, xd);
1679       unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
1680 
1681       if (cm->reference_mode == REFERENCE_MODE_SELECT)
1682         base_cost += vp9_cost_bit(comp_inter_p, 1);
1683 
1684       ref_costs_comp[LAST_FRAME]   = base_cost + vp9_cost_bit(ref_comp_p, 0);
1685       ref_costs_comp[GOLDEN_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 1);
1686     } else {
1687       ref_costs_comp[LAST_FRAME]   = 512;
1688       ref_costs_comp[GOLDEN_FRAME] = 512;
1689     }
1690   }
1691 }
1692 
store_coding_context(MACROBLOCK * x,PICK_MODE_CONTEXT * ctx,int mode_index,int64_t comp_pred_diff[REFERENCE_MODES],const int64_t tx_size_diff[TX_MODES],int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS])1693 static void store_coding_context(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx,
1694                          int mode_index,
1695                          int64_t comp_pred_diff[REFERENCE_MODES],
1696                          const int64_t tx_size_diff[TX_MODES],
1697                          int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS]) {
1698   MACROBLOCKD *const xd = &x->e_mbd;
1699 
1700   // Take a snapshot of the coding context so it can be
1701   // restored if we decide to encode this way
1702   ctx->skip = x->skip;
1703   ctx->best_mode_index = mode_index;
1704   ctx->mic = *xd->mi[0];
1705   ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_REFERENCE];
1706   ctx->comp_pred_diff   = (int)comp_pred_diff[COMPOUND_REFERENCE];
1707   ctx->hybrid_pred_diff = (int)comp_pred_diff[REFERENCE_MODE_SELECT];
1708 
1709   vpx_memcpy(ctx->tx_rd_diff, tx_size_diff, sizeof(ctx->tx_rd_diff));
1710   vpx_memcpy(ctx->best_filter_diff, best_filter_diff,
1711              sizeof(*best_filter_diff) * SWITCHABLE_FILTER_CONTEXTS);
1712 }
1713 
setup_buffer_inter(VP9_COMP * cpi,MACROBLOCK * x,const TileInfo * const tile,MV_REFERENCE_FRAME ref_frame,BLOCK_SIZE block_size,int mi_row,int mi_col,int_mv frame_nearest_mv[MAX_REF_FRAMES],int_mv frame_near_mv[MAX_REF_FRAMES],struct buf_2d yv12_mb[4][MAX_MB_PLANE])1714 static void setup_buffer_inter(VP9_COMP *cpi, MACROBLOCK *x,
1715                                const TileInfo *const tile,
1716                                MV_REFERENCE_FRAME ref_frame,
1717                                BLOCK_SIZE block_size,
1718                                int mi_row, int mi_col,
1719                                int_mv frame_nearest_mv[MAX_REF_FRAMES],
1720                                int_mv frame_near_mv[MAX_REF_FRAMES],
1721                                struct buf_2d yv12_mb[4][MAX_MB_PLANE]) {
1722   const VP9_COMMON *cm = &cpi->common;
1723   const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
1724   MACROBLOCKD *const xd = &x->e_mbd;
1725   MODE_INFO *const mi = xd->mi[0];
1726   int_mv *const candidates = mi->mbmi.ref_mvs[ref_frame];
1727   const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
1728 
1729   // TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this
1730   // use the UV scaling factors.
1731   vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
1732 
1733   // Gets an initial list of candidate vectors from neighbours and orders them
1734   vp9_find_mv_refs(cm, xd, tile, mi, ref_frame, candidates, mi_row, mi_col);
1735 
1736   // Candidate refinement carried out at encoder and decoder
1737   vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
1738                         &frame_nearest_mv[ref_frame],
1739                         &frame_near_mv[ref_frame]);
1740 
1741   // Further refinement that is encode side only to test the top few candidates
1742   // in full and choose the best as the centre point for subsequent searches.
1743   // The current implementation doesn't support scaling.
1744   if (!vp9_is_scaled(sf) && block_size >= BLOCK_8X8)
1745     vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride,
1746                 ref_frame, block_size);
1747 }
1748 
single_motion_search(VP9_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int mi_row,int mi_col,int_mv * tmp_mv,int * rate_mv)1749 static void single_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
1750                                  BLOCK_SIZE bsize,
1751                                  int mi_row, int mi_col,
1752                                  int_mv *tmp_mv, int *rate_mv) {
1753   MACROBLOCKD *xd = &x->e_mbd;
1754   const VP9_COMMON *cm = &cpi->common;
1755   MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
1756   struct buf_2d backup_yv12[MAX_MB_PLANE] = {{0, 0}};
1757   int bestsme = INT_MAX;
1758   int step_param;
1759   int sadpb = x->sadperbit16;
1760   MV mvp_full;
1761   int ref = mbmi->ref_frame[0];
1762   MV ref_mv = mbmi->ref_mvs[ref][0].as_mv;
1763 
1764   int tmp_col_min = x->mv_col_min;
1765   int tmp_col_max = x->mv_col_max;
1766   int tmp_row_min = x->mv_row_min;
1767   int tmp_row_max = x->mv_row_max;
1768 
1769   const YV12_BUFFER_CONFIG *scaled_ref_frame = vp9_get_scaled_ref_frame(cpi,
1770                                                                         ref);
1771 
1772   MV pred_mv[3];
1773   pred_mv[0] = mbmi->ref_mvs[ref][0].as_mv;
1774   pred_mv[1] = mbmi->ref_mvs[ref][1].as_mv;
1775   pred_mv[2] = x->pred_mv[ref];
1776 
1777   if (scaled_ref_frame) {
1778     int i;
1779     // Swap out the reference frame for a version that's been scaled to
1780     // match the resolution of the current frame, allowing the existing
1781     // motion search code to be used without additional modifications.
1782     for (i = 0; i < MAX_MB_PLANE; i++)
1783       backup_yv12[i] = xd->plane[i].pre[0];
1784 
1785     vp9_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
1786   }
1787 
1788   vp9_set_mv_search_range(x, &ref_mv);
1789 
1790   // Work out the size of the first step in the mv step search.
1791   // 0 here is maximum length first step. 1 is MAX >> 1 etc.
1792   if (cpi->sf.mv.auto_mv_step_size && cm->show_frame) {
1793     // Take wtd average of the step_params based on the last frame's
1794     // max mv magnitude and that based on the best ref mvs of the current
1795     // block for the given reference.
1796     step_param = (vp9_init_search_range(x->max_mv_context[ref]) +
1797                     cpi->mv_step_param) / 2;
1798   } else {
1799     step_param = cpi->mv_step_param;
1800   }
1801 
1802   if (cpi->sf.adaptive_motion_search && bsize < BLOCK_64X64 &&
1803       cm->show_frame) {
1804     int boffset = 2 * (b_width_log2(BLOCK_64X64) - MIN(b_height_log2(bsize),
1805                                                        b_width_log2(bsize)));
1806     step_param = MAX(step_param, boffset);
1807   }
1808 
1809   if (cpi->sf.adaptive_motion_search) {
1810     int bwl = b_width_log2(bsize);
1811     int bhl = b_height_log2(bsize);
1812     int i;
1813     int tlevel = x->pred_mv_sad[ref] >> (bwl + bhl + 4);
1814 
1815     if (tlevel < 5)
1816       step_param += 2;
1817 
1818     for (i = LAST_FRAME; i <= ALTREF_FRAME && cm->show_frame; ++i) {
1819       if ((x->pred_mv_sad[ref] >> 3) > x->pred_mv_sad[i]) {
1820         x->pred_mv[ref].row = 0;
1821         x->pred_mv[ref].col = 0;
1822         tmp_mv->as_int = INVALID_MV;
1823 
1824         if (scaled_ref_frame) {
1825           int i;
1826           for (i = 0; i < MAX_MB_PLANE; i++)
1827             xd->plane[i].pre[0] = backup_yv12[i];
1828         }
1829         return;
1830       }
1831     }
1832   }
1833 
1834   mvp_full = pred_mv[x->mv_best_ref_index[ref]];
1835 
1836   mvp_full.col >>= 3;
1837   mvp_full.row >>= 3;
1838 
1839   bestsme = vp9_full_pixel_search(cpi, x, bsize, &mvp_full, step_param, sadpb,
1840                                   &ref_mv, &tmp_mv->as_mv, INT_MAX, 1);
1841 
1842   x->mv_col_min = tmp_col_min;
1843   x->mv_col_max = tmp_col_max;
1844   x->mv_row_min = tmp_row_min;
1845   x->mv_row_max = tmp_row_max;
1846 
1847   if (bestsme < INT_MAX) {
1848     int dis;  /* TODO: use dis in distortion calculation later. */
1849     cpi->find_fractional_mv_step(x, &tmp_mv->as_mv, &ref_mv,
1850                                  cm->allow_high_precision_mv,
1851                                  x->errorperbit,
1852                                  &cpi->fn_ptr[bsize],
1853                                  cpi->sf.mv.subpel_force_stop,
1854                                  cpi->sf.mv.subpel_iters_per_step,
1855                                  x->nmvjointcost, x->mvcost,
1856                                  &dis, &x->pred_sse[ref], NULL, 0, 0);
1857   }
1858   *rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv,
1859                              x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
1860 
1861   if (cpi->sf.adaptive_motion_search && cm->show_frame)
1862     x->pred_mv[ref] = tmp_mv->as_mv;
1863 
1864   if (scaled_ref_frame) {
1865     int i;
1866     for (i = 0; i < MAX_MB_PLANE; i++)
1867       xd->plane[i].pre[0] = backup_yv12[i];
1868   }
1869 }
1870 
joint_motion_search(VP9_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int_mv * frame_mv,int mi_row,int mi_col,int_mv single_newmv[MAX_REF_FRAMES],int * rate_mv)1871 static void joint_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
1872                                 BLOCK_SIZE bsize,
1873                                 int_mv *frame_mv,
1874                                 int mi_row, int mi_col,
1875                                 int_mv single_newmv[MAX_REF_FRAMES],
1876                                 int *rate_mv) {
1877   const int pw = 4 * num_4x4_blocks_wide_lookup[bsize];
1878   const int ph = 4 * num_4x4_blocks_high_lookup[bsize];
1879   MACROBLOCKD *xd = &x->e_mbd;
1880   MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
1881   const int refs[2] = { mbmi->ref_frame[0],
1882                         mbmi->ref_frame[1] < 0 ? 0 : mbmi->ref_frame[1] };
1883   int_mv ref_mv[2];
1884   int ite, ref;
1885   // Prediction buffer from second frame.
1886   uint8_t *second_pred = vpx_memalign(16, pw * ph * sizeof(uint8_t));
1887   const InterpKernel *kernel = vp9_get_interp_kernel(mbmi->interp_filter);
1888 
1889   // Do joint motion search in compound mode to get more accurate mv.
1890   struct buf_2d backup_yv12[2][MAX_MB_PLANE];
1891   struct buf_2d scaled_first_yv12 = xd->plane[0].pre[0];
1892   int last_besterr[2] = {INT_MAX, INT_MAX};
1893   const YV12_BUFFER_CONFIG *const scaled_ref_frame[2] = {
1894     vp9_get_scaled_ref_frame(cpi, mbmi->ref_frame[0]),
1895     vp9_get_scaled_ref_frame(cpi, mbmi->ref_frame[1])
1896   };
1897 
1898   for (ref = 0; ref < 2; ++ref) {
1899     ref_mv[ref] = mbmi->ref_mvs[refs[ref]][0];
1900 
1901     if (scaled_ref_frame[ref]) {
1902       int i;
1903       // Swap out the reference frame for a version that's been scaled to
1904       // match the resolution of the current frame, allowing the existing
1905       // motion search code to be used without additional modifications.
1906       for (i = 0; i < MAX_MB_PLANE; i++)
1907         backup_yv12[ref][i] = xd->plane[i].pre[ref];
1908       vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
1909                            NULL);
1910     }
1911 
1912     frame_mv[refs[ref]].as_int = single_newmv[refs[ref]].as_int;
1913   }
1914 
1915   // Allow joint search multiple times iteratively for each ref frame
1916   // and break out the search loop if it couldn't find better mv.
1917   for (ite = 0; ite < 4; ite++) {
1918     struct buf_2d ref_yv12[2];
1919     int bestsme = INT_MAX;
1920     int sadpb = x->sadperbit16;
1921     MV tmp_mv;
1922     int search_range = 3;
1923 
1924     int tmp_col_min = x->mv_col_min;
1925     int tmp_col_max = x->mv_col_max;
1926     int tmp_row_min = x->mv_row_min;
1927     int tmp_row_max = x->mv_row_max;
1928     int id = ite % 2;
1929 
1930     // Initialized here because of compiler problem in Visual Studio.
1931     ref_yv12[0] = xd->plane[0].pre[0];
1932     ref_yv12[1] = xd->plane[0].pre[1];
1933 
1934     // Get pred block from second frame.
1935     vp9_build_inter_predictor(ref_yv12[!id].buf,
1936                               ref_yv12[!id].stride,
1937                               second_pred, pw,
1938                               &frame_mv[refs[!id]].as_mv,
1939                               &xd->block_refs[!id]->sf,
1940                               pw, ph, 0,
1941                               kernel, MV_PRECISION_Q3,
1942                               mi_col * MI_SIZE, mi_row * MI_SIZE);
1943 
1944     // Compound motion search on first ref frame.
1945     if (id)
1946       xd->plane[0].pre[0] = ref_yv12[id];
1947     vp9_set_mv_search_range(x, &ref_mv[id].as_mv);
1948 
1949     // Use mv result from single mode as mvp.
1950     tmp_mv = frame_mv[refs[id]].as_mv;
1951 
1952     tmp_mv.col >>= 3;
1953     tmp_mv.row >>= 3;
1954 
1955     // Small-range full-pixel motion search
1956     bestsme = vp9_refining_search_8p_c(x, &tmp_mv, sadpb,
1957                                        search_range,
1958                                        &cpi->fn_ptr[bsize],
1959                                        &ref_mv[id].as_mv, second_pred);
1960     if (bestsme < INT_MAX)
1961       bestsme = vp9_get_mvpred_av_var(x, &tmp_mv, &ref_mv[id].as_mv,
1962                                       second_pred, &cpi->fn_ptr[bsize], 1);
1963 
1964     x->mv_col_min = tmp_col_min;
1965     x->mv_col_max = tmp_col_max;
1966     x->mv_row_min = tmp_row_min;
1967     x->mv_row_max = tmp_row_max;
1968 
1969     if (bestsme < INT_MAX) {
1970       int dis; /* TODO: use dis in distortion calculation later. */
1971       unsigned int sse;
1972       bestsme = cpi->find_fractional_mv_step(
1973           x, &tmp_mv,
1974           &ref_mv[id].as_mv,
1975           cpi->common.allow_high_precision_mv,
1976           x->errorperbit,
1977           &cpi->fn_ptr[bsize],
1978           0, cpi->sf.mv.subpel_iters_per_step,
1979           x->nmvjointcost, x->mvcost,
1980           &dis, &sse, second_pred,
1981           pw, ph);
1982     }
1983 
1984     if (id)
1985       xd->plane[0].pre[0] = scaled_first_yv12;
1986 
1987     if (bestsme < last_besterr[id]) {
1988       frame_mv[refs[id]].as_mv = tmp_mv;
1989       last_besterr[id] = bestsme;
1990     } else {
1991       break;
1992     }
1993   }
1994 
1995   *rate_mv = 0;
1996 
1997   for (ref = 0; ref < 2; ++ref) {
1998     if (scaled_ref_frame[ref]) {
1999       // restore the predictor
2000       int i;
2001       for (i = 0; i < MAX_MB_PLANE; i++)
2002         xd->plane[i].pre[ref] = backup_yv12[ref][i];
2003     }
2004 
2005     *rate_mv += vp9_mv_bit_cost(&frame_mv[refs[ref]].as_mv,
2006                                 &mbmi->ref_mvs[refs[ref]][0].as_mv,
2007                                 x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2008   }
2009 
2010   vpx_free(second_pred);
2011 }
2012 
restore_dst_buf(MACROBLOCKD * xd,uint8_t * orig_dst[MAX_MB_PLANE],int orig_dst_stride[MAX_MB_PLANE])2013 static INLINE void restore_dst_buf(MACROBLOCKD *xd,
2014                                    uint8_t *orig_dst[MAX_MB_PLANE],
2015                                    int orig_dst_stride[MAX_MB_PLANE]) {
2016   int i;
2017   for (i = 0; i < MAX_MB_PLANE; i++) {
2018     xd->plane[i].dst.buf = orig_dst[i];
2019     xd->plane[i].dst.stride = orig_dst_stride[i];
2020   }
2021 }
2022 
rd_encode_breakout_test(VP9_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int * rate2,int64_t * distortion,int64_t * distortion_uv,int * disable_skip)2023 static void rd_encode_breakout_test(VP9_COMP *cpi, MACROBLOCK *x,
2024                                     BLOCK_SIZE bsize, int *rate2,
2025                                     int64_t *distortion, int64_t *distortion_uv,
2026                                     int *disable_skip) {
2027   VP9_COMMON *cm = &cpi->common;
2028   MACROBLOCKD *xd = &x->e_mbd;
2029   const BLOCK_SIZE y_size = get_plane_block_size(bsize, &xd->plane[0]);
2030   const BLOCK_SIZE uv_size = get_plane_block_size(bsize, &xd->plane[1]);
2031   unsigned int var, sse;
2032   // Skipping threshold for ac.
2033   unsigned int thresh_ac;
2034   // Skipping threshold for dc
2035   unsigned int thresh_dc;
2036 
2037   var = cpi->fn_ptr[y_size].vf(x->plane[0].src.buf, x->plane[0].src.stride,
2038                                xd->plane[0].dst.buf,
2039                                xd->plane[0].dst.stride, &sse);
2040 
2041   if (x->encode_breakout > 0) {
2042     // Set a maximum for threshold to avoid big PSNR loss in low bitrate
2043     // case. Use extreme low threshold for static frames to limit skipping.
2044     const unsigned int max_thresh = (cpi->allow_encode_breakout ==
2045                                      ENCODE_BREAKOUT_LIMITED) ? 128 : 36000;
2046     // The encode_breakout input
2047     const unsigned int min_thresh =
2048         MIN(((unsigned int)x->encode_breakout << 4), max_thresh);
2049 
2050     // Calculate threshold according to dequant value.
2051     thresh_ac = (xd->plane[0].dequant[1] * xd->plane[0].dequant[1]) / 9;
2052     thresh_ac = clamp(thresh_ac, min_thresh, max_thresh);
2053 
2054     // Adjust threshold according to partition size.
2055     thresh_ac >>= 8 - (b_width_log2(bsize) +
2056         b_height_log2(bsize));
2057     thresh_dc = (xd->plane[0].dequant[0] * xd->plane[0].dequant[0] >> 6);
2058   } else {
2059     thresh_ac = 0;
2060     thresh_dc = 0;
2061   }
2062 
2063   // Y skipping condition checking
2064   if (sse < thresh_ac || sse == 0) {
2065     // dc skipping checking
2066     if ((sse - var) < thresh_dc || sse == var) {
2067       unsigned int sse_u, sse_v;
2068       unsigned int var_u, var_v;
2069 
2070       var_u = cpi->fn_ptr[uv_size].vf(x->plane[1].src.buf,
2071                                       x->plane[1].src.stride,
2072                                       xd->plane[1].dst.buf,
2073                                       xd->plane[1].dst.stride, &sse_u);
2074 
2075       // U skipping condition checking
2076       if ((sse_u * 4 < thresh_ac || sse_u == 0) &&
2077           (sse_u - var_u < thresh_dc || sse_u == var_u)) {
2078         var_v = cpi->fn_ptr[uv_size].vf(x->plane[2].src.buf,
2079                                         x->plane[2].src.stride,
2080                                         xd->plane[2].dst.buf,
2081                                         xd->plane[2].dst.stride, &sse_v);
2082 
2083         // V skipping condition checking
2084         if ((sse_v * 4 < thresh_ac || sse_v == 0) &&
2085             (sse_v - var_v < thresh_dc || sse_v == var_v)) {
2086           x->skip = 1;
2087 
2088           // The cost of skip bit needs to be added.
2089           *rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
2090 
2091           // Scaling factor for SSE from spatial domain to frequency domain
2092           // is 16. Adjust distortion accordingly.
2093           *distortion_uv = (sse_u + sse_v) << 4;
2094           *distortion = (sse << 4) + *distortion_uv;
2095 
2096           *disable_skip = 1;
2097         }
2098       }
2099     }
2100   }
2101 }
2102 
handle_inter_mode(VP9_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int64_t txfm_cache[],int * rate2,int64_t * distortion,int * skippable,int * rate_y,int64_t * distortion_y,int * rate_uv,int64_t * distortion_uv,int * disable_skip,int_mv (* mode_mv)[MAX_REF_FRAMES],int mi_row,int mi_col,int_mv single_newmv[MAX_REF_FRAMES],int64_t * psse,const int64_t ref_best_rd)2103 static int64_t handle_inter_mode(VP9_COMP *cpi, MACROBLOCK *x,
2104                                  BLOCK_SIZE bsize,
2105                                  int64_t txfm_cache[],
2106                                  int *rate2, int64_t *distortion,
2107                                  int *skippable,
2108                                  int *rate_y, int64_t *distortion_y,
2109                                  int *rate_uv, int64_t *distortion_uv,
2110                                  int *disable_skip,
2111                                  int_mv (*mode_mv)[MAX_REF_FRAMES],
2112                                  int mi_row, int mi_col,
2113                                  int_mv single_newmv[MAX_REF_FRAMES],
2114                                  int64_t *psse,
2115                                  const int64_t ref_best_rd) {
2116   VP9_COMMON *cm = &cpi->common;
2117   RD_OPT *rd_opt = &cpi->rd;
2118   MACROBLOCKD *xd = &x->e_mbd;
2119   MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
2120   const int is_comp_pred = has_second_ref(mbmi);
2121   const int this_mode = mbmi->mode;
2122   int_mv *frame_mv = mode_mv[this_mode];
2123   int i;
2124   int refs[2] = { mbmi->ref_frame[0],
2125     (mbmi->ref_frame[1] < 0 ? 0 : mbmi->ref_frame[1]) };
2126   int_mv cur_mv[2];
2127   int64_t this_rd = 0;
2128   DECLARE_ALIGNED_ARRAY(16, uint8_t, tmp_buf, MAX_MB_PLANE * 64 * 64);
2129   int pred_exists = 0;
2130   int intpel_mv;
2131   int64_t rd, best_rd = INT64_MAX;
2132   int best_needs_copy = 0;
2133   uint8_t *orig_dst[MAX_MB_PLANE];
2134   int orig_dst_stride[MAX_MB_PLANE];
2135   int rs = 0;
2136   INTERP_FILTER best_filter = SWITCHABLE;
2137   int skip_txfm[MAX_MB_PLANE] = {0};
2138   int64_t bsse[MAX_MB_PLANE] = {0};
2139 
2140   int bsl = mi_width_log2_lookup[bsize];
2141   int pred_filter_search = cpi->sf.cb_pred_filter_search ?
2142       (((mi_row + mi_col) >> bsl) +
2143        get_chessboard_index(cm->current_video_frame)) & 0x1 : 0;
2144 
2145   if (pred_filter_search) {
2146     INTERP_FILTER af = SWITCHABLE, lf = SWITCHABLE;
2147     if (xd->up_available)
2148       af = xd->mi[-xd->mi_stride]->mbmi.interp_filter;
2149     if (xd->left_available)
2150       lf = xd->mi[-1]->mbmi.interp_filter;
2151 
2152     if ((this_mode != NEWMV) || (af == lf))
2153       best_filter = af;
2154   }
2155 
2156   if (is_comp_pred) {
2157     if (frame_mv[refs[0]].as_int == INVALID_MV ||
2158         frame_mv[refs[1]].as_int == INVALID_MV)
2159       return INT64_MAX;
2160   }
2161 
2162   if (this_mode == NEWMV) {
2163     int rate_mv;
2164     if (is_comp_pred) {
2165       // Initialize mv using single prediction mode result.
2166       frame_mv[refs[0]].as_int = single_newmv[refs[0]].as_int;
2167       frame_mv[refs[1]].as_int = single_newmv[refs[1]].as_int;
2168 
2169       if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
2170         joint_motion_search(cpi, x, bsize, frame_mv,
2171                             mi_row, mi_col, single_newmv, &rate_mv);
2172       } else {
2173         rate_mv  = vp9_mv_bit_cost(&frame_mv[refs[0]].as_mv,
2174                                    &mbmi->ref_mvs[refs[0]][0].as_mv,
2175                                    x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2176         rate_mv += vp9_mv_bit_cost(&frame_mv[refs[1]].as_mv,
2177                                    &mbmi->ref_mvs[refs[1]][0].as_mv,
2178                                    x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2179       }
2180       *rate2 += rate_mv;
2181     } else {
2182       int_mv tmp_mv;
2183       single_motion_search(cpi, x, bsize, mi_row, mi_col,
2184                            &tmp_mv, &rate_mv);
2185       if (tmp_mv.as_int == INVALID_MV)
2186         return INT64_MAX;
2187       *rate2 += rate_mv;
2188       frame_mv[refs[0]].as_int =
2189           xd->mi[0]->bmi[0].as_mv[0].as_int = tmp_mv.as_int;
2190       single_newmv[refs[0]].as_int = tmp_mv.as_int;
2191     }
2192   }
2193 
2194   for (i = 0; i < is_comp_pred + 1; ++i) {
2195     cur_mv[i] = frame_mv[refs[i]];
2196     // Clip "next_nearest" so that it does not extend to far out of image
2197     if (this_mode != NEWMV)
2198       clamp_mv2(&cur_mv[i].as_mv, xd);
2199 
2200     if (mv_check_bounds(x, &cur_mv[i].as_mv))
2201       return INT64_MAX;
2202     mbmi->mv[i].as_int = cur_mv[i].as_int;
2203   }
2204 
2205   // do first prediction into the destination buffer. Do the next
2206   // prediction into a temporary buffer. Then keep track of which one
2207   // of these currently holds the best predictor, and use the other
2208   // one for future predictions. In the end, copy from tmp_buf to
2209   // dst if necessary.
2210   for (i = 0; i < MAX_MB_PLANE; i++) {
2211     orig_dst[i] = xd->plane[i].dst.buf;
2212     orig_dst_stride[i] = xd->plane[i].dst.stride;
2213   }
2214 
2215   /* We don't include the cost of the second reference here, because there
2216    * are only three options: Last/Golden, ARF/Last or Golden/ARF, or in other
2217    * words if you present them in that order, the second one is always known
2218    * if the first is known */
2219   *rate2 += cost_mv_ref(cpi, this_mode, mbmi->mode_context[refs[0]]);
2220 
2221   pred_exists = 0;
2222   // Are all MVs integer pel for Y and UV
2223   intpel_mv = !mv_has_subpel(&mbmi->mv[0].as_mv);
2224   if (is_comp_pred)
2225     intpel_mv &= !mv_has_subpel(&mbmi->mv[1].as_mv);
2226 
2227   // Search for best switchable filter by checking the variance of
2228   // pred error irrespective of whether the filter will be used
2229   rd_opt->mask_filter = 0;
2230   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
2231     rd_opt->filter_cache[i] = INT64_MAX;
2232 
2233   if (cm->interp_filter != BILINEAR) {
2234     if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
2235       best_filter = EIGHTTAP;
2236     } else if (best_filter == SWITCHABLE) {
2237       int newbest;
2238       int tmp_rate_sum = 0;
2239       int64_t tmp_dist_sum = 0;
2240 
2241       for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
2242         int j;
2243         int64_t rs_rd;
2244         mbmi->interp_filter = i;
2245         rs = vp9_get_switchable_rate(cpi);
2246         rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
2247 
2248         if (i > 0 && intpel_mv) {
2249           rd = RDCOST(x->rdmult, x->rddiv, tmp_rate_sum, tmp_dist_sum);
2250           rd_opt->filter_cache[i] = rd;
2251           rd_opt->filter_cache[SWITCHABLE_FILTERS] =
2252               MIN(rd_opt->filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
2253           if (cm->interp_filter == SWITCHABLE)
2254             rd += rs_rd;
2255           rd_opt->mask_filter = MAX(rd_opt->mask_filter, rd);
2256         } else {
2257           int rate_sum = 0;
2258           int64_t dist_sum = 0;
2259           if ((cm->interp_filter == SWITCHABLE &&
2260                (!i || best_needs_copy)) ||
2261               (cm->interp_filter != SWITCHABLE &&
2262                (cm->interp_filter == mbmi->interp_filter ||
2263                 (i == 0 && intpel_mv)))) {
2264             restore_dst_buf(xd, orig_dst, orig_dst_stride);
2265           } else {
2266             for (j = 0; j < MAX_MB_PLANE; j++) {
2267               xd->plane[j].dst.buf = tmp_buf + j * 64 * 64;
2268               xd->plane[j].dst.stride = 64;
2269             }
2270           }
2271           vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
2272           model_rd_for_sb(cpi, bsize, x, xd, &rate_sum, &dist_sum);
2273 
2274           rd = RDCOST(x->rdmult, x->rddiv, rate_sum, dist_sum);
2275           rd_opt->filter_cache[i] = rd;
2276           rd_opt->filter_cache[SWITCHABLE_FILTERS] =
2277               MIN(rd_opt->filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
2278           if (cm->interp_filter == SWITCHABLE)
2279             rd += rs_rd;
2280           rd_opt->mask_filter = MAX(rd_opt->mask_filter, rd);
2281 
2282           if (i == 0 && intpel_mv) {
2283             tmp_rate_sum = rate_sum;
2284             tmp_dist_sum = dist_sum;
2285           }
2286         }
2287 
2288         if (i == 0 && cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
2289           if (rd / 2 > ref_best_rd) {
2290             restore_dst_buf(xd, orig_dst, orig_dst_stride);
2291             return INT64_MAX;
2292           }
2293         }
2294         newbest = i == 0 || rd < best_rd;
2295 
2296         if (newbest) {
2297           best_rd = rd;
2298           best_filter = mbmi->interp_filter;
2299           if (cm->interp_filter == SWITCHABLE && i && !intpel_mv)
2300             best_needs_copy = !best_needs_copy;
2301           vpx_memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
2302           vpx_memcpy(bsse, x->bsse, sizeof(bsse));
2303         }
2304 
2305         if ((cm->interp_filter == SWITCHABLE && newbest) ||
2306             (cm->interp_filter != SWITCHABLE &&
2307              cm->interp_filter == mbmi->interp_filter)) {
2308           pred_exists = 1;
2309         }
2310       }
2311       restore_dst_buf(xd, orig_dst, orig_dst_stride);
2312     }
2313   }
2314   // Set the appropriate filter
2315   mbmi->interp_filter = cm->interp_filter != SWITCHABLE ?
2316       cm->interp_filter : best_filter;
2317   rs = cm->interp_filter == SWITCHABLE ? vp9_get_switchable_rate(cpi) : 0;
2318 
2319   if (pred_exists) {
2320     if (best_needs_copy) {
2321       // again temporarily set the buffers to local memory to prevent a memcpy
2322       for (i = 0; i < MAX_MB_PLANE; i++) {
2323         xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
2324         xd->plane[i].dst.stride = 64;
2325       }
2326     }
2327   } else {
2328     // Handles the special case when a filter that is not in the
2329     // switchable list (ex. bilinear, 6-tap) is indicated at the frame level
2330     vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
2331   }
2332 
2333   if (cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
2334     int tmp_rate;
2335     int64_t tmp_dist;
2336     model_rd_for_sb(cpi, bsize, x, xd, &tmp_rate, &tmp_dist);
2337     rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
2338     // if current pred_error modeled rd is substantially more than the best
2339     // so far, do not bother doing full rd
2340     if (rd / 2 > ref_best_rd) {
2341       restore_dst_buf(xd, orig_dst, orig_dst_stride);
2342       return INT64_MAX;
2343     }
2344   }
2345 
2346   if (cm->interp_filter == SWITCHABLE)
2347     *rate2 += vp9_get_switchable_rate(cpi);
2348 
2349   if (!is_comp_pred) {
2350     if (cpi->allow_encode_breakout)
2351       rd_encode_breakout_test(cpi, x, bsize, rate2, distortion, distortion_uv,
2352                               disable_skip);
2353   }
2354 
2355   vpx_memcpy(x->skip_txfm, skip_txfm, sizeof(skip_txfm));
2356   vpx_memcpy(x->bsse, bsse, sizeof(bsse));
2357 
2358   if (!x->skip) {
2359     int skippable_y, skippable_uv;
2360     int64_t sseuv = INT64_MAX;
2361     int64_t rdcosty = INT64_MAX;
2362 
2363     // Y cost and distortion
2364     inter_super_block_yrd(cpi, x, rate_y, distortion_y, &skippable_y, psse,
2365                           bsize, txfm_cache, ref_best_rd);
2366 
2367     if (*rate_y == INT_MAX) {
2368       *rate2 = INT_MAX;
2369       *distortion = INT64_MAX;
2370       restore_dst_buf(xd, orig_dst, orig_dst_stride);
2371       return INT64_MAX;
2372     }
2373 
2374     *rate2 += *rate_y;
2375     *distortion += *distortion_y;
2376 
2377     rdcosty = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
2378     rdcosty = MIN(rdcosty, RDCOST(x->rdmult, x->rddiv, 0, *psse));
2379 
2380     super_block_uvrd(cpi, x, rate_uv, distortion_uv, &skippable_uv, &sseuv,
2381                      bsize, ref_best_rd - rdcosty);
2382     if (*rate_uv == INT_MAX) {
2383       *rate2 = INT_MAX;
2384       *distortion = INT64_MAX;
2385       restore_dst_buf(xd, orig_dst, orig_dst_stride);
2386       return INT64_MAX;
2387     }
2388 
2389     *psse += sseuv;
2390     *rate2 += *rate_uv;
2391     *distortion += *distortion_uv;
2392     *skippable = skippable_y && skippable_uv;
2393   }
2394 
2395   restore_dst_buf(xd, orig_dst, orig_dst_stride);
2396   return this_rd;  // if 0, this will be re-calculated by caller
2397 }
2398 
vp9_rd_pick_intra_mode_sb(VP9_COMP * cpi,MACROBLOCK * x,int * returnrate,int64_t * returndist,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,int64_t best_rd)2399 void vp9_rd_pick_intra_mode_sb(VP9_COMP *cpi, MACROBLOCK *x,
2400                                int *returnrate, int64_t *returndist,
2401                                BLOCK_SIZE bsize,
2402                                PICK_MODE_CONTEXT *ctx, int64_t best_rd) {
2403   VP9_COMMON *const cm = &cpi->common;
2404   MACROBLOCKD *const xd = &x->e_mbd;
2405   struct macroblockd_plane *const pd = xd->plane;
2406   int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0;
2407   int y_skip = 0, uv_skip = 0;
2408   int64_t dist_y = 0, dist_uv = 0, tx_cache[TX_MODES] = { 0 };
2409   TX_SIZE max_uv_tx_size;
2410   x->skip_encode = 0;
2411   ctx->skip = 0;
2412   xd->mi[0]->mbmi.ref_frame[0] = INTRA_FRAME;
2413 
2414   if (bsize >= BLOCK_8X8) {
2415     if (rd_pick_intra_sby_mode(cpi, x, &rate_y, &rate_y_tokenonly,
2416                                &dist_y, &y_skip, bsize, tx_cache,
2417                                best_rd) >= best_rd) {
2418       *returnrate = INT_MAX;
2419       return;
2420     }
2421     max_uv_tx_size = get_uv_tx_size_impl(xd->mi[0]->mbmi.tx_size, bsize,
2422                                          pd[1].subsampling_x,
2423                                          pd[1].subsampling_y);
2424     rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly,
2425                             &dist_uv, &uv_skip, bsize, max_uv_tx_size);
2426   } else {
2427     y_skip = 0;
2428     if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate_y, &rate_y_tokenonly,
2429                                      &dist_y, best_rd) >= best_rd) {
2430       *returnrate = INT_MAX;
2431       return;
2432     }
2433     max_uv_tx_size = get_uv_tx_size_impl(xd->mi[0]->mbmi.tx_size, bsize,
2434                                          pd[1].subsampling_x,
2435                                          pd[1].subsampling_y);
2436     rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly,
2437                             &dist_uv, &uv_skip, BLOCK_8X8, max_uv_tx_size);
2438   }
2439 
2440   if (y_skip && uv_skip) {
2441     *returnrate = rate_y + rate_uv - rate_y_tokenonly - rate_uv_tokenonly +
2442                   vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
2443     *returndist = dist_y + dist_uv;
2444     vp9_zero(ctx->tx_rd_diff);
2445   } else {
2446     int i;
2447     *returnrate = rate_y + rate_uv + vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
2448     *returndist = dist_y + dist_uv;
2449     if (cpi->sf.tx_size_search_method == USE_FULL_RD)
2450       for (i = 0; i < TX_MODES; i++) {
2451         if (tx_cache[i] < INT64_MAX && tx_cache[cm->tx_mode] < INT64_MAX)
2452           ctx->tx_rd_diff[i] = tx_cache[i] - tx_cache[cm->tx_mode];
2453         else
2454           ctx->tx_rd_diff[i] = 0;
2455       }
2456   }
2457 
2458   ctx->mic = *xd->mi[0];
2459 }
2460 
2461 // Updating rd_thresh_freq_fact[] here means that the different
2462 // partition/block sizes are handled independently based on the best
2463 // choice for the current partition. It may well be better to keep a scaled
2464 // best rd so far value and update rd_thresh_freq_fact based on the mode/size
2465 // combination that wins out.
update_rd_thresh_fact(VP9_COMP * cpi,int bsize,int best_mode_index)2466 static void update_rd_thresh_fact(VP9_COMP *cpi, int bsize,
2467                                   int best_mode_index) {
2468   if (cpi->sf.adaptive_rd_thresh > 0) {
2469     const int top_mode = bsize < BLOCK_8X8 ? MAX_REFS : MAX_MODES;
2470     int mode;
2471     for (mode = 0; mode < top_mode; ++mode) {
2472       int *const fact = &cpi->rd.thresh_freq_fact[bsize][mode];
2473 
2474       if (mode == best_mode_index) {
2475         *fact -= (*fact >> 3);
2476       } else {
2477         *fact = MIN(*fact + RD_THRESH_INC,
2478                     cpi->sf.adaptive_rd_thresh * RD_THRESH_MAX_FACT);
2479       }
2480     }
2481   }
2482 }
2483 
vp9_rd_pick_inter_mode_sb(VP9_COMP * cpi,MACROBLOCK * x,const TileInfo * const tile,int mi_row,int mi_col,int * returnrate,int64_t * returndistortion,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,int64_t best_rd_so_far)2484 int64_t vp9_rd_pick_inter_mode_sb(VP9_COMP *cpi, MACROBLOCK *x,
2485                                   const TileInfo *const tile,
2486                                   int mi_row, int mi_col,
2487                                   int *returnrate,
2488                                   int64_t *returndistortion,
2489                                   BLOCK_SIZE bsize,
2490                                   PICK_MODE_CONTEXT *ctx,
2491                                   int64_t best_rd_so_far) {
2492   VP9_COMMON *const cm = &cpi->common;
2493   RD_OPT *const rd_opt = &cpi->rd;
2494   MACROBLOCKD *const xd = &x->e_mbd;
2495   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
2496   const struct segmentation *const seg = &cm->seg;
2497   struct macroblockd_plane *const pd = xd->plane;
2498   PREDICTION_MODE this_mode;
2499   MV_REFERENCE_FRAME ref_frame, second_ref_frame;
2500   unsigned char segment_id = mbmi->segment_id;
2501   int comp_pred, i;
2502   int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
2503   struct buf_2d yv12_mb[4][MAX_MB_PLANE];
2504   int_mv single_newmv[MAX_REF_FRAMES] = { { 0 } };
2505   static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
2506                                     VP9_ALT_FLAG };
2507   int64_t best_rd = best_rd_so_far;
2508   int64_t best_tx_rd[TX_MODES];
2509   int64_t best_tx_diff[TX_MODES];
2510   int64_t best_pred_diff[REFERENCE_MODES];
2511   int64_t best_pred_rd[REFERENCE_MODES];
2512   int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
2513   int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
2514   MB_MODE_INFO best_mbmode;
2515   int mode_index, best_mode_index = -1;
2516   unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
2517   vp9_prob comp_mode_p;
2518   int64_t best_intra_rd = INT64_MAX;
2519   int64_t best_inter_rd = INT64_MAX;
2520   PREDICTION_MODE best_intra_mode = DC_PRED;
2521   MV_REFERENCE_FRAME best_inter_ref_frame = LAST_FRAME;
2522   int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
2523   int64_t dist_uv[TX_SIZES];
2524   int skip_uv[TX_SIZES];
2525   PREDICTION_MODE mode_uv[TX_SIZES];
2526   int64_t mode_distortions[MB_MODE_COUNT] = {-1};
2527   int intra_cost_penalty = 20 * vp9_dc_quant(cm->base_qindex, cm->y_dc_delta_q);
2528   const int bws = num_8x8_blocks_wide_lookup[bsize] / 2;
2529   const int bhs = num_8x8_blocks_high_lookup[bsize] / 2;
2530   int best_skip2 = 0;
2531   int mode_skip_mask = 0;
2532   int mode_skip_start = cpi->sf.mode_skip_start + 1;
2533   const int *const rd_threshes = rd_opt->threshes[segment_id][bsize];
2534   const int *const rd_thresh_freq_fact = rd_opt->thresh_freq_fact[bsize];
2535   const int mode_search_skip_flags = cpi->sf.mode_search_skip_flags;
2536   const int intra_y_mode_mask =
2537       cpi->sf.intra_y_mode_mask[max_txsize_lookup[bsize]];
2538   int inter_mode_mask = cpi->sf.inter_mode_mask[bsize];
2539   vp9_zero(best_mbmode);
2540   x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
2541 
2542   estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
2543                            &comp_mode_p);
2544 
2545   for (i = 0; i < REFERENCE_MODES; ++i)
2546     best_pred_rd[i] = INT64_MAX;
2547   for (i = 0; i < TX_MODES; i++)
2548     best_tx_rd[i] = INT64_MAX;
2549   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
2550     best_filter_rd[i] = INT64_MAX;
2551   for (i = 0; i < TX_SIZES; i++)
2552     rate_uv_intra[i] = INT_MAX;
2553   for (i = 0; i < MAX_REF_FRAMES; ++i)
2554     x->pred_sse[i] = INT_MAX;
2555 
2556   *returnrate = INT_MAX;
2557 
2558   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2559     x->pred_mv_sad[ref_frame] = INT_MAX;
2560     if (cpi->ref_frame_flags & flag_list[ref_frame]) {
2561       setup_buffer_inter(cpi, x, tile, ref_frame, bsize, mi_row, mi_col,
2562                          frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
2563     }
2564     frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
2565     frame_mv[ZEROMV][ref_frame].as_int = 0;
2566   }
2567 
2568   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2569     // All modes from vp9_mode_order that use this frame as any ref
2570     static const int ref_frame_mask_all[] = {
2571         0x0, 0x123291, 0x25c444, 0x39b722
2572     };
2573     // Fixed mv modes (NEARESTMV, NEARMV, ZEROMV) from vp9_mode_order that use
2574     // this frame as their primary ref
2575     static const int ref_frame_mask_fixedmv[] = {
2576         0x0, 0x121281, 0x24c404, 0x080102
2577     };
2578     if (!(cpi->ref_frame_flags & flag_list[ref_frame])) {
2579       // Skip modes for missing references
2580       mode_skip_mask |= ref_frame_mask_all[ref_frame];
2581     } else if (cpi->sf.reference_masking) {
2582       for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2583         // Skip fixed mv modes for poor references
2584         if ((x->pred_mv_sad[ref_frame] >> 2) > x->pred_mv_sad[i]) {
2585           mode_skip_mask |= ref_frame_mask_fixedmv[ref_frame];
2586           break;
2587         }
2588       }
2589     }
2590     // If the segment reference frame feature is enabled....
2591     // then do nothing if the current ref frame is not allowed..
2592     if (vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
2593         vp9_get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
2594       mode_skip_mask |= ref_frame_mask_all[ref_frame];
2595     }
2596   }
2597 
2598   // Disable this drop out case if the ref frame
2599   // segment level feature is enabled for this segment. This is to
2600   // prevent the possibility that we end up unable to pick any mode.
2601   if (!vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
2602     // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
2603     // unless ARNR filtering is enabled in which case we want
2604     // an unfiltered alternative. We allow near/nearest as well
2605     // because they may result in zero-zero MVs but be cheaper.
2606     if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0)) {
2607       mode_skip_mask =
2608           ~((1 << THR_NEARESTA) | (1 << THR_NEARA) | (1 << THR_ZEROA));
2609       if (frame_mv[NEARMV][ALTREF_FRAME].as_int != 0)
2610         mode_skip_mask |= (1 << THR_NEARA);
2611       if (frame_mv[NEARESTMV][ALTREF_FRAME].as_int != 0)
2612         mode_skip_mask |= (1 << THR_NEARESTA);
2613     }
2614   }
2615 
2616   // TODO(JBB): This is to make up for the fact that we don't have sad
2617   // functions that work when the block size reads outside the umv.  We
2618   // should fix this either by making the motion search just work on
2619   // a representative block in the boundary ( first ) and then implement a
2620   // function that does sads when inside the border..
2621   if ((mi_row + bhs) > cm->mi_rows || (mi_col + bws) > cm->mi_cols) {
2622     const int new_modes_mask =
2623         (1 << THR_NEWMV) | (1 << THR_NEWG) | (1 << THR_NEWA) |
2624         (1 << THR_COMP_NEWLA) | (1 << THR_COMP_NEWGA);
2625     mode_skip_mask |= new_modes_mask;
2626   }
2627 
2628   if (bsize > cpi->sf.max_intra_bsize) {
2629     const int all_intra_modes = (1 << THR_DC) | (1 << THR_TM) |
2630         (1 << THR_H_PRED) | (1 << THR_V_PRED) | (1 << THR_D135_PRED) |
2631         (1 << THR_D207_PRED) | (1 << THR_D153_PRED) | (1 << THR_D63_PRED) |
2632         (1 << THR_D117_PRED) | (1 << THR_D45_PRED);
2633     mode_skip_mask |= all_intra_modes;
2634   }
2635 
2636   for (mode_index = 0; mode_index < MAX_MODES; ++mode_index) {
2637     int mode_excluded = 0;
2638     int64_t this_rd = INT64_MAX;
2639     int disable_skip = 0;
2640     int compmode_cost = 0;
2641     int rate2 = 0, rate_y = 0, rate_uv = 0;
2642     int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
2643     int skippable = 0;
2644     int64_t tx_cache[TX_MODES];
2645     int i;
2646     int this_skip2 = 0;
2647     int64_t total_sse = INT64_MAX;
2648     int early_term = 0;
2649 
2650     // Look at the reference frame of the best mode so far and set the
2651     // skip mask to look at a subset of the remaining modes.
2652     if (mode_index == mode_skip_start && best_mode_index >= 0) {
2653       switch (vp9_mode_order[best_mode_index].ref_frame[0]) {
2654         case INTRA_FRAME:
2655           break;
2656         case LAST_FRAME:
2657           mode_skip_mask |= LAST_FRAME_MODE_MASK;
2658           break;
2659         case GOLDEN_FRAME:
2660           mode_skip_mask |= GOLDEN_FRAME_MODE_MASK;
2661           break;
2662         case ALTREF_FRAME:
2663           mode_skip_mask |= ALT_REF_MODE_MASK;
2664           break;
2665         case NONE:
2666         case MAX_REF_FRAMES:
2667           assert(0 && "Invalid Reference frame");
2668           break;
2669       }
2670     }
2671     if (mode_skip_mask & (1 << mode_index))
2672       continue;
2673 
2674     // Test best rd so far against threshold for trying this mode.
2675     if (rd_less_than_thresh(best_rd, rd_threshes[mode_index],
2676                             rd_thresh_freq_fact[mode_index]))
2677       continue;
2678 
2679     this_mode = vp9_mode_order[mode_index].mode;
2680     ref_frame = vp9_mode_order[mode_index].ref_frame[0];
2681     if (ref_frame != INTRA_FRAME && !(inter_mode_mask & (1 << this_mode)))
2682       continue;
2683     second_ref_frame = vp9_mode_order[mode_index].ref_frame[1];
2684 
2685     if (cpi->sf.motion_field_mode_search) {
2686       const int mi_width  = MIN(num_8x8_blocks_wide_lookup[bsize],
2687                                 tile->mi_col_end - mi_col);
2688       const int mi_height = MIN(num_8x8_blocks_high_lookup[bsize],
2689                                 tile->mi_row_end - mi_row);
2690       const int bsl = mi_width_log2(bsize);
2691       int cb_partition_search_ctrl = (((mi_row + mi_col) >> bsl)
2692           + get_chessboard_index(cm->current_video_frame)) & 0x1;
2693       MB_MODE_INFO *ref_mbmi;
2694       int const_motion = 1;
2695       int skip_ref_frame = !cb_partition_search_ctrl;
2696       MV_REFERENCE_FRAME rf = NONE;
2697       int_mv ref_mv;
2698       ref_mv.as_int = INVALID_MV;
2699 
2700       if ((mi_row - 1) >= tile->mi_row_start) {
2701         ref_mv = xd->mi[-xd->mi_stride]->mbmi.mv[0];
2702         rf = xd->mi[-xd->mi_stride]->mbmi.ref_frame[0];
2703         for (i = 0; i < mi_width; ++i) {
2704           ref_mbmi = &xd->mi[-xd->mi_stride + i]->mbmi;
2705           const_motion &= (ref_mv.as_int == ref_mbmi->mv[0].as_int) &&
2706                           (ref_frame == ref_mbmi->ref_frame[0]);
2707           skip_ref_frame &= (rf == ref_mbmi->ref_frame[0]);
2708         }
2709       }
2710 
2711       if ((mi_col - 1) >= tile->mi_col_start) {
2712         if (ref_mv.as_int == INVALID_MV)
2713           ref_mv = xd->mi[-1]->mbmi.mv[0];
2714         if (rf == NONE)
2715           rf = xd->mi[-1]->mbmi.ref_frame[0];
2716         for (i = 0; i < mi_height; ++i) {
2717           ref_mbmi = &xd->mi[i * xd->mi_stride - 1]->mbmi;
2718           const_motion &= (ref_mv.as_int == ref_mbmi->mv[0].as_int) &&
2719                           (ref_frame == ref_mbmi->ref_frame[0]);
2720           skip_ref_frame &= (rf == ref_mbmi->ref_frame[0]);
2721         }
2722       }
2723 
2724       if (skip_ref_frame && this_mode != NEARESTMV && this_mode != NEWMV)
2725         if (rf > INTRA_FRAME)
2726           if (ref_frame != rf)
2727             continue;
2728 
2729       if (const_motion)
2730         if (this_mode == NEARMV || this_mode == ZEROMV)
2731           continue;
2732     }
2733 
2734     comp_pred = second_ref_frame > INTRA_FRAME;
2735     if (comp_pred) {
2736       if ((mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
2737           best_mode_index >=0 &&
2738           vp9_mode_order[best_mode_index].ref_frame[0] == INTRA_FRAME)
2739         continue;
2740       if ((mode_search_skip_flags & FLAG_SKIP_COMP_REFMISMATCH) &&
2741           ref_frame != best_inter_ref_frame &&
2742           second_ref_frame != best_inter_ref_frame)
2743         continue;
2744       mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
2745     } else {
2746       if (ref_frame != INTRA_FRAME)
2747         mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
2748     }
2749 
2750     if (ref_frame == INTRA_FRAME) {
2751       if (!(intra_y_mode_mask & (1 << this_mode)))
2752         continue;
2753       if (this_mode != DC_PRED) {
2754         // Disable intra modes other than DC_PRED for blocks with low variance
2755         // Threshold for intra skipping based on source variance
2756         // TODO(debargha): Specialize the threshold for super block sizes
2757         const unsigned int skip_intra_var_thresh = 64;
2758         if ((mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
2759             x->source_variance < skip_intra_var_thresh)
2760           continue;
2761         // Only search the oblique modes if the best so far is
2762         // one of the neighboring directional modes
2763         if ((mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
2764             (this_mode >= D45_PRED && this_mode <= TM_PRED)) {
2765           if (best_mode_index >= 0 &&
2766               vp9_mode_order[best_mode_index].ref_frame[0] > INTRA_FRAME)
2767             continue;
2768         }
2769         if (mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
2770           if (conditional_skipintra(this_mode, best_intra_mode))
2771               continue;
2772         }
2773       }
2774     } else {
2775       const MV_REFERENCE_FRAME ref_frames[2] = {ref_frame, second_ref_frame};
2776       if (!check_best_zero_mv(cpi, mbmi->mode_context, frame_mv,
2777                               inter_mode_mask, this_mode, ref_frames))
2778         continue;
2779     }
2780 
2781     mbmi->mode = this_mode;
2782     mbmi->uv_mode = DC_PRED;
2783     mbmi->ref_frame[0] = ref_frame;
2784     mbmi->ref_frame[1] = second_ref_frame;
2785     // Evaluate all sub-pel filters irrespective of whether we can use
2786     // them for this frame.
2787     mbmi->interp_filter = cm->interp_filter == SWITCHABLE ? EIGHTTAP
2788                                                           : cm->interp_filter;
2789     x->skip = 0;
2790     set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
2791 
2792     // Select prediction reference frames.
2793     for (i = 0; i < MAX_MB_PLANE; i++) {
2794       xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
2795       if (comp_pred)
2796         xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
2797     }
2798 
2799     for (i = 0; i < TX_MODES; ++i)
2800       tx_cache[i] = INT64_MAX;
2801 
2802     if (ref_frame == INTRA_FRAME) {
2803       TX_SIZE uv_tx;
2804       intra_super_block_yrd(cpi, x, &rate_y, &distortion_y, &skippable,
2805                             bsize, tx_cache, best_rd);
2806 
2807       if (rate_y == INT_MAX)
2808         continue;
2809 
2810       uv_tx = get_uv_tx_size_impl(mbmi->tx_size, bsize, pd[1].subsampling_x,
2811                                   pd[1].subsampling_y);
2812       if (rate_uv_intra[uv_tx] == INT_MAX) {
2813         choose_intra_uv_mode(cpi, ctx, bsize, uv_tx,
2814                              &rate_uv_intra[uv_tx], &rate_uv_tokenonly[uv_tx],
2815                              &dist_uv[uv_tx], &skip_uv[uv_tx], &mode_uv[uv_tx]);
2816       }
2817 
2818       rate_uv = rate_uv_tokenonly[uv_tx];
2819       distortion_uv = dist_uv[uv_tx];
2820       skippable = skippable && skip_uv[uv_tx];
2821       mbmi->uv_mode = mode_uv[uv_tx];
2822 
2823       rate2 = rate_y + cpi->mbmode_cost[mbmi->mode] + rate_uv_intra[uv_tx];
2824       if (this_mode != DC_PRED && this_mode != TM_PRED)
2825         rate2 += intra_cost_penalty;
2826       distortion2 = distortion_y + distortion_uv;
2827     } else {
2828       this_rd = handle_inter_mode(cpi, x, bsize,
2829                                   tx_cache,
2830                                   &rate2, &distortion2, &skippable,
2831                                   &rate_y, &distortion_y,
2832                                   &rate_uv, &distortion_uv,
2833                                   &disable_skip, frame_mv,
2834                                   mi_row, mi_col,
2835                                   single_newmv, &total_sse, best_rd);
2836       if (this_rd == INT64_MAX)
2837         continue;
2838 
2839       compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
2840 
2841       if (cm->reference_mode == REFERENCE_MODE_SELECT)
2842         rate2 += compmode_cost;
2843     }
2844 
2845     // Estimate the reference frame signaling cost and add it
2846     // to the rolling cost variable.
2847     if (comp_pred) {
2848       rate2 += ref_costs_comp[ref_frame];
2849     } else {
2850       rate2 += ref_costs_single[ref_frame];
2851     }
2852 
2853     if (!disable_skip) {
2854       if (skippable) {
2855         vp9_prob skip_prob = vp9_get_skip_prob(cm, xd);
2856 
2857         // Back out the coefficient coding costs
2858         rate2 -= (rate_y + rate_uv);
2859         // for best yrd calculation
2860         rate_uv = 0;
2861 
2862         // Cost the skip mb case
2863         if (skip_prob) {
2864           int prob_skip_cost = vp9_cost_bit(skip_prob, 1);
2865           rate2 += prob_skip_cost;
2866         }
2867       } else if (ref_frame != INTRA_FRAME && !xd->lossless) {
2868         if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv, distortion2) <
2869             RDCOST(x->rdmult, x->rddiv, 0, total_sse)) {
2870           // Add in the cost of the no skip flag.
2871           rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
2872         } else {
2873           // FIXME(rbultje) make this work for splitmv also
2874           rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
2875           distortion2 = total_sse;
2876           assert(total_sse >= 0);
2877           rate2 -= (rate_y + rate_uv);
2878           rate_y = 0;
2879           rate_uv = 0;
2880           this_skip2 = 1;
2881         }
2882       } else {
2883         // Add in the cost of the no skip flag.
2884         rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
2885       }
2886 
2887       // Calculate the final RD estimate for this mode.
2888       this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
2889     }
2890 
2891     if (ref_frame == INTRA_FRAME) {
2892     // Keep record of best intra rd
2893       if (this_rd < best_intra_rd) {
2894         best_intra_rd = this_rd;
2895         best_intra_mode = mbmi->mode;
2896       }
2897     } else {
2898       // Keep record of best inter rd with single reference
2899       if (!comp_pred && !mode_excluded && this_rd < best_inter_rd) {
2900         best_inter_rd = this_rd;
2901         best_inter_ref_frame = ref_frame;
2902       }
2903     }
2904 
2905     if (!disable_skip && ref_frame == INTRA_FRAME) {
2906       for (i = 0; i < REFERENCE_MODES; ++i)
2907         best_pred_rd[i] = MIN(best_pred_rd[i], this_rd);
2908       for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
2909         best_filter_rd[i] = MIN(best_filter_rd[i], this_rd);
2910     }
2911 
2912     // Store the respective mode distortions for later use.
2913     if (mode_distortions[this_mode] == -1
2914         || distortion2 < mode_distortions[this_mode]) {
2915       mode_distortions[this_mode] = distortion2;
2916     }
2917 
2918     // Did this mode help.. i.e. is it the new best mode
2919     if (this_rd < best_rd || x->skip) {
2920       int max_plane = MAX_MB_PLANE;
2921       if (!mode_excluded) {
2922         // Note index of best mode so far
2923         best_mode_index = mode_index;
2924 
2925         if (ref_frame == INTRA_FRAME) {
2926           /* required for left and above block mv */
2927           mbmi->mv[0].as_int = 0;
2928           max_plane = 1;
2929         }
2930 
2931         *returnrate = rate2;
2932         *returndistortion = distortion2;
2933         best_rd = this_rd;
2934         best_mbmode = *mbmi;
2935         best_skip2 = this_skip2;
2936         if (!x->select_tx_size)
2937           swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
2938         vpx_memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mbmi->tx_size],
2939                    sizeof(uint8_t) * ctx->num_4x4_blk);
2940 
2941         // TODO(debargha): enhance this test with a better distortion prediction
2942         // based on qp, activity mask and history
2943         if ((mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
2944             (mode_index > MIN_EARLY_TERM_INDEX)) {
2945           const int qstep = xd->plane[0].dequant[1];
2946           // TODO(debargha): Enhance this by specializing for each mode_index
2947           int scale = 4;
2948           if (x->source_variance < UINT_MAX) {
2949             const int var_adjust = (x->source_variance < 16);
2950             scale -= var_adjust;
2951           }
2952           if (ref_frame > INTRA_FRAME &&
2953               distortion2 * scale < qstep * qstep) {
2954             early_term = 1;
2955           }
2956         }
2957       }
2958     }
2959 
2960     /* keep record of best compound/single-only prediction */
2961     if (!disable_skip && ref_frame != INTRA_FRAME) {
2962       int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
2963 
2964       if (cm->reference_mode == REFERENCE_MODE_SELECT) {
2965         single_rate = rate2 - compmode_cost;
2966         hybrid_rate = rate2;
2967       } else {
2968         single_rate = rate2;
2969         hybrid_rate = rate2 + compmode_cost;
2970       }
2971 
2972       single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
2973       hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
2974 
2975       if (!comp_pred) {
2976         if (single_rd < best_pred_rd[SINGLE_REFERENCE]) {
2977           best_pred_rd[SINGLE_REFERENCE] = single_rd;
2978         }
2979       } else {
2980         if (single_rd < best_pred_rd[COMPOUND_REFERENCE]) {
2981           best_pred_rd[COMPOUND_REFERENCE] = single_rd;
2982         }
2983       }
2984       if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
2985         best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
2986 
2987       /* keep record of best filter type */
2988       if (!mode_excluded && cm->interp_filter != BILINEAR) {
2989         int64_t ref = rd_opt->filter_cache[cm->interp_filter == SWITCHABLE ?
2990                               SWITCHABLE_FILTERS : cm->interp_filter];
2991 
2992         for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
2993           int64_t adj_rd;
2994           if (ref == INT64_MAX)
2995             adj_rd = 0;
2996           else if (rd_opt->filter_cache[i] == INT64_MAX)
2997             // when early termination is triggered, the encoder does not have
2998             // access to the rate-distortion cost. it only knows that the cost
2999             // should be above the maximum valid value. hence it takes the known
3000             // maximum plus an arbitrary constant as the rate-distortion cost.
3001             adj_rd = rd_opt->mask_filter - ref + 10;
3002           else
3003             adj_rd = rd_opt->filter_cache[i] - ref;
3004 
3005           adj_rd += this_rd;
3006           best_filter_rd[i] = MIN(best_filter_rd[i], adj_rd);
3007         }
3008       }
3009     }
3010 
3011     /* keep record of best txfm size */
3012     if (bsize < BLOCK_32X32) {
3013       if (bsize < BLOCK_16X16)
3014         tx_cache[ALLOW_16X16] = tx_cache[ALLOW_8X8];
3015 
3016       tx_cache[ALLOW_32X32] = tx_cache[ALLOW_16X16];
3017     }
3018     if (!mode_excluded && this_rd != INT64_MAX) {
3019       for (i = 0; i < TX_MODES && tx_cache[i] < INT64_MAX; i++) {
3020         int64_t adj_rd = INT64_MAX;
3021         adj_rd = this_rd + tx_cache[i] - tx_cache[cm->tx_mode];
3022 
3023         if (adj_rd < best_tx_rd[i])
3024           best_tx_rd[i] = adj_rd;
3025       }
3026     }
3027 
3028     if (early_term)
3029       break;
3030 
3031     if (x->skip && !comp_pred)
3032       break;
3033   }
3034 
3035   if (best_mode_index < 0 || best_rd >= best_rd_so_far)
3036     return INT64_MAX;
3037 
3038   // If we used an estimate for the uv intra rd in the loop above...
3039   if (cpi->sf.use_uv_intra_rd_estimate) {
3040     // Do Intra UV best rd mode selection if best mode choice above was intra.
3041     if (vp9_mode_order[best_mode_index].ref_frame[0] == INTRA_FRAME) {
3042       TX_SIZE uv_tx_size;
3043       *mbmi = best_mbmode;
3044       uv_tx_size = get_uv_tx_size(mbmi, &xd->plane[1]);
3045       rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
3046                               &rate_uv_tokenonly[uv_tx_size],
3047                               &dist_uv[uv_tx_size],
3048                               &skip_uv[uv_tx_size],
3049                               bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
3050                               uv_tx_size);
3051     }
3052   }
3053 
3054   assert((cm->interp_filter == SWITCHABLE) ||
3055          (cm->interp_filter == best_mbmode.interp_filter) ||
3056          !is_inter_block(&best_mbmode));
3057 
3058   update_rd_thresh_fact(cpi, bsize, best_mode_index);
3059 
3060   // macroblock modes
3061   *mbmi = best_mbmode;
3062   x->skip |= best_skip2;
3063 
3064   for (i = 0; i < REFERENCE_MODES; ++i) {
3065     if (best_pred_rd[i] == INT64_MAX)
3066       best_pred_diff[i] = INT_MIN;
3067     else
3068       best_pred_diff[i] = best_rd - best_pred_rd[i];
3069   }
3070 
3071   if (!x->skip) {
3072     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
3073       if (best_filter_rd[i] == INT64_MAX)
3074         best_filter_diff[i] = 0;
3075       else
3076         best_filter_diff[i] = best_rd - best_filter_rd[i];
3077     }
3078     if (cm->interp_filter == SWITCHABLE)
3079       assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
3080     for (i = 0; i < TX_MODES; i++) {
3081       if (best_tx_rd[i] == INT64_MAX)
3082         best_tx_diff[i] = 0;
3083       else
3084         best_tx_diff[i] = best_rd - best_tx_rd[i];
3085     }
3086   } else {
3087     vp9_zero(best_filter_diff);
3088     vp9_zero(best_tx_diff);
3089   }
3090 
3091   set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
3092   store_coding_context(x, ctx, best_mode_index,
3093                        best_pred_diff, best_tx_diff, best_filter_diff);
3094 
3095   return best_rd;
3096 }
3097 
vp9_rd_pick_inter_mode_sb_seg_skip(VP9_COMP * cpi,MACROBLOCK * x,int * returnrate,int64_t * returndistortion,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,int64_t best_rd_so_far)3098 int64_t vp9_rd_pick_inter_mode_sb_seg_skip(VP9_COMP *cpi, MACROBLOCK *x,
3099                                            int *returnrate,
3100                                            int64_t *returndistortion,
3101                                            BLOCK_SIZE bsize,
3102                                            PICK_MODE_CONTEXT *ctx,
3103                                            int64_t best_rd_so_far) {
3104   VP9_COMMON *const cm = &cpi->common;
3105   RD_OPT *const rd_opt = &cpi->rd;
3106   MACROBLOCKD *const xd = &x->e_mbd;
3107   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
3108   unsigned char segment_id = mbmi->segment_id;
3109   const int comp_pred = 0;
3110   int i;
3111   int64_t best_tx_diff[TX_MODES];
3112   int64_t best_pred_diff[REFERENCE_MODES];
3113   int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3114   unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3115   vp9_prob comp_mode_p;
3116   INTERP_FILTER best_filter = SWITCHABLE;
3117   int64_t this_rd = INT64_MAX;
3118   int rate2 = 0;
3119   const int64_t distortion2 = 0;
3120 
3121   x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
3122 
3123   estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3124                            &comp_mode_p);
3125 
3126   for (i = 0; i < MAX_REF_FRAMES; ++i)
3127     x->pred_sse[i] = INT_MAX;
3128   for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i)
3129     x->pred_mv_sad[i] = INT_MAX;
3130 
3131   *returnrate = INT_MAX;
3132 
3133   assert(vp9_segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP));
3134 
3135   mbmi->mode = ZEROMV;
3136   mbmi->uv_mode = DC_PRED;
3137   mbmi->ref_frame[0] = LAST_FRAME;
3138   mbmi->ref_frame[1] = NONE;
3139   mbmi->mv[0].as_int = 0;
3140   x->skip = 1;
3141 
3142   // Search for best switchable filter by checking the variance of
3143   // pred error irrespective of whether the filter will be used
3144   rd_opt->mask_filter = 0;
3145   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
3146     rd_opt->filter_cache[i] = INT64_MAX;
3147 
3148   if (cm->interp_filter != BILINEAR) {
3149     best_filter = EIGHTTAP;
3150     if (cm->interp_filter == SWITCHABLE &&
3151         x->source_variance >= cpi->sf.disable_filter_search_var_thresh) {
3152       int rs;
3153       int best_rs = INT_MAX;
3154       for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
3155         mbmi->interp_filter = i;
3156         rs = vp9_get_switchable_rate(cpi);
3157         if (rs < best_rs) {
3158           best_rs = rs;
3159           best_filter = mbmi->interp_filter;
3160         }
3161       }
3162     }
3163   }
3164   // Set the appropriate filter
3165   if (cm->interp_filter == SWITCHABLE) {
3166     mbmi->interp_filter = best_filter;
3167     rate2 += vp9_get_switchable_rate(cpi);
3168   } else {
3169     mbmi->interp_filter = cm->interp_filter;
3170   }
3171 
3172   if (cm->reference_mode == REFERENCE_MODE_SELECT)
3173     rate2 += vp9_cost_bit(comp_mode_p, comp_pred);
3174 
3175   // Estimate the reference frame signaling cost and add it
3176   // to the rolling cost variable.
3177   rate2 += ref_costs_single[LAST_FRAME];
3178   this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3179 
3180   *returnrate = rate2;
3181   *returndistortion = distortion2;
3182 
3183   if (this_rd >= best_rd_so_far)
3184     return INT64_MAX;
3185 
3186   assert((cm->interp_filter == SWITCHABLE) ||
3187          (cm->interp_filter == mbmi->interp_filter));
3188 
3189   update_rd_thresh_fact(cpi, bsize, THR_ZEROMV);
3190 
3191   vp9_zero(best_pred_diff);
3192   vp9_zero(best_filter_diff);
3193   vp9_zero(best_tx_diff);
3194 
3195   if (!x->select_tx_size)
3196     swap_block_ptr(x, ctx, 1, 0, 0, MAX_MB_PLANE);
3197   store_coding_context(x, ctx, THR_ZEROMV,
3198                        best_pred_diff, best_tx_diff, best_filter_diff);
3199 
3200   return this_rd;
3201 }
3202 
vp9_rd_pick_inter_mode_sub8x8(VP9_COMP * cpi,MACROBLOCK * x,const TileInfo * const tile,int mi_row,int mi_col,int * returnrate,int64_t * returndistortion,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,int64_t best_rd_so_far)3203 int64_t vp9_rd_pick_inter_mode_sub8x8(VP9_COMP *cpi, MACROBLOCK *x,
3204                                       const TileInfo *const tile,
3205                                       int mi_row, int mi_col,
3206                                       int *returnrate,
3207                                       int64_t *returndistortion,
3208                                       BLOCK_SIZE bsize,
3209                                       PICK_MODE_CONTEXT *ctx,
3210                                       int64_t best_rd_so_far) {
3211   VP9_COMMON *const cm = &cpi->common;
3212   RD_OPT *const rd_opt = &cpi->rd;
3213   MACROBLOCKD *const xd = &x->e_mbd;
3214   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
3215   const struct segmentation *const seg = &cm->seg;
3216   MV_REFERENCE_FRAME ref_frame, second_ref_frame;
3217   unsigned char segment_id = mbmi->segment_id;
3218   int comp_pred, i;
3219   int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
3220   struct buf_2d yv12_mb[4][MAX_MB_PLANE];
3221   static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
3222                                     VP9_ALT_FLAG };
3223   int64_t best_rd = best_rd_so_far;
3224   int64_t best_yrd = best_rd_so_far;  // FIXME(rbultje) more precise
3225   static const int64_t best_tx_diff[TX_MODES] = { 0 };
3226   int64_t best_pred_diff[REFERENCE_MODES];
3227   int64_t best_pred_rd[REFERENCE_MODES];
3228   int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
3229   int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3230   MB_MODE_INFO best_mbmode;
3231   int ref_index, best_ref_index = 0;
3232   unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3233   vp9_prob comp_mode_p;
3234   int64_t best_inter_rd = INT64_MAX;
3235   MV_REFERENCE_FRAME best_inter_ref_frame = LAST_FRAME;
3236   INTERP_FILTER tmp_best_filter = SWITCHABLE;
3237   int rate_uv_intra, rate_uv_tokenonly;
3238   int64_t dist_uv;
3239   int skip_uv;
3240   PREDICTION_MODE mode_uv = DC_PRED;
3241   int intra_cost_penalty = 20 * vp9_dc_quant(cm->base_qindex, cm->y_dc_delta_q);
3242   int_mv seg_mvs[4][MAX_REF_FRAMES];
3243   b_mode_info best_bmodes[4];
3244   int best_skip2 = 0;
3245   int mode_skip_mask = 0;
3246 
3247   x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
3248   vpx_memset(x->zcoeff_blk[TX_4X4], 0, 4);
3249   vp9_zero(best_mbmode);
3250 
3251   for (i = 0; i < 4; i++) {
3252     int j;
3253     for (j = 0; j < MAX_REF_FRAMES; j++)
3254       seg_mvs[i][j].as_int = INVALID_MV;
3255   }
3256 
3257   estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3258                            &comp_mode_p);
3259 
3260   for (i = 0; i < REFERENCE_MODES; ++i)
3261     best_pred_rd[i] = INT64_MAX;
3262   for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3263     best_filter_rd[i] = INT64_MAX;
3264   rate_uv_intra = INT_MAX;
3265 
3266   *returnrate = INT_MAX;
3267 
3268   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
3269     if (cpi->ref_frame_flags & flag_list[ref_frame]) {
3270       setup_buffer_inter(cpi, x, tile,
3271                              ref_frame, bsize, mi_row, mi_col,
3272                              frame_mv[NEARESTMV], frame_mv[NEARMV],
3273                              yv12_mb);
3274     }
3275     frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
3276     frame_mv[ZEROMV][ref_frame].as_int = 0;
3277   }
3278 
3279   for (ref_index = 0; ref_index < MAX_REFS; ++ref_index) {
3280     int mode_excluded = 0;
3281     int64_t this_rd = INT64_MAX;
3282     int disable_skip = 0;
3283     int compmode_cost = 0;
3284     int rate2 = 0, rate_y = 0, rate_uv = 0;
3285     int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
3286     int skippable = 0;
3287     int i;
3288     int this_skip2 = 0;
3289     int64_t total_sse = INT_MAX;
3290     int early_term = 0;
3291 
3292     ref_frame = vp9_ref_order[ref_index].ref_frame[0];
3293     second_ref_frame = vp9_ref_order[ref_index].ref_frame[1];
3294 
3295     // Look at the reference frame of the best mode so far and set the
3296     // skip mask to look at a subset of the remaining modes.
3297     if (ref_index > 2 && cpi->sf.mode_skip_start < MAX_MODES) {
3298       if (ref_index == 3) {
3299         switch (vp9_ref_order[best_ref_index].ref_frame[0]) {
3300           case INTRA_FRAME:
3301             mode_skip_mask = 0;
3302             break;
3303           case LAST_FRAME:
3304             mode_skip_mask = 0x0010;
3305             break;
3306           case GOLDEN_FRAME:
3307             mode_skip_mask = 0x0008;
3308             break;
3309           case ALTREF_FRAME:
3310             mode_skip_mask = 0x0000;
3311             break;
3312           case NONE:
3313           case MAX_REF_FRAMES:
3314             assert(0 && "Invalid Reference frame");
3315             break;
3316         }
3317       }
3318       if (mode_skip_mask & (1 << ref_index))
3319         continue;
3320     }
3321 
3322     // Test best rd so far against threshold for trying this mode.
3323     if (rd_less_than_thresh(best_rd,
3324                             rd_opt->threshes[segment_id][bsize][ref_index],
3325                             rd_opt->thresh_freq_fact[bsize][ref_index]))
3326       continue;
3327 
3328     if (ref_frame > INTRA_FRAME &&
3329         !(cpi->ref_frame_flags & flag_list[ref_frame])) {
3330       continue;
3331     }
3332 
3333     comp_pred = second_ref_frame > INTRA_FRAME;
3334     if (comp_pred) {
3335       if (!(cpi->ref_frame_flags & flag_list[second_ref_frame]))
3336         continue;
3337       // Do not allow compound prediction if the segment level reference frame
3338       // feature is in use as in this case there can only be one reference.
3339       if (vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
3340         continue;
3341       if ((cpi->sf.mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
3342           vp9_ref_order[best_ref_index].ref_frame[0] == INTRA_FRAME)
3343         continue;
3344       if ((cpi->sf.mode_search_skip_flags & FLAG_SKIP_COMP_REFMISMATCH) &&
3345           ref_frame != best_inter_ref_frame &&
3346           second_ref_frame != best_inter_ref_frame)
3347         continue;
3348     }
3349 
3350     // TODO(jingning, jkoleszar): scaling reference frame not supported for
3351     // sub8x8 blocks.
3352     if (ref_frame > INTRA_FRAME &&
3353         vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf))
3354       continue;
3355 
3356     if (second_ref_frame > INTRA_FRAME &&
3357         vp9_is_scaled(&cm->frame_refs[second_ref_frame - 1].sf))
3358       continue;
3359 
3360     if (comp_pred)
3361       mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
3362     else if (ref_frame != INTRA_FRAME)
3363       mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
3364 
3365     // If the segment reference frame feature is enabled....
3366     // then do nothing if the current ref frame is not allowed..
3367     if (vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
3368         vp9_get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) !=
3369             (int)ref_frame) {
3370       continue;
3371     // Disable this drop out case if the ref frame
3372     // segment level feature is enabled for this segment. This is to
3373     // prevent the possibility that we end up unable to pick any mode.
3374     } else if (!vp9_segfeature_active(seg, segment_id,
3375                                       SEG_LVL_REF_FRAME)) {
3376       // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
3377       // unless ARNR filtering is enabled in which case we want
3378       // an unfiltered alternative. We allow near/nearest as well
3379       // because they may result in zero-zero MVs but be cheaper.
3380       if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
3381         continue;
3382     }
3383 
3384     mbmi->tx_size = TX_4X4;
3385     mbmi->uv_mode = DC_PRED;
3386     mbmi->ref_frame[0] = ref_frame;
3387     mbmi->ref_frame[1] = second_ref_frame;
3388     // Evaluate all sub-pel filters irrespective of whether we can use
3389     // them for this frame.
3390     mbmi->interp_filter = cm->interp_filter == SWITCHABLE ? EIGHTTAP
3391                                                           : cm->interp_filter;
3392     x->skip = 0;
3393     set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
3394 
3395     // Select prediction reference frames.
3396     for (i = 0; i < MAX_MB_PLANE; i++) {
3397       xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
3398       if (comp_pred)
3399         xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
3400     }
3401 
3402     if (ref_frame == INTRA_FRAME) {
3403       int rate;
3404       if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y,
3405                                        &distortion_y, best_rd) >= best_rd)
3406         continue;
3407       rate2 += rate;
3408       rate2 += intra_cost_penalty;
3409       distortion2 += distortion_y;
3410 
3411       if (rate_uv_intra == INT_MAX) {
3412         choose_intra_uv_mode(cpi, ctx, bsize, TX_4X4,
3413                              &rate_uv_intra,
3414                              &rate_uv_tokenonly,
3415                              &dist_uv, &skip_uv,
3416                              &mode_uv);
3417       }
3418       rate2 += rate_uv_intra;
3419       rate_uv = rate_uv_tokenonly;
3420       distortion2 += dist_uv;
3421       distortion_uv = dist_uv;
3422       mbmi->uv_mode = mode_uv;
3423     } else {
3424       int rate;
3425       int64_t distortion;
3426       int64_t this_rd_thresh;
3427       int64_t tmp_rd, tmp_best_rd = INT64_MAX, tmp_best_rdu = INT64_MAX;
3428       int tmp_best_rate = INT_MAX, tmp_best_ratey = INT_MAX;
3429       int64_t tmp_best_distortion = INT_MAX, tmp_best_sse, uv_sse;
3430       int tmp_best_skippable = 0;
3431       int switchable_filter_index;
3432       int_mv *second_ref = comp_pred ?
3433                              &mbmi->ref_mvs[second_ref_frame][0] : NULL;
3434       b_mode_info tmp_best_bmodes[16];
3435       MB_MODE_INFO tmp_best_mbmode;
3436       BEST_SEG_INFO bsi[SWITCHABLE_FILTERS];
3437       int pred_exists = 0;
3438       int uv_skippable;
3439 
3440       this_rd_thresh = (ref_frame == LAST_FRAME) ?
3441           rd_opt->threshes[segment_id][bsize][THR_LAST] :
3442           rd_opt->threshes[segment_id][bsize][THR_ALTR];
3443       this_rd_thresh = (ref_frame == GOLDEN_FRAME) ?
3444       rd_opt->threshes[segment_id][bsize][THR_GOLD] : this_rd_thresh;
3445       rd_opt->mask_filter = 0;
3446       for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
3447         rd_opt->filter_cache[i] = INT64_MAX;
3448 
3449       if (cm->interp_filter != BILINEAR) {
3450         tmp_best_filter = EIGHTTAP;
3451         if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
3452           tmp_best_filter = EIGHTTAP;
3453         } else if (cpi->sf.adaptive_pred_interp_filter == 1 &&
3454                    ctx->pred_interp_filter < SWITCHABLE) {
3455           tmp_best_filter = ctx->pred_interp_filter;
3456         } else if (cpi->sf.adaptive_pred_interp_filter == 2) {
3457           tmp_best_filter = ctx->pred_interp_filter < SWITCHABLE ?
3458                               ctx->pred_interp_filter : 0;
3459         } else {
3460           for (switchable_filter_index = 0;
3461                switchable_filter_index < SWITCHABLE_FILTERS;
3462                ++switchable_filter_index) {
3463             int newbest, rs;
3464             int64_t rs_rd;
3465             mbmi->interp_filter = switchable_filter_index;
3466             tmp_rd = rd_pick_best_sub8x8_mode(cpi, x, tile,
3467                                               &mbmi->ref_mvs[ref_frame][0],
3468                                               second_ref, best_yrd, &rate,
3469                                               &rate_y, &distortion,
3470                                               &skippable, &total_sse,
3471                                               (int) this_rd_thresh, seg_mvs,
3472                                               bsi, switchable_filter_index,
3473                                               mi_row, mi_col);
3474 
3475             if (tmp_rd == INT64_MAX)
3476               continue;
3477             rs = vp9_get_switchable_rate(cpi);
3478             rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
3479             rd_opt->filter_cache[switchable_filter_index] = tmp_rd;
3480             rd_opt->filter_cache[SWITCHABLE_FILTERS] =
3481                 MIN(rd_opt->filter_cache[SWITCHABLE_FILTERS],
3482                     tmp_rd + rs_rd);
3483             if (cm->interp_filter == SWITCHABLE)
3484               tmp_rd += rs_rd;
3485 
3486             rd_opt->mask_filter = MAX(rd_opt->mask_filter, tmp_rd);
3487 
3488             newbest = (tmp_rd < tmp_best_rd);
3489             if (newbest) {
3490               tmp_best_filter = mbmi->interp_filter;
3491               tmp_best_rd = tmp_rd;
3492             }
3493             if ((newbest && cm->interp_filter == SWITCHABLE) ||
3494                 (mbmi->interp_filter == cm->interp_filter &&
3495                  cm->interp_filter != SWITCHABLE)) {
3496               tmp_best_rdu = tmp_rd;
3497               tmp_best_rate = rate;
3498               tmp_best_ratey = rate_y;
3499               tmp_best_distortion = distortion;
3500               tmp_best_sse = total_sse;
3501               tmp_best_skippable = skippable;
3502               tmp_best_mbmode = *mbmi;
3503               for (i = 0; i < 4; i++) {
3504                 tmp_best_bmodes[i] = xd->mi[0]->bmi[i];
3505                 x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
3506               }
3507               pred_exists = 1;
3508               if (switchable_filter_index == 0 &&
3509                   cpi->sf.use_rd_breakout &&
3510                   best_rd < INT64_MAX) {
3511                 if (tmp_best_rdu / 2 > best_rd) {
3512                   // skip searching the other filters if the first is
3513                   // already substantially larger than the best so far
3514                   tmp_best_filter = mbmi->interp_filter;
3515                   tmp_best_rdu = INT64_MAX;
3516                   break;
3517                 }
3518               }
3519             }
3520           }  // switchable_filter_index loop
3521         }
3522       }
3523 
3524       if (tmp_best_rdu == INT64_MAX && pred_exists)
3525         continue;
3526 
3527       mbmi->interp_filter = (cm->interp_filter == SWITCHABLE ?
3528                              tmp_best_filter : cm->interp_filter);
3529       if (!pred_exists) {
3530         // Handles the special case when a filter that is not in the
3531         // switchable list (bilinear, 6-tap) is indicated at the frame level
3532         tmp_rd = rd_pick_best_sub8x8_mode(cpi, x, tile,
3533                                           &mbmi->ref_mvs[ref_frame][0],
3534                                           second_ref, best_yrd, &rate, &rate_y,
3535                                           &distortion, &skippable, &total_sse,
3536                                           (int) this_rd_thresh, seg_mvs, bsi, 0,
3537                                           mi_row, mi_col);
3538         if (tmp_rd == INT64_MAX)
3539           continue;
3540       } else {
3541         total_sse = tmp_best_sse;
3542         rate = tmp_best_rate;
3543         rate_y = tmp_best_ratey;
3544         distortion = tmp_best_distortion;
3545         skippable = tmp_best_skippable;
3546         *mbmi = tmp_best_mbmode;
3547         for (i = 0; i < 4; i++)
3548           xd->mi[0]->bmi[i] = tmp_best_bmodes[i];
3549       }
3550 
3551       rate2 += rate;
3552       distortion2 += distortion;
3553 
3554       if (cm->interp_filter == SWITCHABLE)
3555         rate2 += vp9_get_switchable_rate(cpi);
3556 
3557       if (!mode_excluded)
3558         mode_excluded = comp_pred ? cm->reference_mode == SINGLE_REFERENCE
3559                                   : cm->reference_mode == COMPOUND_REFERENCE;
3560 
3561       compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
3562 
3563       tmp_best_rdu = best_rd -
3564           MIN(RDCOST(x->rdmult, x->rddiv, rate2, distortion2),
3565               RDCOST(x->rdmult, x->rddiv, 0, total_sse));
3566 
3567       if (tmp_best_rdu > 0) {
3568         // If even the 'Y' rd value of split is higher than best so far
3569         // then dont bother looking at UV
3570         vp9_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col,
3571                                         BLOCK_8X8);
3572         super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
3573                          &uv_sse, BLOCK_8X8, tmp_best_rdu);
3574         if (rate_uv == INT_MAX)
3575           continue;
3576         rate2 += rate_uv;
3577         distortion2 += distortion_uv;
3578         skippable = skippable && uv_skippable;
3579         total_sse += uv_sse;
3580       }
3581     }
3582 
3583     if (cm->reference_mode == REFERENCE_MODE_SELECT)
3584       rate2 += compmode_cost;
3585 
3586     // Estimate the reference frame signaling cost and add it
3587     // to the rolling cost variable.
3588     if (second_ref_frame > INTRA_FRAME) {
3589       rate2 += ref_costs_comp[ref_frame];
3590     } else {
3591       rate2 += ref_costs_single[ref_frame];
3592     }
3593 
3594     if (!disable_skip) {
3595       // Skip is never coded at the segment level for sub8x8 blocks and instead
3596       // always coded in the bitstream at the mode info level.
3597 
3598       if (ref_frame != INTRA_FRAME && !xd->lossless) {
3599         if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv, distortion2) <
3600             RDCOST(x->rdmult, x->rddiv, 0, total_sse)) {
3601           // Add in the cost of the no skip flag.
3602           rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
3603         } else {
3604           // FIXME(rbultje) make this work for splitmv also
3605           rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
3606           distortion2 = total_sse;
3607           assert(total_sse >= 0);
3608           rate2 -= (rate_y + rate_uv);
3609           rate_y = 0;
3610           rate_uv = 0;
3611           this_skip2 = 1;
3612         }
3613       } else {
3614         // Add in the cost of the no skip flag.
3615         rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
3616       }
3617 
3618       // Calculate the final RD estimate for this mode.
3619       this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3620     }
3621 
3622     // Keep record of best inter rd with single reference
3623     if (is_inter_block(mbmi) &&
3624         !has_second_ref(mbmi) &&
3625         !mode_excluded &&
3626         this_rd < best_inter_rd) {
3627       best_inter_rd = this_rd;
3628       best_inter_ref_frame = ref_frame;
3629     }
3630 
3631     if (!disable_skip && ref_frame == INTRA_FRAME) {
3632       for (i = 0; i < REFERENCE_MODES; ++i)
3633         best_pred_rd[i] = MIN(best_pred_rd[i], this_rd);
3634       for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3635         best_filter_rd[i] = MIN(best_filter_rd[i], this_rd);
3636     }
3637 
3638     // Did this mode help.. i.e. is it the new best mode
3639     if (this_rd < best_rd || x->skip) {
3640       if (!mode_excluded) {
3641         int max_plane = MAX_MB_PLANE;
3642         // Note index of best mode so far
3643         best_ref_index = ref_index;
3644 
3645         if (ref_frame == INTRA_FRAME) {
3646           /* required for left and above block mv */
3647           mbmi->mv[0].as_int = 0;
3648           max_plane = 1;
3649         }
3650 
3651         *returnrate = rate2;
3652         *returndistortion = distortion2;
3653         best_rd = this_rd;
3654         best_yrd = best_rd -
3655                    RDCOST(x->rdmult, x->rddiv, rate_uv, distortion_uv);
3656         best_mbmode = *mbmi;
3657         best_skip2 = this_skip2;
3658         if (!x->select_tx_size)
3659           swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
3660         vpx_memcpy(ctx->zcoeff_blk, x->zcoeff_blk[TX_4X4],
3661                    sizeof(uint8_t) * ctx->num_4x4_blk);
3662 
3663         for (i = 0; i < 4; i++)
3664           best_bmodes[i] = xd->mi[0]->bmi[i];
3665 
3666         // TODO(debargha): enhance this test with a better distortion prediction
3667         // based on qp, activity mask and history
3668         if ((cpi->sf.mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
3669             (ref_index > MIN_EARLY_TERM_INDEX)) {
3670           const int qstep = xd->plane[0].dequant[1];
3671           // TODO(debargha): Enhance this by specializing for each mode_index
3672           int scale = 4;
3673           if (x->source_variance < UINT_MAX) {
3674             const int var_adjust = (x->source_variance < 16);
3675             scale -= var_adjust;
3676           }
3677           if (ref_frame > INTRA_FRAME &&
3678               distortion2 * scale < qstep * qstep) {
3679             early_term = 1;
3680           }
3681         }
3682       }
3683     }
3684 
3685     /* keep record of best compound/single-only prediction */
3686     if (!disable_skip && ref_frame != INTRA_FRAME) {
3687       int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
3688 
3689       if (cm->reference_mode == REFERENCE_MODE_SELECT) {
3690         single_rate = rate2 - compmode_cost;
3691         hybrid_rate = rate2;
3692       } else {
3693         single_rate = rate2;
3694         hybrid_rate = rate2 + compmode_cost;
3695       }
3696 
3697       single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
3698       hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
3699 
3700       if (!comp_pred && single_rd < best_pred_rd[SINGLE_REFERENCE]) {
3701         best_pred_rd[SINGLE_REFERENCE] = single_rd;
3702       } else if (comp_pred && single_rd < best_pred_rd[COMPOUND_REFERENCE]) {
3703         best_pred_rd[COMPOUND_REFERENCE] = single_rd;
3704       }
3705       if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
3706         best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
3707     }
3708 
3709     /* keep record of best filter type */
3710     if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
3711         cm->interp_filter != BILINEAR) {
3712       int64_t ref = rd_opt->filter_cache[cm->interp_filter == SWITCHABLE ?
3713                               SWITCHABLE_FILTERS : cm->interp_filter];
3714       int64_t adj_rd;
3715       for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
3716         if (ref == INT64_MAX)
3717           adj_rd = 0;
3718         else if (rd_opt->filter_cache[i] == INT64_MAX)
3719           // when early termination is triggered, the encoder does not have
3720           // access to the rate-distortion cost. it only knows that the cost
3721           // should be above the maximum valid value. hence it takes the known
3722           // maximum plus an arbitrary constant as the rate-distortion cost.
3723           adj_rd = rd_opt->mask_filter - ref + 10;
3724         else
3725           adj_rd = rd_opt->filter_cache[i] - ref;
3726 
3727         adj_rd += this_rd;
3728         best_filter_rd[i] = MIN(best_filter_rd[i], adj_rd);
3729       }
3730     }
3731 
3732     if (early_term)
3733       break;
3734 
3735     if (x->skip && !comp_pred)
3736       break;
3737   }
3738 
3739   if (best_rd >= best_rd_so_far)
3740     return INT64_MAX;
3741 
3742   // If we used an estimate for the uv intra rd in the loop above...
3743   if (cpi->sf.use_uv_intra_rd_estimate) {
3744     // Do Intra UV best rd mode selection if best mode choice above was intra.
3745     if (vp9_ref_order[best_ref_index].ref_frame[0] == INTRA_FRAME) {
3746       *mbmi = best_mbmode;
3747       rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra,
3748                               &rate_uv_tokenonly,
3749                               &dist_uv,
3750                               &skip_uv,
3751                               BLOCK_8X8, TX_4X4);
3752     }
3753   }
3754 
3755   if (best_rd == INT64_MAX) {
3756     *returnrate = INT_MAX;
3757     *returndistortion = INT64_MAX;
3758     return best_rd;
3759   }
3760 
3761   assert((cm->interp_filter == SWITCHABLE) ||
3762          (cm->interp_filter == best_mbmode.interp_filter) ||
3763          !is_inter_block(&best_mbmode));
3764 
3765   update_rd_thresh_fact(cpi, bsize, best_ref_index);
3766 
3767   // macroblock modes
3768   *mbmi = best_mbmode;
3769   x->skip |= best_skip2;
3770   if (!is_inter_block(&best_mbmode)) {
3771     for (i = 0; i < 4; i++)
3772       xd->mi[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
3773   } else {
3774     for (i = 0; i < 4; ++i)
3775       vpx_memcpy(&xd->mi[0]->bmi[i], &best_bmodes[i], sizeof(b_mode_info));
3776 
3777     mbmi->mv[0].as_int = xd->mi[0]->bmi[3].as_mv[0].as_int;
3778     mbmi->mv[1].as_int = xd->mi[0]->bmi[3].as_mv[1].as_int;
3779   }
3780 
3781   for (i = 0; i < REFERENCE_MODES; ++i) {
3782     if (best_pred_rd[i] == INT64_MAX)
3783       best_pred_diff[i] = INT_MIN;
3784     else
3785       best_pred_diff[i] = best_rd - best_pred_rd[i];
3786   }
3787 
3788   if (!x->skip) {
3789     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
3790       if (best_filter_rd[i] == INT64_MAX)
3791         best_filter_diff[i] = 0;
3792       else
3793         best_filter_diff[i] = best_rd - best_filter_rd[i];
3794     }
3795     if (cm->interp_filter == SWITCHABLE)
3796       assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
3797   } else {
3798     vp9_zero(best_filter_diff);
3799   }
3800 
3801   set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
3802   store_coding_context(x, ctx, best_ref_index,
3803                        best_pred_diff, best_tx_diff, best_filter_diff);
3804 
3805   return best_rd;
3806 }
3807