Coverage Report

Created: 2026-10-28 08:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvpx/vp9/encoder/vp9_rdopt.c
Line
Count
Source
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
#include "./vpx_dsp_rtcd.h"
16
17
#include "vpx_dsp/vpx_dsp_common.h"
18
#include "vpx_mem/vpx_mem.h"
19
#include "vpx_ports/mem.h"
20
#include "vpx_ports/system_state.h"
21
22
#include "vp9/common/vp9_common.h"
23
#include "vp9/common/vp9_entropy.h"
24
#include "vp9/common/vp9_entropymode.h"
25
#include "vp9/common/vp9_idct.h"
26
#include "vp9/common/vp9_mvref_common.h"
27
#include "vp9/common/vp9_pred_common.h"
28
#include "vp9/common/vp9_quant_common.h"
29
#include "vp9/common/vp9_reconinter.h"
30
#include "vp9/common/vp9_reconintra.h"
31
#include "vp9/common/vp9_scan.h"
32
#include "vp9/common/vp9_seg_common.h"
33
34
#if !CONFIG_REALTIME_ONLY
35
#include "vp9/encoder/vp9_aq_variance.h"
36
#endif
37
#include "vp9/encoder/vp9_cost.h"
38
#include "vp9/encoder/vp9_encodemb.h"
39
#include "vp9/encoder/vp9_encodemv.h"
40
#include "vp9/encoder/vp9_encoder.h"
41
#include "vp9/encoder/vp9_mcomp.h"
42
#include "vp9/encoder/vp9_quantize.h"
43
#include "vp9/encoder/vp9_ratectrl.h"
44
#include "vp9/encoder/vp9_rd.h"
45
#include "vp9/encoder/vp9_rdopt.h"
46
47
#define LAST_FRAME_MODE_MASK \
48
261k
  ((1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME) | (1 << INTRA_FRAME))
49
#define GOLDEN_FRAME_MODE_MASK \
50
104k
  ((1 << LAST_FRAME) | (1 << ALTREF_FRAME) | (1 << INTRA_FRAME))
51
#define ALT_REF_MODE_MASK \
52
25.8k
  ((1 << LAST_FRAME) | (1 << GOLDEN_FRAME) | (1 << INTRA_FRAME))
53
54
4.34M
#define SECOND_REF_FRAME_MASK ((1 << ALTREF_FRAME) | 0x01)
55
56
0
#define MIN_EARLY_TERM_INDEX 3
57
#define NEW_MV_DISCOUNT_FACTOR 8
58
59
typedef struct {
60
  PREDICTION_MODE mode;
61
  MV_REFERENCE_FRAME ref_frame[2];
62
} MODE_DEFINITION;
63
64
typedef struct {
65
  MV_REFERENCE_FRAME ref_frame[2];
66
} REF_DEFINITION;
67
68
struct rdcost_block_args {
69
  const VP9_COMP *cpi;
70
  MACROBLOCK *x;
71
  ENTROPY_CONTEXT t_above[16];
72
  ENTROPY_CONTEXT t_left[16];
73
  int this_rate;
74
  int64_t this_dist;
75
  int64_t this_sse;
76
  int64_t this_rd;
77
  int64_t best_rd;
78
  int exit_early;
79
  int use_fast_coef_costing;
80
  const ScanOrder *so;
81
  uint8_t skippable;
82
  struct buf_2d *this_recon;
83
};
84
85
27.5M
#define LAST_NEW_MV_INDEX 6
86
87
#if !CONFIG_REALTIME_ONLY
88
static const MODE_DEFINITION vp9_mode_order[MAX_MODES] = {
89
  { NEARESTMV, { LAST_FRAME, NO_REF_FRAME } },
90
  { NEARESTMV, { ALTREF_FRAME, NO_REF_FRAME } },
91
  { NEARESTMV, { GOLDEN_FRAME, NO_REF_FRAME } },
92
93
  { DC_PRED, { INTRA_FRAME, NO_REF_FRAME } },
94
95
  { NEWMV, { LAST_FRAME, NO_REF_FRAME } },
96
  { NEWMV, { ALTREF_FRAME, NO_REF_FRAME } },
97
  { NEWMV, { GOLDEN_FRAME, NO_REF_FRAME } },
98
99
  { NEARMV, { LAST_FRAME, NO_REF_FRAME } },
100
  { NEARMV, { ALTREF_FRAME, NO_REF_FRAME } },
101
  { NEARMV, { GOLDEN_FRAME, NO_REF_FRAME } },
102
103
  { ZEROMV, { LAST_FRAME, NO_REF_FRAME } },
104
  { ZEROMV, { GOLDEN_FRAME, NO_REF_FRAME } },
105
  { ZEROMV, { ALTREF_FRAME, NO_REF_FRAME } },
106
107
  { NEARESTMV, { LAST_FRAME, ALTREF_FRAME } },
108
  { NEARESTMV, { GOLDEN_FRAME, ALTREF_FRAME } },
109
110
  { TM_PRED, { INTRA_FRAME, NO_REF_FRAME } },
111
112
  { NEARMV, { LAST_FRAME, ALTREF_FRAME } },
113
  { NEWMV, { LAST_FRAME, ALTREF_FRAME } },
114
  { NEARMV, { GOLDEN_FRAME, ALTREF_FRAME } },
115
  { NEWMV, { GOLDEN_FRAME, ALTREF_FRAME } },
116
117
  { ZEROMV, { LAST_FRAME, ALTREF_FRAME } },
118
  { ZEROMV, { GOLDEN_FRAME, ALTREF_FRAME } },
119
120
  { H_PRED, { INTRA_FRAME, NO_REF_FRAME } },
121
  { V_PRED, { INTRA_FRAME, NO_REF_FRAME } },
122
  { D135_PRED, { INTRA_FRAME, NO_REF_FRAME } },
123
  { D207_PRED, { INTRA_FRAME, NO_REF_FRAME } },
124
  { D153_PRED, { INTRA_FRAME, NO_REF_FRAME } },
125
  { D63_PRED, { INTRA_FRAME, NO_REF_FRAME } },
126
  { D117_PRED, { INTRA_FRAME, NO_REF_FRAME } },
127
  { D45_PRED, { INTRA_FRAME, NO_REF_FRAME } },
128
};
129
130
static const REF_DEFINITION vp9_ref_order[MAX_REFS] = {
131
  { { LAST_FRAME, NO_REF_FRAME } },   { { GOLDEN_FRAME, NO_REF_FRAME } },
132
  { { ALTREF_FRAME, NO_REF_FRAME } }, { { LAST_FRAME, ALTREF_FRAME } },
133
  { { GOLDEN_FRAME, ALTREF_FRAME } }, { { INTRA_FRAME, NO_REF_FRAME } },
134
};
135
#endif  // !CONFIG_REALTIME_ONLY
136
137
static void swap_block_ptr(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx, int m, int n,
138
8.24M
                           int min_plane, int max_plane) {
139
8.24M
  int i;
140
141
25.0M
  for (i = min_plane; i < max_plane; ++i) {
142
16.7M
    struct macroblock_plane *const p = &x->plane[i];
143
16.7M
    struct macroblockd_plane *const pd = &x->e_mbd.plane[i];
144
145
16.7M
    p->coeff = ctx->coeff_pbuf[i][m];
146
16.7M
    p->qcoeff = ctx->qcoeff_pbuf[i][m];
147
16.7M
    pd->dqcoeff = ctx->dqcoeff_pbuf[i][m];
148
16.7M
    p->eobs = ctx->eobs_pbuf[i][m];
149
150
16.7M
    ctx->coeff_pbuf[i][m] = ctx->coeff_pbuf[i][n];
151
16.7M
    ctx->qcoeff_pbuf[i][m] = ctx->qcoeff_pbuf[i][n];
152
16.7M
    ctx->dqcoeff_pbuf[i][m] = ctx->dqcoeff_pbuf[i][n];
153
16.7M
    ctx->eobs_pbuf[i][m] = ctx->eobs_pbuf[i][n];
154
155
16.7M
    ctx->coeff_pbuf[i][n] = p->coeff;
156
16.7M
    ctx->qcoeff_pbuf[i][n] = p->qcoeff;
157
16.7M
    ctx->dqcoeff_pbuf[i][n] = pd->dqcoeff;
158
16.7M
    ctx->eobs_pbuf[i][n] = p->eobs;
159
16.7M
  }
160
8.24M
}
161
162
#if !CONFIG_REALTIME_ONLY
163
// Planewise build inter prediction and compute rdcost with early termination
164
// option
165
static int build_inter_pred_model_rd_earlyterm(
166
    VP9_COMP *cpi, int mi_row, int mi_col, BLOCK_SIZE bsize, MACROBLOCK *x,
167
    MACROBLOCKD *xd, int *out_rate_sum, int64_t *out_dist_sum,
168
    int *skip_txfm_sb, int64_t *skip_sse_sb, int do_earlyterm,
169
25.8M
    int64_t best_rd) {
170
  // Note our transform coeffs are 8 times an orthogonal transform.
171
  // Hence quantizer step is also 8 times. To get effective quantizer
172
  // we need to divide by 8 before sending to modeling function.
173
25.8M
  int i;
174
25.8M
  int64_t rate_sum = 0;
175
25.8M
  int64_t dist_sum = 0;
176
25.8M
  const int ref = xd->mi[0]->ref_frame[0];
177
25.8M
  unsigned int sse;
178
25.8M
  unsigned int var = 0;
179
25.8M
  int64_t total_sse = 0;
180
25.8M
  int skip_flag = 1;
181
25.8M
  const int shift = 6;
182
25.8M
  const int dequant_shift =
183
25.8M
#if CONFIG_VP9_HIGHBITDEPTH
184
25.8M
      (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd - 5 :
185
25.8M
#endif  // CONFIG_VP9_HIGHBITDEPTH
186
25.8M
                                                    3;
187
188
25.8M
  x->pred_sse[ref] = 0;
189
190
  // Build prediction signal, compute stats and RD cost on per-plane basis
191
101M
  for (i = 0; i < MAX_MB_PLANE; ++i) {
192
76.9M
    struct macroblock_plane *const p = &x->plane[i];
193
76.9M
    struct macroblockd_plane *const pd = &xd->plane[i];
194
76.9M
    const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
195
76.9M
    const TX_SIZE max_tx_size = max_txsize_lookup[bs];
196
76.9M
    const BLOCK_SIZE unit_size = txsize_to_bsize[max_tx_size];
197
76.9M
    const int64_t dc_thr = p->quant_thred[0] >> shift;
198
76.9M
    const int64_t ac_thr = p->quant_thred[1] >> shift;
199
76.9M
    unsigned int sum_sse = 0;
200
    // The low thresholds are used to measure if the prediction errors are
201
    // low enough so that we can skip the mode search.
202
76.9M
    const int64_t low_dc_thr = VPXMIN(50, dc_thr >> 2);
203
76.9M
    const int64_t low_ac_thr = VPXMIN(80, ac_thr >> 2);
204
76.9M
    int bw = 1 << (b_width_log2_lookup[bs] - b_width_log2_lookup[unit_size]);
205
76.9M
    int bh = 1 << (b_height_log2_lookup[bs] - b_width_log2_lookup[unit_size]);
206
76.9M
    int idx, idy;
207
76.9M
    int lw = b_width_log2_lookup[unit_size] + 2;
208
76.9M
    int lh = b_height_log2_lookup[unit_size] + 2;
209
76.9M
    unsigned int qstep;
210
76.9M
    unsigned int nlog2;
211
76.9M
    int64_t dist = 0;
212
213
    // Build inter predictor
214
76.9M
    vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, i);
215
216
    // Compute useful stats
217
168M
    for (idy = 0; idy < bh; ++idy) {
218
196M
      for (idx = 0; idx < bw; ++idx) {
219
105M
        uint8_t *src = p->src.buf + (idy * p->src.stride << lh) + (idx << lw);
220
105M
        uint8_t *dst = pd->dst.buf + (idy * pd->dst.stride << lh) + (idx << lh);
221
105M
        int block_idx = (idy << 1) + idx;
222
105M
        int low_err_skip = 0;
223
224
105M
        var = cpi->fn_ptr[unit_size].vf(src, p->src.stride, dst, pd->dst.stride,
225
105M
                                        &sse);
226
105M
        x->bsse[(i << 2) + block_idx] = sse;
227
105M
        sum_sse += sse;
228
229
105M
        x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_NONE;
230
105M
        if (!x->select_tx_size) {
231
          // Check if all ac coefficients can be quantized to zero.
232
76.2M
          if (var < ac_thr || var == 0) {
233
10.4M
            x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_ONLY;
234
235
            // Check if dc coefficient can be quantized to zero.
236
10.4M
            if (sse - var < dc_thr || sse == var) {
237
8.33M
              x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_DC;
238
239
8.33M
              if (!sse || (var < low_ac_thr && sse - var < low_dc_thr))
240
4.25M
                low_err_skip = 1;
241
8.33M
            }
242
10.4M
          }
243
76.2M
        }
244
245
105M
        if (skip_flag && !low_err_skip) skip_flag = 0;
246
247
105M
        if (i == 0) x->pred_sse[ref] += sse;
248
105M
      }
249
91.0M
    }
250
251
76.9M
    total_sse += sum_sse;
252
76.9M
    qstep = pd->dequant[1] >> dequant_shift;
253
76.9M
    nlog2 = num_pels_log2_lookup[bs];
254
255
    // Fast approximate the modelling function.
256
76.9M
    if (cpi->sf.simple_model_rd_from_var) {
257
0
      int64_t rate;
258
0
      if (qstep < 120)
259
0
        rate = ((int64_t)sum_sse * (280 - qstep)) >> (16 - VP9_PROB_COST_SHIFT);
260
0
      else
261
0
        rate = 0;
262
0
      dist = ((int64_t)sum_sse * qstep) >> 8;
263
0
      rate_sum += rate;
264
76.9M
    } else {
265
76.9M
      int rate;
266
76.9M
      vp9_model_rd_from_var_lapndz(sum_sse, nlog2, qstep, &rate, &dist);
267
76.9M
      rate_sum += rate;
268
76.9M
    }
269
76.9M
    dist_sum += dist;
270
76.9M
    if (do_earlyterm) {
271
17.8M
      if (RDCOST(x->rdmult, x->rddiv, rate_sum,
272
17.8M
                 dist_sum << VP9_DIST_SCALE_LOG2) >= best_rd)
273
1.80M
        return 1;
274
17.8M
    }
275
76.9M
  }
276
24.0M
  *skip_txfm_sb = skip_flag;
277
24.0M
  *skip_sse_sb = total_sse << VP9_DIST_SCALE_LOG2;
278
24.0M
  *out_rate_sum = (int)rate_sum;
279
24.0M
  *out_dist_sum = dist_sum << VP9_DIST_SCALE_LOG2;
280
281
24.0M
  return 0;
282
25.8M
}
283
#endif  // !CONFIG_REALTIME_ONLY
284
285
#if CONFIG_VP9_HIGHBITDEPTH
286
int64_t vp9_highbd_block_error_c(const tran_low_t *coeff,
287
                                 const tran_low_t *dqcoeff, intptr_t block_size,
288
0
                                 int64_t *ssz, int bd) {
289
0
  int i;
290
0
  int64_t error = 0, sqcoeff = 0;
291
0
  int shift = 2 * (bd - 8);
292
0
  int rounding = shift > 0 ? 1 << (shift - 1) : 0;
293
294
0
  for (i = 0; i < block_size; i++) {
295
0
    const int64_t diff = coeff[i] - dqcoeff[i];
296
0
    error += diff * diff;
297
0
    sqcoeff += (int64_t)coeff[i] * (int64_t)coeff[i];
298
0
  }
299
0
  assert(error >= 0 && sqcoeff >= 0);
300
0
  error = (error + rounding) >> shift;
301
0
  sqcoeff = (sqcoeff + rounding) >> shift;
302
303
0
  *ssz = sqcoeff;
304
0
  return error;
305
0
}
306
307
static int64_t vp9_highbd_block_error_dispatch(const tran_low_t *coeff,
308
                                               const tran_low_t *dqcoeff,
309
                                               intptr_t block_size,
310
267M
                                               int64_t *ssz, int bd) {
311
267M
  if (bd == 8) {
312
264M
    return vp9_block_error(coeff, dqcoeff, block_size, ssz);
313
264M
  } else {
314
2.78M
    return vp9_highbd_block_error(coeff, dqcoeff, block_size, ssz, bd);
315
2.78M
  }
316
267M
}
317
#endif  // CONFIG_VP9_HIGHBITDEPTH
318
319
int64_t vp9_block_error_c(const tran_low_t *coeff, const tran_low_t *dqcoeff,
320
0
                          intptr_t block_size, int64_t *ssz) {
321
0
  int i;
322
0
  int64_t error = 0, sqcoeff = 0;
323
324
0
  for (i = 0; i < block_size; i++) {
325
0
    const int diff = coeff[i] - dqcoeff[i];
326
0
    error += diff * diff;
327
0
    sqcoeff += coeff[i] * coeff[i];
328
0
  }
329
330
0
  *ssz = sqcoeff;
331
0
  return error;
332
0
}
333
334
int64_t vp9_block_error_fp_c(const tran_low_t *coeff, const tran_low_t *dqcoeff,
335
0
                             int block_size) {
336
0
  int i;
337
0
  int64_t error = 0;
338
339
0
  for (i = 0; i < block_size; i++) {
340
0
    const int diff = coeff[i] - dqcoeff[i];
341
0
    error += diff * diff;
342
0
  }
343
344
0
  return error;
345
0
}
346
347
/* The trailing '0' is a terminator which is used inside cost_coeffs() to
348
 * decide whether to include cost of a trailing EOB node or not (i.e. we
349
 * can skip this if the last coefficient in this transform block, e.g. the
350
 * 16th coefficient in a 4x4 block or the 64th coefficient in a 8x8 block,
351
 * were non-zero). */
352
static const int16_t band_counts[TX_SIZES][8] = {
353
  { 1, 2, 3, 4, 3, 16 - 13, 0 },
354
  { 1, 2, 3, 4, 11, 64 - 21, 0 },
355
  { 1, 2, 3, 4, 11, 256 - 21, 0 },
356
  { 1, 2, 3, 4, 11, 1024 - 21, 0 },
357
};
358
static int cost_coeffs(MACROBLOCK *x, int plane, int block, TX_SIZE tx_size,
359
                       int pt, const int16_t *scan, const int16_t *nb,
360
521M
                       int use_fast_coef_costing) {
361
521M
  MACROBLOCKD *const xd = &x->e_mbd;
362
521M
  MODE_INFO *mi = xd->mi[0];
363
521M
  const struct macroblock_plane *p = &x->plane[plane];
364
521M
  const PLANE_TYPE type = get_plane_type(plane);
365
521M
  const int16_t *band_count = &band_counts[tx_size][1];
366
521M
  const int eob = p->eobs[block];
367
521M
  const tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
368
521M
  unsigned int (*token_costs)[2][COEFF_CONTEXTS][ENTROPY_TOKENS] =
369
521M
      x->token_costs[tx_size][type][is_inter_block(mi)];
370
521M
  uint8_t token_cache[32 * 32];
371
521M
  int cost;
372
521M
#if CONFIG_VP9_HIGHBITDEPTH
373
521M
  const uint16_t *cat6_high_cost = vp9_get_high_cost_table(xd->bd);
374
#else
375
  const uint16_t *cat6_high_cost = vp9_get_high_cost_table(8);
376
#endif
377
378
  // Check for consistency of tx_size with mode info
379
521M
  assert(type == PLANE_TYPE_Y
380
521M
             ? mi->tx_size == tx_size
381
521M
             : get_uv_tx_size(mi, &xd->plane[plane]) == tx_size);
382
383
521M
  if (eob == 0) {
384
    // single eob token
385
111M
    cost = token_costs[0][0][pt][EOB_TOKEN];
386
409M
  } else {
387
409M
    if (use_fast_coef_costing) {
388
280M
      int band_left = *band_count++;
389
280M
      int c;
390
391
      // dc token
392
280M
      int v = qcoeff[0];
393
280M
      int16_t prev_t;
394
280M
      cost = vp9_get_token_cost(v, &prev_t, cat6_high_cost);
395
280M
      cost += (*token_costs)[0][pt][prev_t];
396
397
280M
      token_cache[0] = vp9_pt_energy_class[prev_t];
398
280M
      ++token_costs;
399
400
      // ac tokens
401
9.20G
      for (c = 1; c < eob; c++) {
402
8.91G
        const int rc = scan[c];
403
8.91G
        int16_t t;
404
405
8.91G
        v = qcoeff[rc];
406
8.91G
        cost += vp9_get_token_cost(v, &t, cat6_high_cost);
407
8.91G
        cost += (*token_costs)[!prev_t][!prev_t][t];
408
8.91G
        prev_t = t;
409
8.91G
        if (!--band_left) {
410
1.07G
          band_left = *band_count++;
411
1.07G
          ++token_costs;
412
1.07G
        }
413
8.91G
      }
414
415
      // eob token
416
280M
      if (band_left) cost += (*token_costs)[0][!prev_t][EOB_TOKEN];
417
418
280M
    } else {  // !use_fast_coef_costing
419
129M
      int band_left = *band_count++;
420
129M
      int c;
421
422
      // dc token
423
129M
      int v = qcoeff[0];
424
129M
      int16_t tok;
425
129M
      unsigned int (*tok_cost_ptr)[COEFF_CONTEXTS][ENTROPY_TOKENS];
426
129M
      cost = vp9_get_token_cost(v, &tok, cat6_high_cost);
427
129M
      cost += (*token_costs)[0][pt][tok];
428
429
129M
      token_cache[0] = vp9_pt_energy_class[tok];
430
129M
      ++token_costs;
431
432
129M
      tok_cost_ptr = &((*token_costs)[!tok]);
433
434
      // ac tokens
435
3.48G
      for (c = 1; c < eob; c++) {
436
3.35G
        const int rc = scan[c];
437
438
3.35G
        v = qcoeff[rc];
439
3.35G
        cost += vp9_get_token_cost(v, &tok, cat6_high_cost);
440
3.35G
        pt = get_coef_context(nb, token_cache, c);
441
3.35G
        cost += (*tok_cost_ptr)[pt][tok];
442
3.35G
        token_cache[rc] = vp9_pt_energy_class[tok];
443
3.35G
        if (!--band_left) {
444
505M
          band_left = *band_count++;
445
505M
          ++token_costs;
446
505M
        }
447
3.35G
        tok_cost_ptr = &((*token_costs)[!tok]);
448
3.35G
      }
449
450
      // eob token
451
129M
      if (band_left) {
452
55.9M
        pt = get_coef_context(nb, token_cache, c);
453
55.9M
        cost += (*token_costs)[0][pt][EOB_TOKEN];
454
55.9M
      }
455
129M
    }
456
409M
  }
457
458
521M
  return cost;
459
521M
}
460
461
// Copy all visible 4x4s in the transform block.
462
static void copy_block_visible(const MACROBLOCKD *xd,
463
                               const struct macroblockd_plane *const pd,
464
                               const uint8_t *src, const int src_stride,
465
                               uint8_t *dst, const int dst_stride, int blk_row,
466
                               int blk_col, const BLOCK_SIZE plane_bsize,
467
0
                               const BLOCK_SIZE tx_bsize) {
468
0
  const int plane_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
469
0
  const int plane_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
470
0
  const int tx_4x4_w = num_4x4_blocks_wide_lookup[tx_bsize];
471
0
  const int tx_4x4_h = num_4x4_blocks_high_lookup[tx_bsize];
472
0
  int b4x4s_to_right_edge = num_4x4_to_edge(plane_4x4_w, xd->mb_to_right_edge,
473
0
                                            pd->subsampling_x, blk_col);
474
0
  int b4x4s_to_bottom_edge = num_4x4_to_edge(plane_4x4_h, xd->mb_to_bottom_edge,
475
0
                                             pd->subsampling_y, blk_row);
476
0
  const int is_highbd = xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH;
477
0
  if (tx_bsize == BLOCK_4X4 ||
478
0
      (b4x4s_to_right_edge >= tx_4x4_w && b4x4s_to_bottom_edge >= tx_4x4_h)) {
479
0
    const int w = tx_4x4_w << 2;
480
0
    const int h = tx_4x4_h << 2;
481
0
#if CONFIG_VP9_HIGHBITDEPTH
482
0
    if (is_highbd) {
483
0
      vpx_highbd_convolve_copy(CONVERT_TO_SHORTPTR(src), src_stride,
484
0
                               CONVERT_TO_SHORTPTR(dst), dst_stride, NULL, 0, 0,
485
0
                               0, 0, w, h, xd->bd);
486
0
    } else {
487
0
#endif
488
0
      vpx_convolve_copy(src, src_stride, dst, dst_stride, NULL, 0, 0, 0, 0, w,
489
0
                        h);
490
0
#if CONFIG_VP9_HIGHBITDEPTH
491
0
    }
492
0
#endif
493
0
  } else {
494
0
    int r, c;
495
0
    int max_r = VPXMIN(b4x4s_to_bottom_edge, tx_4x4_h);
496
0
    int max_c = VPXMIN(b4x4s_to_right_edge, tx_4x4_w);
497
    // if we are in the unrestricted motion border.
498
0
    for (r = 0; r < max_r; ++r) {
499
      // Skip visiting the sub blocks that are wholly within the UMV.
500
0
      for (c = 0; c < max_c; ++c) {
501
0
        const uint8_t *src_ptr = src + r * src_stride * 4 + c * 4;
502
0
        uint8_t *dst_ptr = dst + r * dst_stride * 4 + c * 4;
503
0
#if CONFIG_VP9_HIGHBITDEPTH
504
0
        if (is_highbd) {
505
0
          vpx_highbd_convolve_copy(CONVERT_TO_SHORTPTR(src_ptr), src_stride,
506
0
                                   CONVERT_TO_SHORTPTR(dst_ptr), dst_stride,
507
0
                                   NULL, 0, 0, 0, 0, 4, 4, xd->bd);
508
0
        } else {
509
0
#endif
510
0
          vpx_convolve_copy(src_ptr, src_stride, dst_ptr, dst_stride, NULL, 0,
511
0
                            0, 0, 0, 4, 4);
512
0
#if CONFIG_VP9_HIGHBITDEPTH
513
0
        }
514
0
#endif
515
0
      }
516
0
    }
517
0
  }
518
0
  (void)is_highbd;
519
0
}
520
521
// Compute the pixel domain sum square error on all visible 4x4s in the
522
// transform block.
523
static unsigned pixel_sse(const VP9_COMP *const cpi, const MACROBLOCKD *xd,
524
                          const struct macroblockd_plane *const pd,
525
                          const uint8_t *src, const int src_stride,
526
                          const uint8_t *dst, const int dst_stride, int blk_row,
527
                          int blk_col, const BLOCK_SIZE plane_bsize,
528
132M
                          const BLOCK_SIZE tx_bsize) {
529
132M
  unsigned int sse = 0;
530
132M
  const int plane_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
531
132M
  const int plane_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
532
132M
  const int tx_4x4_w = num_4x4_blocks_wide_lookup[tx_bsize];
533
132M
  const int tx_4x4_h = num_4x4_blocks_high_lookup[tx_bsize];
534
132M
  int b4x4s_to_right_edge = num_4x4_to_edge(plane_4x4_w, xd->mb_to_right_edge,
535
132M
                                            pd->subsampling_x, blk_col);
536
132M
  int b4x4s_to_bottom_edge = num_4x4_to_edge(plane_4x4_h, xd->mb_to_bottom_edge,
537
132M
                                             pd->subsampling_y, blk_row);
538
132M
  if (tx_bsize == BLOCK_4X4 ||
539
131M
      (b4x4s_to_right_edge >= tx_4x4_w && b4x4s_to_bottom_edge >= tx_4x4_h)) {
540
131M
    cpi->fn_ptr[tx_bsize].vf(src, src_stride, dst, dst_stride, &sse);
541
131M
  } else {
542
1.37M
    const vpx_variance_fn_t vf_4x4 = cpi->fn_ptr[BLOCK_4X4].vf;
543
1.37M
    int r, c;
544
1.37M
    unsigned this_sse = 0;
545
1.37M
    int max_r = VPXMIN(b4x4s_to_bottom_edge, tx_4x4_h);
546
1.37M
    int max_c = VPXMIN(b4x4s_to_right_edge, tx_4x4_w);
547
1.37M
    sse = 0;
548
    // if we are in the unrestricted motion border.
549
5.56M
    for (r = 0; r < max_r; ++r) {
550
      // Skip visiting the sub blocks that are wholly within the UMV.
551
20.8M
      for (c = 0; c < max_c; ++c) {
552
16.6M
        vf_4x4(src + r * src_stride * 4 + c * 4, src_stride,
553
16.6M
               dst + r * dst_stride * 4 + c * 4, dst_stride, &this_sse);
554
16.6M
        sse += this_sse;
555
16.6M
      }
556
4.19M
    }
557
1.37M
  }
558
132M
  return sse;
559
132M
}
560
561
static void dist_block(const VP9_COMP *cpi, MACROBLOCK *x, int plane,
562
                       BLOCK_SIZE plane_bsize, int block, int blk_row,
563
                       int blk_col, TX_SIZE tx_size, int64_t *out_dist,
564
                       int64_t *out_sse, struct buf_2d *out_recon,
565
277M
                       int sse_calc_done) {
566
277M
  MACROBLOCKD *const xd = &x->e_mbd;
567
277M
  const struct macroblock_plane *const p = &x->plane[plane];
568
277M
  const struct macroblockd_plane *const pd = &xd->plane[plane];
569
277M
  const int eob = p->eobs[block];
570
571
277M
  if (!out_recon && x->block_tx_domain && eob) {
572
212M
    const int ss_txfrm_size = tx_size << 1;
573
212M
    int64_t this_sse;
574
212M
    const int shift = tx_size == TX_32X32 ? 0 : 2;
575
212M
    const tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
576
212M
    const tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
577
212M
#if CONFIG_VP9_HIGHBITDEPTH
578
212M
    const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
579
212M
    *out_dist = vp9_highbd_block_error_dispatch(
580
212M
                    coeff, dqcoeff, 16 << ss_txfrm_size, &this_sse, bd) >>
581
212M
                shift;
582
#else
583
    *out_dist =
584
        vp9_block_error(coeff, dqcoeff, 16 << ss_txfrm_size, &this_sse) >>
585
        shift;
586
#endif  // CONFIG_VP9_HIGHBITDEPTH
587
212M
    *out_sse = this_sse >> shift;
588
589
212M
    if (x->skip_encode && !is_inter_block(xd->mi[0])) {
590
      // TODO(jingning): tune the model to better capture the distortion.
591
0
      const int64_t mean_quant_error =
592
0
          (pd->dequant[1] * pd->dequant[1] * (1 << ss_txfrm_size)) >>
593
0
#if CONFIG_VP9_HIGHBITDEPTH
594
0
          (shift + 2 + (bd - 8) * 2);
595
#else
596
          (shift + 2);
597
#endif  // CONFIG_VP9_HIGHBITDEPTH
598
0
      *out_dist += (mean_quant_error >> 4);
599
0
      *out_sse += mean_quant_error;
600
0
    }
601
212M
  } else {
602
64.2M
    const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
603
64.2M
    const int bs = 4 * num_4x4_blocks_wide_lookup[tx_bsize];
604
64.2M
    const int src_stride = p->src.stride;
605
64.2M
    const int dst_stride = pd->dst.stride;
606
64.2M
    const int src_idx = 4 * (blk_row * src_stride + blk_col);
607
64.2M
    const int dst_idx = 4 * (blk_row * dst_stride + blk_col);
608
64.2M
    const uint8_t *src = &p->src.buf[src_idx];
609
64.2M
    const uint8_t *dst = &pd->dst.buf[dst_idx];
610
64.2M
    uint8_t *out_recon_ptr = 0;
611
612
64.2M
    const tran_low_t *dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
613
64.2M
    unsigned int tmp;
614
615
64.2M
    if (sse_calc_done) {
616
0
      tmp = (unsigned int)(*out_sse);
617
64.2M
    } else {
618
64.2M
      tmp = pixel_sse(cpi, xd, pd, src, src_stride, dst, dst_stride, blk_row,
619
64.2M
                      blk_col, plane_bsize, tx_bsize);
620
64.2M
    }
621
64.2M
    *out_sse = (int64_t)tmp * 16;
622
64.2M
    if (out_recon) {
623
0
      const int out_recon_idx = 4 * (blk_row * out_recon->stride + blk_col);
624
0
      out_recon_ptr = &out_recon->buf[out_recon_idx];
625
0
      copy_block_visible(xd, pd, dst, dst_stride, out_recon_ptr,
626
0
                         out_recon->stride, blk_row, blk_col, plane_bsize,
627
0
                         tx_bsize);
628
0
    }
629
630
64.2M
    if (eob) {
631
9.86M
#if CONFIG_VP9_HIGHBITDEPTH
632
9.86M
      DECLARE_ALIGNED(16, uint16_t, recon16[1024]);
633
9.86M
      uint8_t *recon = (uint8_t *)recon16;
634
#else
635
      DECLARE_ALIGNED(16, uint8_t, recon[1024]);
636
#endif  // CONFIG_VP9_HIGHBITDEPTH
637
638
9.86M
#if CONFIG_VP9_HIGHBITDEPTH
639
9.86M
      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
640
29.9k
        vpx_highbd_convolve_copy(CONVERT_TO_SHORTPTR(dst), dst_stride, recon16,
641
29.9k
                                 32, NULL, 0, 0, 0, 0, bs, bs, xd->bd);
642
29.9k
        if (xd->lossless) {
643
0
          vp9_highbd_iwht4x4_add(dqcoeff, recon16, 32, eob, xd->bd);
644
29.9k
        } else {
645
29.9k
          switch (tx_size) {
646
11.3k
            case TX_4X4:
647
11.3k
              vp9_highbd_idct4x4_add(dqcoeff, recon16, 32, eob, xd->bd);
648
11.3k
              break;
649
10.0k
            case TX_8X8:
650
10.0k
              vp9_highbd_idct8x8_add(dqcoeff, recon16, 32, eob, xd->bd);
651
10.0k
              break;
652
6.63k
            case TX_16X16:
653
6.63k
              vp9_highbd_idct16x16_add(dqcoeff, recon16, 32, eob, xd->bd);
654
6.63k
              break;
655
1.85k
            default:
656
1.85k
              assert(tx_size == TX_32X32);
657
1.85k
              vp9_highbd_idct32x32_add(dqcoeff, recon16, 32, eob, xd->bd);
658
1.85k
              break;
659
29.9k
          }
660
29.9k
        }
661
29.9k
        recon = CONVERT_TO_BYTEPTR(recon16);
662
9.83M
      } else {
663
9.83M
#endif  // CONFIG_VP9_HIGHBITDEPTH
664
9.83M
        vpx_convolve_copy(dst, dst_stride, recon, 32, NULL, 0, 0, 0, 0, bs, bs);
665
9.83M
        switch (tx_size) {
666
103k
          case TX_32X32: vp9_idct32x32_add(dqcoeff, recon, 32, eob); break;
667
660k
          case TX_16X16: vp9_idct16x16_add(dqcoeff, recon, 32, eob); break;
668
2.52M
          case TX_8X8: vp9_idct8x8_add(dqcoeff, recon, 32, eob); break;
669
6.55M
          default:
670
6.55M
            assert(tx_size == TX_4X4);
671
            // this is like vp9_short_idct4x4 but has a special case around
672
            // eob<=1, which is significant (not just an optimization) for
673
            // the lossless case.
674
6.55M
            x->inv_txfm_add(dqcoeff, recon, 32, eob);
675
6.55M
            break;
676
9.83M
        }
677
9.83M
#if CONFIG_VP9_HIGHBITDEPTH
678
9.83M
      }
679
9.86M
#endif  // CONFIG_VP9_HIGHBITDEPTH
680
681
9.86M
      tmp = pixel_sse(cpi, xd, pd, src, src_stride, recon, 32, blk_row, blk_col,
682
9.86M
                      plane_bsize, tx_bsize);
683
9.86M
      if (out_recon) {
684
0
        copy_block_visible(xd, pd, recon, 32, out_recon_ptr, out_recon->stride,
685
0
                           blk_row, blk_col, plane_bsize, tx_bsize);
686
0
      }
687
9.86M
    }
688
689
64.2M
    *out_dist = (int64_t)tmp * 16;
690
64.2M
  }
691
277M
}
692
693
static int rate_block(int plane, int block, TX_SIZE tx_size, int coeff_ctx,
694
327M
                      struct rdcost_block_args *args) {
695
327M
  return cost_coeffs(args->x, plane, block, tx_size, coeff_ctx, args->so->scan,
696
327M
                     args->so->neighbors, args->use_fast_coef_costing);
697
327M
}
698
699
static void block_rd_txfm(int plane, int block, int blk_row, int blk_col,
700
347M
                          BLOCK_SIZE plane_bsize, TX_SIZE tx_size, void *arg) {
701
347M
  struct rdcost_block_args *args = arg;
702
347M
  MACROBLOCK *const x = args->x;
703
347M
  MACROBLOCKD *const xd = &x->e_mbd;
704
347M
  MODE_INFO *const mi = xd->mi[0];
705
347M
  int64_t rd1, rd2, rd;
706
347M
  int rate;
707
347M
  int64_t dist = INT64_MAX;
708
347M
  int64_t sse = INT64_MAX;
709
347M
  const int coeff_ctx =
710
347M
      combine_entropy_contexts(args->t_left[blk_row], args->t_above[blk_col]);
711
347M
  struct buf_2d *recon = args->this_recon;
712
347M
  const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
713
347M
  const struct macroblockd_plane *const pd = &xd->plane[plane];
714
347M
  const int dst_stride = pd->dst.stride;
715
347M
  const uint8_t *dst = &pd->dst.buf[4 * (blk_row * dst_stride + blk_col)];
716
347M
  const int enable_trellis_opt = args->cpi->sf.trellis_opt_tx_rd.method;
717
347M
  const double trellis_opt_thresh = args->cpi->sf.trellis_opt_tx_rd.thresh;
718
347M
  int sse_calc_done = 0;
719
#if CONFIG_MISMATCH_DEBUG
720
  struct encode_b_args encode_b_arg = {
721
    x,    enable_trellis_opt, trellis_opt_thresh, &sse_calc_done,
722
    &sse, args->t_above,      args->t_left,       &mi->skip,
723
    0,  // mi_row
724
    0,  // mi_col
725
    0   // output_enabled
726
  };
727
#else
728
347M
  struct encode_b_args encode_b_arg = {
729
347M
    x,    enable_trellis_opt, trellis_opt_thresh, &sse_calc_done,
730
347M
    &sse, args->t_above,      args->t_left,       &mi->skip
731
347M
  };
732
347M
#endif
733
734
347M
  if (args->exit_early) return;
735
736
335M
  if (!is_inter_block(mi)) {
737
282M
    vp9_encode_block_intra(plane, block, blk_row, blk_col, plane_bsize, tx_size,
738
282M
                           &encode_b_arg);
739
282M
    if (recon) {
740
0
      uint8_t *rec_ptr = &recon->buf[4 * (blk_row * recon->stride + blk_col)];
741
0
      copy_block_visible(xd, pd, dst, dst_stride, rec_ptr, recon->stride,
742
0
                         blk_row, blk_col, plane_bsize, tx_bsize);
743
0
    }
744
282M
    if (x->block_tx_domain) {
745
224M
      dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
746
224M
                 tx_size, &dist, &sse, /*out_recon=*/NULL, sse_calc_done);
747
224M
    } else {
748
58.3M
      const struct macroblock_plane *const p = &x->plane[plane];
749
58.3M
      const int src_stride = p->src.stride;
750
58.3M
      const uint8_t *src = &p->src.buf[4 * (blk_row * src_stride + blk_col)];
751
58.3M
      unsigned int tmp;
752
58.3M
      if (!sse_calc_done) {
753
58.3M
        const int diff_stride = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
754
58.3M
        const int16_t *diff =
755
58.3M
            &p->src_diff[4 * (blk_row * diff_stride + blk_col)];
756
58.3M
        int visible_width, visible_height;
757
58.3M
        sse = sum_squares_visible(xd, pd, diff, diff_stride, blk_row, blk_col,
758
58.3M
                                  plane_bsize, tx_bsize, &visible_width,
759
58.3M
                                  &visible_height);
760
58.3M
      }
761
58.3M
#if CONFIG_VP9_HIGHBITDEPTH
762
58.3M
      if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) && (xd->bd > 8))
763
1.07M
        sse = ROUND64_POWER_OF_TWO(sse, (xd->bd - 8) * 2);
764
58.3M
#endif  // CONFIG_VP9_HIGHBITDEPTH
765
58.3M
      sse = sse * 16;
766
58.3M
      tmp = pixel_sse(args->cpi, xd, pd, src, src_stride, dst, dst_stride,
767
58.3M
                      blk_row, blk_col, plane_bsize, tx_bsize);
768
58.3M
      dist = (int64_t)tmp * 16;
769
58.3M
    }
770
282M
  } else {
771
53.4M
    int skip_txfm_flag = SKIP_TXFM_NONE;
772
53.4M
    if (max_txsize_lookup[plane_bsize] == tx_size)
773
36.4M
      skip_txfm_flag = x->skip_txfm[(plane << 2) + (block >> (tx_size << 1))];
774
775
    // This reduces the risk of bad perceptual quality due to bad prediction.
776
    // We always force the encoder to perform transform and quantization.
777
53.4M
    if (!args->cpi->sf.allow_skip_txfm_ac_dc &&
778
53.4M
        skip_txfm_flag == SKIP_TXFM_AC_DC) {
779
1.86M
      skip_txfm_flag = SKIP_TXFM_NONE;
780
1.86M
    }
781
782
53.4M
    if (skip_txfm_flag == SKIP_TXFM_NONE ||
783
53.0M
        (recon && skip_txfm_flag == SKIP_TXFM_AC_ONLY)) {
784
53.0M
      const struct macroblock_plane *const p = &x->plane[plane];
785
53.0M
      const int diff_stride = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
786
53.0M
      const int16_t *const diff =
787
53.0M
          &p->src_diff[4 * (blk_row * diff_stride + blk_col)];
788
53.0M
      const int use_trellis_opt =
789
53.0M
          do_trellis_opt(pd, diff, diff_stride, blk_row, blk_col, plane_bsize,
790
53.0M
                         tx_size, &encode_b_arg);
791
      // full forward transform and quantization
792
53.0M
      vp9_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, tx_size);
793
53.0M
      if (use_trellis_opt) vp9_optimize_b(x, plane, block, tx_size, coeff_ctx);
794
53.0M
      dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
795
53.0M
                 tx_size, &dist, &sse, recon, sse_calc_done);
796
53.0M
    } else if (skip_txfm_flag == SKIP_TXFM_AC_ONLY) {
797
      // compute DC coefficient
798
355k
      tran_low_t *const coeff = BLOCK_OFFSET(x->plane[plane].coeff, block);
799
355k
      tran_low_t *const dqcoeff = BLOCK_OFFSET(xd->plane[plane].dqcoeff, block);
800
355k
      vp9_xform_quant_dc(x, plane, block, blk_row, blk_col, plane_bsize,
801
355k
                         tx_size);
802
355k
      sse = x->bsse[(plane << 2) + (block >> (tx_size << 1))] << 4;
803
355k
      dist = sse;
804
355k
      if (x->plane[plane].eobs[block]) {
805
349k
        const int64_t orig_sse = (int64_t)coeff[0] * coeff[0];
806
349k
        const int64_t resd_sse = coeff[0] - dqcoeff[0];
807
349k
        int64_t dc_correct = orig_sse - resd_sse * resd_sse;
808
349k
#if CONFIG_VP9_HIGHBITDEPTH
809
349k
        dc_correct >>= ((xd->bd - 8) * 2);
810
349k
#endif
811
349k
        if (tx_size != TX_32X32) dc_correct >>= 2;
812
813
349k
        dist = VPXMAX(0, sse - dc_correct);
814
349k
      }
815
355k
    } else {
816
0
      assert(0 && "allow_skip_txfm_ac_dc does not allow SKIP_TXFM_AC_DC.");
817
0
    }
818
53.4M
  }
819
820
335M
  rd = RDCOST(x->rdmult, x->rddiv, 0, dist);
821
335M
  if (args->this_rd + rd > args->best_rd) {
822
8.83M
    args->exit_early = 1;
823
8.83M
    return;
824
8.83M
  }
825
826
327M
  rate = rate_block(plane, block, tx_size, coeff_ctx, args);
827
327M
  args->t_above[blk_col] = (x->plane[plane].eobs[block] > 0) ? 1 : 0;
828
327M
  args->t_left[blk_row] = (x->plane[plane].eobs[block] > 0) ? 1 : 0;
829
327M
  rd1 = RDCOST(x->rdmult, x->rddiv, rate, dist);
830
327M
  rd2 = RDCOST(x->rdmult, x->rddiv, 0, sse);
831
832
  // TODO(jingning): temporarily enabled only for luma component
833
327M
  rd = VPXMIN(rd1, rd2);
834
327M
  if (plane == 0) {
835
119M
    x->zcoeff_blk[tx_size][block] =
836
119M
        !x->plane[plane].eobs[block] ||
837
99.9M
        (x->sharpness == 0 && rd1 > rd2 && !xd->lossless);
838
119M
    x->sum_y_eobs[tx_size] += x->plane[plane].eobs[block];
839
119M
  }
840
841
327M
  args->this_rate += rate;
842
327M
  args->this_dist += dist;
843
327M
  args->this_sse += sse;
844
327M
  args->this_rd += rd;
845
846
327M
  if (args->this_rd > args->best_rd) {
847
30.2M
    args->exit_early = 1;
848
30.2M
    return;
849
30.2M
  }
850
851
296M
  args->skippable &= !x->plane[plane].eobs[block];
852
296M
}
853
854
static void txfm_rd_in_plane(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
855
                             int64_t *distortion, int *skippable, int64_t *sse,
856
                             int64_t ref_best_rd, int plane, BLOCK_SIZE bsize,
857
                             TX_SIZE tx_size, int use_fast_coef_costing,
858
197M
                             struct buf_2d *recon) {
859
197M
  MACROBLOCKD *const xd = &x->e_mbd;
860
197M
  const struct macroblockd_plane *const pd = &xd->plane[plane];
861
197M
  struct rdcost_block_args args;
862
197M
  vp9_zero(args);
863
197M
  args.cpi = cpi;
864
197M
  args.x = x;
865
197M
  args.best_rd = ref_best_rd;
866
197M
  args.use_fast_coef_costing = use_fast_coef_costing;
867
197M
  args.skippable = 1;
868
197M
  args.this_recon = recon;
869
870
197M
  if (plane == 0) xd->mi[0]->tx_size = tx_size;
871
872
197M
  vp9_get_entropy_contexts(bsize, tx_size, pd, args.t_above, args.t_left);
873
874
197M
  args.so = get_scan(xd, tx_size, get_plane_type(plane), 0);
875
876
197M
  vp9_foreach_transformed_block_in_plane(xd, bsize, plane, block_rd_txfm,
877
197M
                                         &args);
878
197M
  if (args.exit_early) {
879
39.1M
    *rate = INT_MAX;
880
39.1M
    *distortion = INT64_MAX;
881
39.1M
    *sse = INT64_MAX;
882
39.1M
    *skippable = 0;
883
158M
  } else {
884
158M
    *distortion = args.this_dist;
885
158M
    *rate = args.this_rate;
886
158M
    *sse = args.this_sse;
887
158M
    *skippable = args.skippable;
888
158M
  }
889
197M
}
890
891
static void choose_largest_tx_size(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
892
                                   int64_t *distortion, int *skip, int64_t *sse,
893
                                   int64_t ref_best_rd, BLOCK_SIZE bs,
894
23.6M
                                   struct buf_2d *recon) {
895
23.6M
  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
896
23.6M
  VP9_COMMON *const cm = &cpi->common;
897
23.6M
  const TX_SIZE largest_tx_size = tx_mode_to_biggest_tx_size[cm->tx_mode];
898
23.6M
  MACROBLOCKD *const xd = &x->e_mbd;
899
23.6M
  MODE_INFO *const mi = xd->mi[0];
900
901
23.6M
  mi->tx_size = VPXMIN(max_tx_size, largest_tx_size);
902
903
23.6M
  txfm_rd_in_plane(cpi, x, rate, distortion, skip, sse, ref_best_rd, 0, bs,
904
23.6M
                   mi->tx_size, cpi->sf.use_fast_coef_costing, recon);
905
23.6M
}
906
907
static void choose_tx_size_from_rd(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
908
                                   int64_t *distortion, int *skip,
909
                                   int64_t *psse, int64_t ref_best_rd,
910
26.1M
                                   BLOCK_SIZE bs, struct buf_2d *recon) {
911
26.1M
  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
912
26.1M
  VP9_COMMON *const cm = &cpi->common;
913
26.1M
  MACROBLOCKD *const xd = &x->e_mbd;
914
26.1M
  MODE_INFO *const mi = xd->mi[0];
915
26.1M
  vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
916
26.1M
  int r[TX_SIZES][2], s[TX_SIZES];
917
26.1M
  int64_t d[TX_SIZES], sse[TX_SIZES];
918
26.1M
  int64_t rd[TX_SIZES][2] = { { INT64_MAX, INT64_MAX },
919
26.1M
                              { INT64_MAX, INT64_MAX },
920
26.1M
                              { INT64_MAX, INT64_MAX },
921
26.1M
                              { INT64_MAX, INT64_MAX } };
922
26.1M
  int n;
923
26.1M
  int s0, s1;
924
26.1M
  int64_t best_rd = ref_best_rd;
925
26.1M
  TX_SIZE best_tx = max_tx_size;
926
26.1M
  int start_tx, end_tx;
927
26.1M
  const int tx_size_ctx = get_tx_size_context(xd);
928
26.1M
#if CONFIG_VP9_HIGHBITDEPTH
929
26.1M
  DECLARE_ALIGNED(16, uint16_t, recon_buf16[TX_SIZES][64 * 64]);
930
26.1M
  uint8_t *recon_buf[TX_SIZES];
931
130M
  for (n = 0; n < TX_SIZES; ++n) {
932
104M
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
933
1.81M
      recon_buf[n] = CONVERT_TO_BYTEPTR(recon_buf16[n]);
934
102M
    } else {
935
102M
      recon_buf[n] = (uint8_t *)recon_buf16[n];
936
102M
    }
937
104M
  }
938
#else
939
  DECLARE_ALIGNED(16, uint8_t, recon_buf[TX_SIZES][64 * 64]);
940
#endif  // CONFIG_VP9_HIGHBITDEPTH
941
942
26.1M
  assert(skip_prob > 0);
943
26.1M
  s0 = vp9_cost_bit(skip_prob, 0);
944
26.1M
  s1 = vp9_cost_bit(skip_prob, 1);
945
946
26.1M
  if (cm->tx_mode == TX_MODE_SELECT) {
947
26.1M
    start_tx = max_tx_size;
948
26.1M
    end_tx = VPXMAX(start_tx - cpi->sf.tx_size_search_depth, 0);
949
26.1M
    if (bs > BLOCK_32X32) end_tx = VPXMIN(end_tx + 1, start_tx);
950
26.1M
  } else {
951
0
    TX_SIZE chosen_tx_size =
952
0
        VPXMIN(max_tx_size, tx_mode_to_biggest_tx_size[cm->tx_mode]);
953
0
    start_tx = chosen_tx_size;
954
0
    end_tx = chosen_tx_size;
955
0
  }
956
957
35.4M
  for (n = start_tx; n >= end_tx; n--) {
958
32.5M
    const int r_tx_size = cpi->tx_size_cost[max_tx_size - 1][tx_size_ctx][n];
959
32.5M
    if (recon) {
960
0
      struct buf_2d this_recon;
961
0
      this_recon.buf = recon_buf[n];
962
0
      this_recon.stride = recon->stride;
963
0
      txfm_rd_in_plane(cpi, x, &r[n][0], &d[n], &s[n], &sse[n], best_rd, 0, bs,
964
0
                       n, cpi->sf.use_fast_coef_costing, &this_recon);
965
32.5M
    } else {
966
32.5M
      txfm_rd_in_plane(cpi, x, &r[n][0], &d[n], &s[n], &sse[n], best_rd, 0, bs,
967
32.5M
                       n, cpi->sf.use_fast_coef_costing, 0);
968
32.5M
    }
969
32.5M
    r[n][1] = r[n][0];
970
32.5M
    if (r[n][0] < INT_MAX) {
971
15.1M
      r[n][1] += r_tx_size;
972
15.1M
    }
973
32.5M
    if (d[n] == INT64_MAX || r[n][0] == INT_MAX) {
974
17.4M
      rd[n][0] = rd[n][1] = INT64_MAX;
975
17.4M
    } else if (s[n]) {
976
5.27M
      if (is_inter_block(mi)) {
977
735k
        rd[n][0] = rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1, sse[n]);
978
735k
        r[n][1] -= r_tx_size;
979
4.54M
      } else {
980
4.54M
        rd[n][0] = RDCOST(x->rdmult, x->rddiv, s1, sse[n]);
981
4.54M
        rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1 + r_tx_size, sse[n]);
982
4.54M
      }
983
9.83M
    } else {
984
9.83M
      rd[n][0] = RDCOST(x->rdmult, x->rddiv, r[n][0] + s0, d[n]);
985
9.83M
      rd[n][1] = RDCOST(x->rdmult, x->rddiv, r[n][1] + s0, d[n]);
986
9.83M
    }
987
988
32.5M
    if (is_inter_block(mi) && !xd->lossless && !s[n] && sse[n] != INT64_MAX) {
989
2.96M
      rd[n][0] = VPXMIN(rd[n][0], RDCOST(x->rdmult, x->rddiv, s1, sse[n]));
990
2.96M
      rd[n][1] = VPXMIN(rd[n][1], RDCOST(x->rdmult, x->rddiv, s1, sse[n]));
991
2.96M
    }
992
993
    // Early termination in transform size search.
994
32.5M
    if (cpi->sf.tx_size_search_breakout &&
995
32.5M
        (rd[n][1] == INT64_MAX ||
996
15.1M
         (n < (int)max_tx_size && rd[n][1] > rd[n + 1][1]) || s[n] == 1))
997
23.2M
      break;
998
999
9.33M
    if (rd[n][1] < best_rd) {
1000
8.97M
      best_tx = n;
1001
8.97M
      best_rd = rd[n][1];
1002
8.97M
    }
1003
9.33M
  }
1004
26.1M
  mi->tx_size = best_tx;
1005
1006
26.1M
  *distortion = d[mi->tx_size];
1007
26.1M
  *rate = r[mi->tx_size][cm->tx_mode == TX_MODE_SELECT];
1008
26.1M
  *skip = s[mi->tx_size];
1009
26.1M
  *psse = sse[mi->tx_size];
1010
26.1M
  if (recon) {
1011
0
#if CONFIG_VP9_HIGHBITDEPTH
1012
0
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1013
0
      memcpy(CONVERT_TO_SHORTPTR(recon->buf),
1014
0
             CONVERT_TO_SHORTPTR(recon_buf[mi->tx_size]),
1015
0
             64 * 64 * sizeof(uint16_t));
1016
0
    } else {
1017
0
#endif
1018
0
      memcpy(recon->buf, recon_buf[mi->tx_size], 64 * 64);
1019
0
#if CONFIG_VP9_HIGHBITDEPTH
1020
0
    }
1021
0
#endif
1022
0
  }
1023
26.1M
}
1024
1025
static void super_block_yrd(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1026
                            int64_t *distortion, int *skip, int64_t *psse,
1027
                            BLOCK_SIZE bs, int64_t ref_best_rd,
1028
49.7M
                            struct buf_2d *recon) {
1029
49.7M
  MACROBLOCKD *xd = &x->e_mbd;
1030
49.7M
  int64_t sse;
1031
49.7M
  int64_t *ret_sse = psse ? psse : &sse;
1032
1033
49.7M
  assert(bs == xd->mi[0]->sb_type);
1034
1035
49.7M
  if (cpi->sf.tx_size_search_method == USE_LARGESTALL || xd->lossless) {
1036
23.6M
    choose_largest_tx_size(cpi, x, rate, distortion, skip, ret_sse, ref_best_rd,
1037
23.6M
                           bs, recon);
1038
26.1M
  } else {
1039
26.1M
    choose_tx_size_from_rd(cpi, x, rate, distortion, skip, ret_sse, ref_best_rd,
1040
26.1M
                           bs, recon);
1041
26.1M
  }
1042
49.7M
}
1043
1044
static int conditional_skipintra(PREDICTION_MODE mode,
1045
0
                                 PREDICTION_MODE best_intra_mode) {
1046
0
  if (mode == D117_PRED && best_intra_mode != V_PRED &&
1047
0
      best_intra_mode != D135_PRED)
1048
0
    return 1;
1049
0
  if (mode == D63_PRED && best_intra_mode != V_PRED &&
1050
0
      best_intra_mode != D45_PRED)
1051
0
    return 1;
1052
0
  if (mode == D207_PRED && best_intra_mode != H_PRED &&
1053
0
      best_intra_mode != D45_PRED)
1054
0
    return 1;
1055
0
  if (mode == D153_PRED && best_intra_mode != H_PRED &&
1056
0
      best_intra_mode != D135_PRED)
1057
0
    return 1;
1058
0
  return 0;
1059
0
}
1060
1061
static int64_t rd_pick_intra4x4block(VP9_COMP *cpi, MACROBLOCK *x, int row,
1062
                                     int col, PREDICTION_MODE *best_mode,
1063
                                     const int *bmode_costs, ENTROPY_CONTEXT *a,
1064
                                     ENTROPY_CONTEXT *l, int *bestrate,
1065
                                     int *bestratey, int64_t *bestdistortion,
1066
11.2M
                                     BLOCK_SIZE bsize, int64_t rd_thresh) {
1067
11.2M
  PREDICTION_MODE mode;
1068
11.2M
  MACROBLOCKD *const xd = &x->e_mbd;
1069
11.2M
  int64_t best_rd = rd_thresh;
1070
11.2M
  struct macroblock_plane *p = &x->plane[0];
1071
11.2M
  struct macroblockd_plane *pd = &xd->plane[0];
1072
11.2M
  const int src_stride = p->src.stride;
1073
11.2M
  const int dst_stride = pd->dst.stride;
1074
11.2M
  const uint8_t *src_init = &p->src.buf[row * 4 * src_stride + col * 4];
1075
11.2M
  uint8_t *dst_init = &pd->dst.buf[row * 4 * dst_stride + col * 4];
1076
11.2M
  ENTROPY_CONTEXT ta[2], tempa[2];
1077
11.2M
  ENTROPY_CONTEXT tl[2], templ[2];
1078
11.2M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1079
11.2M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1080
11.2M
  int idx, idy;
1081
11.2M
  uint8_t best_dst[8 * 8];
1082
11.2M
#if CONFIG_VP9_HIGHBITDEPTH
1083
11.2M
  uint16_t best_dst16[8 * 8];
1084
11.2M
#endif
1085
11.2M
  memcpy(ta, a, num_4x4_blocks_wide * sizeof(a[0]));
1086
11.2M
  memcpy(tl, l, num_4x4_blocks_high * sizeof(l[0]));
1087
1088
11.2M
  xd->mi[0]->tx_size = TX_4X4;
1089
1090
11.2M
  assert(!x->skip_block);
1091
1092
11.2M
#if CONFIG_VP9_HIGHBITDEPTH
1093
11.2M
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1094
1.37M
    for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1095
1.24M
      int64_t this_rd;
1096
1.24M
      int ratey = 0;
1097
1.24M
      int64_t distortion = 0;
1098
1.24M
      int rate = bmode_costs[mode];
1099
1100
1.24M
      if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
1101
1102
      // Only do the oblique modes if the best so far is
1103
      // one of the neighboring directional modes
1104
1.24M
      if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
1105
0
        if (conditional_skipintra(mode, *best_mode)) continue;
1106
0
      }
1107
1108
1.24M
      memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
1109
1.24M
      memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
1110
1111
2.02M
      for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
1112
2.12M
        for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
1113
1.34M
          const int block = (row + idy) * 2 + (col + idx);
1114
1.34M
          const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
1115
1.34M
          uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
1116
1.34M
          uint16_t *const dst16 = CONVERT_TO_SHORTPTR(dst);
1117
1.34M
          int16_t *const src_diff =
1118
1.34M
              vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
1119
1.34M
          tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
1120
1.34M
          tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
1121
1.34M
          tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
1122
1.34M
          uint16_t *const eob = &p->eobs[block];
1123
1.34M
          xd->mi[0]->bmi[block].as_mode = mode;
1124
1.34M
          vp9_predict_intra_block(xd, 1, TX_4X4, mode,
1125
1.34M
                                  x->skip_encode ? src : dst,
1126
1.34M
                                  x->skip_encode ? src_stride : dst_stride, dst,
1127
1.34M
                                  dst_stride, col + idx, row + idy, 0);
1128
1.34M
          vpx_highbd_subtract_block(4, 4, src_diff, 8, src, src_stride, dst,
1129
1.34M
                                    dst_stride, xd->bd);
1130
1.34M
          if (xd->lossless) {
1131
80
            const ScanOrder *so = &vp9_default_scan_orders[TX_4X4];
1132
80
            const int coeff_ctx =
1133
80
                combine_entropy_contexts(tempa[idx], templ[idy]);
1134
80
            vp9_highbd_fwht4x4(src_diff, coeff, 8);
1135
80
            vpx_highbd_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant,
1136
80
                                  eob, so);
1137
80
            ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1138
80
                                 so->neighbors, cpi->sf.use_fast_coef_costing);
1139
80
            tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
1140
80
            if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1141
47
              goto next_highbd;
1142
33
            vp9_highbd_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst16,
1143
33
                                   dst_stride, p->eobs[block], xd->bd);
1144
1.34M
          } else {
1145
1.34M
            int64_t unused;
1146
1.34M
            const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
1147
1.34M
            const ScanOrder *so = &vp9_scan_orders[TX_4X4][tx_type];
1148
1.34M
            const int coeff_ctx =
1149
1.34M
                combine_entropy_contexts(tempa[idx], templ[idy]);
1150
1.34M
            if (tx_type == DCT_DCT)
1151
270k
              vpx_highbd_fdct4x4(src_diff, coeff, 8);
1152
1.07M
            else
1153
1.07M
              vp9_highbd_fht4x4(src_diff, coeff, 8, tx_type);
1154
1.34M
            vpx_highbd_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant,
1155
1.34M
                                  eob, so);
1156
1.34M
            ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1157
1.34M
                                 so->neighbors, cpi->sf.use_fast_coef_costing);
1158
1.34M
            distortion += vp9_highbd_block_error_dispatch(
1159
1.34M
                              coeff, BLOCK_OFFSET(pd->dqcoeff, block), 16,
1160
1.34M
                              &unused, xd->bd) >>
1161
1.34M
                          2;
1162
1.34M
            tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
1163
1.34M
            if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1164
518k
              goto next_highbd;
1165
822k
            vp9_highbd_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block),
1166
822k
                                  dst16, dst_stride, p->eobs[block], xd->bd);
1167
822k
          }
1168
1.34M
        }
1169
1.29M
      }
1170
1171
727k
      rate += ratey;
1172
727k
      this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1173
1174
727k
      if (this_rd < best_rd) {
1175
143k
        *bestrate = rate;
1176
143k
        *bestratey = ratey;
1177
143k
        *bestdistortion = distortion;
1178
143k
        best_rd = this_rd;
1179
143k
        *best_mode = mode;
1180
143k
        memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
1181
143k
        memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
1182
750k
        for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
1183
606k
          memcpy(best_dst16 + idy * 8,
1184
606k
                 CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
1185
606k
                 num_4x4_blocks_wide * 4 * sizeof(uint16_t));
1186
606k
        }
1187
143k
      }
1188
1.24M
    next_highbd: {}
1189
1.24M
    }
1190
124k
    if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
1191
1192
549k
    for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
1193
444k
      memcpy(CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
1194
444k
             best_dst16 + idy * 8, num_4x4_blocks_wide * 4 * sizeof(uint16_t));
1195
444k
    }
1196
1197
105k
    return best_rd;
1198
124k
  }
1199
11.1M
#endif  // CONFIG_VP9_HIGHBITDEPTH
1200
1201
122M
  for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1202
111M
    int64_t this_rd;
1203
111M
    int ratey = 0;
1204
111M
    int64_t distortion = 0;
1205
111M
    int rate = bmode_costs[mode];
1206
1207
111M
    if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
1208
1209
    // Only do the oblique modes if the best so far is
1210
    // one of the neighboring directional modes
1211
111M
    if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
1212
0
      if (conditional_skipintra(mode, *best_mode)) continue;
1213
0
    }
1214
1215
111M
    memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
1216
111M
    memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
1217
1218
167M
    for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
1219
196M
      for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
1220
139M
        const int block = (row + idy) * 2 + (col + idx);
1221
139M
        const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
1222
139M
        uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
1223
139M
        int16_t *const src_diff =
1224
139M
            vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
1225
139M
        tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
1226
139M
        tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
1227
139M
        tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
1228
139M
        uint16_t *const eob = &p->eobs[block];
1229
139M
        xd->mi[0]->bmi[block].as_mode = mode;
1230
139M
        vp9_predict_intra_block(xd, 1, TX_4X4, mode, x->skip_encode ? src : dst,
1231
139M
                                x->skip_encode ? src_stride : dst_stride, dst,
1232
139M
                                dst_stride, col + idx, row + idy, 0);
1233
139M
        vpx_subtract_block(4, 4, src_diff, 8, src, src_stride, dst, dst_stride);
1234
1235
139M
        if (xd->lossless) {
1236
11.2M
          const ScanOrder *so = &vp9_default_scan_orders[TX_4X4];
1237
11.2M
          const int coeff_ctx =
1238
11.2M
              combine_entropy_contexts(tempa[idx], templ[idy]);
1239
11.2M
          vp9_fwht4x4(src_diff, coeff, 8);
1240
11.2M
          vpx_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant, eob,
1241
11.2M
                         so);
1242
11.2M
          ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1243
11.2M
                               so->neighbors, cpi->sf.use_fast_coef_costing);
1244
11.2M
          tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
1245
11.2M
          if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1246
5.72M
            goto next;
1247
5.55M
          vp9_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst, dst_stride,
1248
5.55M
                          p->eobs[block]);
1249
128M
        } else {
1250
128M
          int64_t unused;
1251
128M
          const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
1252
128M
          const ScanOrder *so = &vp9_scan_orders[TX_4X4][tx_type];
1253
128M
          const int coeff_ctx =
1254
128M
              combine_entropy_contexts(tempa[idx], templ[idy]);
1255
128M
          vp9_fht4x4(src_diff, coeff, 8, tx_type);
1256
128M
          vpx_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant, eob,
1257
128M
                         so);
1258
128M
          ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1259
128M
                               so->neighbors, cpi->sf.use_fast_coef_costing);
1260
128M
          tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
1261
128M
          distortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, block),
1262
128M
                                        16, &unused) >>
1263
128M
                        2;
1264
128M
          if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1265
63.6M
            goto next;
1266
64.9M
          vp9_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block), dst,
1267
64.9M
                         dst_stride, p->eobs[block]);
1268
64.9M
        }
1269
139M
      }
1270
125M
    }
1271
1272
41.8M
    rate += ratey;
1273
41.8M
    this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1274
1275
41.8M
    if (this_rd < best_rd) {
1276
18.4M
      *bestrate = rate;
1277
18.4M
      *bestratey = ratey;
1278
18.4M
      *bestdistortion = distortion;
1279
18.4M
      best_rd = this_rd;
1280
18.4M
      *best_mode = mode;
1281
18.4M
      memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
1282
18.4M
      memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
1283
103M
      for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
1284
84.5M
        memcpy(best_dst + idy * 8, dst_init + idy * dst_stride,
1285
84.5M
               num_4x4_blocks_wide * 4);
1286
18.4M
    }
1287
111M
  next: {}
1288
111M
  }
1289
1290
11.1M
  if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
1291
1292
56.0M
  for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
1293
46.0M
    memcpy(dst_init + idy * dst_stride, best_dst + idy * 8,
1294
46.0M
           num_4x4_blocks_wide * 4);
1295
1296
10.0M
  return best_rd;
1297
11.1M
}
1298
1299
static int64_t rd_pick_intra_sub_8x8_y_mode(VP9_COMP *cpi, MACROBLOCK *mb,
1300
                                            int *rate, int *rate_y,
1301
                                            int64_t *distortion,
1302
3.88M
                                            int64_t best_rd) {
1303
3.88M
  int i, j;
1304
3.88M
  const MACROBLOCKD *const xd = &mb->e_mbd;
1305
3.88M
  MODE_INFO *const mic = xd->mi[0];
1306
3.88M
  const MODE_INFO *above_mi = xd->above_mi;
1307
3.88M
  const MODE_INFO *left_mi = xd->left_mi;
1308
3.88M
  const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
1309
3.88M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1310
3.88M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1311
3.88M
  int idx, idy;
1312
3.88M
  int cost = 0;
1313
3.88M
  int64_t total_distortion = 0;
1314
3.88M
  int tot_rate_y = 0;
1315
3.88M
  int64_t total_rd = 0;
1316
3.88M
  const int *bmode_costs = cpi->mbmode_cost;
1317
1318
  // Pick modes for each sub-block (of size 4x4, 4x8, or 8x4) in an 8x8 block.
1319
9.47M
  for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
1320
16.8M
    for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
1321
11.2M
      PREDICTION_MODE best_mode = DC_PRED;
1322
11.2M
      int r = INT_MAX, ry = INT_MAX;
1323
11.2M
      int64_t d = INT64_MAX, this_rd = INT64_MAX;
1324
11.2M
      i = idy * 2 + idx;
1325
11.2M
      if (cpi->common.frame_type == KEY_FRAME) {
1326
4.67M
        const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, i);
1327
4.67M
        const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, i);
1328
1329
4.67M
        bmode_costs = cpi->y_mode_costs[A][L];
1330
4.67M
      }
1331
1332
11.2M
      this_rd = rd_pick_intra4x4block(
1333
11.2M
          cpi, mb, idy, idx, &best_mode, bmode_costs,
1334
11.2M
          xd->plane[0].above_context + idx, xd->plane[0].left_context + idy, &r,
1335
11.2M
          &ry, &d, bsize, best_rd - total_rd);
1336
1337
11.2M
      if (this_rd >= best_rd - total_rd) return INT64_MAX;
1338
1339
10.1M
      total_rd += this_rd;
1340
10.1M
      cost += r;
1341
10.1M
      total_distortion += d;
1342
10.1M
      tot_rate_y += ry;
1343
1344
10.1M
      mic->bmi[i].as_mode = best_mode;
1345
11.6M
      for (j = 1; j < num_4x4_blocks_high; ++j)
1346
1.45M
        mic->bmi[i + j * 2].as_mode = best_mode;
1347
11.6M
      for (j = 1; j < num_4x4_blocks_wide; ++j)
1348
1.45M
        mic->bmi[i + j].as_mode = best_mode;
1349
1350
10.1M
      if (total_rd >= best_rd) return INT64_MAX;
1351
10.1M
    }
1352
6.67M
  }
1353
1354
2.79M
  *rate = cost;
1355
2.79M
  *rate_y = tot_rate_y;
1356
2.79M
  *distortion = total_distortion;
1357
2.79M
  mic->mode = mic->bmi[3].as_mode;
1358
1359
2.79M
  return RDCOST(mb->rdmult, mb->rddiv, cost, total_distortion);
1360
3.88M
}
1361
1362
// This function is used only for intra_only frames
1363
static int64_t rd_pick_intra_sby_mode(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1364
                                      int *rate_tokenonly, int64_t *distortion,
1365
                                      int *skippable, BLOCK_SIZE bsize,
1366
1.98M
                                      int64_t best_rd) {
1367
1.98M
  PREDICTION_MODE mode;
1368
1.98M
  PREDICTION_MODE mode_selected = DC_PRED;
1369
1.98M
  MACROBLOCKD *const xd = &x->e_mbd;
1370
1.98M
  MODE_INFO *const mic = xd->mi[0];
1371
1.98M
  int this_rate, this_rate_tokenonly, s;
1372
1.98M
  int64_t this_distortion, this_rd;
1373
1.98M
  TX_SIZE best_tx = TX_4X4;
1374
1.98M
  int *bmode_costs;
1375
1.98M
  const MODE_INFO *above_mi = xd->above_mi;
1376
1.98M
  const MODE_INFO *left_mi = xd->left_mi;
1377
1.98M
  const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0);
1378
1.98M
  const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
1379
1.98M
  bmode_costs = cpi->y_mode_costs[A][L];
1380
1381
1.98M
  memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1382
  /* Y Search for intra prediction mode */
1383
21.8M
  for (mode = DC_PRED; mode <= TM_PRED; mode++) {
1384
19.8M
    if (cpi->sf.use_nonrd_pick_mode) {
1385
      // These speed features are turned on in hybrid non-RD and RD mode
1386
      // for key frame coding in the context of real-time setting.
1387
0
      if (conditional_skipintra(mode, mode_selected)) continue;
1388
0
      if (*skippable) break;
1389
0
    }
1390
1391
19.8M
    mic->mode = mode;
1392
1393
19.8M
    super_block_yrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s, NULL,
1394
19.8M
                    bsize, best_rd, /*recon=*/NULL);
1395
1396
19.8M
    if (this_rate_tokenonly == INT_MAX) continue;
1397
1398
5.93M
    this_rate = this_rate_tokenonly + bmode_costs[mode];
1399
5.93M
    this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
1400
1401
5.93M
    if (this_rd < best_rd) {
1402
2.07M
      mode_selected = mode;
1403
2.07M
      best_rd = this_rd;
1404
2.07M
      best_tx = mic->tx_size;
1405
2.07M
      *rate = this_rate;
1406
2.07M
      *rate_tokenonly = this_rate_tokenonly;
1407
2.07M
      *distortion = this_distortion;
1408
2.07M
      *skippable = s;
1409
2.07M
    }
1410
5.93M
  }
1411
1412
1.98M
  mic->mode = mode_selected;
1413
1.98M
  mic->tx_size = best_tx;
1414
1415
1.98M
  return best_rd;
1416
1.98M
}
1417
1418
// Return value 0: early termination triggered, no valid rd cost available;
1419
//              1: rd cost values are valid.
1420
static int super_block_uvrd(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1421
                            int64_t *distortion, int *skippable, int64_t *sse,
1422
75.8M
                            BLOCK_SIZE bsize, int64_t ref_best_rd) {
1423
75.8M
  MACROBLOCKD *const xd = &x->e_mbd;
1424
75.8M
  MODE_INFO *const mi = xd->mi[0];
1425
75.8M
  const TX_SIZE uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
1426
75.8M
  int plane;
1427
75.8M
  int pnrate = 0, pnskip = 1;
1428
75.8M
  int64_t pndist = 0, pnsse = 0;
1429
75.8M
  int is_cost_valid = 1;
1430
1431
75.8M
  if (ref_best_rd < 0) is_cost_valid = 0;
1432
1433
75.8M
  if (is_inter_block(mi) && is_cost_valid) {
1434
32.6M
    for (plane = 1; plane < MAX_MB_PLANE; ++plane)
1435
21.7M
      vp9_subtract_plane(x, bsize, plane);
1436
10.8M
  }
1437
1438
75.8M
  *rate = 0;
1439
75.8M
  *distortion = 0;
1440
75.8M
  *sse = 0;
1441
75.8M
  *skippable = 1;
1442
1443
204M
  for (plane = 1; plane < MAX_MB_PLANE; ++plane) {
1444
141M
    txfm_rd_in_plane(cpi, x, &pnrate, &pndist, &pnskip, &pnsse, ref_best_rd,
1445
141M
                     plane, bsize, uv_tx_size, cpi->sf.use_fast_coef_costing,
1446
141M
                     /*recon=*/NULL);
1447
141M
    if (pnrate == INT_MAX) {
1448
12.9M
      is_cost_valid = 0;
1449
12.9M
      break;
1450
12.9M
    }
1451
128M
    *rate += pnrate;
1452
128M
    *distortion += pndist;
1453
128M
    *sse += pnsse;
1454
128M
    *skippable &= pnskip;
1455
128M
  }
1456
1457
75.8M
  if (!is_cost_valid) {
1458
    // reset cost value
1459
12.9M
    *rate = INT_MAX;
1460
12.9M
    *distortion = INT64_MAX;
1461
12.9M
    *sse = INT64_MAX;
1462
12.9M
    *skippable = 0;
1463
12.9M
  }
1464
1465
75.8M
  return is_cost_valid;
1466
75.8M
}
1467
1468
static int64_t rd_pick_intra_sbuv_mode(VP9_COMP *cpi, MACROBLOCK *x,
1469
                                       PICK_MODE_CONTEXT *ctx, int *rate,
1470
                                       int *rate_tokenonly, int64_t *distortion,
1471
                                       int *skippable, BLOCK_SIZE bsize,
1472
6.66M
                                       TX_SIZE max_tx_size) {
1473
6.66M
  MACROBLOCKD *xd = &x->e_mbd;
1474
6.66M
  PREDICTION_MODE mode;
1475
6.66M
  PREDICTION_MODE mode_selected = DC_PRED;
1476
6.66M
  int64_t best_rd = INT64_MAX, this_rd;
1477
6.66M
  int this_rate_tokenonly, this_rate, s;
1478
6.66M
  int64_t this_distortion, this_sse;
1479
1480
6.66M
  memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1481
73.2M
  for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1482
66.6M
    if (!(cpi->sf.intra_uv_mode_mask[max_tx_size] & (1 << mode))) continue;
1483
#if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
1484
    if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
1485
        (xd->above_mi == NULL || xd->left_mi == NULL) && need_top_left[mode])
1486
      continue;
1487
#endif  // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
1488
1489
64.8M
    xd->mi[0]->uv_mode = mode;
1490
1491
64.8M
    if (!super_block_uvrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s,
1492
64.8M
                          &this_sse, bsize, best_rd))
1493
9.79M
      continue;
1494
55.1M
    this_rate =
1495
55.1M
        this_rate_tokenonly +
1496
55.1M
        cpi->intra_uv_mode_cost[cpi->common.frame_type][xd->mi[0]->mode][mode];
1497
55.1M
    this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
1498
1499
55.1M
    if (this_rd < best_rd) {
1500
11.0M
      mode_selected = mode;
1501
11.0M
      best_rd = this_rd;
1502
11.0M
      *rate = this_rate;
1503
11.0M
      *rate_tokenonly = this_rate_tokenonly;
1504
11.0M
      *distortion = this_distortion;
1505
11.0M
      *skippable = s;
1506
11.0M
      if (!x->select_tx_size) swap_block_ptr(x, ctx, 2, 0, 1, MAX_MB_PLANE);
1507
11.0M
    }
1508
55.1M
  }
1509
1510
6.66M
  xd->mi[0]->uv_mode = mode_selected;
1511
6.66M
  return best_rd;
1512
6.66M
}
1513
1514
#if !CONFIG_REALTIME_ONLY
1515
static int64_t rd_sbuv_dcpred(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1516
                              int *rate_tokenonly, int64_t *distortion,
1517
0
                              int *skippable, BLOCK_SIZE bsize) {
1518
0
  const VP9_COMMON *cm = &cpi->common;
1519
0
  int64_t unused;
1520
1521
0
  x->e_mbd.mi[0]->uv_mode = DC_PRED;
1522
0
  memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1523
0
  super_block_uvrd(cpi, x, rate_tokenonly, distortion, skippable, &unused,
1524
0
                   bsize, INT64_MAX);
1525
0
  *rate =
1526
0
      *rate_tokenonly +
1527
0
      cpi->intra_uv_mode_cost[cm->frame_type][x->e_mbd.mi[0]->mode][DC_PRED];
1528
0
  return RDCOST(x->rdmult, x->rddiv, *rate, *distortion);
1529
0
}
1530
1531
static void choose_intra_uv_mode(VP9_COMP *cpi, MACROBLOCK *const x,
1532
                                 PICK_MODE_CONTEXT *ctx, BLOCK_SIZE bsize,
1533
                                 TX_SIZE max_tx_size, int *rate_uv,
1534
                                 int *rate_uv_tokenonly, int64_t *dist_uv,
1535
3.89M
                                 int *skip_uv, PREDICTION_MODE *mode_uv) {
1536
  // Use an estimated rd for uv_intra based on DC_PRED if the
1537
  // appropriate speed flag is set.
1538
3.89M
  if (cpi->sf.use_uv_intra_rd_estimate) {
1539
0
    rd_sbuv_dcpred(cpi, x, rate_uv, rate_uv_tokenonly, dist_uv, skip_uv,
1540
0
                   bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize);
1541
    // Else do a proper rd search for each possible transform size that may
1542
    // be considered in the main rd loop.
1543
3.89M
  } else {
1544
3.89M
    rd_pick_intra_sbuv_mode(cpi, x, ctx, rate_uv, rate_uv_tokenonly, dist_uv,
1545
3.89M
                            skip_uv, bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
1546
3.89M
                            max_tx_size);
1547
3.89M
  }
1548
3.89M
  *mode_uv = x->e_mbd.mi[0]->uv_mode;
1549
3.89M
}
1550
1551
static int cost_mv_ref(const VP9_COMP *cpi, PREDICTION_MODE mode,
1552
183M
                       int mode_context) {
1553
183M
  assert(is_inter_mode(mode));
1554
183M
  return cpi->inter_mode_cost[mode_context][INTER_OFFSET(mode)];
1555
183M
}
1556
1557
static int set_and_cost_bmi_mvs(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
1558
                                int i, PREDICTION_MODE mode, int_mv this_mv[2],
1559
                                int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1560
                                int_mv seg_mvs[MAX_REF_FRAMES],
1561
                                int_mv *best_ref_mv[2], const int *mvjcost,
1562
55.5M
                                int *mvcost[2]) {
1563
55.5M
  MODE_INFO *const mi = xd->mi[0];
1564
55.5M
  const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
1565
55.5M
  int thismvcost = 0;
1566
55.5M
  int idx, idy;
1567
55.5M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[mi->sb_type];
1568
55.5M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[mi->sb_type];
1569
55.5M
  const int is_compound = has_second_ref(mi);
1570
1571
55.5M
  switch (mode) {
1572
16.6M
    case NEWMV:
1573
16.6M
      this_mv[0].as_int = seg_mvs[mi->ref_frame[0]].as_int;
1574
16.6M
      thismvcost += vp9_mv_bit_cost(&this_mv[0].as_mv, &best_ref_mv[0]->as_mv,
1575
16.6M
                                    mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1576
16.6M
      if (is_compound) {
1577
0
        this_mv[1].as_int = seg_mvs[mi->ref_frame[1]].as_int;
1578
0
        thismvcost += vp9_mv_bit_cost(&this_mv[1].as_mv, &best_ref_mv[1]->as_mv,
1579
0
                                      mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1580
0
      }
1581
16.6M
      break;
1582
10.6M
    case NEARMV:
1583
31.1M
    case NEARESTMV:
1584
31.1M
      this_mv[0].as_int = frame_mv[mode][mi->ref_frame[0]].as_int;
1585
31.1M
      if (is_compound)
1586
0
        this_mv[1].as_int = frame_mv[mode][mi->ref_frame[1]].as_int;
1587
31.1M
      break;
1588
7.72M
    default:
1589
7.72M
      assert(mode == ZEROMV);
1590
7.72M
      this_mv[0].as_int = 0;
1591
7.72M
      if (is_compound) this_mv[1].as_int = 0;
1592
7.72M
      break;
1593
55.5M
  }
1594
1595
55.5M
  mi->bmi[i].as_mv[0].as_int = this_mv[0].as_int;
1596
55.5M
  if (is_compound) mi->bmi[i].as_mv[1].as_int = this_mv[1].as_int;
1597
1598
55.5M
  mi->bmi[i].as_mode = mode;
1599
1600
119M
  for (idy = 0; idy < num_4x4_blocks_high; ++idy)
1601
135M
    for (idx = 0; idx < num_4x4_blocks_wide; ++idx)
1602
71.7M
      memmove(&mi->bmi[i + idy * 2 + idx], &mi->bmi[i], sizeof(mi->bmi[i]));
1603
1604
55.5M
  return cost_mv_ref(cpi, mode, mbmi_ext->mode_context[mi->ref_frame[0]]) +
1605
55.5M
         thismvcost;
1606
55.5M
}
1607
1608
static int64_t encode_inter_mb_segment(VP9_COMP *cpi, MACROBLOCK *x,
1609
                                       int64_t best_yrd, int i, int *labelyrate,
1610
                                       int64_t *distortion, int64_t *sse,
1611
                                       ENTROPY_CONTEXT *ta, ENTROPY_CONTEXT *tl,
1612
42.0M
                                       int mi_row, int mi_col) {
1613
42.0M
  int k;
1614
42.0M
  MACROBLOCKD *xd = &x->e_mbd;
1615
42.0M
  struct macroblockd_plane *const pd = &xd->plane[0];
1616
42.0M
  struct macroblock_plane *const p = &x->plane[0];
1617
42.0M
  MODE_INFO *const mi = xd->mi[0];
1618
42.0M
  const BLOCK_SIZE plane_bsize = get_plane_block_size(mi->sb_type, pd);
1619
42.0M
  const int width = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
1620
42.0M
  const int height = 4 * num_4x4_blocks_high_lookup[plane_bsize];
1621
42.0M
  int idx, idy;
1622
1623
42.0M
  const uint8_t *const src =
1624
42.0M
      &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1625
42.0M
  uint8_t *const dst =
1626
42.0M
      &pd->dst.buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->dst.stride)];
1627
42.0M
  int64_t thisdistortion = 0, thissse = 0;
1628
42.0M
  int thisrate = 0, ref;
1629
42.0M
  const ScanOrder *so = &vp9_default_scan_orders[TX_4X4];
1630
42.0M
  const int is_compound = has_second_ref(mi);
1631
42.0M
  const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
1632
1633
42.0M
  assert(!x->skip_block);
1634
1635
84.0M
  for (ref = 0; ref < 1 + is_compound; ++ref) {
1636
42.0M
    const int bw = b_width_log2_lookup[BLOCK_8X8];
1637
42.0M
    const int h = 4 * (i >> bw);
1638
42.0M
    const int w = 4 * (i & ((1 << bw) - 1));
1639
42.0M
    const struct scale_factors *sf = &xd->block_refs[ref]->sf;
1640
42.0M
    int y_stride = pd->pre[ref].stride;
1641
42.0M
    uint8_t *pre = pd->pre[ref].buf + (h * pd->pre[ref].stride + w);
1642
1643
42.0M
    if (vp9_is_scaled(sf)) {
1644
0
      const int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
1645
0
      const int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
1646
1647
0
      y_stride = xd->block_refs[ref]->buf->y_stride;
1648
0
      pre = xd->block_refs[ref]->buf->y_buffer;
1649
0
      pre += scaled_buffer_offset(x_start + w, y_start + h, y_stride, sf);
1650
0
    }
1651
42.0M
#if CONFIG_VP9_HIGHBITDEPTH
1652
42.0M
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1653
184k
      vp9_highbd_build_inter_predictor(
1654
184k
          CONVERT_TO_SHORTPTR(pre), y_stride, CONVERT_TO_SHORTPTR(dst),
1655
184k
          pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1656
184k
          &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1657
184k
          mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2),
1658
184k
          xd->bd);
1659
41.8M
    } else {
1660
41.8M
      vp9_build_inter_predictor(
1661
41.8M
          pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1662
41.8M
          &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1663
41.8M
          mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
1664
41.8M
    }
1665
#else
1666
    vp9_build_inter_predictor(
1667
        pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1668
        &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1669
        mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
1670
#endif  // CONFIG_VP9_HIGHBITDEPTH
1671
42.0M
  }
1672
1673
42.0M
#if CONFIG_VP9_HIGHBITDEPTH
1674
42.0M
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1675
184k
    vpx_highbd_subtract_block(
1676
184k
        height, width, vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1677
184k
        8, src, p->src.stride, dst, pd->dst.stride, xd->bd);
1678
41.8M
  } else {
1679
41.8M
    vpx_subtract_block(height, width,
1680
41.8M
                       vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1681
41.8M
                       8, src, p->src.stride, dst, pd->dst.stride);
1682
41.8M
  }
1683
#else
1684
  vpx_subtract_block(height, width,
1685
                     vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1686
                     8, src, p->src.stride, dst, pd->dst.stride);
1687
#endif  // CONFIG_VP9_HIGHBITDEPTH
1688
1689
42.0M
  k = i;
1690
82.7M
  for (idy = 0; idy < height / 4; ++idy) {
1691
93.7M
    for (idx = 0; idx < width / 4; ++idx) {
1692
53.0M
#if CONFIG_VP9_HIGHBITDEPTH
1693
53.0M
      const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
1694
53.0M
#endif
1695
53.0M
      int64_t ssz, rd, rd1, rd2;
1696
53.0M
      tran_low_t *coeff, *qcoeff, *dqcoeff;
1697
53.0M
      uint16_t *eob;
1698
53.0M
      int coeff_ctx;
1699
53.0M
      k += (idy * 2 + idx);
1700
53.0M
      coeff_ctx = combine_entropy_contexts(ta[k & 1], tl[k >> 1]);
1701
53.0M
      coeff = BLOCK_OFFSET(p->coeff, k);
1702
53.0M
      qcoeff = BLOCK_OFFSET(p->qcoeff, k);
1703
53.0M
      dqcoeff = BLOCK_OFFSET(pd->dqcoeff, k);
1704
53.0M
      eob = &p->eobs[k];
1705
1706
53.0M
      x->fwd_txfm4x4(vp9_raster_block_offset_int16(BLOCK_8X8, k, p->src_diff),
1707
53.0M
                     coeff, 8);
1708
53.0M
#if CONFIG_VP9_HIGHBITDEPTH
1709
53.0M
      vpx_highbd_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant, eob,
1710
53.0M
                            so);
1711
53.0M
      thisdistortion += vp9_highbd_block_error_dispatch(
1712
53.0M
          coeff, BLOCK_OFFSET(pd->dqcoeff, k), 16, &ssz, bd);
1713
#else
1714
      vpx_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant, eob, so);
1715
      thisdistortion +=
1716
          vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, k), 16, &ssz);
1717
#endif  // CONFIG_VP9_HIGHBITDEPTH
1718
53.0M
      thissse += ssz;
1719
53.0M
      thisrate += cost_coeffs(x, 0, k, TX_4X4, coeff_ctx, so->scan,
1720
53.0M
                              so->neighbors, cpi->sf.use_fast_coef_costing);
1721
53.0M
      ta[k & 1] = tl[k >> 1] = (x->plane[0].eobs[k] > 0) ? 1 : 0;
1722
53.0M
      rd1 = RDCOST(x->rdmult, x->rddiv, thisrate, thisdistortion >> 2);
1723
53.0M
      rd2 = RDCOST(x->rdmult, x->rddiv, 0, thissse >> 2);
1724
53.0M
      rd = VPXMIN(rd1, rd2);
1725
53.0M
      if (rd >= best_yrd) return INT64_MAX;
1726
53.0M
    }
1727
47.5M
  }
1728
1729
35.2M
  *distortion = thisdistortion >> 2;
1730
35.2M
  *labelyrate = thisrate;
1731
35.2M
  *sse = thissse >> 2;
1732
1733
35.2M
  return RDCOST(x->rdmult, x->rddiv, *labelyrate, *distortion);
1734
42.0M
}
1735
#endif  // !CONFIG_REALTIME_ONLY
1736
1737
typedef struct {
1738
  int eobs;
1739
  int brate;
1740
  int byrate;
1741
  int64_t bdist;
1742
  int64_t bsse;
1743
  int64_t brdcost;
1744
  int_mv mvs[2];
1745
  ENTROPY_CONTEXT ta[2];
1746
  ENTROPY_CONTEXT tl[2];
1747
} SEG_RDSTAT;
1748
1749
typedef struct {
1750
  int_mv *ref_mv[2];
1751
  int_mv mvp;
1752
1753
  int64_t segment_rd;
1754
  int r;
1755
  int64_t d;
1756
  int64_t sse;
1757
  int segment_yrate;
1758
  PREDICTION_MODE modes[4];
1759
  SEG_RDSTAT rdstat[4][INTER_MODES];
1760
  int mvthresh;
1761
} BEST_SEG_INFO;
1762
1763
#if !CONFIG_REALTIME_ONLY
1764
60.6M
static INLINE int mv_check_bounds(const MvLimits *mv_limits, const MV *mv) {
1765
60.6M
  return (mv->row >> 3) < mv_limits->row_min ||
1766
60.5M
         (mv->row >> 3) > mv_limits->row_max ||
1767
59.6M
         (mv->col >> 3) < mv_limits->col_min ||
1768
59.5M
         (mv->col >> 3) > mv_limits->col_max;
1769
60.6M
}
1770
1771
13.0M
static INLINE void mi_buf_shift(MACROBLOCK *x, int i) {
1772
13.0M
  MODE_INFO *const mi = x->e_mbd.mi[0];
1773
13.0M
  struct macroblock_plane *const p = &x->plane[0];
1774
13.0M
  struct macroblockd_plane *const pd = &x->e_mbd.plane[0];
1775
1776
13.0M
  p->src.buf =
1777
13.0M
      &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1778
13.0M
  assert(((intptr_t)pd->pre[0].buf & 0x7) == 0);
1779
13.0M
  pd->pre[0].buf =
1780
13.0M
      &pd->pre[0].buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[0].stride)];
1781
13.0M
  if (has_second_ref(mi))
1782
0
    pd->pre[1].buf =
1783
0
        &pd->pre[1]
1784
0
             .buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[1].stride)];
1785
13.0M
}
1786
1787
static INLINE void mi_buf_restore(MACROBLOCK *x, struct buf_2d orig_src,
1788
13.0M
                                  struct buf_2d orig_pre[2]) {
1789
13.0M
  MODE_INFO *mi = x->e_mbd.mi[0];
1790
13.0M
  x->plane[0].src = orig_src;
1791
13.0M
  x->e_mbd.plane[0].pre[0] = orig_pre[0];
1792
13.0M
  if (has_second_ref(mi)) x->e_mbd.plane[0].pre[1] = orig_pre[1];
1793
13.0M
}
1794
1795
16.5M
static INLINE int mv_has_subpel(const MV *mv) {
1796
16.5M
  return (mv->row & 0x0F) || (mv->col & 0x0F);
1797
16.5M
}
1798
1799
// Check if NEARESTMV/NEARMV/ZEROMV is the cheapest way encode zero motion.
1800
// TODO(aconverse): Find out if this is still productive then clean up or remove
1801
static int check_best_zero_mv(const VP9_COMP *cpi,
1802
                              const uint8_t mode_context[MAX_REF_FRAMES],
1803
                              int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1804
                              int this_mode,
1805
76.8M
                              const MV_REFERENCE_FRAME ref_frames[2]) {
1806
76.8M
  if ((this_mode == NEARMV || this_mode == NEARESTMV || this_mode == ZEROMV) &&
1807
56.9M
      frame_mv[this_mode][ref_frames[0]].as_int == 0 &&
1808
35.7M
      (ref_frames[1] == NO_REF_FRAME ||
1809
35.7M
       frame_mv[this_mode][ref_frames[1]].as_int == 0)) {
1810
35.7M
    int rfc = mode_context[ref_frames[0]];
1811
35.7M
    int c1 = cost_mv_ref(cpi, NEARMV, rfc);
1812
35.7M
    int c2 = cost_mv_ref(cpi, NEARESTMV, rfc);
1813
35.7M
    int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
1814
1815
35.7M
    if (this_mode == NEARMV) {
1816
10.5M
      if (c1 > c3) return 0;
1817
25.1M
    } else if (this_mode == NEARESTMV) {
1818
6.86M
      if (c2 > c3) return 0;
1819
18.3M
    } else {
1820
18.3M
      assert(this_mode == ZEROMV);
1821
18.3M
      if (ref_frames[1] == NO_REF_FRAME) {
1822
18.3M
        if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0) ||
1823
12.0M
            (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0))
1824
9.29M
          return 0;
1825
18.3M
      } else {
1826
0
        if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0 &&
1827
0
             frame_mv[NEARESTMV][ref_frames[1]].as_int == 0) ||
1828
0
            (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0 &&
1829
0
             frame_mv[NEARMV][ref_frames[1]].as_int == 0))
1830
0
          return 0;
1831
0
      }
1832
18.3M
    }
1833
35.7M
  }
1834
61.8M
  return 1;
1835
76.8M
}
1836
1837
0
static INLINE int skip_iters(int_mv iter_mvs[][2], int ite, int id) {
1838
0
  if (ite >= 2 && iter_mvs[ite - 2][!id].as_int == iter_mvs[ite][!id].as_int) {
1839
0
    int_mv cur_fullpel_mv, prev_fullpel_mv;
1840
0
    cur_fullpel_mv.as_mv.row = iter_mvs[ite][id].as_mv.row >> 3;
1841
0
    cur_fullpel_mv.as_mv.col = iter_mvs[ite][id].as_mv.col >> 3;
1842
0
    prev_fullpel_mv.as_mv.row = iter_mvs[ite - 2][id].as_mv.row >> 3;
1843
0
    prev_fullpel_mv.as_mv.col = iter_mvs[ite - 2][id].as_mv.col >> 3;
1844
0
    if (cur_fullpel_mv.as_int == prev_fullpel_mv.as_int) return 1;
1845
0
  }
1846
0
  return 0;
1847
0
}
1848
1849
// Compares motion vector and mode rate of current mode and given mode.
1850
static INLINE int compare_mv_mode_rate(MV this_mv, MV mode_mv,
1851
                                       int this_mode_rate, int mode_rate,
1852
3.20M
                                       int mv_thresh) {
1853
3.20M
  const int mv_diff =
1854
3.20M
      abs(mode_mv.col - this_mv.col) + abs(mode_mv.row - this_mv.row);
1855
3.20M
  if (mv_diff <= mv_thresh && mode_rate < this_mode_rate) return 1;
1856
2.97M
  return 0;
1857
3.20M
}
1858
1859
// Skips single reference inter modes NEARMV and ZEROMV based on motion vector
1860
// difference and mode rate.
1861
static INLINE int skip_single_mode_based_on_mode_rate(
1862
    int_mv (*mode_mv)[MAX_REF_FRAMES], int *single_mode_rate, int this_mode,
1863
6.01M
    int ref0, int this_mode_rate, int best_mode_index) {
1864
6.01M
  MV this_mv = mode_mv[this_mode][ref0].as_mv;
1865
6.01M
  const int mv_thresh = 3;
1866
1867
  // Pruning is not applicable for NEARESTMV or NEWMV modes.
1868
6.01M
  if (this_mode == NEARESTMV || this_mode == NEWMV) return 0;
1869
  // Pruning is not done when reference frame of the mode is same as best
1870
  // reference so far.
1871
1.84M
  if (best_mode_index > 0 &&
1872
1.22M
      ref0 == vp9_mode_order[best_mode_index].ref_frame[0])
1873
356k
    return 0;
1874
1875
  // Check absolute mv difference and mode rate of current mode w.r.t NEARESTMV
1876
1.48M
  if (compare_mv_mode_rate(
1877
1.48M
          this_mv, mode_mv[NEARESTMV][ref0].as_mv, this_mode_rate,
1878
1.48M
          single_mode_rate[INTER_OFFSET(NEARESTMV)], mv_thresh))
1879
227k
    return 1;
1880
1881
  // Check absolute mv difference and mode rate of current mode w.r.t NEWMV
1882
1.26M
  if (compare_mv_mode_rate(this_mv, mode_mv[NEWMV][ref0].as_mv, this_mode_rate,
1883
1.26M
                           single_mode_rate[INTER_OFFSET(NEWMV)], mv_thresh))
1884
45
    return 1;
1885
1886
  // Pruning w.r.t NEARMV is applicable only for ZEROMV mode
1887
1.26M
  if (this_mode == NEARMV) return 0;
1888
  // Check absolute mv difference and mode rate of current mode w.r.t NEARMV
1889
452k
  if (compare_mv_mode_rate(this_mv, mode_mv[NEARMV][ref0].as_mv, this_mode_rate,
1890
452k
                           single_mode_rate[INTER_OFFSET(NEARMV)], mv_thresh))
1891
524
    return 1;
1892
451k
  return 0;
1893
452k
}
1894
1895
0
#define MAX_JOINT_MV_SEARCH_ITERS 4
1896
0
static INLINE int get_joint_search_iters(int sf_level, BLOCK_SIZE bsize) {
1897
0
  int num_iters = MAX_JOINT_MV_SEARCH_ITERS;  // sf_level = 0
1898
0
  if (sf_level >= 2)
1899
0
    num_iters = 0;
1900
0
  else if (sf_level >= 1)
1901
0
    num_iters = bsize < BLOCK_8X8
1902
0
                    ? 0
1903
0
                    : (bsize <= BLOCK_16X16 ? 2 : MAX_JOINT_MV_SEARCH_ITERS);
1904
0
  return num_iters;
1905
0
}
1906
1907
static void joint_motion_search(VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
1908
                                int_mv *frame_mv, int mi_row, int mi_col,
1909
                                int_mv single_newmv[MAX_REF_FRAMES],
1910
0
                                int *rate_mv, int num_iters) {
1911
0
  const VP9_COMMON *const cm = &cpi->common;
1912
0
  const int pw = 4 * num_4x4_blocks_wide_lookup[bsize];
1913
0
  const int ph = 4 * num_4x4_blocks_high_lookup[bsize];
1914
0
  MACROBLOCKD *xd = &x->e_mbd;
1915
0
  MODE_INFO *mi = xd->mi[0];
1916
0
  const int refs[2] = { mi->ref_frame[0],
1917
0
                        mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1] };
1918
0
  int_mv ref_mv[2];
1919
0
  int_mv iter_mvs[MAX_JOINT_MV_SEARCH_ITERS][2];
1920
0
  int ite, ref;
1921
0
  const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
1922
0
  struct scale_factors sf;
1923
1924
  // Do joint motion search in compound mode to get more accurate mv.
1925
0
  struct buf_2d backup_yv12[2][MAX_MB_PLANE];
1926
0
  uint32_t last_besterr[2] = { UINT_MAX, UINT_MAX };
1927
0
  const YV12_BUFFER_CONFIG *const scaled_ref_frame[2] = {
1928
0
    vp9_get_scaled_ref_frame(cpi, mi->ref_frame[0]),
1929
0
    vp9_get_scaled_ref_frame(cpi, mi->ref_frame[1])
1930
0
  };
1931
1932
// Prediction buffer from second frame.
1933
0
#if CONFIG_VP9_HIGHBITDEPTH
1934
0
  DECLARE_ALIGNED(32, uint16_t, second_pred_alloc_16[64 * 64]);
1935
0
  uint8_t *second_pred;
1936
#else
1937
  DECLARE_ALIGNED(32, uint8_t, second_pred[64 * 64]);
1938
#endif  // CONFIG_VP9_HIGHBITDEPTH
1939
1940
  // Check number of iterations do not exceed the max
1941
0
  assert(num_iters <= MAX_JOINT_MV_SEARCH_ITERS);
1942
1943
0
  for (ref = 0; ref < 2; ++ref) {
1944
0
    ref_mv[ref] = x->mbmi_ext->ref_mvs[refs[ref]][0];
1945
1946
0
    if (scaled_ref_frame[ref]) {
1947
0
      int i;
1948
      // Swap out the reference frame for a version that's been scaled to
1949
      // match the resolution of the current frame, allowing the existing
1950
      // motion search code to be used without additional modifications.
1951
0
      for (i = 0; i < MAX_MB_PLANE; i++)
1952
0
        backup_yv12[ref][i] = xd->plane[i].pre[ref];
1953
0
      vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
1954
0
                           NULL);
1955
0
    }
1956
1957
0
    frame_mv[refs[ref]].as_int = single_newmv[refs[ref]].as_int;
1958
0
    iter_mvs[0][ref].as_int = single_newmv[refs[ref]].as_int;
1959
0
  }
1960
1961
// Since we have scaled the reference frames to match the size of the current
1962
// frame we must use a unit scaling factor during mode selection.
1963
0
#if CONFIG_VP9_HIGHBITDEPTH
1964
0
  vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
1965
0
                                    cm->height, cm->use_highbitdepth);
1966
#else
1967
  vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
1968
                                    cm->height);
1969
#endif  // CONFIG_VP9_HIGHBITDEPTH
1970
1971
  // Allow joint search multiple times iteratively for each reference frame
1972
  // and break out of the search loop if it couldn't find a better mv.
1973
0
  for (ite = 0; ite < num_iters; ite++) {
1974
0
    struct buf_2d ref_yv12[2];
1975
0
    uint32_t bestsme = UINT_MAX;
1976
0
    int sadpb = x->sadperbit16;
1977
0
    MV tmp_mv;
1978
0
    int search_range = 3;
1979
1980
0
    const MvLimits tmp_mv_limits = x->mv_limits;
1981
0
    int id = ite % 2;  // Even iterations search in the first reference frame,
1982
                       // odd iterations search in the second. The predictor
1983
                       // found for the 'other' reference frame is factored in.
1984
1985
    // Skip further iterations of search if in the previous iteration, the
1986
    // motion vector of the searched ref frame is unchanged, and the other ref
1987
    // frame's full-pixel mv is unchanged.
1988
0
    if (skip_iters(iter_mvs, ite, id)) break;
1989
1990
    // Initialized here because of compiler problem in Visual Studio.
1991
0
    ref_yv12[0] = xd->plane[0].pre[0];
1992
0
    ref_yv12[1] = xd->plane[0].pre[1];
1993
1994
// Get the prediction block from the 'other' reference frame.
1995
0
#if CONFIG_VP9_HIGHBITDEPTH
1996
0
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1997
0
      second_pred = CONVERT_TO_BYTEPTR(second_pred_alloc_16);
1998
0
      vp9_highbd_build_inter_predictor(
1999
0
          CONVERT_TO_SHORTPTR(ref_yv12[!id].buf), ref_yv12[!id].stride,
2000
0
          second_pred_alloc_16, pw, &frame_mv[refs[!id]].as_mv, &sf, pw, ph, 0,
2001
0
          kernel, MV_PRECISION_Q3, mi_col * MI_SIZE, mi_row * MI_SIZE, xd->bd);
2002
0
    } else {
2003
0
      second_pred = (uint8_t *)second_pred_alloc_16;
2004
0
      vp9_build_inter_predictor(ref_yv12[!id].buf, ref_yv12[!id].stride,
2005
0
                                second_pred, pw, &frame_mv[refs[!id]].as_mv,
2006
0
                                &sf, pw, ph, 0, kernel, MV_PRECISION_Q3,
2007
0
                                mi_col * MI_SIZE, mi_row * MI_SIZE);
2008
0
    }
2009
#else
2010
    vp9_build_inter_predictor(ref_yv12[!id].buf, ref_yv12[!id].stride,
2011
                              second_pred, pw, &frame_mv[refs[!id]].as_mv, &sf,
2012
                              pw, ph, 0, kernel, MV_PRECISION_Q3,
2013
                              mi_col * MI_SIZE, mi_row * MI_SIZE);
2014
#endif  // CONFIG_VP9_HIGHBITDEPTH
2015
2016
    // Do compound motion search on the current reference frame.
2017
0
    if (id) xd->plane[0].pre[0] = ref_yv12[id];
2018
0
    vp9_set_mv_search_range(&x->mv_limits, &ref_mv[id].as_mv);
2019
2020
    // Use the mv result from the single mode as mv predictor.
2021
0
    tmp_mv = frame_mv[refs[id]].as_mv;
2022
2023
0
    tmp_mv.col >>= 3;
2024
0
    tmp_mv.row >>= 3;
2025
2026
    // Small-range full-pixel motion search.
2027
0
    bestsme = vp9_refining_search_8p_c(x, &tmp_mv, sadpb, search_range,
2028
0
                                       &cpi->fn_ptr[bsize], &ref_mv[id].as_mv,
2029
0
                                       second_pred);
2030
0
    if (bestsme < UINT_MAX)
2031
0
      bestsme = vp9_get_mvpred_av_var(x, &tmp_mv, &ref_mv[id].as_mv,
2032
0
                                      second_pred, &cpi->fn_ptr[bsize], 1);
2033
2034
0
    x->mv_limits = tmp_mv_limits;
2035
2036
0
    if (bestsme < UINT_MAX) {
2037
0
      uint32_t dis; /* TODO: use dis in distortion calculation later. */
2038
0
      uint32_t sse;
2039
0
      bestsme = cpi->find_fractional_mv_step(
2040
0
          x, &tmp_mv, &ref_mv[id].as_mv, cpi->common.allow_high_precision_mv,
2041
0
          x->errorperbit, &cpi->fn_ptr[bsize], 0,
2042
0
          cpi->sf.mv.subpel_search_level, NULL, x->nmvjointcost, x->mvcost,
2043
0
          &dis, &sse, second_pred, pw, ph, cpi->sf.use_accurate_subpel_search);
2044
0
    }
2045
2046
    // Restore the pointer to the first (possibly scaled) prediction buffer.
2047
0
    if (id) xd->plane[0].pre[0] = ref_yv12[0];
2048
2049
0
    if (bestsme < last_besterr[id]) {
2050
0
      frame_mv[refs[id]].as_mv = tmp_mv;
2051
0
      last_besterr[id] = bestsme;
2052
0
    } else {
2053
0
      break;
2054
0
    }
2055
0
    if (ite < num_iters - 1) {
2056
0
      iter_mvs[ite + 1][0].as_int = frame_mv[refs[0]].as_int;
2057
0
      iter_mvs[ite + 1][1].as_int = frame_mv[refs[1]].as_int;
2058
0
    }
2059
0
  }
2060
2061
0
  *rate_mv = 0;
2062
2063
0
  for (ref = 0; ref < 2; ++ref) {
2064
0
    if (scaled_ref_frame[ref]) {
2065
      // Restore the prediction frame pointers to their unscaled versions.
2066
0
      int i;
2067
0
      for (i = 0; i < MAX_MB_PLANE; i++)
2068
0
        xd->plane[i].pre[ref] = backup_yv12[ref][i];
2069
0
    }
2070
2071
0
    *rate_mv += vp9_mv_bit_cost(&frame_mv[refs[ref]].as_mv,
2072
0
                                &x->mbmi_ext->ref_mvs[refs[ref]][0].as_mv,
2073
0
                                x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2074
0
  }
2075
0
}
2076
2077
static int64_t rd_pick_best_sub8x8_mode(
2078
    VP9_COMP *cpi, MACROBLOCK *x, int_mv *best_ref_mv,
2079
    int_mv *second_best_ref_mv, int64_t best_rd_so_far, int *returntotrate,
2080
    int *returnyrate, int64_t *returndistortion, int *skippable, int64_t *psse,
2081
    int mvthresh, int_mv seg_mvs[4][MAX_REF_FRAMES], BEST_SEG_INFO *bsi_buf,
2082
4.67M
    int filter_idx, int mi_row, int mi_col) {
2083
4.67M
  int i;
2084
4.67M
  BEST_SEG_INFO *bsi = bsi_buf + filter_idx;
2085
4.67M
  MACROBLOCKD *xd = &x->e_mbd;
2086
4.67M
  MODE_INFO *mi = xd->mi[0];
2087
4.67M
  int mode_idx;
2088
4.67M
  int k, br = 0, idx, idy;
2089
4.67M
  int64_t bd = 0, block_sse = 0;
2090
4.67M
  PREDICTION_MODE this_mode;
2091
4.67M
  VP9_COMMON *cm = &cpi->common;
2092
4.67M
  struct macroblock_plane *const p = &x->plane[0];
2093
4.67M
  struct macroblockd_plane *const pd = &xd->plane[0];
2094
4.67M
  const int label_count = 4;
2095
4.67M
  int64_t this_segment_rd = 0;
2096
4.67M
  int label_mv_thresh;
2097
4.67M
  int segmentyrate = 0;
2098
4.67M
  const BLOCK_SIZE bsize = mi->sb_type;
2099
4.67M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2100
4.67M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2101
4.67M
  const int pw = num_4x4_blocks_wide << 2;
2102
4.67M
  const int ph = num_4x4_blocks_high << 2;
2103
4.67M
  ENTROPY_CONTEXT t_above[2], t_left[2];
2104
4.67M
  int subpelmv = 1, have_ref = 0;
2105
4.67M
  SPEED_FEATURES *const sf = &cpi->sf;
2106
4.67M
  const int has_second_rf = has_second_ref(mi);
2107
4.67M
  const int inter_mode_mask = sf->inter_mode_mask[bsize];
2108
4.67M
  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2109
2110
4.67M
  vp9_zero(*bsi);
2111
2112
4.67M
  bsi->segment_rd = best_rd_so_far;
2113
4.67M
  bsi->ref_mv[0] = best_ref_mv;
2114
4.67M
  bsi->ref_mv[1] = second_best_ref_mv;
2115
4.67M
  bsi->mvp.as_int = best_ref_mv->as_int;
2116
4.67M
  bsi->mvthresh = mvthresh;
2117
2118
23.3M
  for (i = 0; i < 4; i++) bsi->modes[i] = ZEROMV;
2119
2120
4.67M
  memcpy(t_above, pd->above_context, sizeof(t_above));
2121
4.67M
  memcpy(t_left, pd->left_context, sizeof(t_left));
2122
2123
  // 64 makes this threshold really big effectively
2124
  // making it so that we very rarely check mvs on
2125
  // segments.   setting this to 1 would make mv thresh
2126
  // roughly equal to what it is for macroblocks
2127
4.67M
  label_mv_thresh = 1 * bsi->mvthresh / label_count;
2128
2129
  // Segmentation method overheads
2130
11.0M
  for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
2131
19.9M
    for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
2132
      // TODO(jingning,rbultje): rewrite the rate-distortion optimization
2133
      // loop for 4x4/4x8/8x4 block coding. to be replaced with new rd loop
2134
13.5M
      int_mv mode_mv[MB_MODE_COUNT][2];
2135
13.5M
      int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
2136
13.5M
      PREDICTION_MODE mode_selected = ZEROMV;
2137
13.5M
      int64_t best_rd = INT64_MAX;
2138
13.5M
      const int block = idy * 2 + idx;
2139
13.5M
      int ref;
2140
2141
27.1M
      for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2142
13.5M
        const MV_REFERENCE_FRAME frame = mi->ref_frame[ref];
2143
13.5M
        frame_mv[ZEROMV][frame].as_int = 0;
2144
13.5M
        vp9_append_sub8x8_mvs_for_idx(
2145
13.5M
            cm, xd, block, ref, mi_row, mi_col, &frame_mv[NEARESTMV][frame],
2146
13.5M
            &frame_mv[NEARMV][frame], mbmi_ext->mode_context);
2147
13.5M
      }
2148
2149
      // search for the best motion vector on this segment
2150
67.3M
      for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
2151
54.3M
        const struct buf_2d orig_src = x->plane[0].src;
2152
54.3M
        struct buf_2d orig_pre[2];
2153
2154
54.3M
        mode_idx = INTER_OFFSET(this_mode);
2155
54.3M
        bsi->rdstat[block][mode_idx].brdcost = INT64_MAX;
2156
54.3M
        if (!(inter_mode_mask & (1 << this_mode))) continue;
2157
2158
54.3M
        if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv,
2159
54.3M
                                this_mode, mi->ref_frame))
2160
10.5M
          continue;
2161
2162
43.7M
        memcpy(orig_pre, pd->pre, sizeof(orig_pre));
2163
43.7M
        memcpy(bsi->rdstat[block][mode_idx].ta, t_above,
2164
43.7M
               sizeof(bsi->rdstat[block][mode_idx].ta));
2165
43.7M
        memcpy(bsi->rdstat[block][mode_idx].tl, t_left,
2166
43.7M
               sizeof(bsi->rdstat[block][mode_idx].tl));
2167
2168
        // motion search for newmv (single predictor case only)
2169
43.7M
        if (!has_second_rf && this_mode == NEWMV &&
2170
13.5M
            seg_mvs[block][mi->ref_frame[0]].as_int == INVALID_MV) {
2171
13.5M
          MV *const new_mv = &mode_mv[NEWMV][0].as_mv;
2172
13.5M
          int step_param = 0;
2173
13.5M
          uint32_t bestsme = UINT_MAX;
2174
13.5M
          int sadpb = x->sadperbit4;
2175
13.5M
          MV mvp_full;
2176
13.5M
          int max_mv;
2177
13.5M
          int cost_list[5];
2178
13.5M
          const MvLimits tmp_mv_limits = x->mv_limits;
2179
2180
          /* Is the best so far sufficiently good that we can't justify doing
2181
           * and new motion search. */
2182
13.5M
          if (best_rd < label_mv_thresh) break;
2183
2184
13.0M
          if (cpi->oxcf.mode != BEST) {
2185
            // use previous block's result as next block's MV predictor.
2186
13.0M
            if (block > 0) {
2187
8.49M
              bsi->mvp.as_int = mi->bmi[block - 1].as_mv[0].as_int;
2188
8.49M
              if (block == 2)
2189
3.17M
                bsi->mvp.as_int = mi->bmi[block - 2].as_mv[0].as_int;
2190
8.49M
            }
2191
13.0M
          }
2192
13.0M
          if (block == 0)
2193
4.54M
            max_mv = x->max_mv_context[mi->ref_frame[0]];
2194
8.49M
          else
2195
8.49M
            max_mv =
2196
8.49M
                VPXMAX(abs(bsi->mvp.as_mv.row), abs(bsi->mvp.as_mv.col)) >> 3;
2197
2198
13.0M
          if (sf->mv.auto_mv_step_size && cm->show_frame) {
2199
            // Take wtd average of the step_params based on the last frame's
2200
            // max mv magnitude and the best ref mvs of the current block for
2201
            // the given reference.
2202
13.0M
            step_param =
2203
13.0M
                (vp9_init_search_range(max_mv) + cpi->mv_step_param) / 2;
2204
13.0M
          } else {
2205
0
            step_param = cpi->mv_step_param;
2206
0
          }
2207
2208
13.0M
          mvp_full.row = bsi->mvp.as_mv.row >> 3;
2209
13.0M
          mvp_full.col = bsi->mvp.as_mv.col >> 3;
2210
2211
13.0M
          if (sf->adaptive_motion_search) {
2212
13.0M
            if (x->pred_mv[mi->ref_frame[0]].row != INT16_MAX &&
2213
12.7M
                x->pred_mv[mi->ref_frame[0]].col != INT16_MAX) {
2214
12.7M
              mvp_full.row = x->pred_mv[mi->ref_frame[0]].row >> 3;
2215
12.7M
              mvp_full.col = x->pred_mv[mi->ref_frame[0]].col >> 3;
2216
12.7M
            }
2217
13.0M
            step_param = VPXMAX(step_param, 8);
2218
13.0M
          }
2219
2220
          // adjust src pointer for this block
2221
13.0M
          mi_buf_shift(x, block);
2222
2223
13.0M
          vp9_set_mv_search_range(&x->mv_limits, &bsi->ref_mv[0]->as_mv);
2224
2225
13.0M
          bestsme = vp9_full_pixel_search(
2226
13.0M
              cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method,
2227
13.0M
              sadpb,
2228
13.0M
              sf->mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL,
2229
13.0M
              &bsi->ref_mv[0]->as_mv, new_mv, INT_MAX, 1);
2230
2231
13.0M
          x->mv_limits = tmp_mv_limits;
2232
2233
13.0M
          if (bestsme < UINT_MAX) {
2234
13.0M
            uint32_t distortion;
2235
13.0M
            cpi->find_fractional_mv_step(
2236
13.0M
                x, new_mv, &bsi->ref_mv[0]->as_mv, cm->allow_high_precision_mv,
2237
13.0M
                x->errorperbit, &cpi->fn_ptr[bsize], sf->mv.subpel_force_stop,
2238
13.0M
                sf->mv.subpel_search_level, cond_cost_list(cpi, cost_list),
2239
13.0M
                x->nmvjointcost, x->mvcost, &distortion,
2240
13.0M
                &x->pred_sse[mi->ref_frame[0]], NULL, pw, ph,
2241
13.0M
                cpi->sf.use_accurate_subpel_search);
2242
2243
            // save motion search result for use in compound prediction
2244
13.0M
            seg_mvs[block][mi->ref_frame[0]].as_mv = *new_mv;
2245
13.0M
          }
2246
2247
13.0M
          x->pred_mv[mi->ref_frame[0]] = *new_mv;
2248
2249
          // restore src pointers
2250
13.0M
          mi_buf_restore(x, orig_src, orig_pre);
2251
13.0M
        }
2252
2253
43.2M
        if (has_second_rf) {
2254
0
          if (seg_mvs[block][mi->ref_frame[1]].as_int == INVALID_MV ||
2255
0
              seg_mvs[block][mi->ref_frame[0]].as_int == INVALID_MV)
2256
0
            continue;
2257
0
        }
2258
2259
43.2M
        if (has_second_rf && this_mode == NEWMV &&
2260
0
            mi->interp_filter == EIGHTTAP) {
2261
          // Decide number of joint motion search iterations
2262
0
          const int num_joint_search_iters = get_joint_search_iters(
2263
0
              cpi->sf.comp_inter_joint_search_iter_level, bsize);
2264
          // adjust src pointers
2265
0
          mi_buf_shift(x, block);
2266
0
          if (num_joint_search_iters) {
2267
0
            int rate_mv;
2268
0
            joint_motion_search(cpi, x, bsize, frame_mv[this_mode], mi_row,
2269
0
                                mi_col, seg_mvs[block], &rate_mv,
2270
0
                                num_joint_search_iters);
2271
0
            seg_mvs[block][mi->ref_frame[0]].as_int =
2272
0
                frame_mv[this_mode][mi->ref_frame[0]].as_int;
2273
0
            seg_mvs[block][mi->ref_frame[1]].as_int =
2274
0
                frame_mv[this_mode][mi->ref_frame[1]].as_int;
2275
0
          }
2276
          // restore src pointers
2277
0
          mi_buf_restore(x, orig_src, orig_pre);
2278
0
        }
2279
2280
43.2M
        bsi->rdstat[block][mode_idx].brate = set_and_cost_bmi_mvs(
2281
43.2M
            cpi, x, xd, block, this_mode, mode_mv[this_mode], frame_mv,
2282
43.2M
            seg_mvs[block], bsi->ref_mv, x->nmvjointcost, x->mvcost);
2283
2284
86.4M
        for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2285
43.2M
          bsi->rdstat[block][mode_idx].mvs[ref].as_int =
2286
43.2M
              mode_mv[this_mode][ref].as_int;
2287
43.2M
          if (num_4x4_blocks_wide > 1)
2288
6.38M
            bsi->rdstat[block + 1][mode_idx].mvs[ref].as_int =
2289
6.38M
                mode_mv[this_mode][ref].as_int;
2290
43.2M
          if (num_4x4_blocks_high > 1)
2291
6.45M
            bsi->rdstat[block + 2][mode_idx].mvs[ref].as_int =
2292
6.45M
                mode_mv[this_mode][ref].as_int;
2293
43.2M
        }
2294
2295
        // Trap vectors that reach beyond the UMV borders
2296
43.2M
        if (mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][0].as_mv) ||
2297
42.0M
            (has_second_rf &&
2298
0
             mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][1].as_mv)))
2299
1.22M
          continue;
2300
2301
42.0M
        if (filter_idx > 0) {
2302
0
          BEST_SEG_INFO *ref_bsi = bsi_buf;
2303
0
          subpelmv = 0;
2304
0
          have_ref = 1;
2305
2306
0
          for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2307
0
            subpelmv |= mv_has_subpel(&mode_mv[this_mode][ref].as_mv);
2308
0
            have_ref &= mode_mv[this_mode][ref].as_int ==
2309
0
                        ref_bsi->rdstat[block][mode_idx].mvs[ref].as_int;
2310
0
          }
2311
2312
0
          if (filter_idx > 1 && !subpelmv && !have_ref) {
2313
0
            ref_bsi = bsi_buf + 1;
2314
0
            have_ref = 1;
2315
0
            for (ref = 0; ref < 1 + has_second_rf; ++ref)
2316
0
              have_ref &= mode_mv[this_mode][ref].as_int ==
2317
0
                          ref_bsi->rdstat[block][mode_idx].mvs[ref].as_int;
2318
0
          }
2319
2320
0
          if (!subpelmv && have_ref &&
2321
0
              ref_bsi->rdstat[block][mode_idx].brdcost < INT64_MAX) {
2322
0
            bsi->rdstat[block][mode_idx] = ref_bsi->rdstat[block][mode_idx];
2323
0
            if (num_4x4_blocks_wide > 1)
2324
0
              bsi->rdstat[block + 1][mode_idx].eobs =
2325
0
                  ref_bsi->rdstat[block + 1][mode_idx].eobs;
2326
0
            if (num_4x4_blocks_high > 1)
2327
0
              bsi->rdstat[block + 2][mode_idx].eobs =
2328
0
                  ref_bsi->rdstat[block + 2][mode_idx].eobs;
2329
2330
0
            if (bsi->rdstat[block][mode_idx].brdcost < best_rd) {
2331
0
              mode_selected = this_mode;
2332
0
              best_rd = bsi->rdstat[block][mode_idx].brdcost;
2333
0
            }
2334
0
            continue;
2335
0
          }
2336
0
        }
2337
2338
42.0M
        bsi->rdstat[block][mode_idx].brdcost = encode_inter_mb_segment(
2339
42.0M
            cpi, x, bsi->segment_rd - this_segment_rd, block,
2340
42.0M
            &bsi->rdstat[block][mode_idx].byrate,
2341
42.0M
            &bsi->rdstat[block][mode_idx].bdist,
2342
42.0M
            &bsi->rdstat[block][mode_idx].bsse, bsi->rdstat[block][mode_idx].ta,
2343
42.0M
            bsi->rdstat[block][mode_idx].tl, mi_row, mi_col);
2344
42.0M
        if (bsi->rdstat[block][mode_idx].brdcost < INT64_MAX) {
2345
35.2M
          bsi->rdstat[block][mode_idx].brdcost += RDCOST(
2346
35.2M
              x->rdmult, x->rddiv, bsi->rdstat[block][mode_idx].brate, 0);
2347
35.2M
          bsi->rdstat[block][mode_idx].brate +=
2348
35.2M
              bsi->rdstat[block][mode_idx].byrate;
2349
35.2M
          bsi->rdstat[block][mode_idx].eobs = p->eobs[block];
2350
35.2M
          if (num_4x4_blocks_wide > 1)
2351
4.45M
            bsi->rdstat[block + 1][mode_idx].eobs = p->eobs[block + 1];
2352
35.2M
          if (num_4x4_blocks_high > 1)
2353
4.44M
            bsi->rdstat[block + 2][mode_idx].eobs = p->eobs[block + 2];
2354
35.2M
        }
2355
2356
42.0M
        if (bsi->rdstat[block][mode_idx].brdcost < best_rd) {
2357
17.7M
          mode_selected = this_mode;
2358
17.7M
          best_rd = bsi->rdstat[block][mode_idx].brdcost;
2359
17.7M
        }
2360
42.0M
      } /*for each 4x4 mode*/
2361
2362
13.5M
      if (best_rd == INT64_MAX) {
2363
1.26M
        int iy, midx;
2364
2.94M
        for (iy = block + 1; iy < 4; ++iy)
2365
8.36M
          for (midx = 0; midx < INTER_MODES; ++midx)
2366
6.68M
            bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2367
1.26M
        bsi->segment_rd = INT64_MAX;
2368
1.26M
        return INT64_MAX;
2369
1.26M
      }
2370
2371
12.3M
      mode_idx = INTER_OFFSET(mode_selected);
2372
12.3M
      memcpy(t_above, bsi->rdstat[block][mode_idx].ta, sizeof(t_above));
2373
12.3M
      memcpy(t_left, bsi->rdstat[block][mode_idx].tl, sizeof(t_left));
2374
2375
12.3M
      set_and_cost_bmi_mvs(cpi, x, xd, block, mode_selected,
2376
12.3M
                           mode_mv[mode_selected], frame_mv, seg_mvs[block],
2377
12.3M
                           bsi->ref_mv, x->nmvjointcost, x->mvcost);
2378
2379
12.3M
      br += bsi->rdstat[block][mode_idx].brate;
2380
12.3M
      bd += bsi->rdstat[block][mode_idx].bdist;
2381
12.3M
      block_sse += bsi->rdstat[block][mode_idx].bsse;
2382
12.3M
      segmentyrate += bsi->rdstat[block][mode_idx].byrate;
2383
12.3M
      this_segment_rd += bsi->rdstat[block][mode_idx].brdcost;
2384
2385
12.3M
      if (this_segment_rd > bsi->segment_rd) {
2386
391k
        int iy, midx;
2387
995k
        for (iy = block + 1; iy < 4; ++iy)
2388
3.01M
          for (midx = 0; midx < INTER_MODES; ++midx)
2389
2.41M
            bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2390
391k
        bsi->segment_rd = INT64_MAX;
2391
391k
        return INT64_MAX;
2392
391k
      }
2393
12.3M
    }
2394
7.98M
  } /* for each label */
2395
2396
3.01M
  bsi->r = br;
2397
3.01M
  bsi->d = bd;
2398
3.01M
  bsi->segment_yrate = segmentyrate;
2399
3.01M
  bsi->segment_rd = this_segment_rd;
2400
3.01M
  bsi->sse = block_sse;
2401
2402
  // update the coding decisions
2403
15.0M
  for (k = 0; k < 4; ++k) bsi->modes[k] = mi->bmi[k].as_mode;
2404
2405
3.01M
  if (bsi->segment_rd > best_rd_so_far) return INT64_MAX;
2406
  /* set it to the best */
2407
15.0M
  for (i = 0; i < 4; i++) {
2408
12.0M
    mode_idx = INTER_OFFSET(bsi->modes[i]);
2409
12.0M
    mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int;
2410
12.0M
    if (has_second_ref(mi))
2411
0
      mi->bmi[i].as_mv[1].as_int = bsi->rdstat[i][mode_idx].mvs[1].as_int;
2412
12.0M
    x->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
2413
12.0M
    mi->bmi[i].as_mode = bsi->modes[i];
2414
12.0M
  }
2415
2416
  /*
2417
   * used to set mbmi->mv.as_int
2418
   */
2419
3.01M
  *returntotrate = bsi->r;
2420
3.01M
  *returndistortion = bsi->d;
2421
3.01M
  *returnyrate = bsi->segment_yrate;
2422
3.01M
  *skippable = vp9_is_skippable_in_plane(x, BLOCK_8X8, 0);
2423
3.01M
  *psse = bsi->sse;
2424
3.01M
  mi->mode = bsi->modes[3];
2425
2426
3.01M
  return bsi->segment_rd;
2427
3.01M
}
2428
2429
static void estimate_ref_frame_costs(const VP9_COMMON *cm,
2430
                                     const MACROBLOCKD *xd, int segment_id,
2431
                                     unsigned int *ref_costs_single,
2432
                                     unsigned int *ref_costs_comp,
2433
5.45M
                                     vpx_prob *comp_mode_p) {
2434
5.45M
  int seg_ref_active =
2435
5.45M
      segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME);
2436
5.45M
  if (seg_ref_active) {
2437
0
    memset(ref_costs_single, 0, MAX_REF_FRAMES * sizeof(*ref_costs_single));
2438
0
    memset(ref_costs_comp, 0, MAX_REF_FRAMES * sizeof(*ref_costs_comp));
2439
0
    *comp_mode_p = 128;
2440
5.45M
  } else {
2441
5.45M
    vpx_prob intra_inter_p = vp9_get_intra_inter_prob(cm, xd);
2442
5.45M
    vpx_prob comp_inter_p = 128;
2443
2444
5.45M
    if (cm->reference_mode == REFERENCE_MODE_SELECT) {
2445
0
      comp_inter_p = vp9_get_reference_mode_prob(cm, xd);
2446
0
      *comp_mode_p = comp_inter_p;
2447
5.45M
    } else {
2448
5.45M
      *comp_mode_p = 128;
2449
5.45M
    }
2450
2451
5.45M
    ref_costs_single[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
2452
2453
5.45M
    if (cm->reference_mode != COMPOUND_REFERENCE) {
2454
5.45M
      vpx_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
2455
5.45M
      vpx_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
2456
5.45M
      unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
2457
2458
5.45M
      if (cm->reference_mode == REFERENCE_MODE_SELECT)
2459
0
        base_cost += vp9_cost_bit(comp_inter_p, 0);
2460
2461
5.45M
      ref_costs_single[LAST_FRAME] = ref_costs_single[GOLDEN_FRAME] =
2462
5.45M
          ref_costs_single[ALTREF_FRAME] = base_cost;
2463
5.45M
      ref_costs_single[LAST_FRAME] += vp9_cost_bit(ref_single_p1, 0);
2464
5.45M
      ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
2465
5.45M
      ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
2466
5.45M
      ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
2467
5.45M
      ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
2468
5.45M
    } else {
2469
0
      ref_costs_single[LAST_FRAME] = 512;
2470
0
      ref_costs_single[GOLDEN_FRAME] = 512;
2471
0
      ref_costs_single[ALTREF_FRAME] = 512;
2472
0
    }
2473
5.45M
    if (cm->reference_mode != SINGLE_REFERENCE) {
2474
0
      vpx_prob ref_comp_p = vp9_get_pred_prob_comp_ref_p(cm, xd);
2475
0
      unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
2476
2477
0
      if (cm->reference_mode == REFERENCE_MODE_SELECT)
2478
0
        base_cost += vp9_cost_bit(comp_inter_p, 1);
2479
2480
0
      ref_costs_comp[LAST_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 0);
2481
0
      ref_costs_comp[GOLDEN_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 1);
2482
5.45M
    } else {
2483
5.45M
      ref_costs_comp[LAST_FRAME] = 512;
2484
5.45M
      ref_costs_comp[GOLDEN_FRAME] = 512;
2485
5.45M
    }
2486
5.45M
  }
2487
5.45M
}
2488
2489
static void store_coding_context(
2490
    MACROBLOCK *x, PICK_MODE_CONTEXT *ctx, int mode_index,
2491
    int64_t comp_pred_diff[REFERENCE_MODES],
2492
3.29M
    int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS], int skippable) {
2493
3.29M
  MACROBLOCKD *const xd = &x->e_mbd;
2494
2495
  // Take a snapshot of the coding context so it can be
2496
  // restored if we decide to encode this way
2497
3.29M
  ctx->skip = x->skip;
2498
3.29M
  ctx->skippable = skippable;
2499
3.29M
  ctx->best_mode_index = mode_index;
2500
3.29M
  ctx->mic = *xd->mi[0];
2501
3.29M
  ctx->mbmi_ext = *x->mbmi_ext;
2502
3.29M
  ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_REFERENCE];
2503
3.29M
  ctx->comp_pred_diff = (int)comp_pred_diff[COMPOUND_REFERENCE];
2504
3.29M
  ctx->hybrid_pred_diff = (int)comp_pred_diff[REFERENCE_MODE_SELECT];
2505
2506
3.29M
  memcpy(ctx->best_filter_diff, best_filter_diff,
2507
3.29M
         sizeof(*best_filter_diff) * SWITCHABLE_FILTER_CONTEXTS);
2508
3.29M
}
2509
2510
static void setup_buffer_inter(VP9_COMP *cpi, MACROBLOCK *x,
2511
                               MV_REFERENCE_FRAME ref_frame,
2512
                               BLOCK_SIZE block_size, int mi_row, int mi_col,
2513
                               int_mv frame_nearest_mv[MAX_REF_FRAMES],
2514
                               int_mv frame_near_mv[MAX_REF_FRAMES],
2515
11.7M
                               struct buf_2d yv12_mb[4][MAX_MB_PLANE]) {
2516
11.7M
  const VP9_COMMON *cm = &cpi->common;
2517
11.7M
  const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
2518
11.7M
  MACROBLOCKD *const xd = &x->e_mbd;
2519
11.7M
  MODE_INFO *const mi = xd->mi[0];
2520
11.7M
  int_mv *const candidates = x->mbmi_ext->ref_mvs[ref_frame];
2521
11.7M
  const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
2522
11.7M
  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2523
2524
11.7M
  assert(yv12 != NULL);
2525
2526
  // TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this
2527
  // use the UV scaling factors.
2528
11.7M
  vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
2529
2530
  // Gets an initial list of candidate vectors from neighbours and orders them
2531
11.7M
  vp9_find_mv_refs(cm, xd, mi, ref_frame, candidates, mi_row, mi_col,
2532
11.7M
                   mbmi_ext->mode_context);
2533
2534
  // Candidate refinement carried out at encoder and decoder
2535
11.7M
  vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
2536
11.7M
                        &frame_nearest_mv[ref_frame],
2537
11.7M
                        &frame_near_mv[ref_frame]);
2538
2539
  // Further refinement that is encode side only to test the top few candidates
2540
  // in full and choose the best as the centre point for subsequent searches.
2541
  // The current implementation doesn't support scaling.
2542
11.7M
  if (!vp9_is_scaled(sf) && block_size >= BLOCK_8X8)
2543
6.44M
    vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride, ref_frame,
2544
6.44M
                block_size);
2545
11.7M
}
2546
2547
#if CONFIG_NON_GREEDY_MV
2548
static int ref_frame_to_gf_rf_idx(int ref_frame) {
2549
  if (ref_frame == GOLDEN_FRAME) {
2550
    return 0;
2551
  }
2552
  if (ref_frame == LAST_FRAME) {
2553
    return 1;
2554
  }
2555
  if (ref_frame == ALTREF_FRAME) {
2556
    return 2;
2557
  }
2558
  assert(0);
2559
  return -1;
2560
}
2561
#endif
2562
2563
static void single_motion_search(VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
2564
                                 int mi_row, int mi_col, int_mv *tmp_mv,
2565
6.35M
                                 int *rate_mv) {
2566
6.35M
  MACROBLOCKD *xd = &x->e_mbd;
2567
6.35M
  const VP9_COMMON *cm = &cpi->common;
2568
6.35M
  MODE_INFO *mi = xd->mi[0];
2569
6.35M
  struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0 } };
2570
6.35M
  int step_param;
2571
6.35M
  MV mvp_full;
2572
6.35M
  int ref = mi->ref_frame[0];
2573
6.35M
  MV ref_mv = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2574
6.35M
  const MvLimits tmp_mv_limits = x->mv_limits;
2575
6.35M
  int cost_list[5];
2576
6.35M
  const int best_predmv_idx = x->mv_best_ref_index[ref];
2577
6.35M
  const YV12_BUFFER_CONFIG *scaled_ref_frame =
2578
6.35M
      vp9_get_scaled_ref_frame(cpi, ref);
2579
6.35M
  const int pw = num_4x4_blocks_wide_lookup[bsize] << 2;
2580
6.35M
  const int ph = num_4x4_blocks_high_lookup[bsize] << 2;
2581
6.35M
  MV pred_mv[3];
2582
2583
6.35M
  int bestsme = INT_MAX;
2584
#if CONFIG_NON_GREEDY_MV
2585
  int gf_group_idx = cpi->twopass.gf_group.index;
2586
  int gf_rf_idx = ref_frame_to_gf_rf_idx(ref);
2587
  BLOCK_SIZE square_bsize = get_square_block_size(bsize);
2588
  int_mv nb_full_mvs[NB_MVS_NUM] = { 0 };
2589
  MotionField *motion_field = vp9_motion_field_info_get_motion_field(
2590
      &cpi->motion_field_info, gf_group_idx, gf_rf_idx, square_bsize);
2591
  const int nb_full_mv_num =
2592
      vp9_prepare_nb_full_mvs(motion_field, mi_row, mi_col, nb_full_mvs);
2593
  const int lambda = (pw * ph) / 4;
2594
  assert(pw * ph == lambda << 2);
2595
#else   // CONFIG_NON_GREEDY_MV
2596
6.35M
  int sadpb = x->sadperbit16;
2597
6.35M
#endif  // CONFIG_NON_GREEDY_MV
2598
2599
6.35M
  pred_mv[0] = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2600
6.35M
  pred_mv[1] = x->mbmi_ext->ref_mvs[ref][1].as_mv;
2601
6.35M
  pred_mv[2] = x->pred_mv[ref];
2602
2603
6.35M
  if (scaled_ref_frame) {
2604
0
    int i;
2605
    // Swap out the reference frame for a version that's been scaled to
2606
    // match the resolution of the current frame, allowing the existing
2607
    // motion search code to be used without additional modifications.
2608
0
    for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
2609
2610
0
    vp9_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
2611
0
  }
2612
2613
  // Work out the size of the first step in the mv step search.
2614
  // 0 here is maximum length first step. 1 is VPXMAX >> 1 etc.
2615
6.35M
  if (cpi->sf.mv.auto_mv_step_size && cm->show_frame) {
2616
    // Take wtd average of the step_params based on the last frame's
2617
    // max mv magnitude and that based on the best ref mvs of the current
2618
    // block for the given reference.
2619
6.35M
    step_param =
2620
6.35M
        (vp9_init_search_range(x->max_mv_context[ref]) + cpi->mv_step_param) /
2621
6.35M
        2;
2622
6.35M
  } else {
2623
0
    step_param = cpi->mv_step_param;
2624
0
  }
2625
2626
6.35M
  if (cpi->sf.adaptive_motion_search && bsize < BLOCK_64X64) {
2627
6.31M
    const int boffset =
2628
6.31M
        2 * (b_width_log2_lookup[BLOCK_64X64] -
2629
6.31M
             VPXMIN(b_height_log2_lookup[bsize], b_width_log2_lookup[bsize]));
2630
6.31M
    step_param = VPXMAX(step_param, boffset);
2631
6.31M
  }
2632
2633
6.35M
  if (cpi->sf.adaptive_motion_search) {
2634
6.35M
    int bwl = b_width_log2_lookup[bsize];
2635
6.35M
    int bhl = b_height_log2_lookup[bsize];
2636
6.35M
    int tlevel = x->pred_mv_sad[ref] >> (bwl + bhl + 4);
2637
2638
6.35M
    if (tlevel < 5) step_param += 2;
2639
2640
    // prev_mv_sad is not setup for dynamically scaled frames.
2641
6.35M
    if (cpi->oxcf.resize_mode != RESIZE_DYNAMIC) {
2642
6.35M
      int i;
2643
23.6M
      for (i = LAST_FRAME; i <= ALTREF_FRAME && cm->show_frame; ++i) {
2644
17.9M
        if ((x->pred_mv_sad[ref] >> 3) > x->pred_mv_sad[i]) {
2645
671k
          x->pred_mv[ref].row = INT16_MAX;
2646
671k
          x->pred_mv[ref].col = INT16_MAX;
2647
671k
          tmp_mv->as_int = INVALID_MV;
2648
2649
671k
          if (scaled_ref_frame) {
2650
0
            int j;
2651
0
            for (j = 0; j < MAX_MB_PLANE; ++j)
2652
0
              xd->plane[j].pre[0] = backup_yv12[j];
2653
0
          }
2654
671k
          return;
2655
671k
        }
2656
17.9M
      }
2657
6.35M
    }
2658
6.35M
  }
2659
2660
  // Note: MV limits are modified here. Always restore the original values
2661
  // after full-pixel motion search.
2662
5.68M
  vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
2663
2664
5.68M
  mvp_full = pred_mv[best_predmv_idx];
2665
5.68M
  mvp_full.col >>= 3;
2666
5.68M
  mvp_full.row >>= 3;
2667
2668
#if CONFIG_NON_GREEDY_MV
2669
  bestsme = vp9_full_pixel_diamond_new(cpi, x, bsize, &mvp_full, step_param,
2670
                                       lambda, 1, nb_full_mvs, nb_full_mv_num,
2671
                                       &tmp_mv->as_mv);
2672
#else   // CONFIG_NON_GREEDY_MV
2673
5.68M
  bestsme = vp9_full_pixel_search(
2674
5.68M
      cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method, sadpb,
2675
5.68M
      cond_cost_list(cpi, cost_list), &ref_mv, &tmp_mv->as_mv, INT_MAX, 1);
2676
5.68M
#endif  // CONFIG_NON_GREEDY_MV
2677
2678
5.68M
  if (cpi->sf.enhanced_full_pixel_motion_search) {
2679
2.17M
    int i;
2680
8.71M
    for (i = 0; i < 3; ++i) {
2681
6.53M
      int this_me;
2682
6.53M
      MV this_mv;
2683
6.53M
      int diff_row;
2684
6.53M
      int diff_col;
2685
6.53M
      int step;
2686
2687
6.53M
      if (pred_mv[i].row == INT16_MAX || pred_mv[i].col == INT16_MAX) continue;
2688
6.40M
      if (i == best_predmv_idx) continue;
2689
2690
4.22M
      diff_row = ((int)pred_mv[i].row -
2691
4.22M
                  pred_mv[i > 0 ? (i - 1) : best_predmv_idx].row) >>
2692
4.22M
                 3;
2693
4.22M
      diff_col = ((int)pred_mv[i].col -
2694
4.22M
                  pred_mv[i > 0 ? (i - 1) : best_predmv_idx].col) >>
2695
4.22M
                 3;
2696
4.22M
      if (diff_row == 0 && diff_col == 0) continue;
2697
3.19M
      if (diff_row < 0) diff_row = -diff_row;
2698
3.19M
      if (diff_col < 0) diff_col = -diff_col;
2699
3.19M
      step = get_msb((diff_row + diff_col + 1) >> 1);
2700
3.19M
      if (step <= 0) continue;
2701
2702
2.97M
      mvp_full = pred_mv[i];
2703
2.97M
      mvp_full.col >>= 3;
2704
2.97M
      mvp_full.row >>= 3;
2705
#if CONFIG_NON_GREEDY_MV
2706
      this_me = vp9_full_pixel_diamond_new(
2707
          cpi, x, bsize, &mvp_full,
2708
          VPXMAX(step_param, MAX_MVSEARCH_STEPS - step), lambda, 1, nb_full_mvs,
2709
          nb_full_mv_num, &this_mv);
2710
#else   // CONFIG_NON_GREEDY_MV
2711
2.97M
      this_me = vp9_full_pixel_search(
2712
2.97M
          cpi, x, bsize, &mvp_full,
2713
2.97M
          VPXMAX(step_param, MAX_MVSEARCH_STEPS - step),
2714
2.97M
          cpi->sf.mv.search_method, sadpb, cond_cost_list(cpi, cost_list),
2715
2.97M
          &ref_mv, &this_mv, INT_MAX, 1);
2716
2.97M
#endif  // CONFIG_NON_GREEDY_MV
2717
2.97M
      if (this_me < bestsme) {
2718
465k
        tmp_mv->as_mv = this_mv;
2719
465k
        bestsme = this_me;
2720
465k
      }
2721
2.97M
    }
2722
2.17M
  }
2723
2724
5.68M
  x->mv_limits = tmp_mv_limits;
2725
2726
5.68M
  if (bestsme < INT_MAX) {
2727
5.68M
    uint32_t dis; /* TODO: use dis in distortion calculation later. */
2728
5.68M
    cpi->find_fractional_mv_step(
2729
5.68M
        x, &tmp_mv->as_mv, &ref_mv, cm->allow_high_precision_mv, x->errorperbit,
2730
5.68M
        &cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop,
2731
5.68M
        cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list),
2732
5.68M
        x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[ref], NULL, pw, ph,
2733
5.68M
        cpi->sf.use_accurate_subpel_search);
2734
5.68M
  }
2735
5.68M
  *rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv, x->nmvjointcost,
2736
5.68M
                             x->mvcost, MV_COST_WEIGHT);
2737
2738
5.68M
  x->pred_mv[ref] = tmp_mv->as_mv;
2739
2740
5.68M
  if (scaled_ref_frame) {
2741
0
    int i;
2742
0
    for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2743
0
  }
2744
5.68M
}
2745
2746
static INLINE void restore_dst_buf(MACROBLOCKD *xd,
2747
                                   uint8_t *orig_dst[MAX_MB_PLANE],
2748
41.5M
                                   int orig_dst_stride[MAX_MB_PLANE]) {
2749
41.5M
  int i;
2750
166M
  for (i = 0; i < MAX_MB_PLANE; i++) {
2751
124M
    xd->plane[i].dst.buf = orig_dst[i];
2752
124M
    xd->plane[i].dst.stride = orig_dst_stride[i];
2753
124M
  }
2754
41.5M
}
2755
2756
// In some situations we want to discount tha pparent cost of a new motion
2757
// vector. Where there is a subtle motion field and especially where there is
2758
// low spatial complexity then it can be hard to cover the cost of a new motion
2759
// vector in a single block, even if that motion vector reduces distortion.
2760
// However, once established that vector may be usable through the nearest and
2761
// near mv modes to reduce distortion in subsequent blocks and also improve
2762
// visual quality.
2763
static int discount_newmv_test(VP9_COMP *cpi, int this_mode, int_mv this_mv,
2764
                               int_mv (*mode_mv)[MAX_REF_FRAMES], int ref_frame,
2765
22.6M
                               int mi_row, int mi_col, BLOCK_SIZE bsize) {
2766
#if CONFIG_NON_GREEDY_MV
2767
  (void)mode_mv;
2768
  (void)this_mv;
2769
  if (this_mode == NEWMV && bsize >= BLOCK_8X8 && cpi->tpl_ready) {
2770
    const int gf_group_idx = cpi->twopass.gf_group.index;
2771
    const int gf_rf_idx = ref_frame_to_gf_rf_idx(ref_frame);
2772
    const TplDepFrame tpl_frame = cpi->tpl_stats[gf_group_idx];
2773
    const MotionField *motion_field = vp9_motion_field_info_get_motion_field(
2774
        &cpi->motion_field_info, gf_group_idx, gf_rf_idx, cpi->tpl_bsize);
2775
    const int tpl_block_mi_h = num_8x8_blocks_high_lookup[cpi->tpl_bsize];
2776
    const int tpl_block_mi_w = num_8x8_blocks_wide_lookup[cpi->tpl_bsize];
2777
    const int tpl_mi_row = mi_row - (mi_row % tpl_block_mi_h);
2778
    const int tpl_mi_col = mi_col - (mi_col % tpl_block_mi_w);
2779
    const int mv_mode =
2780
        tpl_frame
2781
            .mv_mode_arr[gf_rf_idx][tpl_mi_row * tpl_frame.stride + tpl_mi_col];
2782
    if (mv_mode == NEW_MV_MODE) {
2783
      int_mv tpl_new_mv =
2784
          vp9_motion_field_mi_get_mv(motion_field, tpl_mi_row, tpl_mi_col);
2785
      int row_diff = abs(tpl_new_mv.as_mv.row - this_mv.as_mv.row);
2786
      int col_diff = abs(tpl_new_mv.as_mv.col - this_mv.as_mv.col);
2787
      if (VPXMAX(row_diff, col_diff) <= 8) {
2788
        return 1;
2789
      } else {
2790
        return 0;
2791
      }
2792
    } else {
2793
      return 0;
2794
    }
2795
  } else {
2796
    return 0;
2797
  }
2798
#else
2799
22.6M
  (void)mi_row;
2800
22.6M
  (void)mi_col;
2801
22.6M
  (void)bsize;
2802
22.6M
  return (!cpi->rc.is_src_frame_alt_ref && (this_mode == NEWMV) &&
2803
11.3M
          (this_mv.as_int != 0) &&
2804
10.5M
          ((mode_mv[NEARESTMV][ref_frame].as_int == 0) ||
2805
6.67M
           (mode_mv[NEARESTMV][ref_frame].as_int == INVALID_MV)) &&
2806
3.83M
          ((mode_mv[NEARMV][ref_frame].as_int == 0) ||
2807
285k
           (mode_mv[NEARMV][ref_frame].as_int == INVALID_MV)));
2808
22.6M
#endif
2809
22.6M
}
2810
2811
static int64_t handle_inter_mode(
2812
    VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int *rate2,
2813
    int64_t *distortion, int *skippable, int *rate_y, int *rate_uv,
2814
    struct buf_2d *recon, int *disable_skip, int_mv (*mode_mv)[MAX_REF_FRAMES],
2815
    int mi_row, int mi_col, int_mv single_newmv[MAX_REF_FRAMES],
2816
    INTERP_FILTER (*single_filter)[MAX_REF_FRAMES],
2817
    int (*single_skippable)[MAX_REF_FRAMES], int *single_mode_rate,
2818
    int64_t *psse, const int64_t ref_best_rd, int64_t *mask_filter,
2819
18.1M
    int64_t filter_cache[], int best_mode_index) {
2820
18.1M
  VP9_COMMON *cm = &cpi->common;
2821
18.1M
  MACROBLOCKD *xd = &x->e_mbd;
2822
18.1M
  MODE_INFO *mi = xd->mi[0];
2823
18.1M
  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2824
18.1M
  const int is_comp_pred = has_second_ref(mi);
2825
18.1M
  const int this_mode = mi->mode;
2826
18.1M
  int_mv *frame_mv = mode_mv[this_mode];
2827
18.1M
  int i;
2828
18.1M
  int refs[2] = { mi->ref_frame[0],
2829
18.1M
                  (mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1]) };
2830
18.1M
  int_mv cur_mv[2];
2831
18.1M
#if CONFIG_VP9_HIGHBITDEPTH
2832
18.1M
  DECLARE_ALIGNED(16, uint16_t, tmp_buf16[MAX_MB_PLANE * 64 * 64]);
2833
18.1M
  uint8_t *tmp_buf;
2834
#else
2835
  DECLARE_ALIGNED(16, uint8_t, tmp_buf[MAX_MB_PLANE * 64 * 64]);
2836
#endif  // CONFIG_VP9_HIGHBITDEPTH
2837
18.1M
  int intpel_mv;
2838
18.1M
  int64_t rd, tmp_rd = INT64_MAX, best_rd = INT64_MAX;
2839
18.1M
  int best_needs_copy = 0;
2840
18.1M
  uint8_t *orig_dst[MAX_MB_PLANE];
2841
18.1M
  int orig_dst_stride[MAX_MB_PLANE];
2842
18.1M
  int rs = 0;
2843
18.1M
  INTERP_FILTER best_filter = SWITCHABLE;
2844
18.1M
  uint8_t skip_txfm[MAX_MB_PLANE << 2] = { 0 };
2845
18.1M
  int64_t bsse[MAX_MB_PLANE << 2] = { 0 };
2846
2847
18.1M
  const int bsl = mi_width_log2_lookup[bsize];
2848
18.1M
  const int blk_parity = (((mi_row + mi_col) >> bsl) +
2849
18.1M
                          get_chessboard_index(cm->current_video_frame)) &
2850
18.1M
                         0x1;
2851
18.1M
  const int pred_filter_search =
2852
18.1M
      (cpi->sf.cb_pred_filter_search >= 2) && blk_parity;
2853
2854
18.1M
  int skip_txfm_sb = 0;
2855
18.1M
  int64_t skip_sse_sb = INT64_MAX;
2856
18.1M
  int64_t distortion_y = 0, distortion_uv = 0;
2857
2858
18.1M
#if CONFIG_VP9_HIGHBITDEPTH
2859
18.1M
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2860
209k
    tmp_buf = CONVERT_TO_BYTEPTR(tmp_buf16);
2861
17.9M
  } else {
2862
17.9M
    tmp_buf = (uint8_t *)tmp_buf16;
2863
17.9M
  }
2864
18.1M
#endif  // CONFIG_VP9_HIGHBITDEPTH
2865
2866
18.1M
  if (pred_filter_search) {
2867
0
    INTERP_FILTER af = SWITCHABLE, lf = SWITCHABLE;
2868
0
    if (xd->above_mi && is_inter_block(xd->above_mi))
2869
0
      af = xd->above_mi->interp_filter;
2870
0
    if (xd->left_mi && is_inter_block(xd->left_mi))
2871
0
      lf = xd->left_mi->interp_filter;
2872
2873
0
    if ((this_mode != NEWMV) || (af == lf)) best_filter = af;
2874
0
  }
2875
2876
18.1M
  if (is_comp_pred) {
2877
0
    if (frame_mv[refs[0]].as_int == INVALID_MV ||
2878
0
        frame_mv[refs[1]].as_int == INVALID_MV)
2879
0
      return INT64_MAX;
2880
2881
0
    if (cpi->sf.adaptive_mode_search) {
2882
0
      if (single_filter[this_mode][refs[0]] ==
2883
0
          single_filter[this_mode][refs[1]])
2884
0
        best_filter = single_filter[this_mode][refs[0]];
2885
0
    }
2886
0
  }
2887
2888
18.1M
  if (this_mode == NEWMV) {
2889
6.35M
    int rate_mv;
2890
6.35M
    if (is_comp_pred) {
2891
      // Decide number of joint motion search iterations
2892
0
      const int num_joint_search_iters = get_joint_search_iters(
2893
0
          cpi->sf.comp_inter_joint_search_iter_level, bsize);
2894
2895
      // Initialize mv using single prediction mode result.
2896
0
      frame_mv[refs[0]].as_int = single_newmv[refs[0]].as_int;
2897
0
      frame_mv[refs[1]].as_int = single_newmv[refs[1]].as_int;
2898
2899
0
      if (num_joint_search_iters) {
2900
#if CONFIG_COLLECT_COMPONENT_TIMING
2901
        start_timing(cpi, joint_motion_search_time);
2902
#endif
2903
0
        joint_motion_search(cpi, x, bsize, frame_mv, mi_row, mi_col,
2904
0
                            single_newmv, &rate_mv, num_joint_search_iters);
2905
#if CONFIG_COLLECT_COMPONENT_TIMING
2906
        end_timing(cpi, joint_motion_search_time);
2907
#endif
2908
0
      } else {
2909
0
        rate_mv = vp9_mv_bit_cost(&frame_mv[refs[0]].as_mv,
2910
0
                                  &x->mbmi_ext->ref_mvs[refs[0]][0].as_mv,
2911
0
                                  x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2912
0
        rate_mv += vp9_mv_bit_cost(&frame_mv[refs[1]].as_mv,
2913
0
                                   &x->mbmi_ext->ref_mvs[refs[1]][0].as_mv,
2914
0
                                   x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2915
0
      }
2916
0
      *rate2 += rate_mv;
2917
6.35M
    } else {
2918
6.35M
      int_mv tmp_mv;
2919
#if CONFIG_COLLECT_COMPONENT_TIMING
2920
      start_timing(cpi, single_motion_search_time);
2921
#endif
2922
6.35M
      single_motion_search(cpi, x, bsize, mi_row, mi_col, &tmp_mv, &rate_mv);
2923
#if CONFIG_COLLECT_COMPONENT_TIMING
2924
      end_timing(cpi, single_motion_search_time);
2925
#endif
2926
6.35M
      if (tmp_mv.as_int == INVALID_MV) return INT64_MAX;
2927
2928
5.68M
      frame_mv[refs[0]].as_int = xd->mi[0]->bmi[0].as_mv[0].as_int =
2929
5.68M
          tmp_mv.as_int;
2930
5.68M
      single_newmv[refs[0]].as_int = tmp_mv.as_int;
2931
2932
      // Estimate the rate implications of a new mv but discount this
2933
      // under certain circumstances where we want to help initiate a weak
2934
      // motion field, where the distortion gain for a single block may not
2935
      // be enough to overcome the cost of a new mv.
2936
5.68M
      if (discount_newmv_test(cpi, this_mode, tmp_mv, mode_mv, refs[0], mi_row,
2937
5.68M
                              mi_col, bsize)) {
2938
1.77M
        *rate2 += VPXMAX((rate_mv / NEW_MV_DISCOUNT_FACTOR), 1);
2939
3.90M
      } else {
2940
3.90M
        *rate2 += rate_mv;
2941
3.90M
      }
2942
5.68M
    }
2943
6.35M
  }
2944
2945
34.4M
  for (i = 0; i < is_comp_pred + 1; ++i) {
2946
17.4M
    cur_mv[i] = frame_mv[refs[i]];
2947
    // Clip "next_nearest" so that it does not extend to far out of image
2948
17.4M
    if (this_mode != NEWMV) clamp_mv2(&cur_mv[i].as_mv, xd);
2949
2950
17.4M
    if (mv_check_bounds(&x->mv_limits, &cur_mv[i].as_mv)) return INT64_MAX;
2951
17.0M
    mi->mv[i].as_int = cur_mv[i].as_int;
2952
17.0M
  }
2953
2954
  // do first prediction into the destination buffer. Do the next
2955
  // prediction into a temporary buffer. Then keep track of which one
2956
  // of these currently holds the best predictor, and use the other
2957
  // one for future predictions. In the end, copy from tmp_buf to
2958
  // dst if necessary.
2959
68.0M
  for (i = 0; i < MAX_MB_PLANE; i++) {
2960
51.0M
    orig_dst[i] = xd->plane[i].dst.buf;
2961
51.0M
    orig_dst_stride[i] = xd->plane[i].dst.stride;
2962
51.0M
  }
2963
2964
  // We don't include the cost of the second reference here, because there
2965
  // are only two options: Last/ARF or Golden/ARF; The second one is always
2966
  // known, which is ARF.
2967
  //
2968
  // Under some circumstances we discount the cost of new mv mode to encourage
2969
  // initiation of a motion field.
2970
17.0M
  if (discount_newmv_test(cpi, this_mode, frame_mv[refs[0]], mode_mv, refs[0],
2971
17.0M
                          mi_row, mi_col, bsize)) {
2972
1.77M
    *rate2 +=
2973
1.77M
        VPXMIN(cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]),
2974
1.77M
               cost_mv_ref(cpi, NEARESTMV, mbmi_ext->mode_context[refs[0]]));
2975
15.2M
  } else {
2976
15.2M
    *rate2 += cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]);
2977
15.2M
  }
2978
2979
17.0M
  if (!is_comp_pred && cpi->sf.prune_single_mode_based_on_mv_diff_mode_rate) {
2980
6.01M
    single_mode_rate[INTER_OFFSET(this_mode)] = *rate2;
2981
    // Prune NEARMV and ZEROMV modes based on motion vector difference and mode
2982
    // rate.
2983
6.01M
    if (skip_single_mode_based_on_mode_rate(mode_mv, single_mode_rate,
2984
6.01M
                                            this_mode, refs[0], *rate2,
2985
6.01M
                                            best_mode_index)) {
2986
      // Check when the single inter mode is pruned, NEARESTMV or NEWMV modes
2987
      // are not early terminated. This ensures all single modes are not getting
2988
      // skipped when the speed feature is enabled.
2989
228k
      assert(single_mode_rate[INTER_OFFSET(NEARESTMV)] != INT_MAX ||
2990
228k
             single_mode_rate[INTER_OFFSET(NEWMV)] != INT_MAX);
2991
228k
      return INT64_MAX;
2992
228k
    }
2993
6.01M
  }
2994
16.7M
  if (RDCOST(x->rdmult, x->rddiv, *rate2, 0) > ref_best_rd &&
2995
238k
      mi->mode != NEARESTMV)
2996
202k
    return INT64_MAX;
2997
2998
  // Are all MVs integer pel for Y and UV
2999
16.5M
  intpel_mv = !mv_has_subpel(&mi->mv[0].as_mv);
3000
16.5M
  if (is_comp_pred) intpel_mv &= !mv_has_subpel(&mi->mv[1].as_mv);
3001
3002
#if CONFIG_COLLECT_COMPONENT_TIMING
3003
  start_timing(cpi, interp_filter_time);
3004
#endif
3005
  // Search for best switchable filter by checking the variance of
3006
  // pred error irrespective of whether the filter will be used
3007
82.8M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
3008
3009
16.5M
  if (cm->interp_filter != BILINEAR) {
3010
    // Use cb pattern for filter eval when filter is not switchable
3011
16.5M
    const int enable_interp_search =
3012
16.5M
        (cpi->sf.cb_pred_filter_search && cm->interp_filter != SWITCHABLE)
3013
16.5M
            ? blk_parity
3014
16.5M
            : 1;
3015
16.5M
    if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
3016
0
      best_filter = EIGHTTAP;
3017
16.5M
    } else if (best_filter == SWITCHABLE && enable_interp_search) {
3018
15.2M
      int newbest;
3019
15.2M
      int tmp_rate_sum = 0;
3020
15.2M
      int64_t tmp_dist_sum = 0;
3021
3022
42.9M
      for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
3023
33.7M
        int j;
3024
33.7M
        int64_t rs_rd;
3025
33.7M
        int tmp_skip_sb = 0;
3026
33.7M
        int64_t tmp_skip_sse = INT64_MAX;
3027
33.7M
        const int enable_earlyterm =
3028
33.7M
            cpi->sf.early_term_interp_search_plane_rd && cm->interp_filter != i;
3029
33.7M
        int64_t filt_best_rd;
3030
3031
33.7M
        mi->interp_filter = i;
3032
33.7M
        rs = vp9_get_switchable_rate(cpi, xd);
3033
33.7M
        rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
3034
3035
33.7M
        if (i > 0 && intpel_mv) {
3036
9.21M
          rd = RDCOST(x->rdmult, x->rddiv, tmp_rate_sum, tmp_dist_sum);
3037
9.21M
          filter_cache[i] = rd;
3038
9.21M
          filter_cache[SWITCHABLE_FILTERS] =
3039
9.21M
              VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
3040
9.21M
          if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
3041
9.21M
          *mask_filter = VPXMAX(*mask_filter, rd);
3042
24.5M
        } else {
3043
24.5M
          int rate_sum = 0;
3044
24.5M
          int64_t dist_sum = 0;
3045
24.5M
          if (i > 0 && cpi->sf.adaptive_interp_filter_search &&
3046
2.69M
              (cpi->sf.interp_filter_search_mask & (1 << i))) {
3047
0
            rate_sum = INT_MAX;
3048
0
            dist_sum = INT64_MAX;
3049
0
            continue;
3050
0
          }
3051
3052
24.5M
          if ((cm->interp_filter == SWITCHABLE && (!i || best_needs_copy)) ||
3053
16.5M
              (cm->interp_filter != SWITCHABLE &&
3054
13.5M
               (cm->interp_filter == mi->interp_filter ||
3055
15.7M
                (i == 0 && intpel_mv)))) {
3056
15.7M
            restore_dst_buf(xd, orig_dst, orig_dst_stride);
3057
15.7M
          } else {
3058
35.0M
            for (j = 0; j < MAX_MB_PLANE; j++) {
3059
26.3M
              xd->plane[j].dst.buf = tmp_buf + j * 64 * 64;
3060
26.3M
              xd->plane[j].dst.stride = 64;
3061
26.3M
            }
3062
8.76M
          }
3063
3064
24.5M
          filt_best_rd =
3065
24.5M
              cm->interp_filter == SWITCHABLE ? (best_rd - rs_rd) : best_rd;
3066
24.5M
          if (build_inter_pred_model_rd_earlyterm(
3067
24.5M
                  cpi, mi_row, mi_col, bsize, x, xd, &rate_sum, &dist_sum,
3068
24.5M
                  &tmp_skip_sb, &tmp_skip_sse, enable_earlyterm,
3069
24.5M
                  filt_best_rd)) {
3070
1.80M
            filter_cache[i] = INT64_MAX;
3071
1.80M
            continue;
3072
1.80M
          }
3073
3074
22.7M
          rd = RDCOST(x->rdmult, x->rddiv, rate_sum, dist_sum);
3075
22.7M
          filter_cache[i] = rd;
3076
22.7M
          filter_cache[SWITCHABLE_FILTERS] =
3077
22.7M
              VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
3078
22.7M
          if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
3079
22.7M
          *mask_filter = VPXMAX(*mask_filter, rd);
3080
3081
22.7M
          if (i == 0 && intpel_mv) {
3082
8.19M
            tmp_rate_sum = rate_sum;
3083
8.19M
            tmp_dist_sum = dist_sum;
3084
8.19M
          }
3085
22.7M
        }
3086
3087
31.9M
        if (i == 0 && cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
3088
15.0M
          if (rd / 2 > ref_best_rd) {
3089
6.05M
            restore_dst_buf(xd, orig_dst, orig_dst_stride);
3090
6.05M
            return INT64_MAX;
3091
6.05M
          }
3092
15.0M
        }
3093
25.9M
        newbest = i == 0 || rd < best_rd;
3094
3095
25.9M
        if (newbest) {
3096
12.6M
          best_rd = rd;
3097
12.6M
          best_filter = mi->interp_filter;
3098
12.6M
          if (cm->interp_filter == SWITCHABLE && i && !intpel_mv)
3099
1.29M
            best_needs_copy = !best_needs_copy;
3100
12.6M
        }
3101
3102
25.9M
        if ((cm->interp_filter == SWITCHABLE && newbest) ||
3103
20.2M
            (cm->interp_filter != SWITCHABLE &&
3104
15.0M
             cm->interp_filter == mi->interp_filter)) {
3105
10.7M
          tmp_rd = best_rd;
3106
3107
10.7M
          skip_txfm_sb = tmp_skip_sb;
3108
10.7M
          skip_sse_sb = tmp_skip_sse;
3109
10.7M
          memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
3110
10.7M
          memcpy(bsse, x->bsse, sizeof(bsse));
3111
10.7M
        }
3112
25.9M
      }
3113
9.23M
      restore_dst_buf(xd, orig_dst, orig_dst_stride);
3114
9.23M
    }
3115
16.5M
  }
3116
#if CONFIG_COLLECT_COMPONENT_TIMING
3117
  end_timing(cpi, interp_filter_time);
3118
#endif
3119
  // Set the appropriate filter
3120
10.5M
  mi->interp_filter =
3121
10.5M
      cm->interp_filter != SWITCHABLE ? cm->interp_filter : best_filter;
3122
10.5M
  rs = cm->interp_filter == SWITCHABLE ? vp9_get_switchable_rate(cpi, xd) : 0;
3123
3124
10.5M
  if (tmp_rd != INT64_MAX) {
3125
9.23M
    if (best_needs_copy) {
3126
      // again temporarily set the buffers to local memory to prevent a memcpy
3127
5.08M
      for (i = 0; i < MAX_MB_PLANE; i++) {
3128
3.81M
        xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
3129
3.81M
        xd->plane[i].dst.stride = 64;
3130
3.81M
      }
3131
1.27M
    }
3132
9.23M
    rd = tmp_rd + RDCOST(x->rdmult, x->rddiv, rs, 0);
3133
9.23M
  } else {
3134
1.29M
    int tmp_rate;
3135
1.29M
    int64_t tmp_dist;
3136
    // Handles the special case when a filter that is not in the
3137
    // switchable list (ex. bilinear) is indicated at the frame level, or
3138
    // skip condition holds.
3139
1.29M
    build_inter_pred_model_rd_earlyterm(
3140
1.29M
        cpi, mi_row, mi_col, bsize, x, xd, &tmp_rate, &tmp_dist, &skip_txfm_sb,
3141
1.29M
        &skip_sse_sb, 0 /*do_earlyterm*/, INT64_MAX);
3142
1.29M
    rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
3143
1.29M
    memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
3144
1.29M
    memcpy(bsse, x->bsse, sizeof(bsse));
3145
1.29M
  }
3146
3147
10.5M
  if (!is_comp_pred) single_filter[this_mode][refs[0]] = mi->interp_filter;
3148
3149
10.5M
  if (cpi->sf.adaptive_mode_search)
3150
0
    if (is_comp_pred)
3151
0
      if (single_skippable[this_mode][refs[0]] &&
3152
0
          single_skippable[this_mode][refs[1]])
3153
0
        memset(skip_txfm, SKIP_TXFM_AC_DC, sizeof(skip_txfm));
3154
3155
10.5M
  if (cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
3156
    // if current pred_error modeled rd is substantially more than the best
3157
    // so far, do not bother doing full rd
3158
10.2M
    if (rd / 2 > ref_best_rd) {
3159
632k
      restore_dst_buf(xd, orig_dst, orig_dst_stride);
3160
632k
      return INT64_MAX;
3161
632k
    }
3162
10.2M
  }
3163
3164
9.89M
  if (cm->interp_filter == SWITCHABLE) *rate2 += rs;
3165
3166
9.89M
  memcpy(x->skip_txfm, skip_txfm, sizeof(skip_txfm));
3167
9.89M
  memcpy(x->bsse, bsse, sizeof(bsse));
3168
3169
9.89M
  if (!skip_txfm_sb || xd->lossless) {
3170
9.85M
    int skippable_y, skippable_uv;
3171
9.85M
    int64_t sseuv = INT64_MAX;
3172
9.85M
    int64_t rdcosty = INT64_MAX;
3173
3174
    // Y cost and distortion
3175
9.85M
    vp9_subtract_plane(x, bsize, 0);
3176
9.85M
    super_block_yrd(cpi, x, rate_y, &distortion_y, &skippable_y, psse, bsize,
3177
9.85M
                    ref_best_rd, recon);
3178
3179
9.85M
    if (*rate_y == INT_MAX) {
3180
1.85M
      *rate2 = INT_MAX;
3181
1.85M
      *distortion = INT64_MAX;
3182
1.85M
      restore_dst_buf(xd, orig_dst, orig_dst_stride);
3183
1.85M
      return INT64_MAX;
3184
1.85M
    }
3185
3186
7.99M
    *rate2 += *rate_y;
3187
7.99M
    *distortion += distortion_y;
3188
3189
7.99M
    rdcosty = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
3190
7.99M
    rdcosty = VPXMIN(rdcosty, RDCOST(x->rdmult, x->rddiv, 0, *psse));
3191
3192
7.99M
    if (!super_block_uvrd(cpi, x, rate_uv, &distortion_uv, &skippable_uv,
3193
7.99M
                          &sseuv, bsize, ref_best_rd - rdcosty)) {
3194
2.03M
      *rate2 = INT_MAX;
3195
2.03M
      *distortion = INT64_MAX;
3196
2.03M
      restore_dst_buf(xd, orig_dst, orig_dst_stride);
3197
2.03M
      return INT64_MAX;
3198
2.03M
    }
3199
3200
5.96M
    *psse += sseuv;
3201
5.96M
    *rate2 += *rate_uv;
3202
5.96M
    *distortion += distortion_uv;
3203
5.96M
    *skippable = skippable_y && skippable_uv;
3204
5.96M
  } else {
3205
39.4k
    x->skip = 1;
3206
39.4k
    *disable_skip = 1;
3207
3208
    // The cost of skip bit needs to be added.
3209
39.4k
    *rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
3210
3211
39.4k
    *distortion = skip_sse_sb;
3212
39.4k
  }
3213
3214
6.00M
  if (!is_comp_pred) single_skippable[this_mode][refs[0]] = *skippable;
3215
3216
6.00M
  restore_dst_buf(xd, orig_dst, orig_dst_stride);
3217
6.00M
  return 0;  // The rate-distortion cost will be re-calculated by caller.
3218
9.89M
}
3219
#endif  // !CONFIG_REALTIME_ONLY
3220
3221
void vp9_rd_pick_intra_mode_sb(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *rd_cost,
3222
                               BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
3223
3.63M
                               int64_t best_rd) {
3224
3.63M
  VP9_COMMON *const cm = &cpi->common;
3225
3.63M
  MACROBLOCKD *const xd = &x->e_mbd;
3226
3.63M
  struct macroblockd_plane *const pd = xd->plane;
3227
3.63M
  int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0;
3228
3.63M
  int y_skip = 0, uv_skip = 0;
3229
3.63M
  int64_t dist_y = 0, dist_uv = 0;
3230
3.63M
  TX_SIZE max_uv_tx_size;
3231
3.63M
  x->skip_encode = 0;
3232
3.63M
  ctx->skip = 0;
3233
3.63M
  xd->mi[0]->ref_frame[0] = INTRA_FRAME;
3234
3.63M
  xd->mi[0]->ref_frame[1] = NO_REF_FRAME;
3235
  // Initialize interp_filter here so we do not have to check for inter block
3236
  // modes in get_pred_context_switchable_interp()
3237
3.63M
  xd->mi[0]->interp_filter = SWITCHABLE_FILTERS;
3238
3239
3.63M
  if (bsize >= BLOCK_8X8) {
3240
1.98M
    if (rd_pick_intra_sby_mode(cpi, x, &rate_y, &rate_y_tokenonly, &dist_y,
3241
1.98M
                               &y_skip, bsize, best_rd) >= best_rd) {
3242
371k
      rd_cost->rate = INT_MAX;
3243
371k
      return;
3244
371k
    }
3245
1.98M
  } else {
3246
1.64M
    y_skip = 0;
3247
1.64M
    if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate_y, &rate_y_tokenonly,
3248
1.64M
                                     &dist_y, best_rd) >= best_rd) {
3249
498k
      rd_cost->rate = INT_MAX;
3250
498k
      return;
3251
498k
    }
3252
1.64M
  }
3253
2.76M
  max_uv_tx_size = uv_txsize_lookup[bsize][xd->mi[0]->tx_size]
3254
2.76M
                                   [pd[1].subsampling_x][pd[1].subsampling_y];
3255
2.76M
  rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly, &dist_uv,
3256
2.76M
                          &uv_skip, VPXMAX(BLOCK_8X8, bsize), max_uv_tx_size);
3257
3258
2.76M
  if (y_skip && uv_skip) {
3259
387k
    rd_cost->rate = rate_y + rate_uv - rate_y_tokenonly - rate_uv_tokenonly +
3260
387k
                    vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
3261
387k
    rd_cost->dist = dist_y + dist_uv;
3262
2.38M
  } else {
3263
2.38M
    rd_cost->rate =
3264
2.38M
        rate_y + rate_uv + vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
3265
2.38M
    rd_cost->dist = dist_y + dist_uv;
3266
2.38M
  }
3267
3268
2.76M
  ctx->mic = *xd->mi[0];
3269
2.76M
  ctx->mbmi_ext = *x->mbmi_ext;
3270
2.76M
  rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
3271
2.76M
}
3272
3273
#if !CONFIG_REALTIME_ONLY
3274
// This function is designed to apply a bias or adjustment to an rd value based
3275
// on the relative variance of the source and reconstruction.
3276
0
#define LOW_VAR_THRESH 250
3277
0
#define VAR_MULT 250
3278
static unsigned int max_var_adjust[VP9E_CONTENT_INVALID] = { 16, 16, 250 };
3279
3280
static void rd_variance_adjustment(VP9_COMP *cpi, MACROBLOCK *x,
3281
                                   BLOCK_SIZE bsize, int64_t *this_rd,
3282
                                   struct buf_2d *recon,
3283
                                   MV_REFERENCE_FRAME ref_frame,
3284
                                   MV_REFERENCE_FRAME second_ref_frame,
3285
0
                                   PREDICTION_MODE this_mode) {
3286
0
  MACROBLOCKD *const xd = &x->e_mbd;
3287
0
  unsigned int rec_variance;
3288
0
  unsigned int src_variance;
3289
0
  unsigned int src_rec_min;
3290
0
  unsigned int var_diff = 0;
3291
0
  unsigned int var_factor = 0;
3292
0
  unsigned int adj_max;
3293
0
  unsigned int low_var_thresh = LOW_VAR_THRESH;
3294
0
  const int bw = num_8x8_blocks_wide_lookup[bsize];
3295
0
  const int bh = num_8x8_blocks_high_lookup[bsize];
3296
0
  vp9e_tune_content content_type = cpi->oxcf.content;
3297
3298
0
  if (*this_rd == INT64_MAX) return;
3299
3300
0
#if CONFIG_VP9_HIGHBITDEPTH
3301
0
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3302
0
    rec_variance = vp9_high_get_sby_variance(cpi, recon, bsize, xd->bd);
3303
0
    src_variance =
3304
0
        vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, xd->bd);
3305
0
  } else {
3306
0
    rec_variance = vp9_get_sby_variance(cpi, recon, bsize);
3307
0
    src_variance = vp9_get_sby_variance(cpi, &x->plane[0].src, bsize);
3308
0
  }
3309
#else
3310
  rec_variance = vp9_get_sby_variance(cpi, recon, bsize);
3311
  src_variance = vp9_get_sby_variance(cpi, &x->plane[0].src, bsize);
3312
#endif  // CONFIG_VP9_HIGHBITDEPTH
3313
3314
  // Scale based on area in 8x8 blocks
3315
0
  rec_variance /= (bw * bh);
3316
0
  src_variance /= (bw * bh);
3317
3318
0
  if (content_type == VP9E_CONTENT_FILM) {
3319
0
    if (cpi->oxcf.pass == 2) {
3320
      // Adjust low variance threshold based on estimated group noise enegry.
3321
0
      double noise_factor =
3322
0
          (double)cpi->twopass.gf_group.group_noise_energy / SECTION_NOISE_DEF;
3323
0
      low_var_thresh = (unsigned int)(low_var_thresh * noise_factor);
3324
3325
0
      if (ref_frame == INTRA_FRAME) {
3326
0
        low_var_thresh *= 2;
3327
0
        if (this_mode == DC_PRED) low_var_thresh *= 5;
3328
0
      } else if (second_ref_frame > INTRA_FRAME) {
3329
0
        low_var_thresh *= 2;
3330
0
      }
3331
0
    }
3332
0
  } else {
3333
0
    low_var_thresh = LOW_VAR_THRESH / 2;
3334
0
  }
3335
3336
  // Lower of source (raw per pixel value) and recon variance. Note that
3337
  // if the source per pixel is 0 then the recon value here will not be per
3338
  // pixel (see above) so will likely be much larger.
3339
0
  src_rec_min = VPXMIN(src_variance, rec_variance);
3340
3341
0
  if (src_rec_min > low_var_thresh) return;
3342
3343
  // We care more when the reconstruction has lower variance so give this case
3344
  // a stronger weighting.
3345
0
  var_diff = (src_variance > rec_variance) ? (src_variance - rec_variance) * 2
3346
0
                                           : (rec_variance - src_variance) / 2;
3347
3348
0
  adj_max = max_var_adjust[content_type];
3349
3350
0
  var_factor =
3351
0
      (unsigned int)((int64_t)VAR_MULT * var_diff) / VPXMAX(1, src_variance);
3352
0
  var_factor = VPXMIN(adj_max, var_factor);
3353
3354
0
  if ((content_type == VP9E_CONTENT_FILM) &&
3355
0
      ((ref_frame == INTRA_FRAME) || (second_ref_frame > INTRA_FRAME))) {
3356
0
    var_factor *= 2;
3357
0
  }
3358
3359
0
  *this_rd += (*this_rd * var_factor) / 100;
3360
3361
0
  (void)xd;
3362
0
}
3363
#endif  // !CONFIG_REALTIME_ONLY
3364
3365
// Do we have an internal image edge (e.g. formatting bars).
3366
2.24M
int vp9_internal_image_edge(VP9_COMP *cpi) {
3367
2.24M
  return (cpi->oxcf.pass == 2) &&
3368
0
         ((cpi->twopass.this_frame_stats.inactive_zone_rows > 0) ||
3369
0
          (cpi->twopass.this_frame_stats.inactive_zone_cols > 0));
3370
2.24M
}
3371
3372
// Checks to see if a super block is on a horizontal image edge.
3373
// In most cases this is the "real" edge unless there are formatting
3374
// bars embedded in the stream.
3375
3.50M
int vp9_active_h_edge(VP9_COMP *cpi, int mi_row, int mi_step) {
3376
3.50M
  int top_edge = 0;
3377
3.50M
  int bottom_edge = cpi->common.mi_rows;
3378
3.50M
  int is_active_h_edge = 0;
3379
3380
  // For two pass account for any formatting bars detected.
3381
3.50M
  if (cpi->oxcf.pass == 2) {
3382
0
    TWO_PASS *twopass = &cpi->twopass;
3383
0
    vpx_clear_system_state();
3384
3385
    // The inactive region is specified in MBs not mi units.
3386
    // The image edge is in the following MB row.
3387
0
    top_edge += (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
3388
3389
0
    bottom_edge -= (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
3390
0
    bottom_edge = VPXMAX(top_edge, bottom_edge);
3391
0
  }
3392
3393
3.50M
  if (((top_edge >= mi_row) && (top_edge < (mi_row + mi_step))) ||
3394
2.95M
      ((bottom_edge >= mi_row) && (bottom_edge < (mi_row + mi_step)))) {
3395
2.13M
    is_active_h_edge = 1;
3396
2.13M
  }
3397
3.50M
  return is_active_h_edge;
3398
3.50M
}
3399
3400
// Checks to see if a super block is on a vertical image edge.
3401
// In most cases this is the "real" edge unless there are formatting
3402
// bars embedded in the stream.
3403
1.45M
int vp9_active_v_edge(VP9_COMP *cpi, int mi_col, int mi_step) {
3404
1.45M
  int left_edge = 0;
3405
1.45M
  int right_edge = cpi->common.mi_cols;
3406
1.45M
  int is_active_v_edge = 0;
3407
3408
  // For two pass account for any formatting bars detected.
3409
1.45M
  if (cpi->oxcf.pass == 2) {
3410
0
    TWO_PASS *twopass = &cpi->twopass;
3411
0
    vpx_clear_system_state();
3412
3413
    // The inactive region is specified in MBs not mi units.
3414
    // The image edge is in the following MB row.
3415
0
    left_edge += (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
3416
3417
0
    right_edge -= (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
3418
0
    right_edge = VPXMAX(left_edge, right_edge);
3419
0
  }
3420
3421
1.45M
  if (((left_edge >= mi_col) && (left_edge < (mi_col + mi_step))) ||
3422
1.28M
      ((right_edge >= mi_col) && (right_edge < (mi_col + mi_step)))) {
3423
391k
    is_active_v_edge = 1;
3424
391k
  }
3425
1.45M
  return is_active_v_edge;
3426
1.45M
}
3427
3428
// Checks to see if a super block is at the edge of the active image.
3429
// In most cases this is the "real" edge unless there are formatting
3430
// bars embedded in the stream.
3431
2.40M
int vp9_active_edge_sb(VP9_COMP *cpi, int mi_row, int mi_col) {
3432
2.40M
  return vp9_active_h_edge(cpi, mi_row, MI_BLOCK_SIZE) ||
3433
431k
         vp9_active_v_edge(cpi, mi_col, MI_BLOCK_SIZE);
3434
2.40M
}
3435
3436
#if !CONFIG_REALTIME_ONLY
3437
3.05M
static void init_frame_mv(int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES]) {
3438
45.8M
  for (int mode = 0; mode < MB_MODE_COUNT; ++mode) {
3439
213M
    for (int ref_frame = 0; ref_frame < MAX_REF_FRAMES; ++ref_frame) {
3440
171M
      frame_mv[mode][ref_frame].as_int = INVALID_MV;
3441
171M
    }
3442
42.7M
  }
3443
3.05M
}
3444
3445
void vp9_rd_pick_inter_mode_sb(VP9_COMP *cpi, TileDataEnc *tile_data,
3446
                               MACROBLOCK *x, int mi_row, int mi_col,
3447
                               RD_COST *rd_cost, BLOCK_SIZE bsize,
3448
3.05M
                               PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far) {
3449
3.05M
  VP9_COMMON *const cm = &cpi->common;
3450
3.05M
  TileInfo *const tile_info = &tile_data->tile_info;
3451
3.05M
  RD_OPT *const rd_opt = &cpi->rd;
3452
3.05M
  SPEED_FEATURES *const sf = &cpi->sf;
3453
3.05M
  MACROBLOCKD *const xd = &x->e_mbd;
3454
3.05M
  MODE_INFO *const mi = xd->mi[0];
3455
3.05M
  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
3456
3.05M
  const struct segmentation *const seg = &cm->seg;
3457
3.05M
  PREDICTION_MODE this_mode;
3458
3.05M
  MV_REFERENCE_FRAME ref_frame, second_ref_frame;
3459
3.05M
  unsigned char segment_id = mi->segment_id;
3460
3.05M
  int comp_pred, i, k;
3461
3.05M
  int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
3462
3.05M
  struct buf_2d yv12_mb[4][MAX_MB_PLANE] = { 0 };
3463
3.05M
  int_mv single_newmv[MAX_REF_FRAMES] = { { 0 } };
3464
3.05M
  INTERP_FILTER single_inter_filter[MB_MODE_COUNT][MAX_REF_FRAMES];
3465
3.05M
  int single_skippable[MB_MODE_COUNT][MAX_REF_FRAMES];
3466
3.05M
  int single_mode_rate[MAX_REF_FRAMES][INTER_MODES];
3467
3.05M
  int64_t best_rd = best_rd_so_far;
3468
3.05M
  int64_t best_pred_diff[REFERENCE_MODES];
3469
3.05M
  int64_t best_pred_rd[REFERENCE_MODES];
3470
3.05M
  int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
3471
3.05M
  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3472
3.05M
  MODE_INFO best_mbmode;
3473
3.05M
  int best_mode_skippable = 0;
3474
3.05M
  int midx, best_mode_index = -1;
3475
3.05M
  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3476
3.05M
  vpx_prob comp_mode_p;
3477
3.05M
  int64_t best_intra_rd = INT64_MAX;
3478
3.05M
  unsigned int best_pred_sse = UINT_MAX;
3479
3.05M
  PREDICTION_MODE best_intra_mode = DC_PRED;
3480
3.05M
  int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
3481
3.05M
  int64_t dist_uv[TX_SIZES];
3482
3.05M
  int skip_uv[TX_SIZES];
3483
3.05M
  PREDICTION_MODE mode_uv[TX_SIZES];
3484
3.05M
  const int intra_cost_penalty =
3485
3.05M
      vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
3486
3.05M
  int best_skip2 = 0;
3487
3.05M
  uint8_t ref_frame_skip_mask[2] = { 0, 1 };
3488
3.05M
  uint16_t mode_skip_mask[MAX_REF_FRAMES] = { 0 };
3489
3.05M
  int mode_skip_start = sf->mode_skip_start + 1;
3490
3.05M
  const int *const rd_threshes = rd_opt->threshes[segment_id][bsize];
3491
3.05M
  const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
3492
3.05M
  int64_t mode_threshold[MAX_MODES];
3493
3.05M
  int8_t *tile_mode_map = tile_data->mode_map[bsize];
3494
3.05M
  int8_t mode_map[MAX_MODES];  // Maintain mode_map information locally to avoid
3495
                               // lock mechanism involved with reads from
3496
                               // tile_mode_map
3497
3.05M
  const int mode_search_skip_flags = sf->mode_search_skip_flags;
3498
3.05M
  const int is_rect_partition =
3499
3.05M
      num_4x4_blocks_wide_lookup[bsize] != num_4x4_blocks_high_lookup[bsize];
3500
3.05M
  int64_t mask_filter = 0;
3501
3.05M
  int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
3502
3503
3.05M
  struct buf_2d *recon;
3504
3.05M
  struct buf_2d recon_buf;
3505
3.05M
#if CONFIG_VP9_HIGHBITDEPTH
3506
3.05M
  DECLARE_ALIGNED(16, uint16_t, recon16[64 * 64]);
3507
3.05M
  recon_buf.buf = xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH
3508
3.05M
                      ? CONVERT_TO_BYTEPTR(recon16)
3509
3.05M
                      : (uint8_t *)recon16;
3510
#else
3511
  DECLARE_ALIGNED(16, uint8_t, recon8[64 * 64]);
3512
  recon_buf.buf = recon8;
3513
#endif  // CONFIG_VP9_HIGHBITDEPTH
3514
3.05M
  recon_buf.stride = 64;
3515
3.05M
  recon = cpi->oxcf.content == VP9E_CONTENT_FILM ? &recon_buf : 0;
3516
3517
3.05M
  vp9_zero(best_mbmode);
3518
3519
3.05M
  x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
3520
3521
15.2M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
3522
3523
3.05M
  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3524
3.05M
                           &comp_mode_p);
3525
3526
12.2M
  for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
3527
15.2M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3528
12.2M
    best_filter_rd[i] = INT64_MAX;
3529
15.2M
  for (i = 0; i < TX_SIZES; i++) rate_uv_intra[i] = INT_MAX;
3530
15.2M
  for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
3531
45.8M
  for (i = 0; i < MB_MODE_COUNT; ++i) {
3532
213M
    for (k = 0; k < MAX_REF_FRAMES; ++k) {
3533
171M
      single_inter_filter[i][k] = SWITCHABLE;
3534
171M
      single_skippable[i][k] = 0;
3535
171M
    }
3536
42.7M
  }
3537
3538
3.05M
  rd_cost->rate = INT_MAX;
3539
3540
3.05M
  init_frame_mv(frame_mv);
3541
3542
12.2M
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3543
9.16M
    x->pred_mv_sad[ref_frame] = INT_MAX;
3544
9.16M
    if ((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) &&
3545
6.86M
        !(is_rect_partition && (ctx->skip_ref_frame_mask & (1 << ref_frame)))) {
3546
6.44M
      assert(get_ref_frame_buffer(cpi, ref_frame) != NULL);
3547
6.44M
      setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
3548
6.44M
                         frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
3549
6.44M
    }
3550
9.16M
    frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
3551
9.16M
    frame_mv[ZEROMV][ref_frame].as_int = 0;
3552
9.16M
  }
3553
3554
12.2M
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3555
9.16M
    if (!(cpi->ref_frame_flags & ref_frame_to_flag(ref_frame))) {
3556
      // Skip checking missing references in both single and compound reference
3557
      // modes. Note that a mode will be skipped if both reference frames
3558
      // are masked out.
3559
2.30M
      ref_frame_skip_mask[0] |= (1 << ref_frame);
3560
2.30M
      ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3561
6.86M
    } else if (sf->reference_masking) {
3562
9.85M
      for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
3563
        // Skip fixed mv modes for poor references
3564
7.60M
        if ((x->pred_mv_sad[ref_frame] >> 2) > x->pred_mv_sad[i]) {
3565
615k
          mode_skip_mask[ref_frame] |= INTER_NEAREST_NEAR_ZERO;
3566
615k
          break;
3567
615k
        }
3568
7.60M
      }
3569
2.86M
    }
3570
    // If the segment reference frame feature is enabled....
3571
    // then do nothing if the current ref frame is not allowed..
3572
9.16M
    if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
3573
0
        get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
3574
0
      ref_frame_skip_mask[0] |= (1 << ref_frame);
3575
0
      ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3576
0
    }
3577
9.16M
  }
3578
3579
  // Disable this drop out case if the ref frame
3580
  // segment level feature is enabled for this segment. This is to
3581
  // prevent the possibility that we end up unable to pick any mode.
3582
3.05M
  if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
3583
    // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
3584
    // unless ARNR filtering is enabled in which case we want
3585
    // an unfiltered alternative. We allow near/nearest as well
3586
    // because they may result in zero-zero MVs but be cheaper.
3587
3.05M
    if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0)) {
3588
0
      ref_frame_skip_mask[0] = (1 << LAST_FRAME) | (1 << GOLDEN_FRAME);
3589
0
      ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
3590
0
      mode_skip_mask[ALTREF_FRAME] = ~INTER_NEAREST_NEAR_ZERO;
3591
0
      if (frame_mv[NEARMV][ALTREF_FRAME].as_int != 0)
3592
0
        mode_skip_mask[ALTREF_FRAME] |= (1 << NEARMV);
3593
0
      if (frame_mv[NEARESTMV][ALTREF_FRAME].as_int != 0)
3594
0
        mode_skip_mask[ALTREF_FRAME] |= (1 << NEARESTMV);
3595
0
    }
3596
3.05M
  }
3597
3598
3.05M
  if (cpi->rc.is_src_frame_alt_ref) {
3599
0
    if (sf->alt_ref_search_fp) {
3600
0
      mode_skip_mask[ALTREF_FRAME] = 0;
3601
0
      ref_frame_skip_mask[0] = ~(1 << ALTREF_FRAME) & 0xff;
3602
0
      ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
3603
0
    }
3604
0
  }
3605
3606
3.05M
  if (sf->alt_ref_search_fp)
3607
0
    if (!cm->show_frame && x->pred_mv_sad[GOLDEN_FRAME] < INT_MAX)
3608
0
      if (x->pred_mv_sad[ALTREF_FRAME] > (x->pred_mv_sad[GOLDEN_FRAME] << 1))
3609
0
        mode_skip_mask[ALTREF_FRAME] |= INTER_ALL;
3610
3611
3.05M
  if (sf->adaptive_mode_search) {
3612
0
    if (cm->show_frame && !cpi->rc.is_src_frame_alt_ref &&
3613
0
        cpi->rc.frames_since_golden >= 3 &&
3614
0
        x->pred_mv_sad[LAST_FRAME] < INT_MAX)
3615
0
      if (x->pred_mv_sad[GOLDEN_FRAME] > (x->pred_mv_sad[LAST_FRAME] << 1))
3616
0
        mode_skip_mask[GOLDEN_FRAME] |= INTER_ALL;
3617
0
  }
3618
3619
3.05M
  if (bsize > sf->max_intra_bsize && cpi->ref_frame_flags != 0) {
3620
0
    ref_frame_skip_mask[0] |= (1 << INTRA_FRAME);
3621
0
    ref_frame_skip_mask[1] |= (1 << INTRA_FRAME);
3622
0
  }
3623
3624
3.05M
  mode_skip_mask[INTRA_FRAME] |=
3625
3.05M
      (uint16_t)~(sf->intra_y_mode_mask[max_txsize_lookup[bsize]]);
3626
3627
24.4M
  for (i = 0; i <= LAST_NEW_MV_INDEX; ++i) mode_threshold[i] = 0;
3628
3629
73.3M
  for (i = LAST_NEW_MV_INDEX + 1; i < MAX_MODES; ++i)
3630
70.2M
    mode_threshold[i] = ((int64_t)rd_threshes[i] * rd_thresh_freq_fact[i]) >> 5;
3631
3632
3.05M
  midx = sf->schedule_mode_search ? mode_skip_start : 0;
3633
3634
3.05M
  while (midx > 4) {
3635
0
    uint8_t end_pos = 0;
3636
0
    for (i = 5; i < midx; ++i) {
3637
0
      if (mode_threshold[tile_mode_map[i - 1]] >
3638
0
          mode_threshold[tile_mode_map[i]]) {
3639
0
        uint8_t tmp = tile_mode_map[i];
3640
0
        tile_mode_map[i] = tile_mode_map[i - 1];
3641
0
        tile_mode_map[i - 1] = tmp;
3642
0
        end_pos = i;
3643
0
      }
3644
0
    }
3645
0
    midx = end_pos;
3646
0
  }
3647
3648
3.05M
  memcpy(mode_map, tile_mode_map, sizeof(mode_map));
3649
3650
93.5M
  for (midx = 0; midx < MAX_MODES; ++midx) {
3651
90.5M
    int mode_index = mode_map[midx];
3652
90.5M
    int mode_excluded = 0;
3653
90.5M
    int64_t this_rd = INT64_MAX;
3654
90.5M
    int disable_skip = 0;
3655
90.5M
    int compmode_cost = 0;
3656
90.5M
    int rate2 = 0, rate_y = 0, rate_uv = 0;
3657
90.5M
    int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
3658
90.5M
    int skippable = 0;
3659
90.5M
    int this_skip2 = 0;
3660
90.5M
    int64_t total_sse = INT64_MAX;
3661
90.5M
    int early_term = 0;
3662
3663
90.5M
    this_mode = vp9_mode_order[mode_index].mode;
3664
90.5M
    ref_frame = vp9_mode_order[mode_index].ref_frame[0];
3665
90.5M
    second_ref_frame = vp9_mode_order[mode_index].ref_frame[1];
3666
3667
90.5M
    vp9_zero(x->sum_y_eobs);
3668
90.5M
    comp_pred = second_ref_frame > INTRA_FRAME;
3669
90.5M
    if (!comp_pred && ref_frame != INTRA_FRAME &&
3670
36.2M
        sf->prune_single_mode_based_on_mv_diff_mode_rate)
3671
14.3M
      single_mode_rate[ref_frame][INTER_OFFSET(this_mode)] = INT_MAX;
3672
3673
90.5M
    if (is_rect_partition) {
3674
32.3M
      if (ctx->skip_ref_frame_mask & (1 << ref_frame)) continue;
3675
27.4M
      if (second_ref_frame > 0 &&
3676
7.32M
          (ctx->skip_ref_frame_mask & (1 << second_ref_frame)))
3677
793k
        continue;
3678
27.4M
    }
3679
3680
    // Look at the reference frame of the best mode so far and set the
3681
    // skip mask to look at a subset of the remaining modes.
3682
84.8M
    if (midx == mode_skip_start && best_mode_index >= 0) {
3683
874k
      switch (best_mbmode.ref_frame[0]) {
3684
482k
        case INTRA_FRAME: break;
3685
261k
        case LAST_FRAME: ref_frame_skip_mask[0] |= LAST_FRAME_MODE_MASK; break;
3686
104k
        case GOLDEN_FRAME:
3687
104k
          ref_frame_skip_mask[0] |= GOLDEN_FRAME_MODE_MASK;
3688
104k
          break;
3689
25.8k
        case ALTREF_FRAME: ref_frame_skip_mask[0] |= ALT_REF_MODE_MASK; break;
3690
0
        case NO_REF_FRAME:
3691
0
        case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
3692
874k
      }
3693
874k
    }
3694
3695
84.8M
    if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
3696
16.0M
        (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
3697
15.2M
      continue;
3698
3699
69.6M
    if (mode_skip_mask[ref_frame] & (1 << this_mode)) continue;
3700
3701
    // Test best rd so far against threshold for trying this mode.
3702
66.4M
    if (best_mode_skippable && sf->schedule_mode_search)
3703
0
      mode_threshold[mode_index] <<= 1;
3704
3705
66.4M
    if (best_rd < mode_threshold[mode_index]) continue;
3706
3707
    // This is only used in motion vector unit test.
3708
58.1M
    if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
3709
3710
58.1M
    if (sf->motion_field_mode_search) {
3711
0
      const int mi_width = VPXMIN(num_8x8_blocks_wide_lookup[bsize],
3712
0
                                  tile_info->mi_col_end - mi_col);
3713
0
      const int mi_height = VPXMIN(num_8x8_blocks_high_lookup[bsize],
3714
0
                                   tile_info->mi_row_end - mi_row);
3715
0
      const int bsl = mi_width_log2_lookup[bsize];
3716
0
      int cb_partition_search_ctrl =
3717
0
          (((mi_row + mi_col) >> bsl) +
3718
0
           get_chessboard_index(cm->current_video_frame)) &
3719
0
          0x1;
3720
0
      MODE_INFO *ref_mi;
3721
0
      int const_motion = 1;
3722
0
      int skip_ref_frame = !cb_partition_search_ctrl;
3723
0
      MV_REFERENCE_FRAME rf = NO_REF_FRAME;
3724
0
      int_mv ref_mv;
3725
0
      ref_mv.as_int = INVALID_MV;
3726
3727
0
      if ((mi_row - 1) >= tile_info->mi_row_start) {
3728
0
        ref_mv = xd->mi[-xd->mi_stride]->mv[0];
3729
0
        rf = xd->mi[-xd->mi_stride]->ref_frame[0];
3730
0
        for (i = 0; i < mi_width; ++i) {
3731
0
          ref_mi = xd->mi[-xd->mi_stride + i];
3732
0
          const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
3733
0
                          (ref_frame == ref_mi->ref_frame[0]);
3734
0
          skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
3735
0
        }
3736
0
      }
3737
3738
0
      if ((mi_col - 1) >= tile_info->mi_col_start) {
3739
0
        if (ref_mv.as_int == INVALID_MV) ref_mv = xd->mi[-1]->mv[0];
3740
0
        if (rf == NO_REF_FRAME) rf = xd->mi[-1]->ref_frame[0];
3741
0
        for (i = 0; i < mi_height; ++i) {
3742
0
          ref_mi = xd->mi[i * xd->mi_stride - 1];
3743
0
          const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
3744
0
                          (ref_frame == ref_mi->ref_frame[0]);
3745
0
          skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
3746
0
        }
3747
0
      }
3748
3749
0
      if (skip_ref_frame && this_mode != NEARESTMV && this_mode != NEWMV)
3750
0
        if (rf > INTRA_FRAME)
3751
0
          if (ref_frame != rf) continue;
3752
3753
0
      if (const_motion)
3754
0
        if (this_mode == NEARMV || this_mode == ZEROMV) continue;
3755
0
    }
3756
3757
58.1M
    if (comp_pred) {
3758
15.6M
      if (!cpi->allow_comp_inter_inter) continue;
3759
3760
0
      if (cm->ref_frame_sign_bias[ref_frame] ==
3761
0
          cm->ref_frame_sign_bias[second_ref_frame])
3762
0
        continue;
3763
3764
      // Skip compound inter modes if ARF is not available.
3765
0
      if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
3766
0
        continue;
3767
3768
      // Do not allow compound prediction if the segment level reference frame
3769
      // feature is in use as in this case there can only be one reference.
3770
0
      if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
3771
3772
0
      if ((mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
3773
0
          best_mode_index >= 0 && best_mbmode.ref_frame[0] == INTRA_FRAME)
3774
0
        continue;
3775
3776
0
      mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
3777
42.4M
    } else {
3778
42.4M
      if (ref_frame != INTRA_FRAME)
3779
22.5M
        mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
3780
42.4M
    }
3781
3782
42.4M
    if (ref_frame == INTRA_FRAME) {
3783
19.9M
      if (sf->adaptive_mode_search)
3784
0
        if ((x->source_variance << num_pels_log2_lookup[bsize]) > best_pred_sse)
3785
0
          continue;
3786
3787
19.9M
      if (this_mode != DC_PRED) {
3788
        // Disable intra modes other than DC_PRED for blocks with low variance
3789
        // Threshold for intra skipping based on source variance
3790
        // TODO(debargha): Specialize the threshold for super block sizes
3791
17.0M
        const unsigned int skip_intra_var_thresh =
3792
17.0M
            (cpi->oxcf.content == VP9E_CONTENT_FILM) ? 0 : 64;
3793
17.0M
        if ((mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
3794
0
            x->source_variance < skip_intra_var_thresh)
3795
0
          continue;
3796
        // Only search the oblique modes if the best so far is
3797
        // one of the neighboring directional modes
3798
17.0M
        if ((mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
3799
0
            (this_mode >= D45_PRED && this_mode <= TM_PRED)) {
3800
0
          if (best_mode_index >= 0 && best_mbmode.ref_frame[0] > INTRA_FRAME)
3801
0
            continue;
3802
0
        }
3803
17.0M
        if (mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
3804
0
          if (conditional_skipintra(this_mode, best_intra_mode)) continue;
3805
0
        }
3806
17.0M
      }
3807
22.5M
    } else {
3808
22.5M
      const MV_REFERENCE_FRAME ref_frames[2] = { ref_frame, second_ref_frame };
3809
22.5M
      if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv, this_mode,
3810
22.5M
                              ref_frames))
3811
4.40M
        continue;
3812
22.5M
    }
3813
3814
38.0M
    mi->mode = this_mode;
3815
38.0M
    mi->uv_mode = DC_PRED;
3816
38.0M
    mi->ref_frame[0] = ref_frame;
3817
38.0M
    mi->ref_frame[1] = second_ref_frame;
3818
    // Evaluate all sub-pel filters irrespective of whether we can use
3819
    // them for this frame.
3820
38.0M
    mi->interp_filter =
3821
38.0M
        cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
3822
38.0M
    mi->mv[0].as_int = mi->mv[1].as_int = 0;
3823
3824
38.0M
    x->skip = 0;
3825
38.0M
    set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
3826
3827
    // Select prediction reference frames.
3828
152M
    for (i = 0; i < MAX_MB_PLANE; i++) {
3829
114M
      xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
3830
114M
      if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
3831
114M
    }
3832
3833
38.0M
    if (ref_frame == INTRA_FRAME) {
3834
19.9M
      TX_SIZE uv_tx;
3835
19.9M
      struct macroblockd_plane *const pd = &xd->plane[1];
3836
#if CONFIG_COLLECT_COMPONENT_TIMING
3837
      start_timing(cpi, intra_mode_search_time);
3838
#endif
3839
19.9M
      memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
3840
19.9M
      super_block_yrd(cpi, x, &rate_y, &distortion_y, &skippable, NULL, bsize,
3841
19.9M
                      best_rd, recon);
3842
#if CONFIG_COLLECT_COMPONENT_TIMING
3843
      end_timing(cpi, intra_mode_search_time);
3844
#endif
3845
19.9M
      if (rate_y == INT_MAX) continue;
3846
3847
12.0M
      uv_tx = uv_txsize_lookup[bsize][mi->tx_size][pd->subsampling_x]
3848
12.0M
                              [pd->subsampling_y];
3849
#if CONFIG_COLLECT_COMPONENT_TIMING
3850
      start_timing(cpi, intra_mode_search_time);
3851
#endif
3852
12.0M
      if (rate_uv_intra[uv_tx] == INT_MAX) {
3853
2.24M
        choose_intra_uv_mode(cpi, x, ctx, bsize, uv_tx, &rate_uv_intra[uv_tx],
3854
2.24M
                             &rate_uv_tokenonly[uv_tx], &dist_uv[uv_tx],
3855
2.24M
                             &skip_uv[uv_tx], &mode_uv[uv_tx]);
3856
2.24M
      }
3857
#if CONFIG_COLLECT_COMPONENT_TIMING
3858
      end_timing(cpi, intra_mode_search_time);
3859
#endif
3860
12.0M
      rate_uv = rate_uv_tokenonly[uv_tx];
3861
12.0M
      distortion_uv = dist_uv[uv_tx];
3862
12.0M
      skippable = skippable && skip_uv[uv_tx];
3863
12.0M
      mi->uv_mode = mode_uv[uv_tx];
3864
3865
12.0M
      rate2 = rate_y + cpi->mbmode_cost[mi->mode] + rate_uv_intra[uv_tx];
3866
12.0M
      if (this_mode != DC_PRED && this_mode != TM_PRED)
3867
8.64M
        rate2 += intra_cost_penalty;
3868
12.0M
      distortion2 = distortion_y + distortion_uv;
3869
18.1M
    } else {
3870
#if CONFIG_COLLECT_COMPONENT_TIMING
3871
      start_timing(cpi, handle_inter_mode_time);
3872
#endif
3873
18.1M
      this_rd = handle_inter_mode(
3874
18.1M
          cpi, x, bsize, &rate2, &distortion2, &skippable, &rate_y, &rate_uv,
3875
18.1M
          recon, &disable_skip, frame_mv, mi_row, mi_col, single_newmv,
3876
18.1M
          single_inter_filter, single_skippable,
3877
18.1M
          &single_mode_rate[ref_frame][0], &total_sse, best_rd, &mask_filter,
3878
18.1M
          filter_cache, best_mode_index);
3879
#if CONFIG_COLLECT_COMPONENT_TIMING
3880
      end_timing(cpi, handle_inter_mode_time);
3881
#endif
3882
18.1M
      if (this_rd == INT64_MAX) continue;
3883
3884
6.00M
      compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
3885
3886
6.00M
      if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
3887
6.00M
    }
3888
3889
    // Estimate the reference frame signaling cost and add it
3890
    // to the rolling cost variable.
3891
18.0M
    if (comp_pred) {
3892
0
      rate2 += ref_costs_comp[ref_frame];
3893
18.0M
    } else {
3894
18.0M
      rate2 += ref_costs_single[ref_frame];
3895
18.0M
    }
3896
3897
18.0M
    if (!disable_skip) {
3898
18.0M
      const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
3899
18.0M
      const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
3900
18.0M
      const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
3901
3902
18.0M
      if (skippable) {
3903
        // Back out the coefficient coding costs
3904
1.15M
        rate2 -= (rate_y + rate_uv);
3905
3906
        // Cost the skip mb case
3907
1.15M
        rate2 += skip_cost1;
3908
16.8M
      } else if (ref_frame != INTRA_FRAME && !xd->lossless &&
3909
5.34M
                 !cpi->oxcf.sharpness) {
3910
5.34M
        if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
3911
5.34M
                   distortion2) <
3912
5.34M
            RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
3913
          // Add in the cost of the no skip flag.
3914
4.87M
          rate2 += skip_cost0;
3915
4.87M
        } else {
3916
          // FIXME(rbultje) make this work for splitmv also
3917
468k
          assert(total_sse >= 0);
3918
3919
468k
          rate2 += skip_cost1;
3920
468k
          distortion2 = total_sse;
3921
468k
          rate2 -= (rate_y + rate_uv);
3922
468k
          this_skip2 = 1;
3923
468k
        }
3924
11.5M
      } else {
3925
        // Add in the cost of the no skip flag.
3926
11.5M
        rate2 += skip_cost0;
3927
11.5M
      }
3928
3929
      // Calculate the final RD estimate for this mode.
3930
18.0M
      this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3931
18.0M
    }
3932
3933
18.0M
    if (recon) {
3934
      // In film mode bias against DC pred and other intra if there is a
3935
      // significant difference between the variance of the sub blocks in the
3936
      // the source. Also apply some bias against compound modes which also
3937
      // tend to blur fine texture such as film grain over time.
3938
      //
3939
      // The sub block test here acts in the case where one or more sub
3940
      // blocks have high relatively variance but others relatively low
3941
      // variance. Here the high variance sub blocks may push the
3942
      // total variance for the current block size over the thresholds
3943
      // used in rd_variance_adjustment() below.
3944
0
      if (cpi->oxcf.content == VP9E_CONTENT_FILM) {
3945
0
        if (bsize >= BLOCK_16X16) {
3946
0
          int min_energy, max_energy;
3947
0
          vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3948
0
                                   &max_energy);
3949
0
          if (max_energy > min_energy) {
3950
0
            if (ref_frame == INTRA_FRAME) {
3951
0
              if (this_mode == DC_PRED)
3952
0
                this_rd += (this_rd * (max_energy - min_energy));
3953
0
              else
3954
0
                this_rd += (this_rd * (max_energy - min_energy)) / 4;
3955
0
            } else if (second_ref_frame > INTRA_FRAME) {
3956
0
              this_rd += this_rd / 4;
3957
0
            }
3958
0
          }
3959
0
        }
3960
0
      }
3961
      // Apply an adjustment to the rd value based on the similarity of the
3962
      // source variance and reconstructed variance.
3963
0
      rd_variance_adjustment(cpi, x, bsize, &this_rd, recon, ref_frame,
3964
0
                             second_ref_frame, this_mode);
3965
0
    }
3966
3967
18.0M
    if (ref_frame == INTRA_FRAME) {
3968
      // Keep record of best intra rd
3969
12.0M
      if (this_rd < best_intra_rd) {
3970
3.16M
        best_intra_rd = this_rd;
3971
3.16M
        best_intra_mode = mi->mode;
3972
3.16M
      }
3973
12.0M
    }
3974
3975
18.0M
    if (!disable_skip && ref_frame == INTRA_FRAME) {
3976
48.3M
      for (i = 0; i < REFERENCE_MODES; ++i)
3977
36.2M
        best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
3978
60.4M
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3979
48.3M
        best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
3980
12.0M
    }
3981
3982
    // Did this mode help.. i.e. is it the new best mode
3983
18.0M
    if (this_rd < best_rd || x->skip) {
3984
5.10M
      int max_plane = MAX_MB_PLANE;
3985
5.10M
      if (!mode_excluded) {
3986
        // Note index of best mode so far
3987
5.10M
        best_mode_index = mode_index;
3988
3989
5.10M
        if (ref_frame == INTRA_FRAME) {
3990
          /* required for left and above block mv */
3991
2.24M
          mi->mv[0].as_int = 0;
3992
2.24M
          max_plane = 1;
3993
          // Initialize interp_filter here so we do not have to check for
3994
          // inter block modes in get_pred_context_switchable_interp()
3995
2.24M
          mi->interp_filter = SWITCHABLE_FILTERS;
3996
2.86M
        } else {
3997
2.86M
          best_pred_sse = x->pred_sse[ref_frame];
3998
2.86M
        }
3999
4000
5.10M
        rd_cost->rate = rate2;
4001
5.10M
        rd_cost->dist = distortion2;
4002
5.10M
        rd_cost->rdcost = this_rd;
4003
5.10M
        best_rd = this_rd;
4004
5.10M
        best_mbmode = *mi;
4005
5.10M
        best_skip2 = this_skip2;
4006
5.10M
        best_mode_skippable = skippable;
4007
4008
5.10M
        if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
4009
5.10M
        memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mi->tx_size],
4010
5.10M
               sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
4011
5.10M
        ctx->sum_y_eobs = x->sum_y_eobs[mi->tx_size];
4012
4013
        // TODO(debargha): enhance this test with a better distortion prediction
4014
        // based on qp, activity mask and history
4015
5.10M
        if ((mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
4016
0
            (mode_index > MIN_EARLY_TERM_INDEX)) {
4017
0
          int qstep = xd->plane[0].dequant[1];
4018
          // TODO(debargha): Enhance this by specializing for each mode_index
4019
0
          int scale = 4;
4020
0
#if CONFIG_VP9_HIGHBITDEPTH
4021
0
          if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
4022
0
            qstep >>= (xd->bd - 8);
4023
0
          }
4024
0
#endif  // CONFIG_VP9_HIGHBITDEPTH
4025
0
          if (x->source_variance < UINT_MAX) {
4026
0
            const int var_adjust = (x->source_variance < 16);
4027
0
            scale -= var_adjust;
4028
0
          }
4029
0
          if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
4030
0
            early_term = 1;
4031
0
          }
4032
0
        }
4033
5.10M
      }
4034
5.10M
    }
4035
4036
    /* keep record of best compound/single-only prediction */
4037
18.0M
    if (!disable_skip && ref_frame != INTRA_FRAME) {
4038
5.96M
      int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
4039
4040
5.96M
      if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4041
0
        single_rate = rate2 - compmode_cost;
4042
0
        hybrid_rate = rate2;
4043
5.96M
      } else {
4044
5.96M
        single_rate = rate2;
4045
5.96M
        hybrid_rate = rate2 + compmode_cost;
4046
5.96M
      }
4047
4048
5.96M
      single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
4049
5.96M
      hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
4050
4051
5.96M
      if (!comp_pred) {
4052
5.96M
        if (single_rd < best_pred_rd[SINGLE_REFERENCE])
4053
3.11M
          best_pred_rd[SINGLE_REFERENCE] = single_rd;
4054
5.96M
      } else {
4055
0
        if (single_rd < best_pred_rd[COMPOUND_REFERENCE])
4056
0
          best_pred_rd[COMPOUND_REFERENCE] = single_rd;
4057
0
      }
4058
5.96M
      if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
4059
3.10M
        best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
4060
4061
      /* keep record of best filter type */
4062
5.96M
      if (!mode_excluded && cm->interp_filter != BILINEAR) {
4063
5.96M
        int64_t ref =
4064
5.96M
            filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
4065
5.96M
                                                         : cm->interp_filter];
4066
4067
29.8M
        for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4068
23.8M
          int64_t adj_rd;
4069
23.8M
          if (ref == INT64_MAX)
4070
1.88M
            adj_rd = 0;
4071
21.9M
          else if (filter_cache[i] == INT64_MAX)
4072
            // when early termination is triggered, the encoder does not have
4073
            // access to the rate-distortion cost. it only knows that the cost
4074
            // should be above the maximum valid value. hence it takes the known
4075
            // maximum plus an arbitrary constant as the rate-distortion cost.
4076
1.30M
            adj_rd = mask_filter - ref + 10;
4077
20.6M
          else
4078
20.6M
            adj_rd = filter_cache[i] - ref;
4079
4080
23.8M
          adj_rd += this_rd;
4081
23.8M
          best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
4082
23.8M
        }
4083
5.96M
      }
4084
5.96M
    }
4085
4086
18.0M
    if (early_term) break;
4087
4088
18.0M
    if (x->skip && !comp_pred) break;
4089
18.0M
  }
4090
4091
  // The inter modes' rate costs are not calculated precisely in some cases.
4092
  // Therefore, sometimes, NEWMV is chosen instead of NEARESTMV, NEARMV, and
4093
  // ZEROMV. Here, checks are added for those cases, and the mode decisions
4094
  // are corrected.
4095
3.05M
  if (best_mbmode.mode == NEWMV) {
4096
363k
    const MV_REFERENCE_FRAME refs[2] = { best_mbmode.ref_frame[0],
4097
363k
                                         best_mbmode.ref_frame[1] };
4098
363k
    int comp_pred_mode = refs[1] > INTRA_FRAME;
4099
4100
363k
    if (frame_mv[NEARESTMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
4101
5.43k
        ((comp_pred_mode &&
4102
0
          frame_mv[NEARESTMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
4103
5.43k
         !comp_pred_mode))
4104
5.43k
      best_mbmode.mode = NEARESTMV;
4105
358k
    else if (frame_mv[NEARMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
4106
4.36k
             ((comp_pred_mode &&
4107
0
               frame_mv[NEARMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
4108
4.36k
              !comp_pred_mode))
4109
4.36k
      best_mbmode.mode = NEARMV;
4110
354k
    else if (best_mbmode.mv[0].as_int == 0 &&
4111
461
             ((comp_pred_mode && best_mbmode.mv[1].as_int == 0) ||
4112
461
              !comp_pred_mode))
4113
461
      best_mbmode.mode = ZEROMV;
4114
363k
  }
4115
4116
3.05M
  if (best_mode_index < 0 || best_rd >= best_rd_so_far) {
4117
    // If adaptive interp filter is enabled, then the current leaf node of 8x8
4118
    // data is needed for sub8x8. Hence preserve the context.
4119
683k
    if (bsize == BLOCK_8X8) ctx->mic = *xd->mi[0];
4120
683k
    rd_cost->rate = INT_MAX;
4121
683k
    rd_cost->rdcost = INT64_MAX;
4122
683k
    return;
4123
683k
  }
4124
4125
  // If we used an estimate for the uv intra rd in the loop above...
4126
2.37M
  if (sf->use_uv_intra_rd_estimate) {
4127
    // Do Intra UV best rd mode selection if best mode choice above was intra.
4128
0
    if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
4129
0
      TX_SIZE uv_tx_size;
4130
0
      *mi = best_mbmode;
4131
0
      uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
4132
0
      rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
4133
0
                              &rate_uv_tokenonly[uv_tx_size],
4134
0
                              &dist_uv[uv_tx_size], &skip_uv[uv_tx_size],
4135
0
                              bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
4136
0
                              uv_tx_size);
4137
0
    }
4138
0
  }
4139
4140
2.37M
  assert((cm->interp_filter == SWITCHABLE) ||
4141
2.37M
         (cm->interp_filter == best_mbmode.interp_filter) ||
4142
2.37M
         !is_inter_block(&best_mbmode));
4143
4144
2.37M
  if (!cpi->rc.is_src_frame_alt_ref)
4145
2.37M
    vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
4146
2.37M
                              sf->adaptive_rd_thresh, bsize, best_mode_index);
4147
4148
  // macroblock modes
4149
2.37M
  *mi = best_mbmode;
4150
2.37M
  x->skip |= best_skip2;
4151
4152
9.48M
  for (i = 0; i < REFERENCE_MODES; ++i) {
4153
7.11M
    if (best_pred_rd[i] == INT64_MAX)
4154
511k
      best_pred_diff[i] = INT_MIN;
4155
6.60M
    else
4156
6.60M
      best_pred_diff[i] = best_rd - best_pred_rd[i];
4157
7.11M
  }
4158
4159
2.37M
  if (!x->skip) {
4160
11.0M
    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4161
8.85M
      if (best_filter_rd[i] == INT64_MAX)
4162
0
        best_filter_diff[i] = 0;
4163
8.85M
      else
4164
8.85M
        best_filter_diff[i] = best_rd - best_filter_rd[i];
4165
8.85M
    }
4166
2.21M
    if (cm->interp_filter == SWITCHABLE)
4167
2.21M
      assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
4168
2.21M
  } else {
4169
157k
    vp9_zero(best_filter_diff);
4170
157k
  }
4171
4172
  // TODO(yunqingwang): Moving this line in front of the above best_filter_diff
4173
  // updating code causes PSNR loss. Need to figure out the confliction.
4174
2.37M
  x->skip |= best_mode_skippable;
4175
4176
2.37M
  if (!x->skip && !x->select_tx_size) {
4177
1.11M
    int has_high_freq_coeff = 0;
4178
1.11M
    int plane;
4179
1.11M
    int max_plane = is_inter_block(xd->mi[0]) ? MAX_MB_PLANE : 1;
4180
3.02M
    for (plane = 0; plane < max_plane; ++plane) {
4181
1.91M
      x->plane[plane].eobs = ctx->eobs_pbuf[plane][1];
4182
1.91M
      has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
4183
1.91M
    }
4184
4185
2.55M
    for (plane = max_plane; plane < MAX_MB_PLANE; ++plane) {
4186
1.43M
      x->plane[plane].eobs = ctx->eobs_pbuf[plane][2];
4187
1.43M
      has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
4188
1.43M
    }
4189
4190
1.11M
    best_mode_skippable |= !has_high_freq_coeff;
4191
1.11M
  }
4192
4193
2.37M
  assert(best_mode_index >= 0);
4194
4195
2.37M
  store_coding_context(x, ctx, best_mode_index, best_pred_diff,
4196
2.37M
                       best_filter_diff, best_mode_skippable);
4197
2.37M
}
4198
4199
void vp9_rd_pick_inter_mode_sb_seg_skip(VP9_COMP *cpi, TileDataEnc *tile_data,
4200
                                        MACROBLOCK *x, RD_COST *rd_cost,
4201
                                        BLOCK_SIZE bsize,
4202
                                        PICK_MODE_CONTEXT *ctx,
4203
0
                                        int64_t best_rd_so_far) {
4204
0
  VP9_COMMON *const cm = &cpi->common;
4205
0
  MACROBLOCKD *const xd = &x->e_mbd;
4206
0
  MODE_INFO *const mi = xd->mi[0];
4207
0
  unsigned char segment_id = mi->segment_id;
4208
0
  const int comp_pred = 0;
4209
0
  int i;
4210
0
  int64_t best_pred_diff[REFERENCE_MODES];
4211
0
  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
4212
0
  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
4213
0
  vpx_prob comp_mode_p;
4214
0
  INTERP_FILTER best_filter = SWITCHABLE;
4215
0
  int64_t this_rd = INT64_MAX;
4216
0
  int rate2 = 0;
4217
0
  const int64_t distortion2 = 0;
4218
4219
0
  x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
4220
4221
0
  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
4222
0
                           &comp_mode_p);
4223
4224
0
  for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
4225
0
  for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i) x->pred_mv_sad[i] = INT_MAX;
4226
4227
0
  rd_cost->rate = INT_MAX;
4228
4229
0
  assert(segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP));
4230
4231
0
  mi->mode = ZEROMV;
4232
0
  mi->uv_mode = DC_PRED;
4233
0
  mi->ref_frame[0] = LAST_FRAME;
4234
0
  mi->ref_frame[1] = NO_REF_FRAME;
4235
0
  mi->mv[0].as_int = 0;
4236
0
  x->skip = 1;
4237
4238
0
  ctx->sum_y_eobs = 0;
4239
4240
0
  if (cm->interp_filter != BILINEAR) {
4241
0
    best_filter = EIGHTTAP;
4242
0
    if (cm->interp_filter == SWITCHABLE &&
4243
0
        x->source_variance >= cpi->sf.disable_filter_search_var_thresh) {
4244
0
      int rs;
4245
0
      int best_rs = INT_MAX;
4246
0
      for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
4247
0
        mi->interp_filter = i;
4248
0
        rs = vp9_get_switchable_rate(cpi, xd);
4249
0
        if (rs < best_rs) {
4250
0
          best_rs = rs;
4251
0
          best_filter = mi->interp_filter;
4252
0
        }
4253
0
      }
4254
0
    }
4255
0
  }
4256
  // Set the appropriate filter
4257
0
  if (cm->interp_filter == SWITCHABLE) {
4258
0
    mi->interp_filter = best_filter;
4259
0
    rate2 += vp9_get_switchable_rate(cpi, xd);
4260
0
  } else {
4261
0
    mi->interp_filter = cm->interp_filter;
4262
0
  }
4263
4264
0
  if (cm->reference_mode == REFERENCE_MODE_SELECT)
4265
0
    rate2 += vp9_cost_bit(comp_mode_p, comp_pred);
4266
4267
  // Estimate the reference frame signaling cost and add it
4268
  // to the rolling cost variable.
4269
0
  rate2 += ref_costs_single[LAST_FRAME];
4270
0
  this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
4271
4272
0
  rd_cost->rate = rate2;
4273
0
  rd_cost->dist = distortion2;
4274
0
  rd_cost->rdcost = this_rd;
4275
4276
0
  if (this_rd >= best_rd_so_far) {
4277
0
    rd_cost->rate = INT_MAX;
4278
0
    rd_cost->rdcost = INT64_MAX;
4279
0
    return;
4280
0
  }
4281
4282
0
  assert((cm->interp_filter == SWITCHABLE) ||
4283
0
         (cm->interp_filter == mi->interp_filter));
4284
4285
0
  vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
4286
0
                            cpi->sf.adaptive_rd_thresh, bsize, THR_ZEROMV);
4287
4288
0
  vp9_zero(best_pred_diff);
4289
0
  vp9_zero(best_filter_diff);
4290
4291
0
  if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, MAX_MB_PLANE);
4292
0
  store_coding_context(x, ctx, THR_ZEROMV, best_pred_diff, best_filter_diff, 0);
4293
0
}
4294
4295
void vp9_rd_pick_inter_mode_sub8x8(VP9_COMP *cpi, TileDataEnc *tile_data,
4296
                                   MACROBLOCK *x, int mi_row, int mi_col,
4297
                                   RD_COST *rd_cost, BLOCK_SIZE bsize,
4298
                                   PICK_MODE_CONTEXT *ctx,
4299
2.40M
                                   int64_t best_rd_so_far) {
4300
2.40M
  VP9_COMMON *const cm = &cpi->common;
4301
2.40M
  RD_OPT *const rd_opt = &cpi->rd;
4302
2.40M
  SPEED_FEATURES *const sf = &cpi->sf;
4303
2.40M
  MACROBLOCKD *const xd = &x->e_mbd;
4304
2.40M
  MODE_INFO *const mi = xd->mi[0];
4305
2.40M
  const struct segmentation *const seg = &cm->seg;
4306
2.40M
  MV_REFERENCE_FRAME ref_frame, second_ref_frame;
4307
2.40M
  unsigned char segment_id = mi->segment_id;
4308
2.40M
  int comp_pred, i;
4309
2.40M
  int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
4310
2.40M
  struct buf_2d yv12_mb[4][MAX_MB_PLANE] = { 0 };
4311
2.40M
  int64_t best_rd = best_rd_so_far;
4312
2.40M
  int64_t best_yrd = best_rd_so_far;  // FIXME(rbultje) more precise
4313
2.40M
  int64_t best_pred_diff[REFERENCE_MODES];
4314
2.40M
  int64_t best_pred_rd[REFERENCE_MODES];
4315
2.40M
  int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
4316
2.40M
  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
4317
2.40M
  MODE_INFO best_mbmode;
4318
2.40M
  int ref_index, best_ref_index = 0;
4319
2.40M
  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
4320
2.40M
  vpx_prob comp_mode_p;
4321
2.40M
  INTERP_FILTER tmp_best_filter = SWITCHABLE;
4322
2.40M
  int rate_uv_intra, rate_uv_tokenonly;
4323
2.40M
  int64_t dist_uv;
4324
2.40M
  int skip_uv;
4325
2.40M
  PREDICTION_MODE mode_uv = DC_PRED;
4326
2.40M
  const int intra_cost_penalty =
4327
2.40M
      vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
4328
2.40M
  int_mv seg_mvs[4][MAX_REF_FRAMES];
4329
2.40M
  b_mode_info best_bmodes[4];
4330
2.40M
  int best_skip2 = 0;
4331
2.40M
  int ref_frame_skip_mask[2] = { 0 };
4332
2.40M
  int64_t mask_filter = 0;
4333
2.40M
  int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
4334
2.40M
  int internal_active_edge =
4335
2.40M
      vp9_active_edge_sb(cpi, mi_row, mi_col) && vp9_internal_image_edge(cpi);
4336
2.40M
  const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
4337
4338
2.40M
  x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
4339
2.40M
  memset(x->zcoeff_blk[TX_4X4], 0, 4);
4340
2.40M
  vp9_zero(best_mbmode);
4341
4342
12.0M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
4343
4344
12.0M
  for (i = 0; i < 4; i++) {
4345
9.61M
    int j;
4346
48.0M
    for (j = 0; j < MAX_REF_FRAMES; j++) seg_mvs[i][j].as_int = INVALID_MV;
4347
9.61M
  }
4348
4349
2.40M
  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
4350
2.40M
                           &comp_mode_p);
4351
4352
9.61M
  for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
4353
12.0M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
4354
9.61M
    best_filter_rd[i] = INT64_MAX;
4355
2.40M
  rate_uv_intra = INT_MAX;
4356
4357
2.40M
  rd_cost->rate = INT_MAX;
4358
4359
9.61M
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
4360
7.20M
    if (cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) {
4361
5.27M
      setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
4362
5.27M
                         frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
4363
5.27M
    } else {
4364
1.93M
      ref_frame_skip_mask[0] |= (1 << ref_frame);
4365
1.93M
      ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4366
1.93M
    }
4367
7.20M
    frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
4368
7.20M
    frame_mv[ZEROMV][ref_frame].as_int = 0;
4369
7.20M
  }
4370
4371
16.8M
  for (ref_index = 0; ref_index < MAX_REFS; ++ref_index) {
4372
14.4M
    int mode_excluded = 0;
4373
14.4M
    int64_t this_rd = INT64_MAX;
4374
14.4M
    int disable_skip = 0;
4375
14.4M
    int compmode_cost = 0;
4376
14.4M
    int rate2 = 0, rate_y = 0, rate_uv = 0;
4377
14.4M
    int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
4378
14.4M
    int skippable = 0;
4379
14.4M
    int this_skip2 = 0;
4380
14.4M
    int64_t total_sse = INT_MAX;
4381
14.4M
    int early_term = 0;
4382
14.4M
    struct buf_2d backup_yv12[2][MAX_MB_PLANE];
4383
4384
14.4M
    ref_frame = vp9_ref_order[ref_index].ref_frame[0];
4385
14.4M
    second_ref_frame = vp9_ref_order[ref_index].ref_frame[1];
4386
4387
14.4M
    vp9_zero(x->sum_y_eobs);
4388
4389
#if CONFIG_BETTER_HW_COMPATIBILITY
4390
    // forbid 8X4 and 4X8 partitions if any reference frame is scaled.
4391
    if (bsize == BLOCK_8X4 || bsize == BLOCK_4X8) {
4392
      int ref_scaled = ref_frame > INTRA_FRAME &&
4393
                       vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf);
4394
      if (second_ref_frame > INTRA_FRAME)
4395
        ref_scaled += vp9_is_scaled(&cm->frame_refs[second_ref_frame - 1].sf);
4396
      if (ref_scaled) continue;
4397
    }
4398
#endif
4399
    // Look at the reference frame of the best mode so far and set the
4400
    // skip mask to look at a subset of the remaining modes.
4401
14.4M
    if (ref_index > 2 && sf->mode_skip_start < MAX_MODES) {
4402
1.71M
      if (ref_index == 3) {
4403
570k
        switch (best_mbmode.ref_frame[0]) {
4404
452k
          case INTRA_FRAME: break;
4405
76.6k
          case LAST_FRAME:
4406
76.6k
            ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME);
4407
76.6k
            ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4408
76.6k
            break;
4409
32.2k
          case GOLDEN_FRAME:
4410
32.2k
            ref_frame_skip_mask[0] |= (1 << LAST_FRAME) | (1 << ALTREF_FRAME);
4411
32.2k
            ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4412
32.2k
            break;
4413
9.04k
          case ALTREF_FRAME:
4414
9.04k
            ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << LAST_FRAME);
4415
9.04k
            break;
4416
0
          case NO_REF_FRAME:
4417
0
          case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
4418
570k
        }
4419
570k
      }
4420
1.71M
    }
4421
4422
14.4M
    if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
4423
2.61M
        (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
4424
2.59M
      continue;
4425
4426
    // Test best rd so far against threshold for trying this mode.
4427
11.8M
    if (!internal_active_edge &&
4428
11.8M
        rd_less_than_thresh(best_rd,
4429
11.8M
                            rd_opt->threshes[segment_id][bsize][ref_index],
4430
11.8M
                            &rd_thresh_freq_fact[ref_index]))
4431
4.90M
      continue;
4432
4433
    // This is only used in motion vector unit test.
4434
6.91M
    if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
4435
4436
6.91M
    comp_pred = second_ref_frame > INTRA_FRAME;
4437
6.91M
    if (comp_pred) {
4438
0
      if (!cpi->allow_comp_inter_inter) continue;
4439
4440
0
      if (cm->ref_frame_sign_bias[ref_frame] ==
4441
0
          cm->ref_frame_sign_bias[second_ref_frame])
4442
0
        continue;
4443
4444
0
      if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
4445
0
        continue;
4446
      // Do not allow compound prediction if the segment level reference frame
4447
      // feature is in use as in this case there can only be one reference.
4448
0
      if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
4449
4450
0
      if ((sf->mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
4451
0
          best_mbmode.ref_frame[0] == INTRA_FRAME)
4452
0
        continue;
4453
0
    }
4454
4455
6.91M
    if (comp_pred)
4456
0
      mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
4457
6.91M
    else if (ref_frame != INTRA_FRAME)
4458
4.67M
      mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
4459
4460
    // If the segment reference frame feature is enabled....
4461
    // then do nothing if the current ref frame is not allowed..
4462
6.91M
    if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
4463
0
        get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
4464
0
      continue;
4465
      // Disable this drop out case if the ref frame
4466
      // segment level feature is enabled for this segment. This is to
4467
      // prevent the possibility that we end up unable to pick any mode.
4468
6.91M
    } else if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
4469
      // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
4470
      // unless ARNR filtering is enabled in which case we want
4471
      // an unfiltered alternative. We allow near/nearest as well
4472
      // because they may result in zero-zero MVs but be cheaper.
4473
6.91M
      if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
4474
0
        continue;
4475
6.91M
    }
4476
4477
6.91M
    mi->tx_size = TX_4X4;
4478
6.91M
    mi->uv_mode = DC_PRED;
4479
6.91M
    mi->ref_frame[0] = ref_frame;
4480
6.91M
    mi->ref_frame[1] = second_ref_frame;
4481
    // Evaluate all sub-pel filters irrespective of whether we can use
4482
    // them for this frame.
4483
6.91M
    mi->interp_filter =
4484
6.91M
        cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
4485
6.91M
    x->skip = 0;
4486
6.91M
    set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
4487
4488
    // Select prediction reference frames.
4489
27.6M
    for (i = 0; i < MAX_MB_PLANE; i++) {
4490
20.7M
      xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
4491
20.7M
      if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
4492
20.7M
    }
4493
4494
6.91M
    if (ref_frame == INTRA_FRAME) {
4495
2.23M
      int rate;
4496
2.23M
      if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y, &distortion_y,
4497
2.23M
                                       best_rd) >= best_rd)
4498
590k
        continue;
4499
1.64M
      rate2 += rate;
4500
1.64M
      rate2 += intra_cost_penalty;
4501
1.64M
      distortion2 += distortion_y;
4502
4503
1.64M
      if (rate_uv_intra == INT_MAX) {
4504
1.64M
        choose_intra_uv_mode(cpi, x, ctx, bsize, TX_4X4, &rate_uv_intra,
4505
1.64M
                             &rate_uv_tokenonly, &dist_uv, &skip_uv, &mode_uv);
4506
1.64M
      }
4507
1.64M
      rate2 += rate_uv_intra;
4508
1.64M
      rate_uv = rate_uv_tokenonly;
4509
1.64M
      distortion2 += dist_uv;
4510
1.64M
      distortion_uv = dist_uv;
4511
1.64M
      mi->uv_mode = mode_uv;
4512
4.67M
    } else {
4513
4.67M
      int rate;
4514
4.67M
      int64_t distortion;
4515
4.67M
      int64_t this_rd_thresh;
4516
4.67M
      int64_t tmp_rd, tmp_best_rd = INT64_MAX, tmp_best_rdu = INT64_MAX;
4517
4.67M
      int tmp_best_rate = INT_MAX, tmp_best_ratey = INT_MAX;
4518
4.67M
      int64_t tmp_best_distortion = INT_MAX, tmp_best_sse, uv_sse;
4519
4.67M
      int tmp_best_skippable = 0;
4520
4.67M
      int switchable_filter_index;
4521
4.67M
      int_mv *second_ref =
4522
4.67M
          comp_pred ? &x->mbmi_ext->ref_mvs[second_ref_frame][0] : NULL;
4523
4.67M
      b_mode_info tmp_best_bmodes[16];
4524
4.67M
      MODE_INFO tmp_best_mbmode;
4525
4.67M
      BEST_SEG_INFO bsi[SWITCHABLE_FILTERS];
4526
4.67M
      int pred_exists = 0;
4527
4.67M
      int uv_skippable;
4528
4529
4.67M
      YV12_BUFFER_CONFIG *scaled_ref_frame[2] = { NULL, NULL };
4530
4.67M
      int ref;
4531
4532
14.0M
      for (ref = 0; ref < 2; ++ref) {
4533
9.34M
        scaled_ref_frame[ref] =
4534
9.34M
            mi->ref_frame[ref] > INTRA_FRAME
4535
9.34M
                ? vp9_get_scaled_ref_frame(cpi, mi->ref_frame[ref])
4536
9.34M
                : NULL;
4537
4538
9.34M
        if (scaled_ref_frame[ref]) {
4539
          // Swap out the reference frame for a version that's been scaled to
4540
          // match the resolution of the current frame, allowing the existing
4541
          // motion search code to be used without additional modifications.
4542
0
          for (i = 0; i < MAX_MB_PLANE; i++)
4543
0
            backup_yv12[ref][i] = xd->plane[i].pre[ref];
4544
0
          vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
4545
0
                               NULL);
4546
0
        }
4547
9.34M
      }
4548
4549
4.67M
      this_rd_thresh = (ref_frame == LAST_FRAME)
4550
4.67M
                           ? rd_opt->threshes[segment_id][bsize][THR_LAST]
4551
4.67M
                           : rd_opt->threshes[segment_id][bsize][THR_ALTR];
4552
4.67M
      this_rd_thresh = (ref_frame == GOLDEN_FRAME)
4553
4.67M
                           ? rd_opt->threshes[segment_id][bsize][THR_GOLD]
4554
4.67M
                           : this_rd_thresh;
4555
23.3M
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
4556
18.6M
        filter_cache[i] = INT64_MAX;
4557
4558
4.67M
      if (cm->interp_filter != BILINEAR) {
4559
4.67M
        tmp_best_filter = EIGHTTAP;
4560
4.67M
        if (x->source_variance < sf->disable_filter_search_var_thresh) {
4561
0
          tmp_best_filter = EIGHTTAP;
4562
4.67M
        } else if (sf->adaptive_pred_interp_filter == 1 &&
4563
4.67M
                   ctx->pred_interp_filter < SWITCHABLE) {
4564
4.67M
          tmp_best_filter = ctx->pred_interp_filter;
4565
4.67M
        } else if (sf->adaptive_pred_interp_filter == 2) {
4566
0
          tmp_best_filter = ctx->pred_interp_filter < SWITCHABLE
4567
0
                                ? ctx->pred_interp_filter
4568
0
                                : 0;
4569
0
        } else {
4570
0
          for (switchable_filter_index = 0;
4571
0
               switchable_filter_index < SWITCHABLE_FILTERS;
4572
0
               ++switchable_filter_index) {
4573
0
            int newbest, rs;
4574
0
            int64_t rs_rd;
4575
0
            MB_MODE_INFO_EXT *mbmi_ext = x->mbmi_ext;
4576
0
            mi->interp_filter = switchable_filter_index;
4577
0
            tmp_rd = rd_pick_best_sub8x8_mode(
4578
0
                cpi, x, &mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
4579
0
                &rate, &rate_y, &distortion, &skippable, &total_sse,
4580
0
                (int)this_rd_thresh, seg_mvs, bsi, switchable_filter_index,
4581
0
                mi_row, mi_col);
4582
4583
0
            if (tmp_rd == INT64_MAX) continue;
4584
0
            rs = vp9_get_switchable_rate(cpi, xd);
4585
0
            rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
4586
0
            filter_cache[switchable_filter_index] = tmp_rd;
4587
0
            filter_cache[SWITCHABLE_FILTERS] =
4588
0
                VPXMIN(filter_cache[SWITCHABLE_FILTERS], tmp_rd + rs_rd);
4589
0
            if (cm->interp_filter == SWITCHABLE) tmp_rd += rs_rd;
4590
4591
0
            mask_filter = VPXMAX(mask_filter, tmp_rd);
4592
4593
0
            newbest = (tmp_rd < tmp_best_rd);
4594
0
            if (newbest) {
4595
0
              tmp_best_filter = mi->interp_filter;
4596
0
              tmp_best_rd = tmp_rd;
4597
0
            }
4598
0
            if ((newbest && cm->interp_filter == SWITCHABLE) ||
4599
0
                (mi->interp_filter == cm->interp_filter &&
4600
0
                 cm->interp_filter != SWITCHABLE)) {
4601
0
              tmp_best_rdu = tmp_rd;
4602
0
              tmp_best_rate = rate;
4603
0
              tmp_best_ratey = rate_y;
4604
0
              tmp_best_distortion = distortion;
4605
0
              tmp_best_sse = total_sse;
4606
0
              tmp_best_skippable = skippable;
4607
0
              tmp_best_mbmode = *mi;
4608
0
              x->sum_y_eobs[TX_4X4] = 0;
4609
0
              for (i = 0; i < 4; i++) {
4610
0
                tmp_best_bmodes[i] = xd->mi[0]->bmi[i];
4611
0
                x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
4612
0
                x->sum_y_eobs[TX_4X4] += x->plane[0].eobs[i];
4613
0
              }
4614
0
              pred_exists = 1;
4615
0
              if (switchable_filter_index == 0 && sf->use_rd_breakout &&
4616
0
                  best_rd < INT64_MAX) {
4617
0
                if (tmp_best_rdu / 2 > best_rd) {
4618
                  // skip searching the other filters if the first is
4619
                  // already substantially larger than the best so far
4620
0
                  tmp_best_filter = mi->interp_filter;
4621
0
                  tmp_best_rdu = INT64_MAX;
4622
0
                  break;
4623
0
                }
4624
0
              }
4625
0
            }
4626
0
          }  // switchable_filter_index loop
4627
0
        }
4628
4.67M
      }
4629
4630
4.67M
      if (tmp_best_rdu == INT64_MAX && pred_exists) continue;
4631
4632
4.67M
      mi->interp_filter = (cm->interp_filter == SWITCHABLE ? tmp_best_filter
4633
4.67M
                                                           : cm->interp_filter);
4634
4.67M
      if (!pred_exists) {
4635
        // Handles the special case when a filter that is not in the
4636
        // switchable list (bilinear, 6-tap) is indicated at the frame level
4637
4.67M
        tmp_rd = rd_pick_best_sub8x8_mode(
4638
4.67M
            cpi, x, &x->mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
4639
4.67M
            &rate, &rate_y, &distortion, &skippable, &total_sse,
4640
4.67M
            (int)this_rd_thresh, seg_mvs, bsi, 0, mi_row, mi_col);
4641
4.67M
        if (tmp_rd == INT64_MAX) continue;
4642
3.01M
        x->sum_y_eobs[TX_4X4] = 0;
4643
15.0M
        for (i = 0; i < 4; i++) {
4644
12.0M
          x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
4645
12.0M
          x->sum_y_eobs[TX_4X4] += x->plane[0].eobs[i];
4646
12.0M
        }
4647
3.01M
      } else {
4648
0
        total_sse = tmp_best_sse;
4649
0
        rate = tmp_best_rate;
4650
0
        rate_y = tmp_best_ratey;
4651
0
        distortion = tmp_best_distortion;
4652
0
        skippable = tmp_best_skippable;
4653
0
        *mi = tmp_best_mbmode;
4654
0
        for (i = 0; i < 4; i++) xd->mi[0]->bmi[i] = tmp_best_bmodes[i];
4655
0
      }
4656
4657
3.01M
      rate2 += rate;
4658
3.01M
      distortion2 += distortion;
4659
4660
3.01M
      if (cm->interp_filter == SWITCHABLE)
4661
1.22M
        rate2 += vp9_get_switchable_rate(cpi, xd);
4662
4663
3.01M
      if (!mode_excluded)
4664
3.01M
        mode_excluded = comp_pred ? cm->reference_mode == SINGLE_REFERENCE
4665
3.01M
                                  : cm->reference_mode == COMPOUND_REFERENCE;
4666
4667
3.01M
      compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
4668
4669
3.01M
      tmp_best_rdu =
4670
3.01M
          best_rd - VPXMIN(RDCOST(x->rdmult, x->rddiv, rate2, distortion2),
4671
3.01M
                           RDCOST(x->rdmult, x->rddiv, 0, total_sse));
4672
4673
3.01M
      if (tmp_best_rdu > 0) {
4674
        // If even the 'Y' rd value of split is higher than best so far
4675
        // then don't bother looking at UV
4676
3.00M
        vp9_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col, BLOCK_8X8);
4677
3.00M
        memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
4678
3.00M
        if (!super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
4679
3.00M
                              &uv_sse, BLOCK_8X8, tmp_best_rdu)) {
4680
3.25M
          for (ref = 0; ref < 2; ++ref) {
4681
2.16M
            if (scaled_ref_frame[ref]) {
4682
0
              for (i = 0; i < MAX_MB_PLANE; ++i)
4683
0
                xd->plane[i].pre[ref] = backup_yv12[ref][i];
4684
0
            }
4685
2.16M
          }
4686
1.08M
          continue;
4687
1.08M
        }
4688
4689
1.92M
        rate2 += rate_uv;
4690
1.92M
        distortion2 += distortion_uv;
4691
1.92M
        skippable = skippable && uv_skippable;
4692
1.92M
        total_sse += uv_sse;
4693
1.92M
      }
4694
4695
5.78M
      for (ref = 0; ref < 2; ++ref) {
4696
3.85M
        if (scaled_ref_frame[ref]) {
4697
          // Restore the prediction frame pointers to their unscaled versions.
4698
0
          for (i = 0; i < MAX_MB_PLANE; ++i)
4699
0
            xd->plane[i].pre[ref] = backup_yv12[ref][i];
4700
0
        }
4701
3.85M
      }
4702
1.92M
    }
4703
4704
3.57M
    if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
4705
4706
    // Estimate the reference frame signaling cost and add it
4707
    // to the rolling cost variable.
4708
3.57M
    if (second_ref_frame > INTRA_FRAME) {
4709
0
      rate2 += ref_costs_comp[ref_frame];
4710
3.57M
    } else {
4711
3.57M
      rate2 += ref_costs_single[ref_frame];
4712
3.57M
    }
4713
4714
3.57M
    if (!disable_skip) {
4715
3.57M
      const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
4716
3.57M
      const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
4717
3.57M
      const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
4718
4719
      // Skip is never coded at the segment level for sub8x8 blocks and instead
4720
      // always coded in the bitstream at the mode info level.
4721
3.57M
      if (ref_frame != INTRA_FRAME && !xd->lossless) {
4722
1.71M
        if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
4723
1.71M
                   distortion2) <
4724
1.71M
            RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
4725
          // Add in the cost of the no skip flag.
4726
1.54M
          rate2 += skip_cost0;
4727
1.54M
        } else {
4728
          // FIXME(rbultje) make this work for splitmv also
4729
177k
          rate2 += skip_cost1;
4730
177k
          distortion2 = total_sse;
4731
177k
          assert(total_sse >= 0);
4732
177k
          rate2 -= (rate_y + rate_uv);
4733
177k
          rate_y = 0;
4734
177k
          rate_uv = 0;
4735
177k
          this_skip2 = 1;
4736
177k
        }
4737
1.85M
      } else {
4738
        // Add in the cost of the no skip flag.
4739
1.85M
        rate2 += skip_cost0;
4740
1.85M
      }
4741
4742
      // Calculate the final RD estimate for this mode.
4743
3.57M
      this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
4744
3.57M
    }
4745
4746
3.57M
    if (!disable_skip && ref_frame == INTRA_FRAME) {
4747
6.59M
      for (i = 0; i < REFERENCE_MODES; ++i)
4748
4.94M
        best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
4749
8.24M
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
4750
6.59M
        best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
4751
1.64M
    }
4752
4753
    // Did this mode help.. i.e. is it the new best mode
4754
3.57M
    if (this_rd < best_rd || x->skip) {
4755
1.04M
      if (!mode_excluded) {
4756
1.04M
        int max_plane = MAX_MB_PLANE;
4757
        // Note index of best mode so far
4758
1.04M
        best_ref_index = ref_index;
4759
4760
1.04M
        if (ref_frame == INTRA_FRAME) {
4761
          /* required for left and above block mv */
4762
602k
          mi->mv[0].as_int = 0;
4763
602k
          max_plane = 1;
4764
          // Initialize interp_filter here so we do not have to check for
4765
          // inter block modes in get_pred_context_switchable_interp()
4766
602k
          mi->interp_filter = SWITCHABLE_FILTERS;
4767
602k
        }
4768
4769
1.04M
        rd_cost->rate = rate2;
4770
1.04M
        rd_cost->dist = distortion2;
4771
1.04M
        rd_cost->rdcost = this_rd;
4772
1.04M
        best_rd = this_rd;
4773
1.04M
        best_yrd =
4774
1.04M
            best_rd - RDCOST(x->rdmult, x->rddiv, rate_uv, distortion_uv);
4775
1.04M
        best_mbmode = *mi;
4776
1.04M
        best_skip2 = this_skip2;
4777
1.04M
        if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
4778
1.04M
        memcpy(ctx->zcoeff_blk, x->zcoeff_blk[TX_4X4],
4779
1.04M
               sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
4780
1.04M
        ctx->sum_y_eobs = x->sum_y_eobs[TX_4X4];
4781
4782
5.23M
        for (i = 0; i < 4; i++) best_bmodes[i] = xd->mi[0]->bmi[i];
4783
4784
        // TODO(debargha): enhance this test with a better distortion prediction
4785
        // based on qp, activity mask and history
4786
1.04M
        if ((sf->mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
4787
0
            (ref_index > MIN_EARLY_TERM_INDEX)) {
4788
0
          int qstep = xd->plane[0].dequant[1];
4789
          // TODO(debargha): Enhance this by specializing for each mode_index
4790
0
          int scale = 4;
4791
0
#if CONFIG_VP9_HIGHBITDEPTH
4792
0
          if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
4793
0
            qstep >>= (xd->bd - 8);
4794
0
          }
4795
0
#endif  // CONFIG_VP9_HIGHBITDEPTH
4796
0
          if (x->source_variance < UINT_MAX) {
4797
0
            const int var_adjust = (x->source_variance < 16);
4798
0
            scale -= var_adjust;
4799
0
          }
4800
0
          if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
4801
0
            early_term = 1;
4802
0
          }
4803
0
        }
4804
1.04M
      }
4805
1.04M
    }
4806
4807
    /* keep record of best compound/single-only prediction */
4808
3.57M
    if (!disable_skip && ref_frame != INTRA_FRAME) {
4809
1.92M
      int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
4810
4811
1.92M
      if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4812
0
        single_rate = rate2 - compmode_cost;
4813
0
        hybrid_rate = rate2;
4814
1.92M
      } else {
4815
1.92M
        single_rate = rate2;
4816
1.92M
        hybrid_rate = rate2 + compmode_cost;
4817
1.92M
      }
4818
4819
1.92M
      single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
4820
1.92M
      hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
4821
4822
1.92M
      if (!comp_pred && single_rd < best_pred_rd[SINGLE_REFERENCE])
4823
1.54M
        best_pred_rd[SINGLE_REFERENCE] = single_rd;
4824
388k
      else if (comp_pred && single_rd < best_pred_rd[COMPOUND_REFERENCE])
4825
0
        best_pred_rd[COMPOUND_REFERENCE] = single_rd;
4826
4827
1.92M
      if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
4828
1.54M
        best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
4829
1.92M
    }
4830
4831
    /* keep record of best filter type */
4832
3.57M
    if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
4833
1.92M
        cm->interp_filter != BILINEAR) {
4834
1.92M
      int64_t ref =
4835
1.92M
          filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
4836
1.92M
                                                       : cm->interp_filter];
4837
1.92M
      int64_t adj_rd;
4838
9.64M
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4839
7.71M
        if (ref == INT64_MAX)
4840
7.71M
          adj_rd = 0;
4841
0
        else if (filter_cache[i] == INT64_MAX)
4842
          // when early termination is triggered, the encoder does not have
4843
          // access to the rate-distortion cost. it only knows that the cost
4844
          // should be above the maximum valid value. hence it takes the known
4845
          // maximum plus an arbitrary constant as the rate-distortion cost.
4846
0
          adj_rd = mask_filter - ref + 10;
4847
0
        else
4848
0
          adj_rd = filter_cache[i] - ref;
4849
4850
7.71M
        adj_rd += this_rd;
4851
7.71M
        best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
4852
7.71M
      }
4853
1.92M
    }
4854
4855
3.57M
    if (early_term) break;
4856
4857
3.57M
    if (x->skip && !comp_pred) break;
4858
3.57M
  }
4859
4860
2.40M
  if (best_rd >= best_rd_so_far) {
4861
1.48M
    rd_cost->rate = INT_MAX;
4862
1.48M
    rd_cost->rdcost = INT64_MAX;
4863
1.48M
    return;
4864
1.48M
  }
4865
4866
  // If we used an estimate for the uv intra rd in the loop above...
4867
918k
  if (sf->use_uv_intra_rd_estimate) {
4868
    // Do Intra UV best rd mode selection if best mode choice above was intra.
4869
0
    if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
4870
0
      *mi = best_mbmode;
4871
0
      rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra, &rate_uv_tokenonly,
4872
0
                              &dist_uv, &skip_uv, BLOCK_8X8, TX_4X4);
4873
0
    }
4874
0
  }
4875
4876
918k
  if (best_rd == INT64_MAX) {
4877
0
    rd_cost->rate = INT_MAX;
4878
0
    rd_cost->dist = INT64_MAX;
4879
0
    rd_cost->rdcost = INT64_MAX;
4880
0
    return;
4881
0
  }
4882
4883
918k
  assert((cm->interp_filter == SWITCHABLE) ||
4884
918k
         (cm->interp_filter == best_mbmode.interp_filter) ||
4885
918k
         !is_inter_block(&best_mbmode));
4886
4887
918k
  vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact, sf->adaptive_rd_thresh,
4888
918k
                            bsize, best_ref_index);
4889
4890
  // macroblock modes
4891
918k
  *mi = best_mbmode;
4892
918k
  x->skip |= best_skip2;
4893
918k
  if (!is_inter_block(&best_mbmode)) {
4894
3.01M
    for (i = 0; i < 4; i++) xd->mi[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
4895
602k
  } else {
4896
1.57M
    for (i = 0; i < 4; ++i) xd->mi[0]->bmi[i] = best_bmodes[i];
4897
4898
315k
    mi->mv[0].as_int = xd->mi[0]->bmi[3].as_mv[0].as_int;
4899
315k
    mi->mv[1].as_int = xd->mi[0]->bmi[3].as_mv[1].as_int;
4900
315k
  }
4901
  // If the second reference does not exist, set the corresponding mv to zero.
4902
918k
  if (mi->ref_frame[1] == NO_REF_FRAME) {
4903
918k
    mi->mv[1].as_int = 0;
4904
4.59M
    for (i = 0; i < 4; ++i) {
4905
3.67M
      mi->bmi[i].as_mv[1].as_int = 0;
4906
3.67M
    }
4907
918k
  }
4908
4909
3.67M
  for (i = 0; i < REFERENCE_MODES; ++i) {
4910
2.75M
    if (best_pred_rd[i] == INT64_MAX)
4911
157k
      best_pred_diff[i] = INT_MIN;
4912
2.59M
    else
4913
2.59M
      best_pred_diff[i] = best_rd - best_pred_rd[i];
4914
2.75M
  }
4915
4916
918k
  if (!x->skip) {
4917
4.47M
    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4918
3.58M
      if (best_filter_rd[i] == INT64_MAX)
4919
0
        best_filter_diff[i] = 0;
4920
3.58M
      else
4921
3.58M
        best_filter_diff[i] = best_rd - best_filter_rd[i];
4922
3.58M
    }
4923
895k
    if (cm->interp_filter == SWITCHABLE)
4924
895k
      assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
4925
895k
  } else {
4926
22.6k
    vp9_zero(best_filter_diff);
4927
22.6k
  }
4928
4929
918k
  store_coding_context(x, ctx, best_ref_index, best_pred_diff, best_filter_diff,
4930
918k
                       0);
4931
918k
}
4932
#endif  // !CONFIG_REALTIME_ONLY