Coverage Report

Created: 2025-08-28 07:12

/src/libvpx/vp9/encoder/vp9_rdopt.c
Line
Count
Source (jump to first uncovered line)
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
253k
  ((1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME) | (1 << INTRA_FRAME))
49
#define GOLDEN_FRAME_MODE_MASK \
50
111k
  ((1 << LAST_FRAME) | (1 << ALTREF_FRAME) | (1 << INTRA_FRAME))
51
#define ALT_REF_MODE_MASK \
52
23.9k
  ((1 << LAST_FRAME) | (1 << GOLDEN_FRAME) | (1 << INTRA_FRAME))
53
54
5.18M
#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
32.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
11.4M
                           int min_plane, int max_plane) {
139
11.4M
  int i;
140
141
34.2M
  for (i = min_plane; i < max_plane; ++i) {
142
22.8M
    struct macroblock_plane *const p = &x->plane[i];
143
22.8M
    struct macroblockd_plane *const pd = &x->e_mbd.plane[i];
144
145
22.8M
    p->coeff = ctx->coeff_pbuf[i][m];
146
22.8M
    p->qcoeff = ctx->qcoeff_pbuf[i][m];
147
22.8M
    pd->dqcoeff = ctx->dqcoeff_pbuf[i][m];
148
22.8M
    p->eobs = ctx->eobs_pbuf[i][m];
149
150
22.8M
    ctx->coeff_pbuf[i][m] = ctx->coeff_pbuf[i][n];
151
22.8M
    ctx->qcoeff_pbuf[i][m] = ctx->qcoeff_pbuf[i][n];
152
22.8M
    ctx->dqcoeff_pbuf[i][m] = ctx->dqcoeff_pbuf[i][n];
153
22.8M
    ctx->eobs_pbuf[i][m] = ctx->eobs_pbuf[i][n];
154
155
22.8M
    ctx->coeff_pbuf[i][n] = p->coeff;
156
22.8M
    ctx->qcoeff_pbuf[i][n] = p->qcoeff;
157
22.8M
    ctx->dqcoeff_pbuf[i][n] = pd->dqcoeff;
158
22.8M
    ctx->eobs_pbuf[i][n] = p->eobs;
159
22.8M
  }
160
11.4M
}
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
32.2M
    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
32.2M
  int i;
174
32.2M
  int64_t rate_sum = 0;
175
32.2M
  int64_t dist_sum = 0;
176
32.2M
  const int ref = xd->mi[0]->ref_frame[0];
177
32.2M
  unsigned int sse;
178
32.2M
  unsigned int var = 0;
179
32.2M
  int64_t total_sse = 0;
180
32.2M
  int skip_flag = 1;
181
32.2M
  const int shift = 6;
182
32.2M
  const int dequant_shift =
183
32.2M
#if CONFIG_VP9_HIGHBITDEPTH
184
32.2M
      (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd - 5 :
185
32.2M
#endif  // CONFIG_VP9_HIGHBITDEPTH
186
32.2M
                                                    3;
187
188
32.2M
  x->pred_sse[ref] = 0;
189
190
  // Build prediction signal, compute stats and RD cost on per-plane basis
191
126M
  for (i = 0; i < MAX_MB_PLANE; ++i) {
192
96.3M
    struct macroblock_plane *const p = &x->plane[i];
193
96.3M
    struct macroblockd_plane *const pd = &xd->plane[i];
194
96.3M
    const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
195
96.3M
    const TX_SIZE max_tx_size = max_txsize_lookup[bs];
196
96.3M
    const BLOCK_SIZE unit_size = txsize_to_bsize[max_tx_size];
197
96.3M
    const int64_t dc_thr = p->quant_thred[0] >> shift;
198
96.3M
    const int64_t ac_thr = p->quant_thred[1] >> shift;
199
96.3M
    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
96.3M
    const int64_t low_dc_thr = VPXMIN(50, dc_thr >> 2);
203
96.3M
    const int64_t low_ac_thr = VPXMIN(80, ac_thr >> 2);
204
96.3M
    int bw = 1 << (b_width_log2_lookup[bs] - b_width_log2_lookup[unit_size]);
205
96.3M
    int bh = 1 << (b_height_log2_lookup[bs] - b_width_log2_lookup[unit_size]);
206
96.3M
    int idx, idy;
207
96.3M
    int lw = b_width_log2_lookup[unit_size] + 2;
208
96.3M
    int lh = b_height_log2_lookup[unit_size] + 2;
209
96.3M
    unsigned int qstep;
210
96.3M
    unsigned int nlog2;
211
96.3M
    int64_t dist = 0;
212
213
    // Build inter predictor
214
96.3M
    vp9_build_inter_predictors_sbp(xd, mi_row, mi_col, bsize, i);
215
216
    // Compute useful stats
217
209M
    for (idy = 0; idy < bh; ++idy) {
218
244M
      for (idx = 0; idx < bw; ++idx) {
219
131M
        uint8_t *src = p->src.buf + (idy * p->src.stride << lh) + (idx << lw);
220
131M
        uint8_t *dst = pd->dst.buf + (idy * pd->dst.stride << lh) + (idx << lh);
221
131M
        int block_idx = (idy << 1) + idx;
222
131M
        int low_err_skip = 0;
223
224
131M
        var = cpi->fn_ptr[unit_size].vf(src, p->src.stride, dst, pd->dst.stride,
225
131M
                                        &sse);
226
131M
        x->bsse[(i << 2) + block_idx] = sse;
227
131M
        sum_sse += sse;
228
229
131M
        x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_NONE;
230
131M
        if (!x->select_tx_size) {
231
          // Check if all ac coefficients can be quantized to zero.
232
99.9M
          if (var < ac_thr || var == 0) {
233
10.1M
            x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_ONLY;
234
235
            // Check if dc coefficient can be quantized to zero.
236
10.1M
            if (sse - var < dc_thr || sse == var) {
237
7.79M
              x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_DC;
238
239
7.79M
              if (!sse || (var < low_ac_thr && sse - var < low_dc_thr))
240
2.76M
                low_err_skip = 1;
241
7.79M
            }
242
10.1M
          }
243
99.9M
        }
244
245
131M
        if (skip_flag && !low_err_skip) skip_flag = 0;
246
247
131M
        if (i == 0) x->pred_sse[ref] += sse;
248
131M
      }
249
113M
    }
250
251
96.3M
    total_sse += sum_sse;
252
96.3M
    qstep = pd->dequant[1] >> dequant_shift;
253
96.3M
    nlog2 = num_pels_log2_lookup[bs];
254
255
    // Fast approximate the modelling function.
256
96.3M
    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
96.3M
    } else {
265
96.3M
      int rate;
266
96.3M
      vp9_model_rd_from_var_lapndz(sum_sse, nlog2, qstep, &rate, &dist);
267
96.3M
      rate_sum += rate;
268
96.3M
    }
269
96.3M
    dist_sum += dist;
270
96.3M
    if (do_earlyterm) {
271
22.1M
      if (RDCOST(x->rdmult, x->rddiv, rate_sum,
272
22.1M
                 dist_sum << VP9_DIST_SCALE_LOG2) >= best_rd)
273
2.12M
        return 1;
274
22.1M
    }
275
96.3M
  }
276
30.0M
  *skip_txfm_sb = skip_flag;
277
30.0M
  *skip_sse_sb = total_sse << VP9_DIST_SCALE_LOG2;
278
30.0M
  *out_rate_sum = (int)rate_sum;
279
30.0M
  *out_dist_sum = dist_sum << VP9_DIST_SCALE_LOG2;
280
281
30.0M
  return 0;
282
32.2M
}
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
322M
                                               int64_t *ssz, int bd) {
311
322M
  if (bd == 8) {
312
322M
    return vp9_block_error(coeff, dqcoeff, block_size, ssz);
313
322M
  } else {
314
0
    return vp9_highbd_block_error(coeff, dqcoeff, block_size, ssz, bd);
315
0
  }
316
322M
}
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
601M
                       int use_fast_coef_costing) {
361
601M
  MACROBLOCKD *const xd = &x->e_mbd;
362
601M
  MODE_INFO *mi = xd->mi[0];
363
601M
  const struct macroblock_plane *p = &x->plane[plane];
364
601M
  const PLANE_TYPE type = get_plane_type(plane);
365
601M
  const int16_t *band_count = &band_counts[tx_size][1];
366
601M
  const int eob = p->eobs[block];
367
601M
  const tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
368
601M
  unsigned int(*token_costs)[2][COEFF_CONTEXTS][ENTROPY_TOKENS] =
369
601M
      x->token_costs[tx_size][type][is_inter_block(mi)];
370
601M
  uint8_t token_cache[32 * 32];
371
601M
  int cost;
372
601M
#if CONFIG_VP9_HIGHBITDEPTH
373
601M
  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
601M
  assert(type == PLANE_TYPE_Y
380
601M
             ? mi->tx_size == tx_size
381
601M
             : get_uv_tx_size(mi, &xd->plane[plane]) == tx_size);
382
383
601M
  if (eob == 0) {
384
    // single eob token
385
120M
    cost = token_costs[0][0][pt][EOB_TOKEN];
386
480M
  } else {
387
480M
    if (use_fast_coef_costing) {
388
347M
      int band_left = *band_count++;
389
347M
      int c;
390
391
      // dc token
392
347M
      int v = qcoeff[0];
393
347M
      int16_t prev_t;
394
347M
      cost = vp9_get_token_cost(v, &prev_t, cat6_high_cost);
395
347M
      cost += (*token_costs)[0][pt][prev_t];
396
397
347M
      token_cache[0] = vp9_pt_energy_class[prev_t];
398
347M
      ++token_costs;
399
400
      // ac tokens
401
11.1G
      for (c = 1; c < eob; c++) {
402
10.7G
        const int rc = scan[c];
403
10.7G
        int16_t t;
404
405
10.7G
        v = qcoeff[rc];
406
10.7G
        cost += vp9_get_token_cost(v, &t, cat6_high_cost);
407
10.7G
        cost += (*token_costs)[!prev_t][!prev_t][t];
408
10.7G
        prev_t = t;
409
10.7G
        if (!--band_left) {
410
1.32G
          band_left = *band_count++;
411
1.32G
          ++token_costs;
412
1.32G
        }
413
10.7G
      }
414
415
      // eob token
416
347M
      if (band_left) cost += (*token_costs)[0][!prev_t][EOB_TOKEN];
417
418
347M
    } else {  // !use_fast_coef_costing
419
132M
      int band_left = *band_count++;
420
132M
      int c;
421
422
      // dc token
423
132M
      int v = qcoeff[0];
424
132M
      int16_t tok;
425
132M
      unsigned int(*tok_cost_ptr)[COEFF_CONTEXTS][ENTROPY_TOKENS];
426
132M
      cost = vp9_get_token_cost(v, &tok, cat6_high_cost);
427
132M
      cost += (*token_costs)[0][pt][tok];
428
429
132M
      token_cache[0] = vp9_pt_energy_class[tok];
430
132M
      ++token_costs;
431
432
132M
      tok_cost_ptr = &((*token_costs)[!tok]);
433
434
      // ac tokens
435
3.84G
      for (c = 1; c < eob; c++) {
436
3.71G
        const int rc = scan[c];
437
438
3.71G
        v = qcoeff[rc];
439
3.71G
        cost += vp9_get_token_cost(v, &tok, cat6_high_cost);
440
3.71G
        pt = get_coef_context(nb, token_cache, c);
441
3.71G
        cost += (*tok_cost_ptr)[pt][tok];
442
3.71G
        token_cache[rc] = vp9_pt_energy_class[tok];
443
3.71G
        if (!--band_left) {
444
520M
          band_left = *band_count++;
445
520M
          ++token_costs;
446
520M
        }
447
3.71G
        tok_cost_ptr = &((*token_costs)[!tok]);
448
3.71G
      }
449
450
      // eob token
451
132M
      if (band_left) {
452
56.3M
        pt = get_coef_context(nb, token_cache, c);
453
56.3M
        cost += (*token_costs)[0][pt][EOB_TOKEN];
454
56.3M
      }
455
132M
    }
456
480M
  }
457
458
601M
  return cost;
459
601M
}
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
128M
                          const BLOCK_SIZE tx_bsize) {
529
128M
  unsigned int sse = 0;
530
128M
  const int plane_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
531
128M
  const int plane_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
532
128M
  const int tx_4x4_w = num_4x4_blocks_wide_lookup[tx_bsize];
533
128M
  const int tx_4x4_h = num_4x4_blocks_high_lookup[tx_bsize];
534
128M
  int b4x4s_to_right_edge = num_4x4_to_edge(plane_4x4_w, xd->mb_to_right_edge,
535
128M
                                            pd->subsampling_x, blk_col);
536
128M
  int b4x4s_to_bottom_edge = num_4x4_to_edge(plane_4x4_h, xd->mb_to_bottom_edge,
537
128M
                                             pd->subsampling_y, blk_row);
538
128M
  if (tx_bsize == BLOCK_4X4 ||
539
128M
      (b4x4s_to_right_edge >= tx_4x4_w && b4x4s_to_bottom_edge >= tx_4x4_h)) {
540
127M
    cpi->fn_ptr[tx_bsize].vf(src, src_stride, dst, dst_stride, &sse);
541
127M
  } else {
542
1.22M
    const vpx_variance_fn_t vf_4x4 = cpi->fn_ptr[BLOCK_4X4].vf;
543
1.22M
    int r, c;
544
1.22M
    unsigned this_sse = 0;
545
1.22M
    int max_r = VPXMIN(b4x4s_to_bottom_edge, tx_4x4_h);
546
1.22M
    int max_c = VPXMIN(b4x4s_to_right_edge, tx_4x4_w);
547
1.22M
    sse = 0;
548
    // if we are in the unrestricted motion border.
549
4.95M
    for (r = 0; r < max_r; ++r) {
550
      // Skip visiting the sub blocks that are wholly within the UMV.
551
17.6M
      for (c = 0; c < max_c; ++c) {
552
13.9M
        vf_4x4(src + r * src_stride * 4 + c * 4, src_stride,
553
13.9M
               dst + r * dst_stride * 4 + c * 4, dst_stride, &this_sse);
554
13.9M
        sse += this_sse;
555
13.9M
      }
556
3.72M
    }
557
1.22M
  }
558
128M
  return sse;
559
128M
}
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
322M
                       int sse_calc_done) {
566
322M
  MACROBLOCKD *const xd = &x->e_mbd;
567
322M
  const struct macroblock_plane *const p = &x->plane[plane];
568
322M
  const struct macroblockd_plane *const pd = &xd->plane[plane];
569
322M
  const int eob = p->eobs[block];
570
571
322M
  if (!out_recon && x->block_tx_domain && eob) {
572
253M
    const int ss_txfrm_size = tx_size << 1;
573
253M
    int64_t this_sse;
574
253M
    const int shift = tx_size == TX_32X32 ? 0 : 2;
575
253M
    const tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
576
253M
    const tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
577
253M
#if CONFIG_VP9_HIGHBITDEPTH
578
253M
    const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
579
253M
    *out_dist = vp9_highbd_block_error_dispatch(
580
253M
                    coeff, dqcoeff, 16 << ss_txfrm_size, &this_sse, bd) >>
581
253M
                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
253M
    *out_sse = this_sse >> shift;
588
589
253M
    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
253M
  } else {
602
68.3M
    const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
603
68.3M
    const int bs = 4 * num_4x4_blocks_wide_lookup[tx_bsize];
604
68.3M
    const int src_stride = p->src.stride;
605
68.3M
    const int dst_stride = pd->dst.stride;
606
68.3M
    const int src_idx = 4 * (blk_row * src_stride + blk_col);
607
68.3M
    const int dst_idx = 4 * (blk_row * dst_stride + blk_col);
608
68.3M
    const uint8_t *src = &p->src.buf[src_idx];
609
68.3M
    const uint8_t *dst = &pd->dst.buf[dst_idx];
610
68.3M
    uint8_t *out_recon_ptr = 0;
611
612
68.3M
    const tran_low_t *dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
613
68.3M
    unsigned int tmp;
614
615
68.3M
    if (sse_calc_done) {
616
0
      tmp = (unsigned int)(*out_sse);
617
68.3M
    } else {
618
68.3M
      tmp = pixel_sse(cpi, xd, pd, src, src_stride, dst, dst_stride, blk_row,
619
68.3M
                      blk_col, plane_bsize, tx_bsize);
620
68.3M
    }
621
68.3M
    *out_sse = (int64_t)tmp * 16;
622
68.3M
    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
68.3M
    if (eob) {
631
10.5M
#if CONFIG_VP9_HIGHBITDEPTH
632
10.5M
      DECLARE_ALIGNED(16, uint16_t, recon16[1024]);
633
10.5M
      uint8_t *recon = (uint8_t *)recon16;
634
#else
635
      DECLARE_ALIGNED(16, uint8_t, recon[1024]);
636
#endif  // CONFIG_VP9_HIGHBITDEPTH
637
638
10.5M
#if CONFIG_VP9_HIGHBITDEPTH
639
10.5M
      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
640
0
        vpx_highbd_convolve_copy(CONVERT_TO_SHORTPTR(dst), dst_stride, recon16,
641
0
                                 32, NULL, 0, 0, 0, 0, bs, bs, xd->bd);
642
0
        if (xd->lossless) {
643
0
          vp9_highbd_iwht4x4_add(dqcoeff, recon16, 32, eob, xd->bd);
644
0
        } else {
645
0
          switch (tx_size) {
646
0
            case TX_4X4:
647
0
              vp9_highbd_idct4x4_add(dqcoeff, recon16, 32, eob, xd->bd);
648
0
              break;
649
0
            case TX_8X8:
650
0
              vp9_highbd_idct8x8_add(dqcoeff, recon16, 32, eob, xd->bd);
651
0
              break;
652
0
            case TX_16X16:
653
0
              vp9_highbd_idct16x16_add(dqcoeff, recon16, 32, eob, xd->bd);
654
0
              break;
655
0
            default:
656
0
              assert(tx_size == TX_32X32);
657
0
              vp9_highbd_idct32x32_add(dqcoeff, recon16, 32, eob, xd->bd);
658
0
              break;
659
0
          }
660
0
        }
661
0
        recon = CONVERT_TO_BYTEPTR(recon16);
662
10.5M
      } else {
663
10.5M
#endif  // CONFIG_VP9_HIGHBITDEPTH
664
10.5M
        vpx_convolve_copy(dst, dst_stride, recon, 32, NULL, 0, 0, 0, 0, bs, bs);
665
10.5M
        switch (tx_size) {
666
101k
          case TX_32X32: vp9_idct32x32_add(dqcoeff, recon, 32, eob); break;
667
700k
          case TX_16X16: vp9_idct16x16_add(dqcoeff, recon, 32, eob); break;
668
2.69M
          case TX_8X8: vp9_idct8x8_add(dqcoeff, recon, 32, eob); break;
669
7.10M
          default:
670
7.10M
            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
7.10M
            x->inv_txfm_add(dqcoeff, recon, 32, eob);
675
7.10M
            break;
676
10.5M
        }
677
10.5M
#if CONFIG_VP9_HIGHBITDEPTH
678
10.5M
      }
679
10.5M
#endif  // CONFIG_VP9_HIGHBITDEPTH
680
681
10.5M
      tmp = pixel_sse(cpi, xd, pd, src, src_stride, recon, 32, blk_row, blk_col,
682
10.5M
                      plane_bsize, tx_bsize);
683
10.5M
      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
10.5M
    }
688
689
68.3M
    *out_dist = (int64_t)tmp * 16;
690
68.3M
  }
691
322M
}
692
693
static int rate_block(int plane, int block, TX_SIZE tx_size, int coeff_ctx,
694
362M
                      struct rdcost_block_args *args) {
695
362M
  return cost_coeffs(args->x, plane, block, tx_size, coeff_ctx, args->so->scan,
696
362M
                     args->so->neighbors, args->use_fast_coef_costing);
697
362M
}
698
699
static void block_rd_txfm(int plane, int block, int blk_row, int blk_col,
700
382M
                          BLOCK_SIZE plane_bsize, TX_SIZE tx_size, void *arg) {
701
382M
  struct rdcost_block_args *args = arg;
702
382M
  MACROBLOCK *const x = args->x;
703
382M
  MACROBLOCKD *const xd = &x->e_mbd;
704
382M
  MODE_INFO *const mi = xd->mi[0];
705
382M
  int64_t rd1, rd2, rd;
706
382M
  int rate;
707
382M
  int64_t dist = INT64_MAX;
708
382M
  int64_t sse = INT64_MAX;
709
382M
  const int coeff_ctx =
710
382M
      combine_entropy_contexts(args->t_left[blk_row], args->t_above[blk_col]);
711
382M
  struct buf_2d *recon = args->this_recon;
712
382M
  const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
713
382M
  const struct macroblockd_plane *const pd = &xd->plane[plane];
714
382M
  const int dst_stride = pd->dst.stride;
715
382M
  const uint8_t *dst = &pd->dst.buf[4 * (blk_row * dst_stride + blk_col)];
716
382M
  const int enable_trellis_opt = args->cpi->sf.trellis_opt_tx_rd.method;
717
382M
  const double trellis_opt_thresh = args->cpi->sf.trellis_opt_tx_rd.thresh;
718
382M
  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
382M
  struct encode_b_args encode_b_arg = {
729
382M
    x,    enable_trellis_opt, trellis_opt_thresh, &sse_calc_done,
730
382M
    &sse, args->t_above,      args->t_left,       &mi->skip
731
382M
  };
732
382M
#endif
733
734
382M
  if (args->exit_early) return;
735
736
372M
  if (!is_inter_block(mi)) {
737
308M
    vp9_encode_block_intra(plane, block, blk_row, blk_col, plane_bsize, tx_size,
738
308M
                           &encode_b_arg);
739
308M
    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
308M
    if (x->block_tx_domain) {
745
258M
      dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
746
258M
                 tx_size, &dist, &sse, /*out_recon=*/NULL, sse_calc_done);
747
258M
    } else {
748
49.7M
      const struct macroblock_plane *const p = &x->plane[plane];
749
49.7M
      const int src_stride = p->src.stride;
750
49.7M
      const uint8_t *src = &p->src.buf[4 * (blk_row * src_stride + blk_col)];
751
49.7M
      unsigned int tmp;
752
49.7M
      if (!sse_calc_done) {
753
49.7M
        const int diff_stride = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
754
49.7M
        const int16_t *diff =
755
49.7M
            &p->src_diff[4 * (blk_row * diff_stride + blk_col)];
756
49.7M
        int visible_width, visible_height;
757
49.7M
        sse = sum_squares_visible(xd, pd, diff, diff_stride, blk_row, blk_col,
758
49.7M
                                  plane_bsize, tx_bsize, &visible_width,
759
49.7M
                                  &visible_height);
760
49.7M
      }
761
49.7M
#if CONFIG_VP9_HIGHBITDEPTH
762
49.7M
      if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) && (xd->bd > 8))
763
0
        sse = ROUND64_POWER_OF_TWO(sse, (xd->bd - 8) * 2);
764
49.7M
#endif  // CONFIG_VP9_HIGHBITDEPTH
765
49.7M
      sse = sse * 16;
766
49.7M
      tmp = pixel_sse(args->cpi, xd, pd, src, src_stride, dst, dst_stride,
767
49.7M
                      blk_row, blk_col, plane_bsize, tx_bsize);
768
49.7M
      dist = (int64_t)tmp * 16;
769
49.7M
    }
770
308M
  } else {
771
63.5M
    int skip_txfm_flag = SKIP_TXFM_NONE;
772
63.5M
    if (max_txsize_lookup[plane_bsize] == tx_size)
773
45.7M
      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
63.5M
    if (!args->cpi->sf.allow_skip_txfm_ac_dc &&
778
63.5M
        skip_txfm_flag == SKIP_TXFM_AC_DC) {
779
2.01M
      skip_txfm_flag = SKIP_TXFM_NONE;
780
2.01M
    }
781
782
63.5M
    if (skip_txfm_flag == SKIP_TXFM_NONE ||
783
63.5M
        (recon && skip_txfm_flag == SKIP_TXFM_AC_ONLY)) {
784
63.1M
      const struct macroblock_plane *const p = &x->plane[plane];
785
63.1M
      const int diff_stride = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
786
63.1M
      const int16_t *const diff =
787
63.1M
          &p->src_diff[4 * (blk_row * diff_stride + blk_col)];
788
63.1M
      const int use_trellis_opt =
789
63.1M
          do_trellis_opt(pd, diff, diff_stride, blk_row, blk_col, plane_bsize,
790
63.1M
                         tx_size, &encode_b_arg);
791
      // full forward transform and quantization
792
63.1M
      vp9_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, tx_size);
793
63.1M
      if (use_trellis_opt) vp9_optimize_b(x, plane, block, tx_size, coeff_ctx);
794
63.1M
      dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
795
63.1M
                 tx_size, &dist, &sse, recon, sse_calc_done);
796
63.1M
    } else if (skip_txfm_flag == SKIP_TXFM_AC_ONLY) {
797
      // compute DC coefficient
798
434k
      tran_low_t *const coeff = BLOCK_OFFSET(x->plane[plane].coeff, block);
799
434k
      tran_low_t *const dqcoeff = BLOCK_OFFSET(xd->plane[plane].dqcoeff, block);
800
434k
      vp9_xform_quant_dc(x, plane, block, blk_row, blk_col, plane_bsize,
801
434k
                         tx_size);
802
434k
      sse = x->bsse[(plane << 2) + (block >> (tx_size << 1))] << 4;
803
434k
      dist = sse;
804
434k
      if (x->plane[plane].eobs[block]) {
805
427k
        const int64_t orig_sse = (int64_t)coeff[0] * coeff[0];
806
427k
        const int64_t resd_sse = coeff[0] - dqcoeff[0];
807
427k
        int64_t dc_correct = orig_sse - resd_sse * resd_sse;
808
427k
#if CONFIG_VP9_HIGHBITDEPTH
809
427k
        dc_correct >>= ((xd->bd - 8) * 2);
810
427k
#endif
811
427k
        if (tx_size != TX_32X32) dc_correct >>= 2;
812
813
427k
        dist = VPXMAX(0, sse - dc_correct);
814
427k
      }
815
434k
    } else {
816
0
      assert(0 && "allow_skip_txfm_ac_dc does not allow SKIP_TXFM_AC_DC.");
817
0
    }
818
63.5M
  }
819
820
372M
  rd = RDCOST(x->rdmult, x->rddiv, 0, dist);
821
372M
  if (args->this_rd + rd > args->best_rd) {
822
9.96M
    args->exit_early = 1;
823
9.96M
    return;
824
9.96M
  }
825
826
362M
  rate = rate_block(plane, block, tx_size, coeff_ctx, args);
827
362M
  args->t_above[blk_col] = (x->plane[plane].eobs[block] > 0) ? 1 : 0;
828
362M
  args->t_left[blk_row] = (x->plane[plane].eobs[block] > 0) ? 1 : 0;
829
362M
  rd1 = RDCOST(x->rdmult, x->rddiv, rate, dist);
830
362M
  rd2 = RDCOST(x->rdmult, x->rddiv, 0, sse);
831
832
  // TODO(jingning): temporarily enabled only for luma component
833
362M
  rd = VPXMIN(rd1, rd2);
834
362M
  if (plane == 0) {
835
141M
    x->zcoeff_blk[tx_size][block] =
836
141M
        !x->plane[plane].eobs[block] ||
837
141M
        (x->sharpness == 0 && rd1 > rd2 && !xd->lossless);
838
141M
    x->sum_y_eobs[tx_size] += x->plane[plane].eobs[block];
839
141M
  }
840
841
362M
  args->this_rate += rate;
842
362M
  args->this_dist += dist;
843
362M
  args->this_sse += sse;
844
362M
  args->this_rd += rd;
845
846
362M
  if (args->this_rd > args->best_rd) {
847
35.2M
    args->exit_early = 1;
848
35.2M
    return;
849
35.2M
  }
850
851
327M
  args->skippable &= !x->plane[plane].eobs[block];
852
327M
}
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
240M
                             struct buf_2d *recon) {
859
240M
  MACROBLOCKD *const xd = &x->e_mbd;
860
240M
  const struct macroblockd_plane *const pd = &xd->plane[plane];
861
240M
  struct rdcost_block_args args;
862
240M
  vp9_zero(args);
863
240M
  args.cpi = cpi;
864
240M
  args.x = x;
865
240M
  args.best_rd = ref_best_rd;
866
240M
  args.use_fast_coef_costing = use_fast_coef_costing;
867
240M
  args.skippable = 1;
868
240M
  args.this_recon = recon;
869
870
240M
  if (plane == 0) xd->mi[0]->tx_size = tx_size;
871
872
240M
  vp9_get_entropy_contexts(bsize, tx_size, pd, args.t_above, args.t_left);
873
874
240M
  args.so = get_scan(xd, tx_size, get_plane_type(plane), 0);
875
876
240M
  vp9_foreach_transformed_block_in_plane(xd, bsize, plane, block_rd_txfm,
877
240M
                                         &args);
878
240M
  if (args.exit_early) {
879
45.1M
    *rate = INT_MAX;
880
45.1M
    *distortion = INT64_MAX;
881
45.1M
    *sse = INT64_MAX;
882
45.1M
    *skippable = 0;
883
194M
  } else {
884
194M
    *distortion = args.this_dist;
885
194M
    *rate = args.this_rate;
886
194M
    *sse = args.this_sse;
887
194M
    *skippable = args.skippable;
888
194M
  }
889
240M
}
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
29.7M
                                   struct buf_2d *recon) {
895
29.7M
  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
896
29.7M
  VP9_COMMON *const cm = &cpi->common;
897
29.7M
  const TX_SIZE largest_tx_size = tx_mode_to_biggest_tx_size[cm->tx_mode];
898
29.7M
  MACROBLOCKD *const xd = &x->e_mbd;
899
29.7M
  MODE_INFO *const mi = xd->mi[0];
900
901
29.7M
  mi->tx_size = VPXMIN(max_tx_size, largest_tx_size);
902
903
29.7M
  txfm_rd_in_plane(cpi, x, rate, distortion, skip, sse, ref_best_rd, 0, bs,
904
29.7M
                   mi->tx_size, cpi->sf.use_fast_coef_costing, recon);
905
29.7M
}
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
29.5M
                                   BLOCK_SIZE bs, struct buf_2d *recon) {
911
29.5M
  const TX_SIZE max_tx_size = max_txsize_lookup[bs];
912
29.5M
  VP9_COMMON *const cm = &cpi->common;
913
29.5M
  MACROBLOCKD *const xd = &x->e_mbd;
914
29.5M
  MODE_INFO *const mi = xd->mi[0];
915
29.5M
  vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
916
29.5M
  int r[TX_SIZES][2], s[TX_SIZES];
917
29.5M
  int64_t d[TX_SIZES], sse[TX_SIZES];
918
29.5M
  int64_t rd[TX_SIZES][2] = { { INT64_MAX, INT64_MAX },
919
29.5M
                              { INT64_MAX, INT64_MAX },
920
29.5M
                              { INT64_MAX, INT64_MAX },
921
29.5M
                              { INT64_MAX, INT64_MAX } };
922
29.5M
  int n;
923
29.5M
  int s0, s1;
924
29.5M
  int64_t best_rd = ref_best_rd;
925
29.5M
  TX_SIZE best_tx = max_tx_size;
926
29.5M
  int start_tx, end_tx;
927
29.5M
  const int tx_size_ctx = get_tx_size_context(xd);
928
29.5M
#if CONFIG_VP9_HIGHBITDEPTH
929
29.5M
  DECLARE_ALIGNED(16, uint16_t, recon_buf16[TX_SIZES][64 * 64]);
930
29.5M
  uint8_t *recon_buf[TX_SIZES];
931
147M
  for (n = 0; n < TX_SIZES; ++n) {
932
118M
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
933
0
      recon_buf[n] = CONVERT_TO_BYTEPTR(recon_buf16[n]);
934
118M
    } else {
935
118M
      recon_buf[n] = (uint8_t *)recon_buf16[n];
936
118M
    }
937
118M
  }
938
#else
939
  DECLARE_ALIGNED(16, uint8_t, recon_buf[TX_SIZES][64 * 64]);
940
#endif  // CONFIG_VP9_HIGHBITDEPTH
941
942
29.5M
  assert(skip_prob > 0);
943
29.5M
  s0 = vp9_cost_bit(skip_prob, 0);
944
29.5M
  s1 = vp9_cost_bit(skip_prob, 1);
945
946
29.5M
  if (cm->tx_mode == TX_MODE_SELECT) {
947
29.5M
    start_tx = max_tx_size;
948
29.5M
    end_tx = VPXMAX(start_tx - cpi->sf.tx_size_search_depth, 0);
949
29.5M
    if (bs > BLOCK_32X32) end_tx = VPXMIN(end_tx + 1, start_tx);
950
29.5M
  } 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
41.6M
  for (n = start_tx; n >= end_tx; n--) {
958
37.8M
    const int r_tx_size = cpi->tx_size_cost[max_tx_size - 1][tx_size_ctx][n];
959
37.8M
    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
37.8M
    } else {
966
37.8M
      txfm_rd_in_plane(cpi, x, &r[n][0], &d[n], &s[n], &sse[n], best_rd, 0, bs,
967
37.8M
                       n, cpi->sf.use_fast_coef_costing, 0);
968
37.8M
    }
969
37.8M
    r[n][1] = r[n][0];
970
37.8M
    if (r[n][0] < INT_MAX) {
971
18.3M
      r[n][1] += r_tx_size;
972
18.3M
    }
973
37.8M
    if (d[n] == INT64_MAX || r[n][0] == INT_MAX) {
974
19.5M
      rd[n][0] = rd[n][1] = INT64_MAX;
975
19.5M
    } else if (s[n]) {
976
5.62M
      if (is_inter_block(mi)) {
977
595k
        rd[n][0] = rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1, sse[n]);
978
595k
        r[n][1] -= r_tx_size;
979
5.03M
      } else {
980
5.03M
        rd[n][0] = RDCOST(x->rdmult, x->rddiv, s1, sse[n]);
981
5.03M
        rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1 + r_tx_size, sse[n]);
982
5.03M
      }
983
12.6M
    } else {
984
12.6M
      rd[n][0] = RDCOST(x->rdmult, x->rddiv, r[n][0] + s0, d[n]);
985
12.6M
      rd[n][1] = RDCOST(x->rdmult, x->rddiv, r[n][1] + s0, d[n]);
986
12.6M
    }
987
988
37.8M
    if (is_inter_block(mi) && !xd->lossless && !s[n] && sse[n] != INT64_MAX) {
989
3.72M
      rd[n][0] = VPXMIN(rd[n][0], RDCOST(x->rdmult, x->rddiv, s1, sse[n]));
990
3.72M
      rd[n][1] = VPXMIN(rd[n][1], RDCOST(x->rdmult, x->rddiv, s1, sse[n]));
991
3.72M
    }
992
993
    // Early termination in transform size search.
994
37.8M
    if (cpi->sf.tx_size_search_breakout &&
995
37.8M
        (rd[n][1] == INT64_MAX ||
996
37.8M
         (n < (int)max_tx_size && rd[n][1] > rd[n + 1][1]) || s[n] == 1))
997
25.8M
      break;
998
999
12.0M
    if (rd[n][1] < best_rd) {
1000
11.5M
      best_tx = n;
1001
11.5M
      best_rd = rd[n][1];
1002
11.5M
    }
1003
12.0M
  }
1004
29.5M
  mi->tx_size = best_tx;
1005
1006
29.5M
  *distortion = d[mi->tx_size];
1007
29.5M
  *rate = r[mi->tx_size][cm->tx_mode == TX_MODE_SELECT];
1008
29.5M
  *skip = s[mi->tx_size];
1009
29.5M
  *psse = sse[mi->tx_size];
1010
29.5M
  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
29.5M
}
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
59.3M
                            struct buf_2d *recon) {
1029
59.3M
  MACROBLOCKD *xd = &x->e_mbd;
1030
59.3M
  int64_t sse;
1031
59.3M
  int64_t *ret_sse = psse ? psse : &sse;
1032
1033
59.3M
  assert(bs == xd->mi[0]->sb_type);
1034
1035
59.3M
  if (cpi->sf.tx_size_search_method == USE_LARGESTALL || xd->lossless) {
1036
29.7M
    choose_largest_tx_size(cpi, x, rate, distortion, skip, ret_sse, ref_best_rd,
1037
29.7M
                           bs, recon);
1038
29.7M
  } else {
1039
29.5M
    choose_tx_size_from_rd(cpi, x, rate, distortion, skip, ret_sse, ref_best_rd,
1040
29.5M
                           bs, recon);
1041
29.5M
  }
1042
59.3M
}
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
13.4M
                                     BLOCK_SIZE bsize, int64_t rd_thresh) {
1067
13.4M
  PREDICTION_MODE mode;
1068
13.4M
  MACROBLOCKD *const xd = &x->e_mbd;
1069
13.4M
  int64_t best_rd = rd_thresh;
1070
13.4M
  struct macroblock_plane *p = &x->plane[0];
1071
13.4M
  struct macroblockd_plane *pd = &xd->plane[0];
1072
13.4M
  const int src_stride = p->src.stride;
1073
13.4M
  const int dst_stride = pd->dst.stride;
1074
13.4M
  const uint8_t *src_init = &p->src.buf[row * 4 * src_stride + col * 4];
1075
13.4M
  uint8_t *dst_init = &pd->dst.buf[row * 4 * src_stride + col * 4];
1076
13.4M
  ENTROPY_CONTEXT ta[2], tempa[2];
1077
13.4M
  ENTROPY_CONTEXT tl[2], templ[2];
1078
13.4M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1079
13.4M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1080
13.4M
  int idx, idy;
1081
13.4M
  uint8_t best_dst[8 * 8];
1082
13.4M
#if CONFIG_VP9_HIGHBITDEPTH
1083
13.4M
  uint16_t best_dst16[8 * 8];
1084
13.4M
#endif
1085
13.4M
  memcpy(ta, a, num_4x4_blocks_wide * sizeof(a[0]));
1086
13.4M
  memcpy(tl, l, num_4x4_blocks_high * sizeof(l[0]));
1087
1088
13.4M
  xd->mi[0]->tx_size = TX_4X4;
1089
1090
13.4M
  assert(!x->skip_block);
1091
1092
13.4M
#if CONFIG_VP9_HIGHBITDEPTH
1093
13.4M
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1094
0
    for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1095
0
      int64_t this_rd;
1096
0
      int ratey = 0;
1097
0
      int64_t distortion = 0;
1098
0
      int rate = bmode_costs[mode];
1099
1100
0
      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
0
      if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
1105
0
        if (conditional_skipintra(mode, *best_mode)) continue;
1106
0
      }
1107
1108
0
      memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
1109
0
      memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
1110
1111
0
      for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
1112
0
        for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
1113
0
          const int block = (row + idy) * 2 + (col + idx);
1114
0
          const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
1115
0
          uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
1116
0
          uint16_t *const dst16 = CONVERT_TO_SHORTPTR(dst);
1117
0
          int16_t *const src_diff =
1118
0
              vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
1119
0
          tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
1120
0
          tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
1121
0
          tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
1122
0
          uint16_t *const eob = &p->eobs[block];
1123
0
          xd->mi[0]->bmi[block].as_mode = mode;
1124
0
          vp9_predict_intra_block(xd, 1, TX_4X4, mode,
1125
0
                                  x->skip_encode ? src : dst,
1126
0
                                  x->skip_encode ? src_stride : dst_stride, dst,
1127
0
                                  dst_stride, col + idx, row + idy, 0);
1128
0
          vpx_highbd_subtract_block(4, 4, src_diff, 8, src, src_stride, dst,
1129
0
                                    dst_stride, xd->bd);
1130
0
          if (xd->lossless) {
1131
0
            const ScanOrder *so = &vp9_default_scan_orders[TX_4X4];
1132
0
            const int coeff_ctx =
1133
0
                combine_entropy_contexts(tempa[idx], templ[idy]);
1134
0
            vp9_highbd_fwht4x4(src_diff, coeff, 8);
1135
0
            vpx_highbd_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant,
1136
0
                                  eob, so);
1137
0
            ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1138
0
                                 so->neighbors, cpi->sf.use_fast_coef_costing);
1139
0
            tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
1140
0
            if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1141
0
              goto next_highbd;
1142
0
            vp9_highbd_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst16,
1143
0
                                   dst_stride, p->eobs[block], xd->bd);
1144
0
          } else {
1145
0
            int64_t unused;
1146
0
            const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
1147
0
            const ScanOrder *so = &vp9_scan_orders[TX_4X4][tx_type];
1148
0
            const int coeff_ctx =
1149
0
                combine_entropy_contexts(tempa[idx], templ[idy]);
1150
0
            if (tx_type == DCT_DCT)
1151
0
              vpx_highbd_fdct4x4(src_diff, coeff, 8);
1152
0
            else
1153
0
              vp9_highbd_fht4x4(src_diff, coeff, 8, tx_type);
1154
0
            vpx_highbd_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant,
1155
0
                                  eob, so);
1156
0
            ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1157
0
                                 so->neighbors, cpi->sf.use_fast_coef_costing);
1158
0
            distortion += vp9_highbd_block_error_dispatch(
1159
0
                              coeff, BLOCK_OFFSET(pd->dqcoeff, block), 16,
1160
0
                              &unused, xd->bd) >>
1161
0
                          2;
1162
0
            tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
1163
0
            if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1164
0
              goto next_highbd;
1165
0
            vp9_highbd_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block),
1166
0
                                  dst16, dst_stride, p->eobs[block], xd->bd);
1167
0
          }
1168
0
        }
1169
0
      }
1170
1171
0
      rate += ratey;
1172
0
      this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1173
1174
0
      if (this_rd < best_rd) {
1175
0
        *bestrate = rate;
1176
0
        *bestratey = ratey;
1177
0
        *bestdistortion = distortion;
1178
0
        best_rd = this_rd;
1179
0
        *best_mode = mode;
1180
0
        memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
1181
0
        memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
1182
0
        for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
1183
0
          memcpy(best_dst16 + idy * 8,
1184
0
                 CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
1185
0
                 num_4x4_blocks_wide * 4 * sizeof(uint16_t));
1186
0
        }
1187
0
      }
1188
0
    next_highbd: {}
1189
0
    }
1190
0
    if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
1191
1192
0
    for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
1193
0
      memcpy(CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
1194
0
             best_dst16 + idy * 8, num_4x4_blocks_wide * 4 * sizeof(uint16_t));
1195
0
    }
1196
1197
0
    return best_rd;
1198
0
  }
1199
13.4M
#endif  // CONFIG_VP9_HIGHBITDEPTH
1200
1201
147M
  for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1202
134M
    int64_t this_rd;
1203
134M
    int ratey = 0;
1204
134M
    int64_t distortion = 0;
1205
134M
    int rate = bmode_costs[mode];
1206
1207
134M
    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
134M
    if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
1212
0
      if (conditional_skipintra(mode, *best_mode)) continue;
1213
0
    }
1214
1215
134M
    memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
1216
134M
    memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
1217
1218
203M
    for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
1219
239M
      for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
1220
170M
        const int block = (row + idy) * 2 + (col + idx);
1221
170M
        const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
1222
170M
        uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
1223
170M
        int16_t *const src_diff =
1224
170M
            vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
1225
170M
        tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
1226
170M
        tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
1227
170M
        tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
1228
170M
        uint16_t *const eob = &p->eobs[block];
1229
170M
        xd->mi[0]->bmi[block].as_mode = mode;
1230
170M
        vp9_predict_intra_block(xd, 1, TX_4X4, mode, x->skip_encode ? src : dst,
1231
170M
                                x->skip_encode ? src_stride : dst_stride, dst,
1232
170M
                                dst_stride, col + idx, row + idy, 0);
1233
170M
        vpx_subtract_block(4, 4, src_diff, 8, src, src_stride, dst, dst_stride);
1234
1235
170M
        if (xd->lossless) {
1236
9.94M
          const ScanOrder *so = &vp9_default_scan_orders[TX_4X4];
1237
9.94M
          const int coeff_ctx =
1238
9.94M
              combine_entropy_contexts(tempa[idx], templ[idy]);
1239
9.94M
          vp9_fwht4x4(src_diff, coeff, 8);
1240
9.94M
          vpx_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant, eob,
1241
9.94M
                         so);
1242
9.94M
          ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1243
9.94M
                               so->neighbors, cpi->sf.use_fast_coef_costing);
1244
9.94M
          tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
1245
9.94M
          if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1246
4.77M
            goto next;
1247
5.17M
          vp9_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst, dst_stride,
1248
5.17M
                          p->eobs[block]);
1249
160M
        } else {
1250
160M
          int64_t unused;
1251
160M
          const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
1252
160M
          const ScanOrder *so = &vp9_scan_orders[TX_4X4][tx_type];
1253
160M
          const int coeff_ctx =
1254
160M
              combine_entropy_contexts(tempa[idx], templ[idy]);
1255
160M
          vp9_fht4x4(src_diff, coeff, 8, tx_type);
1256
160M
          vpx_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant, eob,
1257
160M
                         so);
1258
160M
          ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1259
160M
                               so->neighbors, cpi->sf.use_fast_coef_costing);
1260
160M
          tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
1261
160M
          distortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, block),
1262
160M
                                        16, &unused) >>
1263
160M
                        2;
1264
160M
          if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1265
78.5M
            goto next;
1266
82.1M
          vp9_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block), dst,
1267
82.1M
                         dst_stride, p->eobs[block]);
1268
82.1M
        }
1269
170M
      }
1270
152M
    }
1271
1272
50.7M
    rate += ratey;
1273
50.7M
    this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1274
1275
50.7M
    if (this_rd < best_rd) {
1276
22.5M
      *bestrate = rate;
1277
22.5M
      *bestratey = ratey;
1278
22.5M
      *bestdistortion = distortion;
1279
22.5M
      best_rd = this_rd;
1280
22.5M
      *best_mode = mode;
1281
22.5M
      memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
1282
22.5M
      memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
1283
126M
      for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
1284
103M
        memcpy(best_dst + idy * 8, dst_init + idy * dst_stride,
1285
103M
               num_4x4_blocks_wide * 4);
1286
22.5M
    }
1287
134M
  next: {}
1288
134M
  }
1289
1290
13.4M
  if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
1291
1292
68.6M
  for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
1293
56.4M
    memcpy(dst_init + idy * dst_stride, best_dst + idy * 8,
1294
56.4M
           num_4x4_blocks_wide * 4);
1295
1296
12.2M
  return best_rd;
1297
13.4M
}
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
4.65M
                                            int64_t best_rd) {
1303
4.65M
  int i, j;
1304
4.65M
  const MACROBLOCKD *const xd = &mb->e_mbd;
1305
4.65M
  MODE_INFO *const mic = xd->mi[0];
1306
4.65M
  const MODE_INFO *above_mi = xd->above_mi;
1307
4.65M
  const MODE_INFO *left_mi = xd->left_mi;
1308
4.65M
  const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
1309
4.65M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1310
4.65M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1311
4.65M
  int idx, idy;
1312
4.65M
  int cost = 0;
1313
4.65M
  int64_t total_distortion = 0;
1314
4.65M
  int tot_rate_y = 0;
1315
4.65M
  int64_t total_rd = 0;
1316
4.65M
  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
11.4M
  for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
1320
20.2M
    for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
1321
13.4M
      PREDICTION_MODE best_mode = DC_PRED;
1322
13.4M
      int r = INT_MAX, ry = INT_MAX;
1323
13.4M
      int64_t d = INT64_MAX, this_rd = INT64_MAX;
1324
13.4M
      i = idy * 2 + idx;
1325
13.4M
      if (cpi->common.frame_type == KEY_FRAME) {
1326
5.04M
        const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, i);
1327
5.04M
        const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, i);
1328
1329
5.04M
        bmode_costs = cpi->y_mode_costs[A][L];
1330
5.04M
      }
1331
1332
13.4M
      this_rd = rd_pick_intra4x4block(
1333
13.4M
          cpi, mb, idy, idx, &best_mode, bmode_costs,
1334
13.4M
          xd->plane[0].above_context + idx, xd->plane[0].left_context + idy, &r,
1335
13.4M
          &ry, &d, bsize, best_rd - total_rd);
1336
1337
13.4M
      if (this_rd >= best_rd - total_rd) return INT64_MAX;
1338
1339
12.2M
      total_rd += this_rd;
1340
12.2M
      cost += r;
1341
12.2M
      total_distortion += d;
1342
12.2M
      tot_rate_y += ry;
1343
1344
12.2M
      mic->bmi[i].as_mode = best_mode;
1345
14.1M
      for (j = 1; j < num_4x4_blocks_high; ++j)
1346
1.85M
        mic->bmi[i + j * 2].as_mode = best_mode;
1347
14.1M
      for (j = 1; j < num_4x4_blocks_wide; ++j)
1348
1.86M
        mic->bmi[i + j].as_mode = best_mode;
1349
1350
12.2M
      if (total_rd >= best_rd) return INT64_MAX;
1351
12.2M
    }
1352
7.97M
  }
1353
1354
3.49M
  *rate = cost;
1355
3.49M
  *rate_y = tot_rate_y;
1356
3.49M
  *distortion = total_distortion;
1357
3.49M
  mic->mode = mic->bmi[3].as_mode;
1358
1359
3.49M
  return RDCOST(mb->rdmult, mb->rddiv, cost, total_distortion);
1360
4.65M
}
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
2.16M
                                      int64_t best_rd) {
1367
2.16M
  PREDICTION_MODE mode;
1368
2.16M
  PREDICTION_MODE mode_selected = DC_PRED;
1369
2.16M
  MACROBLOCKD *const xd = &x->e_mbd;
1370
2.16M
  MODE_INFO *const mic = xd->mi[0];
1371
2.16M
  int this_rate, this_rate_tokenonly, s;
1372
2.16M
  int64_t this_distortion, this_rd;
1373
2.16M
  TX_SIZE best_tx = TX_4X4;
1374
2.16M
  int *bmode_costs;
1375
2.16M
  const MODE_INFO *above_mi = xd->above_mi;
1376
2.16M
  const MODE_INFO *left_mi = xd->left_mi;
1377
2.16M
  const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0);
1378
2.16M
  const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
1379
2.16M
  bmode_costs = cpi->y_mode_costs[A][L];
1380
1381
2.16M
  memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1382
  /* Y Search for intra prediction mode */
1383
23.7M
  for (mode = DC_PRED; mode <= TM_PRED; mode++) {
1384
21.6M
    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
21.6M
    mic->mode = mode;
1392
1393
21.6M
    super_block_yrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s, NULL,
1394
21.6M
                    bsize, best_rd, /*recon=*/NULL);
1395
1396
21.6M
    if (this_rate_tokenonly == INT_MAX) continue;
1397
1398
6.55M
    this_rate = this_rate_tokenonly + bmode_costs[mode];
1399
6.55M
    this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
1400
1401
6.55M
    if (this_rd < best_rd) {
1402
2.23M
      mode_selected = mode;
1403
2.23M
      best_rd = this_rd;
1404
2.23M
      best_tx = mic->tx_size;
1405
2.23M
      *rate = this_rate;
1406
2.23M
      *rate_tokenonly = this_rate_tokenonly;
1407
2.23M
      *distortion = this_distortion;
1408
2.23M
      *skippable = s;
1409
2.23M
    }
1410
6.55M
  }
1411
1412
2.16M
  mic->mode = mode_selected;
1413
2.16M
  mic->tx_size = best_tx;
1414
1415
2.16M
  return best_rd;
1416
2.16M
}
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
92.4M
                            BLOCK_SIZE bsize, int64_t ref_best_rd) {
1423
92.4M
  MACROBLOCKD *const xd = &x->e_mbd;
1424
92.4M
  MODE_INFO *const mi = xd->mi[0];
1425
92.4M
  const TX_SIZE uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
1426
92.4M
  int plane;
1427
92.4M
  int pnrate = 0, pnskip = 1;
1428
92.4M
  int64_t pndist = 0, pnsse = 0;
1429
92.4M
  int is_cost_valid = 1;
1430
1431
92.4M
  if (ref_best_rd < 0) is_cost_valid = 0;
1432
1433
92.4M
  if (is_inter_block(mi) && is_cost_valid) {
1434
41.9M
    for (plane = 1; plane < MAX_MB_PLANE; ++plane)
1435
27.9M
      vp9_subtract_plane(x, bsize, plane);
1436
13.9M
  }
1437
1438
92.4M
  *rate = 0;
1439
92.4M
  *distortion = 0;
1440
92.4M
  *sse = 0;
1441
92.4M
  *skippable = 1;
1442
1443
249M
  for (plane = 1; plane < MAX_MB_PLANE; ++plane) {
1444
172M
    txfm_rd_in_plane(cpi, x, &pnrate, &pndist, &pnskip, &pnsse, ref_best_rd,
1445
172M
                     plane, bsize, uv_tx_size, cpi->sf.use_fast_coef_costing,
1446
                     /*recon=*/NULL);
1447
172M
    if (pnrate == INT_MAX) {
1448
15.8M
      is_cost_valid = 0;
1449
15.8M
      break;
1450
15.8M
    }
1451
156M
    *rate += pnrate;
1452
156M
    *distortion += pndist;
1453
156M
    *sse += pnsse;
1454
156M
    *skippable &= pnskip;
1455
156M
  }
1456
1457
92.4M
  if (!is_cost_valid) {
1458
    // reset cost value
1459
15.8M
    *rate = INT_MAX;
1460
15.8M
    *distortion = INT64_MAX;
1461
15.8M
    *sse = INT64_MAX;
1462
15.8M
    *skippable = 0;
1463
15.8M
  }
1464
1465
92.4M
  return is_cost_valid;
1466
92.4M
}
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
8.00M
                                       TX_SIZE max_tx_size) {
1473
8.00M
  MACROBLOCKD *xd = &x->e_mbd;
1474
8.00M
  PREDICTION_MODE mode;
1475
8.00M
  PREDICTION_MODE mode_selected = DC_PRED;
1476
8.00M
  int64_t best_rd = INT64_MAX, this_rd;
1477
8.00M
  int this_rate_tokenonly, this_rate, s;
1478
8.00M
  int64_t this_distortion, this_sse;
1479
1480
8.00M
  memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1481
88.0M
  for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1482
80.0M
    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
78.3M
    xd->mi[0]->uv_mode = mode;
1490
1491
78.3M
    if (!super_block_uvrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s,
1492
78.3M
                          &this_sse, bsize, best_rd))
1493
11.5M
      continue;
1494
66.8M
    this_rate =
1495
66.8M
        this_rate_tokenonly +
1496
66.8M
        cpi->intra_uv_mode_cost[cpi->common.frame_type][xd->mi[0]->mode][mode];
1497
66.8M
    this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
1498
1499
66.8M
    if (this_rd < best_rd) {
1500
13.7M
      mode_selected = mode;
1501
13.7M
      best_rd = this_rd;
1502
13.7M
      *rate = this_rate;
1503
13.7M
      *rate_tokenonly = this_rate_tokenonly;
1504
13.7M
      *distortion = this_distortion;
1505
13.7M
      *skippable = s;
1506
13.7M
      if (!x->select_tx_size) swap_block_ptr(x, ctx, 2, 0, 1, MAX_MB_PLANE);
1507
13.7M
    }
1508
66.8M
  }
1509
1510
8.00M
  xd->mi[0]->uv_mode = mode_selected;
1511
8.00M
  return best_rd;
1512
8.00M
}
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
4.98M
                                 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
4.98M
  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
4.98M
  } else {
1544
4.98M
    rd_pick_intra_sbuv_mode(cpi, x, ctx, rate_uv, rate_uv_tokenonly, dist_uv,
1545
4.98M
                            skip_uv, bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
1546
4.98M
                            max_tx_size);
1547
4.98M
  }
1548
4.98M
  *mode_uv = x->e_mbd.mi[0]->uv_mode;
1549
4.98M
}
1550
1551
static int cost_mv_ref(const VP9_COMP *cpi, PREDICTION_MODE mode,
1552
236M
                       int mode_context) {
1553
236M
  assert(is_inter_mode(mode));
1554
236M
  return cpi->inter_mode_cost[mode_context][INTER_OFFSET(mode)];
1555
236M
}
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
71.4M
                                int *mvcost[2]) {
1563
71.4M
  MODE_INFO *const mi = xd->mi[0];
1564
71.4M
  const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
1565
71.4M
  int thismvcost = 0;
1566
71.4M
  int idx, idy;
1567
71.4M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[mi->sb_type];
1568
71.4M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[mi->sb_type];
1569
71.4M
  const int is_compound = has_second_ref(mi);
1570
1571
71.4M
  switch (mode) {
1572
21.7M
    case NEWMV:
1573
21.7M
      this_mv[0].as_int = seg_mvs[mi->ref_frame[0]].as_int;
1574
21.7M
      thismvcost += vp9_mv_bit_cost(&this_mv[0].as_mv, &best_ref_mv[0]->as_mv,
1575
21.7M
                                    mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1576
21.7M
      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
21.7M
      break;
1582
13.1M
    case NEARMV:
1583
39.5M
    case NEARESTMV:
1584
39.5M
      this_mv[0].as_int = frame_mv[mode][mi->ref_frame[0]].as_int;
1585
39.5M
      if (is_compound)
1586
0
        this_mv[1].as_int = frame_mv[mode][mi->ref_frame[1]].as_int;
1587
39.5M
      break;
1588
10.1M
    default:
1589
10.1M
      assert(mode == ZEROMV);
1590
10.1M
      this_mv[0].as_int = 0;
1591
10.1M
      if (is_compound) this_mv[1].as_int = 0;
1592
10.1M
      break;
1593
71.4M
  }
1594
1595
71.4M
  mi->bmi[i].as_mv[0].as_int = this_mv[0].as_int;
1596
71.4M
  if (is_compound) mi->bmi[i].as_mv[1].as_int = this_mv[1].as_int;
1597
1598
71.4M
  mi->bmi[i].as_mode = mode;
1599
1600
153M
  for (idy = 0; idy < num_4x4_blocks_high; ++idy)
1601
175M
    for (idx = 0; idx < num_4x4_blocks_wide; ++idx)
1602
93.1M
      memmove(&mi->bmi[i + idy * 2 + idx], &mi->bmi[i], sizeof(mi->bmi[i]));
1603
1604
71.4M
  return cost_mv_ref(cpi, mode, mbmi_ext->mode_context[mi->ref_frame[0]]) +
1605
71.4M
         thismvcost;
1606
71.4M
}
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
53.9M
                                       int mi_row, int mi_col) {
1613
53.9M
  int k;
1614
53.9M
  MACROBLOCKD *xd = &x->e_mbd;
1615
53.9M
  struct macroblockd_plane *const pd = &xd->plane[0];
1616
53.9M
  struct macroblock_plane *const p = &x->plane[0];
1617
53.9M
  MODE_INFO *const mi = xd->mi[0];
1618
53.9M
  const BLOCK_SIZE plane_bsize = get_plane_block_size(mi->sb_type, pd);
1619
53.9M
  const int width = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
1620
53.9M
  const int height = 4 * num_4x4_blocks_high_lookup[plane_bsize];
1621
53.9M
  int idx, idy;
1622
1623
53.9M
  const uint8_t *const src =
1624
53.9M
      &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1625
53.9M
  uint8_t *const dst =
1626
53.9M
      &pd->dst.buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->dst.stride)];
1627
53.9M
  int64_t thisdistortion = 0, thissse = 0;
1628
53.9M
  int thisrate = 0, ref;
1629
53.9M
  const ScanOrder *so = &vp9_default_scan_orders[TX_4X4];
1630
53.9M
  const int is_compound = has_second_ref(mi);
1631
53.9M
  const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
1632
1633
53.9M
  assert(!x->skip_block);
1634
1635
107M
  for (ref = 0; ref < 1 + is_compound; ++ref) {
1636
53.9M
    const int bw = b_width_log2_lookup[BLOCK_8X8];
1637
53.9M
    const int h = 4 * (i >> bw);
1638
53.9M
    const int w = 4 * (i & ((1 << bw) - 1));
1639
53.9M
    const struct scale_factors *sf = &xd->block_refs[ref]->sf;
1640
53.9M
    int y_stride = pd->pre[ref].stride;
1641
53.9M
    uint8_t *pre = pd->pre[ref].buf + (h * pd->pre[ref].stride + w);
1642
1643
53.9M
    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
53.9M
#if CONFIG_VP9_HIGHBITDEPTH
1652
53.9M
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1653
0
      vp9_highbd_build_inter_predictor(
1654
0
          CONVERT_TO_SHORTPTR(pre), y_stride, CONVERT_TO_SHORTPTR(dst),
1655
0
          pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1656
0
          &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1657
0
          mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2),
1658
0
          xd->bd);
1659
53.9M
    } else {
1660
53.9M
      vp9_build_inter_predictor(
1661
53.9M
          pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1662
53.9M
          &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1663
53.9M
          mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
1664
53.9M
    }
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
53.9M
  }
1672
1673
53.9M
#if CONFIG_VP9_HIGHBITDEPTH
1674
53.9M
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1675
0
    vpx_highbd_subtract_block(
1676
0
        height, width, vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1677
0
        8, src, p->src.stride, dst, pd->dst.stride, xd->bd);
1678
53.9M
  } else {
1679
53.9M
    vpx_subtract_block(height, width,
1680
53.9M
                       vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1681
53.9M
                       8, src, p->src.stride, dst, pd->dst.stride);
1682
53.9M
  }
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
53.9M
  k = i;
1690
106M
  for (idy = 0; idy < height / 4; ++idy) {
1691
120M
    for (idx = 0; idx < width / 4; ++idx) {
1692
68.5M
#if CONFIG_VP9_HIGHBITDEPTH
1693
68.5M
      const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
1694
68.5M
#endif
1695
68.5M
      int64_t ssz, rd, rd1, rd2;
1696
68.5M
      tran_low_t *coeff, *qcoeff, *dqcoeff;
1697
68.5M
      uint16_t *eob;
1698
68.5M
      int coeff_ctx;
1699
68.5M
      k += (idy * 2 + idx);
1700
68.5M
      coeff_ctx = combine_entropy_contexts(ta[k & 1], tl[k >> 1]);
1701
68.5M
      coeff = BLOCK_OFFSET(p->coeff, k);
1702
68.5M
      qcoeff = BLOCK_OFFSET(p->qcoeff, k);
1703
68.5M
      dqcoeff = BLOCK_OFFSET(pd->dqcoeff, k);
1704
68.5M
      eob = &p->eobs[k];
1705
1706
68.5M
      x->fwd_txfm4x4(vp9_raster_block_offset_int16(BLOCK_8X8, k, p->src_diff),
1707
68.5M
                     coeff, 8);
1708
68.5M
#if CONFIG_VP9_HIGHBITDEPTH
1709
68.5M
      vpx_highbd_quantize_b(coeff, 4 * 4, p, qcoeff, dqcoeff, pd->dequant, eob,
1710
68.5M
                            so);
1711
68.5M
      thisdistortion += vp9_highbd_block_error_dispatch(
1712
68.5M
          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
68.5M
      thissse += ssz;
1719
68.5M
      thisrate += cost_coeffs(x, 0, k, TX_4X4, coeff_ctx, so->scan,
1720
68.5M
                              so->neighbors, cpi->sf.use_fast_coef_costing);
1721
68.5M
      ta[k & 1] = tl[k >> 1] = (x->plane[0].eobs[k] > 0) ? 1 : 0;
1722
68.5M
      rd1 = RDCOST(x->rdmult, x->rddiv, thisrate, thisdistortion >> 2);
1723
68.5M
      rd2 = RDCOST(x->rdmult, x->rddiv, 0, thissse >> 2);
1724
68.5M
      rd = VPXMIN(rd1, rd2);
1725
68.5M
      if (rd >= best_yrd) return INT64_MAX;
1726
68.5M
    }
1727
61.2M
  }
1728
1729
45.0M
  *distortion = thisdistortion >> 2;
1730
45.0M
  *labelyrate = thisrate;
1731
45.0M
  *sse = thissse >> 2;
1732
1733
45.0M
  return RDCOST(x->rdmult, x->rddiv, *labelyrate, *distortion);
1734
53.9M
}
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
76.6M
static INLINE int mv_check_bounds(const MvLimits *mv_limits, const MV *mv) {
1765
76.6M
  return (mv->row >> 3) < mv_limits->row_min ||
1766
76.6M
         (mv->row >> 3) > mv_limits->row_max ||
1767
76.6M
         (mv->col >> 3) < mv_limits->col_min ||
1768
76.6M
         (mv->col >> 3) > mv_limits->col_max;
1769
76.6M
}
1770
1771
16.8M
static INLINE void mi_buf_shift(MACROBLOCK *x, int i) {
1772
16.8M
  MODE_INFO *const mi = x->e_mbd.mi[0];
1773
16.8M
  struct macroblock_plane *const p = &x->plane[0];
1774
16.8M
  struct macroblockd_plane *const pd = &x->e_mbd.plane[0];
1775
1776
16.8M
  p->src.buf =
1777
16.8M
      &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1778
16.8M
  assert(((intptr_t)pd->pre[0].buf & 0x7) == 0);
1779
16.8M
  pd->pre[0].buf =
1780
16.8M
      &pd->pre[0].buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[0].stride)];
1781
16.8M
  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
16.8M
}
1786
1787
static INLINE void mi_buf_restore(MACROBLOCK *x, struct buf_2d orig_src,
1788
16.8M
                                  struct buf_2d orig_pre[2]) {
1789
16.8M
  MODE_INFO *mi = x->e_mbd.mi[0];
1790
16.8M
  x->plane[0].src = orig_src;
1791
16.8M
  x->e_mbd.plane[0].pre[0] = orig_pre[0];
1792
16.8M
  if (has_second_ref(mi)) x->e_mbd.plane[0].pre[1] = orig_pre[1];
1793
16.8M
}
1794
1795
20.2M
static INLINE int mv_has_subpel(const MV *mv) {
1796
20.2M
  return (mv->row & 0x0F) || (mv->col & 0x0F);
1797
20.2M
}
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
98.0M
                              const MV_REFERENCE_FRAME ref_frames[2]) {
1806
98.0M
  if ((this_mode == NEARMV || this_mode == NEARESTMV || this_mode == ZEROMV) &&
1807
98.0M
      frame_mv[this_mode][ref_frames[0]].as_int == 0 &&
1808
98.0M
      (ref_frames[1] == NO_REF_FRAME ||
1809
46.5M
       frame_mv[this_mode][ref_frames[1]].as_int == 0)) {
1810
46.5M
    int rfc = mode_context[ref_frames[0]];
1811
46.5M
    int c1 = cost_mv_ref(cpi, NEARMV, rfc);
1812
46.5M
    int c2 = cost_mv_ref(cpi, NEARESTMV, rfc);
1813
46.5M
    int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
1814
1815
46.5M
    if (this_mode == NEARMV) {
1816
13.8M
      if (c1 > c3) return 0;
1817
32.6M
    } else if (this_mode == NEARESTMV) {
1818
9.01M
      if (c2 > c3) return 0;
1819
23.6M
    } else {
1820
23.6M
      assert(this_mode == ZEROMV);
1821
23.6M
      if (ref_frames[1] == NO_REF_FRAME) {
1822
23.6M
        if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0) ||
1823
23.6M
            (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0))
1824
11.9M
          return 0;
1825
23.6M
      } 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
23.6M
    }
1833
46.5M
  }
1834
78.0M
  return 1;
1835
98.0M
}
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.63M
                                       int mv_thresh) {
1853
3.63M
  const int mv_diff =
1854
3.63M
      abs(mode_mv.col - this_mv.col) + abs(mode_mv.row - this_mv.row);
1855
3.63M
  if (mv_diff <= mv_thresh && mode_rate < this_mode_rate) return 1;
1856
3.40M
  return 0;
1857
3.63M
}
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.21M
    int ref0, int this_mode_rate, int best_mode_index) {
1864
6.21M
  MV this_mv = mode_mv[this_mode][ref0].as_mv;
1865
6.21M
  const int mv_thresh = 3;
1866
1867
  // Pruning is not applicable for NEARESTMV or NEWMV modes.
1868
6.21M
  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
2.03M
  if (best_mode_index > 0 &&
1872
2.03M
      ref0 == vp9_mode_order[best_mode_index].ref_frame[0])
1873
378k
    return 0;
1874
1875
  // Check absolute mv difference and mode rate of current mode w.r.t NEARESTMV
1876
1.65M
  if (compare_mv_mode_rate(
1877
1.65M
          this_mv, mode_mv[NEARESTMV][ref0].as_mv, this_mode_rate,
1878
1.65M
          single_mode_rate[INTER_OFFSET(NEARESTMV)], mv_thresh))
1879
230k
    return 1;
1880
1881
  // Check absolute mv difference and mode rate of current mode w.r.t NEWMV
1882
1.42M
  if (compare_mv_mode_rate(this_mv, mode_mv[NEWMV][ref0].as_mv, this_mode_rate,
1883
1.42M
                           single_mode_rate[INTER_OFFSET(NEWMV)], mv_thresh))
1884
42
    return 1;
1885
1886
  // Pruning w.r.t NEARMV is applicable only for ZEROMV mode
1887
1.42M
  if (this_mode == NEARMV) return 0;
1888
  // Check absolute mv difference and mode rate of current mode w.r.t NEARMV
1889
552k
  if (compare_mv_mode_rate(this_mv, mode_mv[NEARMV][ref0].as_mv, this_mode_rate,
1890
552k
                           single_mode_rate[INTER_OFFSET(NEARMV)], mv_thresh))
1891
262
    return 1;
1892
552k
  return 0;
1893
552k
}
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
6.11M
    int filter_idx, int mi_row, int mi_col) {
2083
6.11M
  int i;
2084
6.11M
  BEST_SEG_INFO *bsi = bsi_buf + filter_idx;
2085
6.11M
  MACROBLOCKD *xd = &x->e_mbd;
2086
6.11M
  MODE_INFO *mi = xd->mi[0];
2087
6.11M
  int mode_idx;
2088
6.11M
  int k, br = 0, idx, idy;
2089
6.11M
  int64_t bd = 0, block_sse = 0;
2090
6.11M
  PREDICTION_MODE this_mode;
2091
6.11M
  VP9_COMMON *cm = &cpi->common;
2092
6.11M
  struct macroblock_plane *const p = &x->plane[0];
2093
6.11M
  struct macroblockd_plane *const pd = &xd->plane[0];
2094
6.11M
  const int label_count = 4;
2095
6.11M
  int64_t this_segment_rd = 0;
2096
6.11M
  int label_mv_thresh;
2097
6.11M
  int segmentyrate = 0;
2098
6.11M
  const BLOCK_SIZE bsize = mi->sb_type;
2099
6.11M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2100
6.11M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2101
6.11M
  const int pw = num_4x4_blocks_wide << 2;
2102
6.11M
  const int ph = num_4x4_blocks_high << 2;
2103
6.11M
  ENTROPY_CONTEXT t_above[2], t_left[2];
2104
6.11M
  int subpelmv = 1, have_ref = 0;
2105
6.11M
  SPEED_FEATURES *const sf = &cpi->sf;
2106
6.11M
  const int has_second_rf = has_second_ref(mi);
2107
6.11M
  const int inter_mode_mask = sf->inter_mode_mask[bsize];
2108
6.11M
  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2109
2110
6.11M
  vp9_zero(*bsi);
2111
2112
6.11M
  bsi->segment_rd = best_rd_so_far;
2113
6.11M
  bsi->ref_mv[0] = best_ref_mv;
2114
6.11M
  bsi->ref_mv[1] = second_best_ref_mv;
2115
6.11M
  bsi->mvp.as_int = best_ref_mv->as_int;
2116
6.11M
  bsi->mvthresh = mvthresh;
2117
2118
30.5M
  for (i = 0; i < 4; i++) bsi->modes[i] = ZEROMV;
2119
2120
6.11M
  memcpy(t_above, pd->above_context, sizeof(t_above));
2121
6.11M
  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
6.11M
  label_mv_thresh = 1 * bsi->mvthresh / label_count;
2128
2129
  // Segmentation method overheads
2130
14.3M
  for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
2131
25.7M
    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
17.5M
      int_mv mode_mv[MB_MODE_COUNT][2];
2135
17.5M
      int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
2136
17.5M
      PREDICTION_MODE mode_selected = ZEROMV;
2137
17.5M
      int64_t best_rd = INT64_MAX;
2138
17.5M
      const int block = idy * 2 + idx;
2139
17.5M
      int ref;
2140
2141
35.1M
      for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2142
17.5M
        const MV_REFERENCE_FRAME frame = mi->ref_frame[ref];
2143
17.5M
        frame_mv[ZEROMV][frame].as_int = 0;
2144
17.5M
        vp9_append_sub8x8_mvs_for_idx(
2145
17.5M
            cm, xd, block, ref, mi_row, mi_col, &frame_mv[NEARESTMV][frame],
2146
17.5M
            &frame_mv[NEARMV][frame], mbmi_ext->mode_context);
2147
17.5M
      }
2148
2149
      // search for the best motion vector on this segment
2150
87.2M
      for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
2151
70.3M
        const struct buf_2d orig_src = x->plane[0].src;
2152
70.3M
        struct buf_2d orig_pre[2];
2153
2154
70.3M
        mode_idx = INTER_OFFSET(this_mode);
2155
70.3M
        bsi->rdstat[block][mode_idx].brdcost = INT64_MAX;
2156
70.3M
        if (!(inter_mode_mask & (1 << this_mode))) continue;
2157
2158
70.3M
        if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv,
2159
70.3M
                                this_mode, mi->ref_frame))
2160
14.1M
          continue;
2161
2162
56.2M
        memcpy(orig_pre, pd->pre, sizeof(orig_pre));
2163
56.2M
        memcpy(bsi->rdstat[block][mode_idx].ta, t_above,
2164
56.2M
               sizeof(bsi->rdstat[block][mode_idx].ta));
2165
56.2M
        memcpy(bsi->rdstat[block][mode_idx].tl, t_left,
2166
56.2M
               sizeof(bsi->rdstat[block][mode_idx].tl));
2167
2168
        // motion search for newmv (single predictor case only)
2169
56.2M
        if (!has_second_rf && this_mode == NEWMV &&
2170
56.2M
            seg_mvs[block][mi->ref_frame[0]].as_int == INVALID_MV) {
2171
17.5M
          MV *const new_mv = &mode_mv[NEWMV][0].as_mv;
2172
17.5M
          int step_param = 0;
2173
17.5M
          uint32_t bestsme = UINT_MAX;
2174
17.5M
          int sadpb = x->sadperbit4;
2175
17.5M
          MV mvp_full;
2176
17.5M
          int max_mv;
2177
17.5M
          int cost_list[5];
2178
17.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
17.5M
          if (best_rd < label_mv_thresh) break;
2183
2184
16.8M
          if (cpi->oxcf.mode != BEST) {
2185
            // use previous block's result as next block's MV predictor.
2186
16.8M
            if (block > 0) {
2187
10.9M
              bsi->mvp.as_int = mi->bmi[block - 1].as_mv[0].as_int;
2188
10.9M
              if (block == 2)
2189
4.11M
                bsi->mvp.as_int = mi->bmi[block - 2].as_mv[0].as_int;
2190
10.9M
            }
2191
16.8M
          }
2192
16.8M
          if (block == 0)
2193
5.94M
            max_mv = x->max_mv_context[mi->ref_frame[0]];
2194
10.9M
          else
2195
10.9M
            max_mv =
2196
10.9M
                VPXMAX(abs(bsi->mvp.as_mv.row), abs(bsi->mvp.as_mv.col)) >> 3;
2197
2198
16.8M
          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
16.8M
            step_param =
2203
16.8M
                (vp9_init_search_range(max_mv) + cpi->mv_step_param) / 2;
2204
16.8M
          } else {
2205
0
            step_param = cpi->mv_step_param;
2206
0
          }
2207
2208
16.8M
          mvp_full.row = bsi->mvp.as_mv.row >> 3;
2209
16.8M
          mvp_full.col = bsi->mvp.as_mv.col >> 3;
2210
2211
16.8M
          if (sf->adaptive_motion_search) {
2212
16.8M
            if (x->pred_mv[mi->ref_frame[0]].row != INT16_MAX &&
2213
16.8M
                x->pred_mv[mi->ref_frame[0]].col != INT16_MAX) {
2214
16.4M
              mvp_full.row = x->pred_mv[mi->ref_frame[0]].row >> 3;
2215
16.4M
              mvp_full.col = x->pred_mv[mi->ref_frame[0]].col >> 3;
2216
16.4M
            }
2217
16.8M
            step_param = VPXMAX(step_param, 8);
2218
16.8M
          }
2219
2220
          // adjust src pointer for this block
2221
16.8M
          mi_buf_shift(x, block);
2222
2223
16.8M
          vp9_set_mv_search_range(&x->mv_limits, &bsi->ref_mv[0]->as_mv);
2224
2225
16.8M
          bestsme = vp9_full_pixel_search(
2226
16.8M
              cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method,
2227
16.8M
              sadpb,
2228
16.8M
              sf->mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL,
2229
16.8M
              &bsi->ref_mv[0]->as_mv, new_mv, INT_MAX, 1);
2230
2231
16.8M
          x->mv_limits = tmp_mv_limits;
2232
2233
16.8M
          if (bestsme < UINT_MAX) {
2234
16.8M
            uint32_t distortion;
2235
16.8M
            cpi->find_fractional_mv_step(
2236
16.8M
                x, new_mv, &bsi->ref_mv[0]->as_mv, cm->allow_high_precision_mv,
2237
16.8M
                x->errorperbit, &cpi->fn_ptr[bsize], sf->mv.subpel_force_stop,
2238
16.8M
                sf->mv.subpel_search_level, cond_cost_list(cpi, cost_list),
2239
16.8M
                x->nmvjointcost, x->mvcost, &distortion,
2240
16.8M
                &x->pred_sse[mi->ref_frame[0]], NULL, pw, ph,
2241
16.8M
                cpi->sf.use_accurate_subpel_search);
2242
2243
            // save motion search result for use in compound prediction
2244
16.8M
            seg_mvs[block][mi->ref_frame[0]].as_mv = *new_mv;
2245
16.8M
          }
2246
2247
16.8M
          x->pred_mv[mi->ref_frame[0]] = *new_mv;
2248
2249
          // restore src pointers
2250
16.8M
          mi_buf_restore(x, orig_src, orig_pre);
2251
16.8M
        }
2252
2253
55.5M
        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
55.5M
        if (has_second_rf && this_mode == NEWMV &&
2260
55.5M
            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
55.5M
        bsi->rdstat[block][mode_idx].brate = set_and_cost_bmi_mvs(
2281
55.5M
            cpi, x, xd, block, this_mode, mode_mv[this_mode], frame_mv,
2282
55.5M
            seg_mvs[block], bsi->ref_mv, x->nmvjointcost, x->mvcost);
2283
2284
111M
        for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2285
55.5M
          bsi->rdstat[block][mode_idx].mvs[ref].as_int =
2286
55.5M
              mode_mv[this_mode][ref].as_int;
2287
55.5M
          if (num_4x4_blocks_wide > 1)
2288
8.58M
            bsi->rdstat[block + 1][mode_idx].mvs[ref].as_int =
2289
8.58M
                mode_mv[this_mode][ref].as_int;
2290
55.5M
          if (num_4x4_blocks_high > 1)
2291
8.62M
            bsi->rdstat[block + 2][mode_idx].mvs[ref].as_int =
2292
8.62M
                mode_mv[this_mode][ref].as_int;
2293
55.5M
        }
2294
2295
        // Trap vectors that reach beyond the UMV borders
2296
55.5M
        if (mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][0].as_mv) ||
2297
55.5M
            (has_second_rf &&
2298
53.9M
             mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][1].as_mv)))
2299
1.56M
          continue;
2300
2301
53.9M
        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
53.9M
        bsi->rdstat[block][mode_idx].brdcost = encode_inter_mb_segment(
2339
53.9M
            cpi, x, bsi->segment_rd - this_segment_rd, block,
2340
53.9M
            &bsi->rdstat[block][mode_idx].byrate,
2341
53.9M
            &bsi->rdstat[block][mode_idx].bdist,
2342
53.9M
            &bsi->rdstat[block][mode_idx].bsse, bsi->rdstat[block][mode_idx].ta,
2343
53.9M
            bsi->rdstat[block][mode_idx].tl, mi_row, mi_col);
2344
53.9M
        if (bsi->rdstat[block][mode_idx].brdcost < INT64_MAX) {
2345
45.0M
          bsi->rdstat[block][mode_idx].brdcost += RDCOST(
2346
45.0M
              x->rdmult, x->rddiv, bsi->rdstat[block][mode_idx].brate, 0);
2347
45.0M
          bsi->rdstat[block][mode_idx].brate +=
2348
45.0M
              bsi->rdstat[block][mode_idx].byrate;
2349
45.0M
          bsi->rdstat[block][mode_idx].eobs = p->eobs[block];
2350
45.0M
          if (num_4x4_blocks_wide > 1)
2351
5.86M
            bsi->rdstat[block + 1][mode_idx].eobs = p->eobs[block + 1];
2352
45.0M
          if (num_4x4_blocks_high > 1)
2353
5.80M
            bsi->rdstat[block + 2][mode_idx].eobs = p->eobs[block + 2];
2354
45.0M
        }
2355
2356
53.9M
        if (bsi->rdstat[block][mode_idx].brdcost < best_rd) {
2357
23.1M
          mode_selected = this_mode;
2358
23.1M
          best_rd = bsi->rdstat[block][mode_idx].brdcost;
2359
23.1M
        }
2360
53.9M
      } /*for each 4x4 mode*/
2361
2362
17.5M
      if (best_rd == INT64_MAX) {
2363
1.63M
        int iy, midx;
2364
3.89M
        for (iy = block + 1; iy < 4; ++iy)
2365
11.2M
          for (midx = 0; midx < INTER_MODES; ++midx)
2366
9.02M
            bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2367
1.63M
        bsi->segment_rd = INT64_MAX;
2368
1.63M
        return INT64_MAX;
2369
1.63M
      }
2370
2371
15.9M
      mode_idx = INTER_OFFSET(mode_selected);
2372
15.9M
      memcpy(t_above, bsi->rdstat[block][mode_idx].ta, sizeof(t_above));
2373
15.9M
      memcpy(t_left, bsi->rdstat[block][mode_idx].tl, sizeof(t_left));
2374
2375
15.9M
      set_and_cost_bmi_mvs(cpi, x, xd, block, mode_selected,
2376
15.9M
                           mode_mv[mode_selected], frame_mv, seg_mvs[block],
2377
15.9M
                           bsi->ref_mv, x->nmvjointcost, x->mvcost);
2378
2379
15.9M
      br += bsi->rdstat[block][mode_idx].brate;
2380
15.9M
      bd += bsi->rdstat[block][mode_idx].bdist;
2381
15.9M
      block_sse += bsi->rdstat[block][mode_idx].bsse;
2382
15.9M
      segmentyrate += bsi->rdstat[block][mode_idx].byrate;
2383
15.9M
      this_segment_rd += bsi->rdstat[block][mode_idx].brdcost;
2384
2385
15.9M
      if (this_segment_rd > bsi->segment_rd) {
2386
568k
        int iy, midx;
2387
1.46M
        for (iy = block + 1; iy < 4; ++iy)
2388
4.48M
          for (midx = 0; midx < INTER_MODES; ++midx)
2389
3.59M
            bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2390
568k
        bsi->segment_rd = INT64_MAX;
2391
568k
        return INT64_MAX;
2392
568k
      }
2393
15.9M
    }
2394
10.4M
  } /* for each label */
2395
2396
3.91M
  bsi->r = br;
2397
3.91M
  bsi->d = bd;
2398
3.91M
  bsi->segment_yrate = segmentyrate;
2399
3.91M
  bsi->segment_rd = this_segment_rd;
2400
3.91M
  bsi->sse = block_sse;
2401
2402
  // update the coding decisions
2403
19.5M
  for (k = 0; k < 4; ++k) bsi->modes[k] = mi->bmi[k].as_mode;
2404
2405
3.91M
  if (bsi->segment_rd > best_rd_so_far) return INT64_MAX;
2406
  /* set it to the best */
2407
19.5M
  for (i = 0; i < 4; i++) {
2408
15.6M
    mode_idx = INTER_OFFSET(bsi->modes[i]);
2409
15.6M
    mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int;
2410
15.6M
    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
15.6M
    x->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
2413
15.6M
    mi->bmi[i].as_mode = bsi->modes[i];
2414
15.6M
  }
2415
2416
  /*
2417
   * used to set mbmi->mv.as_int
2418
   */
2419
3.91M
  *returntotrate = bsi->r;
2420
3.91M
  *returndistortion = bsi->d;
2421
3.91M
  *returnyrate = bsi->segment_yrate;
2422
3.91M
  *skippable = vp9_is_skippable_in_plane(x, BLOCK_8X8, 0);
2423
3.91M
  *psse = bsi->sse;
2424
3.91M
  mi->mode = bsi->modes[3];
2425
2426
3.91M
  return bsi->segment_rd;
2427
3.91M
}
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
6.63M
                                     vpx_prob *comp_mode_p) {
2434
6.63M
  int seg_ref_active =
2435
6.63M
      segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME);
2436
6.63M
  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
6.63M
  } else {
2441
6.63M
    vpx_prob intra_inter_p = vp9_get_intra_inter_prob(cm, xd);
2442
6.63M
    vpx_prob comp_inter_p = 128;
2443
2444
6.63M
    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
6.63M
    } else {
2448
6.63M
      *comp_mode_p = 128;
2449
6.63M
    }
2450
2451
6.63M
    ref_costs_single[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
2452
2453
6.63M
    if (cm->reference_mode != COMPOUND_REFERENCE) {
2454
6.63M
      vpx_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
2455
6.63M
      vpx_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
2456
6.63M
      unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
2457
2458
6.63M
      if (cm->reference_mode == REFERENCE_MODE_SELECT)
2459
0
        base_cost += vp9_cost_bit(comp_inter_p, 0);
2460
2461
6.63M
      ref_costs_single[LAST_FRAME] = ref_costs_single[GOLDEN_FRAME] =
2462
6.63M
          ref_costs_single[ALTREF_FRAME] = base_cost;
2463
6.63M
      ref_costs_single[LAST_FRAME] += vp9_cost_bit(ref_single_p1, 0);
2464
6.63M
      ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
2465
6.63M
      ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
2466
6.63M
      ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
2467
6.63M
      ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
2468
6.63M
    } 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
6.63M
    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
6.63M
    } else {
2483
6.63M
      ref_costs_comp[LAST_FRAME] = 512;
2484
6.63M
      ref_costs_comp[GOLDEN_FRAME] = 512;
2485
6.63M
    }
2486
6.63M
  }
2487
6.63M
}
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.96M
    int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS], int skippable) {
2493
3.96M
  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.96M
  ctx->skip = x->skip;
2498
3.96M
  ctx->skippable = skippable;
2499
3.96M
  ctx->best_mode_index = mode_index;
2500
3.96M
  ctx->mic = *xd->mi[0];
2501
3.96M
  ctx->mbmi_ext = *x->mbmi_ext;
2502
3.96M
  ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_REFERENCE];
2503
3.96M
  ctx->comp_pred_diff = (int)comp_pred_diff[COMPOUND_REFERENCE];
2504
3.96M
  ctx->hybrid_pred_diff = (int)comp_pred_diff[REFERENCE_MODE_SELECT];
2505
2506
3.96M
  memcpy(ctx->best_filter_diff, best_filter_diff,
2507
3.96M
         sizeof(*best_filter_diff) * SWITCHABLE_FILTER_CONTEXTS);
2508
3.96M
}
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
14.4M
                               struct buf_2d yv12_mb[4][MAX_MB_PLANE]) {
2516
14.4M
  const VP9_COMMON *cm = &cpi->common;
2517
14.4M
  const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
2518
14.4M
  MACROBLOCKD *const xd = &x->e_mbd;
2519
14.4M
  MODE_INFO *const mi = xd->mi[0];
2520
14.4M
  int_mv *const candidates = x->mbmi_ext->ref_mvs[ref_frame];
2521
14.4M
  const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
2522
14.4M
  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2523
2524
14.4M
  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
14.4M
  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
14.4M
  vp9_find_mv_refs(cm, xd, mi, ref_frame, candidates, mi_row, mi_col,
2532
14.4M
                   mbmi_ext->mode_context);
2533
2534
  // Candidate refinement carried out at encoder and decoder
2535
14.4M
  vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
2536
14.4M
                        &frame_nearest_mv[ref_frame],
2537
14.4M
                        &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
14.4M
  if (!vp9_is_scaled(sf) && block_size >= BLOCK_8X8)
2543
7.70M
    vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride, ref_frame,
2544
7.70M
                block_size);
2545
14.4M
}
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
7.61M
                                 int *rate_mv) {
2566
7.61M
  MACROBLOCKD *xd = &x->e_mbd;
2567
7.61M
  const VP9_COMMON *cm = &cpi->common;
2568
7.61M
  MODE_INFO *mi = xd->mi[0];
2569
7.61M
  struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0 } };
2570
7.61M
  int step_param;
2571
7.61M
  MV mvp_full;
2572
7.61M
  int ref = mi->ref_frame[0];
2573
7.61M
  MV ref_mv = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2574
7.61M
  const MvLimits tmp_mv_limits = x->mv_limits;
2575
7.61M
  int cost_list[5];
2576
7.61M
  const int best_predmv_idx = x->mv_best_ref_index[ref];
2577
7.61M
  const YV12_BUFFER_CONFIG *scaled_ref_frame =
2578
7.61M
      vp9_get_scaled_ref_frame(cpi, ref);
2579
7.61M
  const int pw = num_4x4_blocks_wide_lookup[bsize] << 2;
2580
7.61M
  const int ph = num_4x4_blocks_high_lookup[bsize] << 2;
2581
7.61M
  MV pred_mv[3];
2582
2583
7.61M
  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
7.61M
  int sadpb = x->sadperbit16;
2597
7.61M
#endif  // CONFIG_NON_GREEDY_MV
2598
2599
7.61M
  pred_mv[0] = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2600
7.61M
  pred_mv[1] = x->mbmi_ext->ref_mvs[ref][1].as_mv;
2601
7.61M
  pred_mv[2] = x->pred_mv[ref];
2602
2603
7.61M
  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
7.61M
  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
7.61M
    step_param =
2620
7.61M
        (vp9_init_search_range(x->max_mv_context[ref]) + cpi->mv_step_param) /
2621
7.61M
        2;
2622
7.61M
  } else {
2623
0
    step_param = cpi->mv_step_param;
2624
0
  }
2625
2626
7.61M
  if (cpi->sf.adaptive_motion_search && bsize < BLOCK_64X64) {
2627
7.56M
    const int boffset =
2628
7.56M
        2 * (b_width_log2_lookup[BLOCK_64X64] -
2629
7.56M
             VPXMIN(b_height_log2_lookup[bsize], b_width_log2_lookup[bsize]));
2630
7.56M
    step_param = VPXMAX(step_param, boffset);
2631
7.56M
  }
2632
2633
7.61M
  if (cpi->sf.adaptive_motion_search) {
2634
7.61M
    int bwl = b_width_log2_lookup[bsize];
2635
7.61M
    int bhl = b_height_log2_lookup[bsize];
2636
7.61M
    int tlevel = x->pred_mv_sad[ref] >> (bwl + bhl + 4);
2637
2638
7.61M
    if (tlevel < 5) step_param += 2;
2639
2640
    // prev_mv_sad is not setup for dynamically scaled frames.
2641
7.61M
    if (cpi->oxcf.resize_mode != RESIZE_DYNAMIC) {
2642
7.61M
      int i;
2643
28.5M
      for (i = LAST_FRAME; i <= ALTREF_FRAME && cm->show_frame; ++i) {
2644
21.6M
        if ((x->pred_mv_sad[ref] >> 3) > x->pred_mv_sad[i]) {
2645
716k
          x->pred_mv[ref].row = INT16_MAX;
2646
716k
          x->pred_mv[ref].col = INT16_MAX;
2647
716k
          tmp_mv->as_int = INVALID_MV;
2648
2649
716k
          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
716k
          return;
2655
716k
        }
2656
21.6M
      }
2657
7.61M
    }
2658
7.61M
  }
2659
2660
  // Note: MV limits are modified here. Always restore the original values
2661
  // after full-pixel motion search.
2662
6.90M
  vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
2663
2664
6.90M
  mvp_full = pred_mv[best_predmv_idx];
2665
6.90M
  mvp_full.col >>= 3;
2666
6.90M
  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
6.90M
  bestsme = vp9_full_pixel_search(
2674
6.90M
      cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method, sadpb,
2675
6.90M
      cond_cost_list(cpi, cost_list), &ref_mv, &tmp_mv->as_mv, INT_MAX, 1);
2676
6.90M
#endif  // CONFIG_NON_GREEDY_MV
2677
2678
6.90M
  if (cpi->sf.enhanced_full_pixel_motion_search) {
2679
2.19M
    int i;
2680
8.76M
    for (i = 0; i < 3; ++i) {
2681
6.57M
      int this_me;
2682
6.57M
      MV this_mv;
2683
6.57M
      int diff_row;
2684
6.57M
      int diff_col;
2685
6.57M
      int step;
2686
2687
6.57M
      if (pred_mv[i].row == INT16_MAX || pred_mv[i].col == INT16_MAX) continue;
2688
6.45M
      if (i == best_predmv_idx) continue;
2689
2690
4.26M
      diff_row = ((int)pred_mv[i].row -
2691
4.26M
                  pred_mv[i > 0 ? (i - 1) : best_predmv_idx].row) >>
2692
4.26M
                 3;
2693
4.26M
      diff_col = ((int)pred_mv[i].col -
2694
4.26M
                  pred_mv[i > 0 ? (i - 1) : best_predmv_idx].col) >>
2695
4.26M
                 3;
2696
4.26M
      if (diff_row == 0 && diff_col == 0) continue;
2697
3.33M
      if (diff_row < 0) diff_row = -diff_row;
2698
3.33M
      if (diff_col < 0) diff_col = -diff_col;
2699
3.33M
      step = get_msb((diff_row + diff_col + 1) >> 1);
2700
3.33M
      if (step <= 0) continue;
2701
2702
3.16M
      mvp_full = pred_mv[i];
2703
3.16M
      mvp_full.col >>= 3;
2704
3.16M
      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
3.16M
      this_me = vp9_full_pixel_search(
2712
3.16M
          cpi, x, bsize, &mvp_full,
2713
3.16M
          VPXMAX(step_param, MAX_MVSEARCH_STEPS - step),
2714
3.16M
          cpi->sf.mv.search_method, sadpb, cond_cost_list(cpi, cost_list),
2715
3.16M
          &ref_mv, &this_mv, INT_MAX, 1);
2716
3.16M
#endif  // CONFIG_NON_GREEDY_MV
2717
3.16M
      if (this_me < bestsme) {
2718
508k
        tmp_mv->as_mv = this_mv;
2719
508k
        bestsme = this_me;
2720
508k
      }
2721
3.16M
    }
2722
2.19M
  }
2723
2724
6.90M
  x->mv_limits = tmp_mv_limits;
2725
2726
6.90M
  if (bestsme < INT_MAX) {
2727
6.90M
    uint32_t dis; /* TODO: use dis in distortion calculation later. */
2728
6.90M
    cpi->find_fractional_mv_step(
2729
6.90M
        x, &tmp_mv->as_mv, &ref_mv, cm->allow_high_precision_mv, x->errorperbit,
2730
6.90M
        &cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop,
2731
6.90M
        cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list),
2732
6.90M
        x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[ref], NULL, pw, ph,
2733
6.90M
        cpi->sf.use_accurate_subpel_search);
2734
6.90M
  }
2735
6.90M
  *rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv, x->nmvjointcost,
2736
6.90M
                             x->mvcost, MV_COST_WEIGHT);
2737
2738
6.90M
  x->pred_mv[ref] = tmp_mv->as_mv;
2739
2740
6.90M
  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
6.90M
}
2745
2746
static INLINE void restore_dst_buf(MACROBLOCKD *xd,
2747
                                   uint8_t *orig_dst[MAX_MB_PLANE],
2748
51.8M
                                   int orig_dst_stride[MAX_MB_PLANE]) {
2749
51.8M
  int i;
2750
207M
  for (i = 0; i < MAX_MB_PLANE; i++) {
2751
155M
    xd->plane[i].dst.buf = orig_dst[i];
2752
155M
    xd->plane[i].dst.stride = orig_dst_stride[i];
2753
155M
  }
2754
51.8M
}
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
27.4M
                               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
27.4M
  (void)mi_row;
2800
27.4M
  (void)mi_col;
2801
27.4M
  (void)bsize;
2802
27.4M
  return (!cpi->rc.is_src_frame_alt_ref && (this_mode == NEWMV) &&
2803
27.4M
          (this_mv.as_int != 0) &&
2804
27.4M
          ((mode_mv[NEARESTMV][ref_frame].as_int == 0) ||
2805
13.0M
           (mode_mv[NEARESTMV][ref_frame].as_int == INVALID_MV)) &&
2806
27.4M
          ((mode_mv[NEARMV][ref_frame].as_int == 0) ||
2807
5.34M
           (mode_mv[NEARMV][ref_frame].as_int == INVALID_MV)));
2808
27.4M
#endif
2809
27.4M
}
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
21.8M
    int64_t filter_cache[], int best_mode_index) {
2820
21.8M
  VP9_COMMON *cm = &cpi->common;
2821
21.8M
  MACROBLOCKD *xd = &x->e_mbd;
2822
21.8M
  MODE_INFO *mi = xd->mi[0];
2823
21.8M
  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2824
21.8M
  const int is_comp_pred = has_second_ref(mi);
2825
21.8M
  const int this_mode = mi->mode;
2826
21.8M
  int_mv *frame_mv = mode_mv[this_mode];
2827
21.8M
  int i;
2828
21.8M
  int refs[2] = { mi->ref_frame[0],
2829
21.8M
                  (mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1]) };
2830
21.8M
  int_mv cur_mv[2];
2831
21.8M
#if CONFIG_VP9_HIGHBITDEPTH
2832
21.8M
  DECLARE_ALIGNED(16, uint16_t, tmp_buf16[MAX_MB_PLANE * 64 * 64]);
2833
21.8M
  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
21.8M
  int intpel_mv;
2838
21.8M
  int64_t rd, tmp_rd = INT64_MAX, best_rd = INT64_MAX;
2839
21.8M
  int best_needs_copy = 0;
2840
21.8M
  uint8_t *orig_dst[MAX_MB_PLANE];
2841
21.8M
  int orig_dst_stride[MAX_MB_PLANE];
2842
21.8M
  int rs = 0;
2843
21.8M
  INTERP_FILTER best_filter = SWITCHABLE;
2844
21.8M
  uint8_t skip_txfm[MAX_MB_PLANE << 2] = { 0 };
2845
21.8M
  int64_t bsse[MAX_MB_PLANE << 2] = { 0 };
2846
2847
21.8M
  const int bsl = mi_width_log2_lookup[bsize];
2848
21.8M
  const int blk_parity = (((mi_row + mi_col) >> bsl) +
2849
21.8M
                          get_chessboard_index(cm->current_video_frame)) &
2850
21.8M
                         0x1;
2851
21.8M
  const int pred_filter_search =
2852
21.8M
      (cpi->sf.cb_pred_filter_search >= 2) && blk_parity;
2853
2854
21.8M
  int skip_txfm_sb = 0;
2855
21.8M
  int64_t skip_sse_sb = INT64_MAX;
2856
21.8M
  int64_t distortion_y = 0, distortion_uv = 0;
2857
2858
21.8M
#if CONFIG_VP9_HIGHBITDEPTH
2859
21.8M
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2860
0
    tmp_buf = CONVERT_TO_BYTEPTR(tmp_buf16);
2861
21.8M
  } else {
2862
21.8M
    tmp_buf = (uint8_t *)tmp_buf16;
2863
21.8M
  }
2864
21.8M
#endif  // CONFIG_VP9_HIGHBITDEPTH
2865
2866
21.8M
  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
21.8M
  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
21.8M
  if (this_mode == NEWMV) {
2889
7.61M
    int rate_mv;
2890
7.61M
    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
7.61M
    } else {
2918
7.61M
      int_mv tmp_mv;
2919
#if CONFIG_COLLECT_COMPONENT_TIMING
2920
      start_timing(cpi, single_motion_search_time);
2921
#endif
2922
7.61M
      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
7.61M
      if (tmp_mv.as_int == INVALID_MV) return INT64_MAX;
2927
2928
6.90M
      frame_mv[refs[0]].as_int = xd->mi[0]->bmi[0].as_mv[0].as_int =
2929
6.90M
          tmp_mv.as_int;
2930
6.90M
      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
6.90M
      if (discount_newmv_test(cpi, this_mode, tmp_mv, mode_mv, refs[0], mi_row,
2937
6.90M
                              mi_col, bsize)) {
2938
2.51M
        *rate2 += VPXMAX((rate_mv / NEW_MV_DISCOUNT_FACTOR), 1);
2939
4.38M
      } else {
2940
4.38M
        *rate2 += rate_mv;
2941
4.38M
      }
2942
6.90M
    }
2943
7.61M
  }
2944
2945
41.6M
  for (i = 0; i < is_comp_pred + 1; ++i) {
2946
21.1M
    cur_mv[i] = frame_mv[refs[i]];
2947
    // Clip "next_nearest" so that it does not extend to far out of image
2948
21.1M
    if (this_mode != NEWMV) clamp_mv2(&cur_mv[i].as_mv, xd);
2949
2950
21.1M
    if (mv_check_bounds(&x->mv_limits, &cur_mv[i].as_mv)) return INT64_MAX;
2951
20.5M
    mi->mv[i].as_int = cur_mv[i].as_int;
2952
20.5M
  }
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
82.3M
  for (i = 0; i < MAX_MB_PLANE; i++) {
2960
61.7M
    orig_dst[i] = xd->plane[i].dst.buf;
2961
61.7M
    orig_dst_stride[i] = xd->plane[i].dst.stride;
2962
61.7M
  }
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
20.5M
  if (discount_newmv_test(cpi, this_mode, frame_mv[refs[0]], mode_mv, refs[0],
2971
20.5M
                          mi_row, mi_col, bsize)) {
2972
2.51M
    *rate2 +=
2973
2.51M
        VPXMIN(cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]),
2974
2.51M
               cost_mv_ref(cpi, NEARESTMV, mbmi_ext->mode_context[refs[0]]));
2975
18.0M
  } else {
2976
18.0M
    *rate2 += cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]);
2977
18.0M
  }
2978
2979
20.5M
  if (!is_comp_pred && cpi->sf.prune_single_mode_based_on_mv_diff_mode_rate) {
2980
6.21M
    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.21M
    if (skip_single_mode_based_on_mode_rate(mode_mv, single_mode_rate,
2984
6.21M
                                            this_mode, refs[0], *rate2,
2985
6.21M
                                            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
230k
      assert(single_mode_rate[INTER_OFFSET(NEARESTMV)] != INT_MAX ||
2990
230k
             single_mode_rate[INTER_OFFSET(NEWMV)] != INT_MAX);
2991
230k
      return INT64_MAX;
2992
230k
    }
2993
6.21M
  }
2994
20.3M
  if (RDCOST(x->rdmult, x->rddiv, *rate2, 0) > ref_best_rd &&
2995
20.3M
      mi->mode != NEARESTMV)
2996
156k
    return INT64_MAX;
2997
2998
  // Are all MVs integer pel for Y and UV
2999
20.2M
  intpel_mv = !mv_has_subpel(&mi->mv[0].as_mv);
3000
20.2M
  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
101M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
3008
3009
20.2M
  if (cm->interp_filter != BILINEAR) {
3010
    // Use cb pattern for filter eval when filter is not switchable
3011
20.2M
    const int enable_interp_search =
3012
20.2M
        (cpi->sf.cb_pred_filter_search && cm->interp_filter != SWITCHABLE)
3013
20.2M
            ? blk_parity
3014
20.2M
            : 1;
3015
20.2M
    if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
3016
0
      best_filter = EIGHTTAP;
3017
20.2M
    } else if (best_filter == SWITCHABLE && enable_interp_search) {
3018
19.1M
      int newbest;
3019
19.1M
      int tmp_rate_sum = 0;
3020
19.1M
      int64_t tmp_dist_sum = 0;
3021
3022
54.6M
      for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
3023
42.8M
        int j;
3024
42.8M
        int64_t rs_rd;
3025
42.8M
        int tmp_skip_sb = 0;
3026
42.8M
        int64_t tmp_skip_sse = INT64_MAX;
3027
42.8M
        const int enable_earlyterm =
3028
42.8M
            cpi->sf.early_term_interp_search_plane_rd && cm->interp_filter != i;
3029
42.8M
        int64_t filt_best_rd;
3030
3031
42.8M
        mi->interp_filter = i;
3032
42.8M
        rs = vp9_get_switchable_rate(cpi, xd);
3033
42.8M
        rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
3034
3035
42.8M
        if (i > 0 && intpel_mv) {
3036
11.6M
          rd = RDCOST(x->rdmult, x->rddiv, tmp_rate_sum, tmp_dist_sum);
3037
11.6M
          filter_cache[i] = rd;
3038
11.6M
          filter_cache[SWITCHABLE_FILTERS] =
3039
11.6M
              VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
3040
11.6M
          if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
3041
11.6M
          *mask_filter = VPXMAX(*mask_filter, rd);
3042
31.1M
        } else {
3043
31.1M
          int rate_sum = 0;
3044
31.1M
          int64_t dist_sum = 0;
3045
31.1M
          if (i > 0 && cpi->sf.adaptive_interp_filter_search &&
3046
31.1M
              (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
31.1M
          if ((cm->interp_filter == SWITCHABLE && (!i || best_needs_copy)) ||
3053
31.1M
              (cm->interp_filter != SWITCHABLE &&
3054
20.5M
               (cm->interp_filter == mi->interp_filter ||
3055
19.8M
                (i == 0 && intpel_mv)))) {
3056
19.8M
            restore_dst_buf(xd, orig_dst, orig_dst_stride);
3057
19.8M
          } else {
3058
45.4M
            for (j = 0; j < MAX_MB_PLANE; j++) {
3059
34.0M
              xd->plane[j].dst.buf = tmp_buf + j * 64 * 64;
3060
34.0M
              xd->plane[j].dst.stride = 64;
3061
34.0M
            }
3062
11.3M
          }
3063
3064
31.1M
          filt_best_rd =
3065
31.1M
              cm->interp_filter == SWITCHABLE ? (best_rd - rs_rd) : best_rd;
3066
31.1M
          if (build_inter_pred_model_rd_earlyterm(
3067
31.1M
                  cpi, mi_row, mi_col, bsize, x, xd, &rate_sum, &dist_sum,
3068
31.1M
                  &tmp_skip_sb, &tmp_skip_sse, enable_earlyterm,
3069
31.1M
                  filt_best_rd)) {
3070
2.12M
            filter_cache[i] = INT64_MAX;
3071
2.12M
            continue;
3072
2.12M
          }
3073
3074
29.0M
          rd = RDCOST(x->rdmult, x->rddiv, rate_sum, dist_sum);
3075
29.0M
          filter_cache[i] = rd;
3076
29.0M
          filter_cache[SWITCHABLE_FILTERS] =
3077
29.0M
              VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
3078
29.0M
          if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
3079
29.0M
          *mask_filter = VPXMAX(*mask_filter, rd);
3080
3081
29.0M
          if (i == 0 && intpel_mv) {
3082
10.1M
            tmp_rate_sum = rate_sum;
3083
10.1M
            tmp_dist_sum = dist_sum;
3084
10.1M
          }
3085
29.0M
        }
3086
3087
40.6M
        if (i == 0 && cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
3088
18.9M
          if (rd / 2 > ref_best_rd) {
3089
7.36M
            restore_dst_buf(xd, orig_dst, orig_dst_stride);
3090
7.36M
            return INT64_MAX;
3091
7.36M
          }
3092
18.9M
        }
3093
33.3M
        newbest = i == 0 || rd < best_rd;
3094
3095
33.3M
        if (newbest) {
3096
16.4M
          best_rd = rd;
3097
16.4M
          best_filter = mi->interp_filter;
3098
16.4M
          if (cm->interp_filter == SWITCHABLE && i && !intpel_mv)
3099
1.75M
            best_needs_copy = !best_needs_copy;
3100
16.4M
        }
3101
3102
33.3M
        if ((cm->interp_filter == SWITCHABLE && newbest) ||
3103
33.3M
            (cm->interp_filter != SWITCHABLE &&
3104
25.9M
             cm->interp_filter == mi->interp_filter)) {
3105
13.8M
          tmp_rd = best_rd;
3106
3107
13.8M
          skip_txfm_sb = tmp_skip_sb;
3108
13.8M
          skip_sse_sb = tmp_skip_sse;
3109
13.8M
          memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
3110
13.8M
          memcpy(bsse, x->bsse, sizeof(bsse));
3111
13.8M
        }
3112
33.3M
      }
3113
11.8M
      restore_dst_buf(xd, orig_dst, orig_dst_stride);
3114
11.8M
    }
3115
20.2M
  }
3116
#if CONFIG_COLLECT_COMPONENT_TIMING
3117
  end_timing(cpi, interp_filter_time);
3118
#endif
3119
  // Set the appropriate filter
3120
12.8M
  mi->interp_filter =
3121
12.8M
      cm->interp_filter != SWITCHABLE ? cm->interp_filter : best_filter;
3122
12.8M
  rs = cm->interp_filter == SWITCHABLE ? vp9_get_switchable_rate(cpi, xd) : 0;
3123
3124
12.8M
  if (tmp_rd != INT64_MAX) {
3125
11.8M
    if (best_needs_copy) {
3126
      // again temporarily set the buffers to local memory to prevent a memcpy
3127
6.87M
      for (i = 0; i < MAX_MB_PLANE; i++) {
3128
5.15M
        xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
3129
5.15M
        xd->plane[i].dst.stride = 64;
3130
5.15M
      }
3131
1.71M
    }
3132
11.8M
    rd = tmp_rd + RDCOST(x->rdmult, x->rddiv, rs, 0);
3133
11.8M
  } else {
3134
1.02M
    int tmp_rate;
3135
1.02M
    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.02M
    build_inter_pred_model_rd_earlyterm(
3140
1.02M
        cpi, mi_row, mi_col, bsize, x, xd, &tmp_rate, &tmp_dist, &skip_txfm_sb,
3141
1.02M
        &skip_sse_sb, 0 /*do_earlyterm*/, INT64_MAX);
3142
1.02M
    rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
3143
1.02M
    memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
3144
1.02M
    memcpy(bsse, x->bsse, sizeof(bsse));
3145
1.02M
  }
3146
3147
12.8M
  if (!is_comp_pred) single_filter[this_mode][refs[0]] = mi->interp_filter;
3148
3149
12.8M
  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
12.8M
  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
12.5M
    if (rd / 2 > ref_best_rd) {
3159
496k
      restore_dst_buf(xd, orig_dst, orig_dst_stride);
3160
496k
      return INT64_MAX;
3161
496k
    }
3162
12.5M
  }
3163
3164
12.3M
  if (cm->interp_filter == SWITCHABLE) *rate2 += rs;
3165
3166
12.3M
  memcpy(x->skip_txfm, skip_txfm, sizeof(skip_txfm));
3167
12.3M
  memcpy(x->bsse, bsse, sizeof(bsse));
3168
3169
12.3M
  if (!skip_txfm_sb || xd->lossless) {
3170
12.3M
    int skippable_y, skippable_uv;
3171
12.3M
    int64_t sseuv = INT64_MAX;
3172
12.3M
    int64_t rdcosty = INT64_MAX;
3173
3174
    // Y cost and distortion
3175
12.3M
    vp9_subtract_plane(x, bsize, 0);
3176
12.3M
    super_block_yrd(cpi, x, rate_y, &distortion_y, &skippable_y, psse, bsize,
3177
12.3M
                    ref_best_rd, recon);
3178
3179
12.3M
    if (*rate_y == INT_MAX) {
3180
2.07M
      *rate2 = INT_MAX;
3181
2.07M
      *distortion = INT64_MAX;
3182
2.07M
      restore_dst_buf(xd, orig_dst, orig_dst_stride);
3183
2.07M
      return INT64_MAX;
3184
2.07M
    }
3185
3186
10.2M
    *rate2 += *rate_y;
3187
10.2M
    *distortion += distortion_y;
3188
3189
10.2M
    rdcosty = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
3190
10.2M
    rdcosty = VPXMIN(rdcosty, RDCOST(x->rdmult, x->rddiv, 0, *psse));
3191
3192
10.2M
    if (!super_block_uvrd(cpi, x, rate_uv, &distortion_uv, &skippable_uv,
3193
10.2M
                          &sseuv, bsize, ref_best_rd - rdcosty)) {
3194
2.90M
      *rate2 = INT_MAX;
3195
2.90M
      *distortion = INT64_MAX;
3196
2.90M
      restore_dst_buf(xd, orig_dst, orig_dst_stride);
3197
2.90M
      return INT64_MAX;
3198
2.90M
    }
3199
3200
7.31M
    *psse += sseuv;
3201
7.31M
    *rate2 += *rate_uv;
3202
7.31M
    *distortion += distortion_uv;
3203
7.31M
    *skippable = skippable_y && skippable_uv;
3204
7.31M
  } else {
3205
35.3k
    x->skip = 1;
3206
35.3k
    *disable_skip = 1;
3207
3208
    // The cost of skip bit needs to be added.
3209
35.3k
    *rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
3210
3211
35.3k
    *distortion = skip_sse_sb;
3212
35.3k
  }
3213
3214
7.35M
  if (!is_comp_pred) single_skippable[this_mode][refs[0]] = *skippable;
3215
3216
7.35M
  restore_dst_buf(xd, orig_dst, orig_dst_stride);
3217
7.35M
  return 0;  // The rate-distortion cost will be re-calculated by caller.
3218
12.3M
}
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.94M
                               int64_t best_rd) {
3224
3.94M
  VP9_COMMON *const cm = &cpi->common;
3225
3.94M
  MACROBLOCKD *const xd = &x->e_mbd;
3226
3.94M
  struct macroblockd_plane *const pd = xd->plane;
3227
3.94M
  int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0;
3228
3.94M
  int y_skip = 0, uv_skip = 0;
3229
3.94M
  int64_t dist_y = 0, dist_uv = 0;
3230
3.94M
  TX_SIZE max_uv_tx_size;
3231
3.94M
  x->skip_encode = 0;
3232
3.94M
  ctx->skip = 0;
3233
3.94M
  xd->mi[0]->ref_frame[0] = INTRA_FRAME;
3234
3.94M
  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.94M
  xd->mi[0]->interp_filter = SWITCHABLE_FILTERS;
3238
3239
3.94M
  if (bsize >= BLOCK_8X8) {
3240
2.16M
    if (rd_pick_intra_sby_mode(cpi, x, &rate_y, &rate_y_tokenonly, &dist_y,
3241
2.16M
                               &y_skip, bsize, best_rd) >= best_rd) {
3242
401k
      rd_cost->rate = INT_MAX;
3243
401k
      return;
3244
401k
    }
3245
2.16M
  } else {
3246
1.78M
    y_skip = 0;
3247
1.78M
    if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate_y, &rate_y_tokenonly,
3248
1.78M
                                     &dist_y, best_rd) >= best_rd) {
3249
526k
      rd_cost->rate = INT_MAX;
3250
526k
      return;
3251
526k
    }
3252
1.78M
  }
3253
3.01M
  max_uv_tx_size = uv_txsize_lookup[bsize][xd->mi[0]->tx_size]
3254
3.01M
                                   [pd[1].subsampling_x][pd[1].subsampling_y];
3255
3.01M
  rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly, &dist_uv,
3256
3.01M
                          &uv_skip, VPXMAX(BLOCK_8X8, bsize), max_uv_tx_size);
3257
3258
3.01M
  if (y_skip && uv_skip) {
3259
428k
    rd_cost->rate = rate_y + rate_uv - rate_y_tokenonly - rate_uv_tokenonly +
3260
428k
                    vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
3261
428k
    rd_cost->dist = dist_y + dist_uv;
3262
2.59M
  } else {
3263
2.59M
    rd_cost->rate =
3264
2.59M
        rate_y + rate_uv + vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
3265
2.59M
    rd_cost->dist = dist_y + dist_uv;
3266
2.59M
  }
3267
3268
3.01M
  ctx->mic = *xd->mi[0];
3269
3.01M
  ctx->mbmi_ext = *x->mbmi_ext;
3270
3.01M
  rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
3271
3.01M
}
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.84M
int vp9_internal_image_edge(VP9_COMP *cpi) {
3367
2.84M
  return (cpi->oxcf.pass == 2) &&
3368
2.84M
         ((cpi->twopass.this_frame_stats.inactive_zone_rows > 0) ||
3369
0
          (cpi->twopass.this_frame_stats.inactive_zone_cols > 0));
3370
2.84M
}
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
4.32M
int vp9_active_h_edge(VP9_COMP *cpi, int mi_row, int mi_step) {
3376
4.32M
  int top_edge = 0;
3377
4.32M
  int bottom_edge = cpi->common.mi_rows;
3378
4.32M
  int is_active_h_edge = 0;
3379
3380
  // For two pass account for any formatting bars detected.
3381
4.32M
  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
4.32M
  if (((top_edge >= mi_row) && (top_edge < (mi_row + mi_step))) ||
3394
4.32M
      ((bottom_edge >= mi_row) && (bottom_edge < (mi_row + mi_step)))) {
3395
2.86M
    is_active_h_edge = 1;
3396
2.86M
  }
3397
4.32M
  return is_active_h_edge;
3398
4.32M
}
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.60M
int vp9_active_v_edge(VP9_COMP *cpi, int mi_col, int mi_step) {
3404
1.60M
  int left_edge = 0;
3405
1.60M
  int right_edge = cpi->common.mi_cols;
3406
1.60M
  int is_active_v_edge = 0;
3407
3408
  // For two pass account for any formatting bars detected.
3409
1.60M
  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.60M
  if (((left_edge >= mi_col) && (left_edge < (mi_col + mi_step))) ||
3422
1.60M
      ((right_edge >= mi_col) && (right_edge < (mi_col + mi_step)))) {
3423
301k
    is_active_v_edge = 1;
3424
301k
  }
3425
1.60M
  return is_active_v_edge;
3426
1.60M
}
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
3.02M
int vp9_active_edge_sb(VP9_COMP *cpi, int mi_row, int mi_col) {
3432
3.02M
  return vp9_active_h_edge(cpi, mi_row, MI_BLOCK_SIZE) ||
3433
3.02M
         vp9_active_v_edge(cpi, mi_col, MI_BLOCK_SIZE);
3434
3.02M
}
3435
3436
#if !CONFIG_REALTIME_ONLY
3437
3.61M
static void init_frame_mv(int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES]) {
3438
54.2M
  for (int mode = 0; mode < MB_MODE_COUNT; ++mode) {
3439
253M
    for (int ref_frame = 0; ref_frame < MAX_REF_FRAMES; ++ref_frame) {
3440
202M
      frame_mv[mode][ref_frame].as_int = INVALID_MV;
3441
202M
    }
3442
50.6M
  }
3443
3.61M
}
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.61M
                               PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far) {
3449
3.61M
  VP9_COMMON *const cm = &cpi->common;
3450
3.61M
  TileInfo *const tile_info = &tile_data->tile_info;
3451
3.61M
  RD_OPT *const rd_opt = &cpi->rd;
3452
3.61M
  SPEED_FEATURES *const sf = &cpi->sf;
3453
3.61M
  MACROBLOCKD *const xd = &x->e_mbd;
3454
3.61M
  MODE_INFO *const mi = xd->mi[0];
3455
3.61M
  MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
3456
3.61M
  const struct segmentation *const seg = &cm->seg;
3457
3.61M
  PREDICTION_MODE this_mode;
3458
3.61M
  MV_REFERENCE_FRAME ref_frame, second_ref_frame;
3459
3.61M
  unsigned char segment_id = mi->segment_id;
3460
3.61M
  int comp_pred, i, k;
3461
3.61M
  int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
3462
3.61M
  struct buf_2d yv12_mb[4][MAX_MB_PLANE] = { 0 };
3463
3.61M
  int_mv single_newmv[MAX_REF_FRAMES] = { { 0 } };
3464
3.61M
  INTERP_FILTER single_inter_filter[MB_MODE_COUNT][MAX_REF_FRAMES];
3465
3.61M
  int single_skippable[MB_MODE_COUNT][MAX_REF_FRAMES];
3466
3.61M
  int single_mode_rate[MAX_REF_FRAMES][INTER_MODES];
3467
3.61M
  int64_t best_rd = best_rd_so_far;
3468
3.61M
  int64_t best_pred_diff[REFERENCE_MODES];
3469
3.61M
  int64_t best_pred_rd[REFERENCE_MODES];
3470
3.61M
  int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
3471
3.61M
  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3472
3.61M
  MODE_INFO best_mbmode;
3473
3.61M
  int best_mode_skippable = 0;
3474
3.61M
  int midx, best_mode_index = -1;
3475
3.61M
  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3476
3.61M
  vpx_prob comp_mode_p;
3477
3.61M
  int64_t best_intra_rd = INT64_MAX;
3478
3.61M
  unsigned int best_pred_sse = UINT_MAX;
3479
3.61M
  PREDICTION_MODE best_intra_mode = DC_PRED;
3480
3.61M
  int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
3481
3.61M
  int64_t dist_uv[TX_SIZES];
3482
3.61M
  int skip_uv[TX_SIZES];
3483
3.61M
  PREDICTION_MODE mode_uv[TX_SIZES];
3484
3.61M
  const int intra_cost_penalty =
3485
3.61M
      vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
3486
3.61M
  int best_skip2 = 0;
3487
3.61M
  uint8_t ref_frame_skip_mask[2] = { 0, 1 };
3488
3.61M
  uint16_t mode_skip_mask[MAX_REF_FRAMES] = { 0 };
3489
3.61M
  int mode_skip_start = sf->mode_skip_start + 1;
3490
3.61M
  const int *const rd_threshes = rd_opt->threshes[segment_id][bsize];
3491
3.61M
  const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
3492
3.61M
  int64_t mode_threshold[MAX_MODES];
3493
3.61M
  int8_t *tile_mode_map = tile_data->mode_map[bsize];
3494
3.61M
  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.61M
  const int mode_search_skip_flags = sf->mode_search_skip_flags;
3498
3.61M
  const int is_rect_partition =
3499
3.61M
      num_4x4_blocks_wide_lookup[bsize] != num_4x4_blocks_high_lookup[bsize];
3500
3.61M
  int64_t mask_filter = 0;
3501
3.61M
  int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
3502
3503
3.61M
  struct buf_2d *recon;
3504
3.61M
  struct buf_2d recon_buf;
3505
3.61M
#if CONFIG_VP9_HIGHBITDEPTH
3506
3.61M
  DECLARE_ALIGNED(16, uint16_t, recon16[64 * 64]);
3507
3.61M
  recon_buf.buf = xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH
3508
3.61M
                      ? CONVERT_TO_BYTEPTR(recon16)
3509
3.61M
                      : (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.61M
  recon_buf.stride = 64;
3515
3.61M
  recon = cpi->oxcf.content == VP9E_CONTENT_FILM ? &recon_buf : 0;
3516
3517
3.61M
  vp9_zero(best_mbmode);
3518
3519
3.61M
  x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
3520
3521
18.0M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
3522
3523
3.61M
  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3524
3.61M
                           &comp_mode_p);
3525
3526
14.4M
  for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
3527
18.0M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3528
14.4M
    best_filter_rd[i] = INT64_MAX;
3529
18.0M
  for (i = 0; i < TX_SIZES; i++) rate_uv_intra[i] = INT_MAX;
3530
18.0M
  for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
3531
54.2M
  for (i = 0; i < MB_MODE_COUNT; ++i) {
3532
253M
    for (k = 0; k < MAX_REF_FRAMES; ++k) {
3533
202M
      single_inter_filter[i][k] = SWITCHABLE;
3534
202M
      single_skippable[i][k] = 0;
3535
202M
    }
3536
50.6M
  }
3537
3538
3.61M
  rd_cost->rate = INT_MAX;
3539
3540
3.61M
  init_frame_mv(frame_mv);
3541
3542
14.4M
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3543
10.8M
    x->pred_mv_sad[ref_frame] = INT_MAX;
3544
10.8M
    if ((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) &&
3545
10.8M
        !(is_rect_partition && (ctx->skip_ref_frame_mask & (1 << ref_frame)))) {
3546
7.70M
      assert(get_ref_frame_buffer(cpi, ref_frame) != NULL);
3547
7.70M
      setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
3548
7.70M
                         frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
3549
7.70M
    }
3550
10.8M
    frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
3551
10.8M
    frame_mv[ZEROMV][ref_frame].as_int = 0;
3552
10.8M
  }
3553
3554
14.4M
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3555
10.8M
    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.70M
      ref_frame_skip_mask[0] |= (1 << ref_frame);
3560
2.70M
      ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3561
8.13M
    } else if (sf->reference_masking) {
3562
10.0M
      for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
3563
        // Skip fixed mv modes for poor references
3564
7.71M
        if ((x->pred_mv_sad[ref_frame] >> 2) > x->pred_mv_sad[i]) {
3565
566k
          mode_skip_mask[ref_frame] |= INTER_NEAREST_NEAR_ZERO;
3566
566k
          break;
3567
566k
        }
3568
7.71M
      }
3569
2.87M
    }
3570
    // If the segment reference frame feature is enabled....
3571
    // then do nothing if the current ref frame is not allowed..
3572
10.8M
    if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
3573
10.8M
        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
10.8M
  }
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.61M
  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.61M
    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.61M
  }
3597
3598
3.61M
  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.61M
  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.61M
  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
      if (x->pred_mv_sad[GOLDEN_FRAME] > (x->pred_mv_sad[LAST_FRAME] << 1))
3615
0
        mode_skip_mask[GOLDEN_FRAME] |= INTER_ALL;
3616
0
  }
3617
3618
3.61M
  if (bsize > sf->max_intra_bsize && cpi->ref_frame_flags != 0) {
3619
0
    ref_frame_skip_mask[0] |= (1 << INTRA_FRAME);
3620
0
    ref_frame_skip_mask[1] |= (1 << INTRA_FRAME);
3621
0
  }
3622
3623
3.61M
  mode_skip_mask[INTRA_FRAME] |=
3624
3.61M
      (uint16_t)~(sf->intra_y_mode_mask[max_txsize_lookup[bsize]]);
3625
3626
28.9M
  for (i = 0; i <= LAST_NEW_MV_INDEX; ++i) mode_threshold[i] = 0;
3627
3628
86.7M
  for (i = LAST_NEW_MV_INDEX + 1; i < MAX_MODES; ++i)
3629
83.1M
    mode_threshold[i] = ((int64_t)rd_threshes[i] * rd_thresh_freq_fact[i]) >> 5;
3630
3631
3.61M
  midx = sf->schedule_mode_search ? mode_skip_start : 0;
3632
3633
3.61M
  while (midx > 4) {
3634
0
    uint8_t end_pos = 0;
3635
0
    for (i = 5; i < midx; ++i) {
3636
0
      if (mode_threshold[tile_mode_map[i - 1]] >
3637
0
          mode_threshold[tile_mode_map[i]]) {
3638
0
        uint8_t tmp = tile_mode_map[i];
3639
0
        tile_mode_map[i] = tile_mode_map[i - 1];
3640
0
        tile_mode_map[i - 1] = tmp;
3641
0
        end_pos = i;
3642
0
      }
3643
0
    }
3644
0
    midx = end_pos;
3645
0
  }
3646
3647
3.61M
  memcpy(mode_map, tile_mode_map, sizeof(mode_map));
3648
3649
111M
  for (midx = 0; midx < MAX_MODES; ++midx) {
3650
107M
    int mode_index = mode_map[midx];
3651
107M
    int mode_excluded = 0;
3652
107M
    int64_t this_rd = INT64_MAX;
3653
107M
    int disable_skip = 0;
3654
107M
    int compmode_cost = 0;
3655
107M
    int rate2 = 0, rate_y = 0, rate_uv = 0;
3656
107M
    int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
3657
107M
    int skippable = 0;
3658
107M
    int this_skip2 = 0;
3659
107M
    int64_t total_sse = INT64_MAX;
3660
107M
    int early_term = 0;
3661
3662
107M
    this_mode = vp9_mode_order[mode_index].mode;
3663
107M
    ref_frame = vp9_mode_order[mode_index].ref_frame[0];
3664
107M
    second_ref_frame = vp9_mode_order[mode_index].ref_frame[1];
3665
3666
107M
    vp9_zero(x->sum_y_eobs);
3667
107M
    comp_pred = second_ref_frame > INTRA_FRAME;
3668
107M
    if (!comp_pred && ref_frame != INTRA_FRAME &&
3669
107M
        sf->prune_single_mode_based_on_mv_diff_mode_rate)
3670
14.7M
      single_mode_rate[ref_frame][INTER_OFFSET(this_mode)] = INT_MAX;
3671
3672
107M
    if (is_rect_partition) {
3673
40.0M
      if (ctx->skip_ref_frame_mask & (1 << ref_frame)) continue;
3674
35.1M
      if (second_ref_frame > 0 &&
3675
35.1M
          (ctx->skip_ref_frame_mask & (1 << second_ref_frame)))
3676
770k
        continue;
3677
35.1M
    }
3678
3679
    // Look at the reference frame of the best mode so far and set the
3680
    // skip mask to look at a subset of the remaining modes.
3681
101M
    if (midx == mode_skip_start && best_mode_index >= 0) {
3682
896k
      switch (best_mbmode.ref_frame[0]) {
3683
507k
        case INTRA_FRAME: break;
3684
253k
        case LAST_FRAME: ref_frame_skip_mask[0] |= LAST_FRAME_MODE_MASK; break;
3685
111k
        case GOLDEN_FRAME:
3686
111k
          ref_frame_skip_mask[0] |= GOLDEN_FRAME_MODE_MASK;
3687
111k
          break;
3688
23.9k
        case ALTREF_FRAME: ref_frame_skip_mask[0] |= ALT_REF_MODE_MASK; break;
3689
0
        case NO_REF_FRAME:
3690
0
        case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
3691
896k
      }
3692
896k
    }
3693
3694
101M
    if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
3695
101M
        (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
3696
17.0M
      continue;
3697
3698
84.6M
    if (mode_skip_mask[ref_frame] & (1 << this_mode)) continue;
3699
3700
    // Test best rd so far against threshold for trying this mode.
3701
81.2M
    if (best_mode_skippable && sf->schedule_mode_search)
3702
0
      mode_threshold[mode_index] <<= 1;
3703
3704
81.2M
    if (best_rd < mode_threshold[mode_index]) continue;
3705
3706
    // This is only used in motion vector unit test.
3707
72.9M
    if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
3708
3709
72.9M
    if (sf->motion_field_mode_search) {
3710
0
      const int mi_width = VPXMIN(num_8x8_blocks_wide_lookup[bsize],
3711
0
                                  tile_info->mi_col_end - mi_col);
3712
0
      const int mi_height = VPXMIN(num_8x8_blocks_high_lookup[bsize],
3713
0
                                   tile_info->mi_row_end - mi_row);
3714
0
      const int bsl = mi_width_log2_lookup[bsize];
3715
0
      int cb_partition_search_ctrl =
3716
0
          (((mi_row + mi_col) >> bsl) +
3717
0
           get_chessboard_index(cm->current_video_frame)) &
3718
0
          0x1;
3719
0
      MODE_INFO *ref_mi;
3720
0
      int const_motion = 1;
3721
0
      int skip_ref_frame = !cb_partition_search_ctrl;
3722
0
      MV_REFERENCE_FRAME rf = NO_REF_FRAME;
3723
0
      int_mv ref_mv;
3724
0
      ref_mv.as_int = INVALID_MV;
3725
3726
0
      if ((mi_row - 1) >= tile_info->mi_row_start) {
3727
0
        ref_mv = xd->mi[-xd->mi_stride]->mv[0];
3728
0
        rf = xd->mi[-xd->mi_stride]->ref_frame[0];
3729
0
        for (i = 0; i < mi_width; ++i) {
3730
0
          ref_mi = xd->mi[-xd->mi_stride + i];
3731
0
          const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
3732
0
                          (ref_frame == ref_mi->ref_frame[0]);
3733
0
          skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
3734
0
        }
3735
0
      }
3736
3737
0
      if ((mi_col - 1) >= tile_info->mi_col_start) {
3738
0
        if (ref_mv.as_int == INVALID_MV) ref_mv = xd->mi[-1]->mv[0];
3739
0
        if (rf == NO_REF_FRAME) rf = xd->mi[-1]->ref_frame[0];
3740
0
        for (i = 0; i < mi_height; ++i) {
3741
0
          ref_mi = xd->mi[i * xd->mi_stride - 1];
3742
0
          const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
3743
0
                          (ref_frame == ref_mi->ref_frame[0]);
3744
0
          skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
3745
0
        }
3746
0
      }
3747
3748
0
      if (skip_ref_frame && this_mode != NEARESTMV && this_mode != NEWMV)
3749
0
        if (rf > INTRA_FRAME)
3750
0
          if (ref_frame != rf) continue;
3751
3752
0
      if (const_motion)
3753
0
        if (this_mode == NEARMV || this_mode == ZEROMV) continue;
3754
0
    }
3755
3756
72.9M
    if (comp_pred) {
3757
19.7M
      if (!cpi->allow_comp_inter_inter) continue;
3758
3759
0
      if (cm->ref_frame_sign_bias[ref_frame] ==
3760
0
          cm->ref_frame_sign_bias[second_ref_frame])
3761
0
        continue;
3762
3763
      // Skip compound inter modes if ARF is not available.
3764
0
      if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
3765
0
        continue;
3766
3767
      // Do not allow compound prediction if the segment level reference frame
3768
      // feature is in use as in this case there can only be one reference.
3769
0
      if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
3770
3771
0
      if ((mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
3772
0
          best_mode_index >= 0 && best_mbmode.ref_frame[0] == INTRA_FRAME)
3773
0
        continue;
3774
3775
0
      mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
3776
53.1M
    } else {
3777
53.1M
      if (ref_frame != INTRA_FRAME)
3778
27.7M
        mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
3779
53.1M
    }
3780
3781
53.1M
    if (ref_frame == INTRA_FRAME) {
3782
25.4M
      if (sf->adaptive_mode_search)
3783
0
        if ((x->source_variance << num_pels_log2_lookup[bsize]) > best_pred_sse)
3784
0
          continue;
3785
3786
25.4M
      if (this_mode != DC_PRED) {
3787
        // Disable intra modes other than DC_PRED for blocks with low variance
3788
        // Threshold for intra skipping based on source variance
3789
        // TODO(debargha): Specialize the threshold for super block sizes
3790
21.9M
        const unsigned int skip_intra_var_thresh =
3791
21.9M
            (cpi->oxcf.content == VP9E_CONTENT_FILM) ? 0 : 64;
3792
21.9M
        if ((mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
3793
21.9M
            x->source_variance < skip_intra_var_thresh)
3794
0
          continue;
3795
        // Only search the oblique modes if the best so far is
3796
        // one of the neighboring directional modes
3797
21.9M
        if ((mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
3798
21.9M
            (this_mode >= D45_PRED && this_mode <= TM_PRED)) {
3799
0
          if (best_mode_index >= 0 && best_mbmode.ref_frame[0] > INTRA_FRAME)
3800
0
            continue;
3801
0
        }
3802
21.9M
        if (mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
3803
0
          if (conditional_skipintra(this_mode, best_intra_mode)) continue;
3804
0
        }
3805
21.9M
      }
3806
27.7M
    } else {
3807
27.7M
      const MV_REFERENCE_FRAME ref_frames[2] = { ref_frame, second_ref_frame };
3808
27.7M
      if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv, this_mode,
3809
27.7M
                              ref_frames))
3810
5.88M
        continue;
3811
27.7M
    }
3812
3813
47.2M
    mi->mode = this_mode;
3814
47.2M
    mi->uv_mode = DC_PRED;
3815
47.2M
    mi->ref_frame[0] = ref_frame;
3816
47.2M
    mi->ref_frame[1] = second_ref_frame;
3817
    // Evaluate all sub-pel filters irrespective of whether we can use
3818
    // them for this frame.
3819
47.2M
    mi->interp_filter =
3820
47.2M
        cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
3821
47.2M
    mi->mv[0].as_int = mi->mv[1].as_int = 0;
3822
3823
47.2M
    x->skip = 0;
3824
47.2M
    set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
3825
3826
    // Select prediction reference frames.
3827
189M
    for (i = 0; i < MAX_MB_PLANE; i++) {
3828
141M
      xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
3829
141M
      if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
3830
141M
    }
3831
3832
47.2M
    if (ref_frame == INTRA_FRAME) {
3833
25.4M
      TX_SIZE uv_tx;
3834
25.4M
      struct macroblockd_plane *const pd = &xd->plane[1];
3835
#if CONFIG_COLLECT_COMPONENT_TIMING
3836
      start_timing(cpi, intra_mode_search_time);
3837
#endif
3838
25.4M
      memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
3839
25.4M
      super_block_yrd(cpi, x, &rate_y, &distortion_y, &skippable, NULL, bsize,
3840
25.4M
                      best_rd, recon);
3841
#if CONFIG_COLLECT_COMPONENT_TIMING
3842
      end_timing(cpi, intra_mode_search_time);
3843
#endif
3844
25.4M
      if (rate_y == INT_MAX) continue;
3845
3846
16.4M
      uv_tx = uv_txsize_lookup[bsize][mi->tx_size][pd->subsampling_x]
3847
16.4M
                              [pd->subsampling_y];
3848
#if CONFIG_COLLECT_COMPONENT_TIMING
3849
      start_timing(cpi, intra_mode_search_time);
3850
#endif
3851
16.4M
      if (rate_uv_intra[uv_tx] == INT_MAX) {
3852
2.75M
        choose_intra_uv_mode(cpi, x, ctx, bsize, uv_tx, &rate_uv_intra[uv_tx],
3853
2.75M
                             &rate_uv_tokenonly[uv_tx], &dist_uv[uv_tx],
3854
2.75M
                             &skip_uv[uv_tx], &mode_uv[uv_tx]);
3855
2.75M
      }
3856
#if CONFIG_COLLECT_COMPONENT_TIMING
3857
      end_timing(cpi, intra_mode_search_time);
3858
#endif
3859
16.4M
      rate_uv = rate_uv_tokenonly[uv_tx];
3860
16.4M
      distortion_uv = dist_uv[uv_tx];
3861
16.4M
      skippable = skippable && skip_uv[uv_tx];
3862
16.4M
      mi->uv_mode = mode_uv[uv_tx];
3863
3864
16.4M
      rate2 = rate_y + cpi->mbmode_cost[mi->mode] + rate_uv_intra[uv_tx];
3865
16.4M
      if (this_mode != DC_PRED && this_mode != TM_PRED)
3866
12.1M
        rate2 += intra_cost_penalty;
3867
16.4M
      distortion2 = distortion_y + distortion_uv;
3868
21.8M
    } else {
3869
#if CONFIG_COLLECT_COMPONENT_TIMING
3870
      start_timing(cpi, handle_inter_mode_time);
3871
#endif
3872
21.8M
      this_rd = handle_inter_mode(
3873
21.8M
          cpi, x, bsize, &rate2, &distortion2, &skippable, &rate_y, &rate_uv,
3874
21.8M
          recon, &disable_skip, frame_mv, mi_row, mi_col, single_newmv,
3875
21.8M
          single_inter_filter, single_skippable,
3876
21.8M
          &single_mode_rate[ref_frame][0], &total_sse, best_rd, &mask_filter,
3877
21.8M
          filter_cache, best_mode_index);
3878
#if CONFIG_COLLECT_COMPONENT_TIMING
3879
      end_timing(cpi, handle_inter_mode_time);
3880
#endif
3881
21.8M
      if (this_rd == INT64_MAX) continue;
3882
3883
7.35M
      compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
3884
3885
7.35M
      if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
3886
7.35M
    }
3887
3888
    // Estimate the reference frame signaling cost and add it
3889
    // to the rolling cost variable.
3890
23.8M
    if (comp_pred) {
3891
0
      rate2 += ref_costs_comp[ref_frame];
3892
23.8M
    } else {
3893
23.8M
      rate2 += ref_costs_single[ref_frame];
3894
23.8M
    }
3895
3896
23.8M
    if (!disable_skip) {
3897
23.8M
      const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
3898
23.8M
      const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
3899
23.8M
      const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
3900
3901
23.8M
      if (skippable) {
3902
        // Back out the coefficient coding costs
3903
1.15M
        rate2 -= (rate_y + rate_uv);
3904
3905
        // Cost the skip mb case
3906
1.15M
        rate2 += skip_cost1;
3907
22.6M
      } else if (ref_frame != INTRA_FRAME && !xd->lossless &&
3908
22.6M
                 !cpi->oxcf.sharpness) {
3909
6.83M
        if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
3910
6.83M
                   distortion2) <
3911
6.83M
            RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
3912
          // Add in the cost of the no skip flag.
3913
6.22M
          rate2 += skip_cost0;
3914
6.22M
        } else {
3915
          // FIXME(rbultje) make this work for splitmv also
3916
605k
          assert(total_sse >= 0);
3917
3918
605k
          rate2 += skip_cost1;
3919
605k
          distortion2 = total_sse;
3920
605k
          rate2 -= (rate_y + rate_uv);
3921
605k
          this_skip2 = 1;
3922
605k
        }
3923
15.8M
      } else {
3924
        // Add in the cost of the no skip flag.
3925
15.8M
        rate2 += skip_cost0;
3926
15.8M
      }
3927
3928
      // Calculate the final RD estimate for this mode.
3929
23.8M
      this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3930
23.8M
    }
3931
3932
23.8M
    if (recon) {
3933
      // In film mode bias against DC pred and other intra if there is a
3934
      // significant difference between the variance of the sub blocks in the
3935
      // the source. Also apply some bias against compound modes which also
3936
      // tend to blur fine texture such as film grain over time.
3937
      //
3938
      // The sub block test here acts in the case where one or more sub
3939
      // blocks have high relatively variance but others relatively low
3940
      // variance. Here the high variance sub blocks may push the
3941
      // total variance for the current block size over the thresholds
3942
      // used in rd_variance_adjustment() below.
3943
0
      if (cpi->oxcf.content == VP9E_CONTENT_FILM) {
3944
0
        if (bsize >= BLOCK_16X16) {
3945
0
          int min_energy, max_energy;
3946
0
          vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3947
0
                                   &max_energy);
3948
0
          if (max_energy > min_energy) {
3949
0
            if (ref_frame == INTRA_FRAME) {
3950
0
              if (this_mode == DC_PRED)
3951
0
                this_rd += (this_rd * (max_energy - min_energy));
3952
0
              else
3953
0
                this_rd += (this_rd * (max_energy - min_energy)) / 4;
3954
0
            } else if (second_ref_frame > INTRA_FRAME) {
3955
0
              this_rd += this_rd / 4;
3956
0
            }
3957
0
          }
3958
0
        }
3959
0
      }
3960
      // Apply an adjustment to the rd value based on the similarity of the
3961
      // source variance and reconstructed variance.
3962
0
      rd_variance_adjustment(cpi, x, bsize, &this_rd, recon, ref_frame,
3963
0
                             second_ref_frame, this_mode);
3964
0
    }
3965
3966
23.8M
    if (ref_frame == INTRA_FRAME) {
3967
      // Keep record of best intra rd
3968
16.4M
      if (this_rd < best_intra_rd) {
3969
3.97M
        best_intra_rd = this_rd;
3970
3.97M
        best_intra_mode = mi->mode;
3971
3.97M
      }
3972
16.4M
    }
3973
3974
23.8M
    if (!disable_skip && ref_frame == INTRA_FRAME) {
3975
65.9M
      for (i = 0; i < REFERENCE_MODES; ++i)
3976
49.4M
        best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
3977
82.4M
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3978
65.9M
        best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
3979
16.4M
    }
3980
3981
    // Did this mode help.. i.e. is it the new best mode
3982
23.8M
    if (this_rd < best_rd || x->skip) {
3983
6.30M
      int max_plane = MAX_MB_PLANE;
3984
6.30M
      if (!mode_excluded) {
3985
        // Note index of best mode so far
3986
6.30M
        best_mode_index = mode_index;
3987
3988
6.30M
        if (ref_frame == INTRA_FRAME) {
3989
          /* required for left and above block mv */
3990
2.90M
          mi->mv[0].as_int = 0;
3991
2.90M
          max_plane = 1;
3992
          // Initialize interp_filter here so we do not have to check for
3993
          // inter block modes in get_pred_context_switchable_interp()
3994
2.90M
          mi->interp_filter = SWITCHABLE_FILTERS;
3995
3.40M
        } else {
3996
3.40M
          best_pred_sse = x->pred_sse[ref_frame];
3997
3.40M
        }
3998
3999
6.30M
        rd_cost->rate = rate2;
4000
6.30M
        rd_cost->dist = distortion2;
4001
6.30M
        rd_cost->rdcost = this_rd;
4002
6.30M
        best_rd = this_rd;
4003
6.30M
        best_mbmode = *mi;
4004
6.30M
        best_skip2 = this_skip2;
4005
6.30M
        best_mode_skippable = skippable;
4006
4007
6.30M
        if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
4008
6.30M
        memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mi->tx_size],
4009
6.30M
               sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
4010
6.30M
        ctx->sum_y_eobs = x->sum_y_eobs[mi->tx_size];
4011
4012
        // TODO(debargha): enhance this test with a better distortion prediction
4013
        // based on qp, activity mask and history
4014
6.30M
        if ((mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
4015
6.30M
            (mode_index > MIN_EARLY_TERM_INDEX)) {
4016
0
          int qstep = xd->plane[0].dequant[1];
4017
          // TODO(debargha): Enhance this by specializing for each mode_index
4018
0
          int scale = 4;
4019
0
#if CONFIG_VP9_HIGHBITDEPTH
4020
0
          if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
4021
0
            qstep >>= (xd->bd - 8);
4022
0
          }
4023
0
#endif  // CONFIG_VP9_HIGHBITDEPTH
4024
0
          if (x->source_variance < UINT_MAX) {
4025
0
            const int var_adjust = (x->source_variance < 16);
4026
0
            scale -= var_adjust;
4027
0
          }
4028
0
          if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
4029
0
            early_term = 1;
4030
0
          }
4031
0
        }
4032
6.30M
      }
4033
6.30M
    }
4034
4035
    /* keep record of best compound/single-only prediction */
4036
23.8M
    if (!disable_skip && ref_frame != INTRA_FRAME) {
4037
7.31M
      int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
4038
4039
7.31M
      if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4040
0
        single_rate = rate2 - compmode_cost;
4041
0
        hybrid_rate = rate2;
4042
7.31M
      } else {
4043
7.31M
        single_rate = rate2;
4044
7.31M
        hybrid_rate = rate2 + compmode_cost;
4045
7.31M
      }
4046
4047
7.31M
      single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
4048
7.31M
      hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
4049
4050
7.31M
      if (!comp_pred) {
4051
7.31M
        if (single_rd < best_pred_rd[SINGLE_REFERENCE])
4052
3.70M
          best_pred_rd[SINGLE_REFERENCE] = single_rd;
4053
7.31M
      } else {
4054
0
        if (single_rd < best_pred_rd[COMPOUND_REFERENCE])
4055
0
          best_pred_rd[COMPOUND_REFERENCE] = single_rd;
4056
0
      }
4057
7.31M
      if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
4058
3.68M
        best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
4059
4060
      /* keep record of best filter type */
4061
7.31M
      if (!mode_excluded && cm->interp_filter != BILINEAR) {
4062
7.31M
        int64_t ref =
4063
7.31M
            filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
4064
7.31M
                                                         : cm->interp_filter];
4065
4066
36.5M
        for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4067
29.2M
          int64_t adj_rd;
4068
29.2M
          if (ref == INT64_MAX)
4069
1.47M
            adj_rd = 0;
4070
27.7M
          else if (filter_cache[i] == INT64_MAX)
4071
            // when early termination is triggered, the encoder does not have
4072
            // access to the rate-distortion cost. it only knows that the cost
4073
            // should be above the maximum valid value. hence it takes the known
4074
            // maximum plus an arbitrary constant as the rate-distortion cost.
4075
1.56M
            adj_rd = mask_filter - ref + 10;
4076
26.2M
          else
4077
26.2M
            adj_rd = filter_cache[i] - ref;
4078
4079
29.2M
          adj_rd += this_rd;
4080
29.2M
          best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
4081
29.2M
        }
4082
7.31M
      }
4083
7.31M
    }
4084
4085
23.8M
    if (early_term) break;
4086
4087
23.8M
    if (x->skip && !comp_pred) break;
4088
23.8M
  }
4089
4090
  // The inter modes' rate costs are not calculated precisely in some cases.
4091
  // Therefore, sometimes, NEWMV is chosen instead of NEARESTMV, NEARMV, and
4092
  // ZEROMV. Here, checks are added for those cases, and the mode decisions
4093
  // are corrected.
4094
3.61M
  if (best_mbmode.mode == NEWMV) {
4095
395k
    const MV_REFERENCE_FRAME refs[2] = { best_mbmode.ref_frame[0],
4096
395k
                                         best_mbmode.ref_frame[1] };
4097
395k
    int comp_pred_mode = refs[1] > INTRA_FRAME;
4098
4099
395k
    if (frame_mv[NEARESTMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
4100
395k
        ((comp_pred_mode &&
4101
5.69k
          frame_mv[NEARESTMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
4102
5.69k
         !comp_pred_mode))
4103
5.69k
      best_mbmode.mode = NEARESTMV;
4104
389k
    else if (frame_mv[NEARMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
4105
389k
             ((comp_pred_mode &&
4106
4.77k
               frame_mv[NEARMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
4107
4.77k
              !comp_pred_mode))
4108
4.77k
      best_mbmode.mode = NEARMV;
4109
384k
    else if (best_mbmode.mv[0].as_int == 0 &&
4110
384k
             ((comp_pred_mode && best_mbmode.mv[1].as_int == 0) ||
4111
320
              !comp_pred_mode))
4112
320
      best_mbmode.mode = ZEROMV;
4113
395k
  }
4114
4115
3.61M
  if (best_mode_index < 0 || best_rd >= best_rd_so_far) {
4116
    // If adaptive interp filter is enabled, then the current leaf node of 8x8
4117
    // data is needed for sub8x8. Hence preserve the context.
4118
813k
    if (bsize == BLOCK_8X8) ctx->mic = *xd->mi[0];
4119
813k
    rd_cost->rate = INT_MAX;
4120
813k
    rd_cost->rdcost = INT64_MAX;
4121
813k
    return;
4122
813k
  }
4123
4124
  // If we used an estimate for the uv intra rd in the loop above...
4125
2.80M
  if (sf->use_uv_intra_rd_estimate) {
4126
    // Do Intra UV best rd mode selection if best mode choice above was intra.
4127
0
    if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
4128
0
      TX_SIZE uv_tx_size;
4129
0
      *mi = best_mbmode;
4130
0
      uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
4131
0
      rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
4132
0
                              &rate_uv_tokenonly[uv_tx_size],
4133
0
                              &dist_uv[uv_tx_size], &skip_uv[uv_tx_size],
4134
0
                              bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
4135
0
                              uv_tx_size);
4136
0
    }
4137
0
  }
4138
4139
2.80M
  assert((cm->interp_filter == SWITCHABLE) ||
4140
2.80M
         (cm->interp_filter == best_mbmode.interp_filter) ||
4141
2.80M
         !is_inter_block(&best_mbmode));
4142
4143
2.80M
  if (!cpi->rc.is_src_frame_alt_ref)
4144
2.80M
    vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
4145
2.80M
                              sf->adaptive_rd_thresh, bsize, best_mode_index);
4146
4147
  // macroblock modes
4148
2.80M
  *mi = best_mbmode;
4149
2.80M
  x->skip |= best_skip2;
4150
4151
11.2M
  for (i = 0; i < REFERENCE_MODES; ++i) {
4152
8.40M
    if (best_pred_rd[i] == INT64_MAX)
4153
509k
      best_pred_diff[i] = INT_MIN;
4154
7.89M
    else
4155
7.89M
      best_pred_diff[i] = best_rd - best_pred_rd[i];
4156
8.40M
  }
4157
4158
2.80M
  if (!x->skip) {
4159
13.1M
    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4160
10.4M
      if (best_filter_rd[i] == INT64_MAX)
4161
0
        best_filter_diff[i] = 0;
4162
10.4M
      else
4163
10.4M
        best_filter_diff[i] = best_rd - best_filter_rd[i];
4164
10.4M
    }
4165
2.62M
    if (cm->interp_filter == SWITCHABLE)
4166
1.39M
      assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
4167
2.62M
  } else {
4168
176k
    vp9_zero(best_filter_diff);
4169
176k
  }
4170
4171
  // TODO(yunqingwang): Moving this line in front of the above best_filter_diff
4172
  // updating code causes PSNR loss. Need to figure out the confliction.
4173
2.80M
  x->skip |= best_mode_skippable;
4174
4175
2.80M
  if (!x->skip && !x->select_tx_size) {
4176
1.45M
    int has_high_freq_coeff = 0;
4177
1.45M
    int plane;
4178
1.45M
    int max_plane = is_inter_block(xd->mi[0]) ? MAX_MB_PLANE : 1;
4179
3.78M
    for (plane = 0; plane < max_plane; ++plane) {
4180
2.32M
      x->plane[plane].eobs = ctx->eobs_pbuf[plane][1];
4181
2.32M
      has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
4182
2.32M
    }
4183
4184
3.50M
    for (plane = max_plane; plane < MAX_MB_PLANE; ++plane) {
4185
2.04M
      x->plane[plane].eobs = ctx->eobs_pbuf[plane][2];
4186
2.04M
      has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
4187
2.04M
    }
4188
4189
1.45M
    best_mode_skippable |= !has_high_freq_coeff;
4190
1.45M
  }
4191
4192
2.80M
  assert(best_mode_index >= 0);
4193
4194
2.80M
  store_coding_context(x, ctx, best_mode_index, best_pred_diff,
4195
2.80M
                       best_filter_diff, best_mode_skippable);
4196
2.80M
}
4197
4198
void vp9_rd_pick_inter_mode_sb_seg_skip(VP9_COMP *cpi, TileDataEnc *tile_data,
4199
                                        MACROBLOCK *x, RD_COST *rd_cost,
4200
                                        BLOCK_SIZE bsize,
4201
                                        PICK_MODE_CONTEXT *ctx,
4202
0
                                        int64_t best_rd_so_far) {
4203
0
  VP9_COMMON *const cm = &cpi->common;
4204
0
  MACROBLOCKD *const xd = &x->e_mbd;
4205
0
  MODE_INFO *const mi = xd->mi[0];
4206
0
  unsigned char segment_id = mi->segment_id;
4207
0
  const int comp_pred = 0;
4208
0
  int i;
4209
0
  int64_t best_pred_diff[REFERENCE_MODES];
4210
0
  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
4211
0
  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
4212
0
  vpx_prob comp_mode_p;
4213
0
  INTERP_FILTER best_filter = SWITCHABLE;
4214
0
  int64_t this_rd = INT64_MAX;
4215
0
  int rate2 = 0;
4216
0
  const int64_t distortion2 = 0;
4217
4218
0
  x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
4219
4220
0
  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
4221
0
                           &comp_mode_p);
4222
4223
0
  for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
4224
0
  for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i) x->pred_mv_sad[i] = INT_MAX;
4225
4226
0
  rd_cost->rate = INT_MAX;
4227
4228
0
  assert(segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP));
4229
4230
0
  mi->mode = ZEROMV;
4231
0
  mi->uv_mode = DC_PRED;
4232
0
  mi->ref_frame[0] = LAST_FRAME;
4233
0
  mi->ref_frame[1] = NO_REF_FRAME;
4234
0
  mi->mv[0].as_int = 0;
4235
0
  x->skip = 1;
4236
4237
0
  ctx->sum_y_eobs = 0;
4238
4239
0
  if (cm->interp_filter != BILINEAR) {
4240
0
    best_filter = EIGHTTAP;
4241
0
    if (cm->interp_filter == SWITCHABLE &&
4242
0
        x->source_variance >= cpi->sf.disable_filter_search_var_thresh) {
4243
0
      int rs;
4244
0
      int best_rs = INT_MAX;
4245
0
      for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
4246
0
        mi->interp_filter = i;
4247
0
        rs = vp9_get_switchable_rate(cpi, xd);
4248
0
        if (rs < best_rs) {
4249
0
          best_rs = rs;
4250
0
          best_filter = mi->interp_filter;
4251
0
        }
4252
0
      }
4253
0
    }
4254
0
  }
4255
  // Set the appropriate filter
4256
0
  if (cm->interp_filter == SWITCHABLE) {
4257
0
    mi->interp_filter = best_filter;
4258
0
    rate2 += vp9_get_switchable_rate(cpi, xd);
4259
0
  } else {
4260
0
    mi->interp_filter = cm->interp_filter;
4261
0
  }
4262
4263
0
  if (cm->reference_mode == REFERENCE_MODE_SELECT)
4264
0
    rate2 += vp9_cost_bit(comp_mode_p, comp_pred);
4265
4266
  // Estimate the reference frame signaling cost and add it
4267
  // to the rolling cost variable.
4268
0
  rate2 += ref_costs_single[LAST_FRAME];
4269
0
  this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
4270
4271
0
  rd_cost->rate = rate2;
4272
0
  rd_cost->dist = distortion2;
4273
0
  rd_cost->rdcost = this_rd;
4274
4275
0
  if (this_rd >= best_rd_so_far) {
4276
0
    rd_cost->rate = INT_MAX;
4277
0
    rd_cost->rdcost = INT64_MAX;
4278
0
    return;
4279
0
  }
4280
4281
0
  assert((cm->interp_filter == SWITCHABLE) ||
4282
0
         (cm->interp_filter == mi->interp_filter));
4283
4284
0
  vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
4285
0
                            cpi->sf.adaptive_rd_thresh, bsize, THR_ZEROMV);
4286
4287
0
  vp9_zero(best_pred_diff);
4288
0
  vp9_zero(best_filter_diff);
4289
4290
0
  if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, MAX_MB_PLANE);
4291
0
  store_coding_context(x, ctx, THR_ZEROMV, best_pred_diff, best_filter_diff, 0);
4292
0
}
4293
4294
void vp9_rd_pick_inter_mode_sub8x8(VP9_COMP *cpi, TileDataEnc *tile_data,
4295
                                   MACROBLOCK *x, int mi_row, int mi_col,
4296
                                   RD_COST *rd_cost, BLOCK_SIZE bsize,
4297
                                   PICK_MODE_CONTEXT *ctx,
4298
3.02M
                                   int64_t best_rd_so_far) {
4299
3.02M
  VP9_COMMON *const cm = &cpi->common;
4300
3.02M
  RD_OPT *const rd_opt = &cpi->rd;
4301
3.02M
  SPEED_FEATURES *const sf = &cpi->sf;
4302
3.02M
  MACROBLOCKD *const xd = &x->e_mbd;
4303
3.02M
  MODE_INFO *const mi = xd->mi[0];
4304
3.02M
  const struct segmentation *const seg = &cm->seg;
4305
3.02M
  MV_REFERENCE_FRAME ref_frame, second_ref_frame;
4306
3.02M
  unsigned char segment_id = mi->segment_id;
4307
3.02M
  int comp_pred, i;
4308
3.02M
  int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
4309
3.02M
  struct buf_2d yv12_mb[4][MAX_MB_PLANE] = { 0 };
4310
3.02M
  int64_t best_rd = best_rd_so_far;
4311
3.02M
  int64_t best_yrd = best_rd_so_far;  // FIXME(rbultje) more precise
4312
3.02M
  int64_t best_pred_diff[REFERENCE_MODES];
4313
3.02M
  int64_t best_pred_rd[REFERENCE_MODES];
4314
3.02M
  int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
4315
3.02M
  int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
4316
3.02M
  MODE_INFO best_mbmode;
4317
3.02M
  int ref_index, best_ref_index = 0;
4318
3.02M
  unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
4319
3.02M
  vpx_prob comp_mode_p;
4320
3.02M
  INTERP_FILTER tmp_best_filter = SWITCHABLE;
4321
3.02M
  int rate_uv_intra, rate_uv_tokenonly;
4322
3.02M
  int64_t dist_uv;
4323
3.02M
  int skip_uv;
4324
3.02M
  PREDICTION_MODE mode_uv = DC_PRED;
4325
3.02M
  const int intra_cost_penalty =
4326
3.02M
      vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
4327
3.02M
  int_mv seg_mvs[4][MAX_REF_FRAMES];
4328
3.02M
  b_mode_info best_bmodes[4];
4329
3.02M
  int best_skip2 = 0;
4330
3.02M
  int ref_frame_skip_mask[2] = { 0 };
4331
3.02M
  int64_t mask_filter = 0;
4332
3.02M
  int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
4333
3.02M
  int internal_active_edge =
4334
3.02M
      vp9_active_edge_sb(cpi, mi_row, mi_col) && vp9_internal_image_edge(cpi);
4335
3.02M
  const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
4336
4337
3.02M
  x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
4338
3.02M
  memset(x->zcoeff_blk[TX_4X4], 0, 4);
4339
3.02M
  vp9_zero(best_mbmode);
4340
4341
15.1M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
4342
4343
15.1M
  for (i = 0; i < 4; i++) {
4344
12.0M
    int j;
4345
60.4M
    for (j = 0; j < MAX_REF_FRAMES; j++) seg_mvs[i][j].as_int = INVALID_MV;
4346
12.0M
  }
4347
4348
3.02M
  estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
4349
3.02M
                           &comp_mode_p);
4350
4351
12.0M
  for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
4352
15.1M
  for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
4353
12.0M
    best_filter_rd[i] = INT64_MAX;
4354
3.02M
  rate_uv_intra = INT_MAX;
4355
4356
3.02M
  rd_cost->rate = INT_MAX;
4357
4358
12.0M
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
4359
9.06M
    if (cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) {
4360
6.71M
      setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
4361
6.71M
                         frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
4362
6.71M
    } else {
4363
2.35M
      ref_frame_skip_mask[0] |= (1 << ref_frame);
4364
2.35M
      ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4365
2.35M
    }
4366
9.06M
    frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
4367
9.06M
    frame_mv[ZEROMV][ref_frame].as_int = 0;
4368
9.06M
  }
4369
4370
21.1M
  for (ref_index = 0; ref_index < MAX_REFS; ++ref_index) {
4371
18.1M
    int mode_excluded = 0;
4372
18.1M
    int64_t this_rd = INT64_MAX;
4373
18.1M
    int disable_skip = 0;
4374
18.1M
    int compmode_cost = 0;
4375
18.1M
    int rate2 = 0, rate_y = 0, rate_uv = 0;
4376
18.1M
    int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
4377
18.1M
    int skippable = 0;
4378
18.1M
    int this_skip2 = 0;
4379
18.1M
    int64_t total_sse = INT_MAX;
4380
18.1M
    int early_term = 0;
4381
18.1M
    struct buf_2d backup_yv12[2][MAX_MB_PLANE];
4382
4383
18.1M
    ref_frame = vp9_ref_order[ref_index].ref_frame[0];
4384
18.1M
    second_ref_frame = vp9_ref_order[ref_index].ref_frame[1];
4385
4386
18.1M
    vp9_zero(x->sum_y_eobs);
4387
4388
#if CONFIG_BETTER_HW_COMPATIBILITY
4389
    // forbid 8X4 and 4X8 partitions if any reference frame is scaled.
4390
    if (bsize == BLOCK_8X4 || bsize == BLOCK_4X8) {
4391
      int ref_scaled = ref_frame > INTRA_FRAME &&
4392
                       vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf);
4393
      if (second_ref_frame > INTRA_FRAME)
4394
        ref_scaled += vp9_is_scaled(&cm->frame_refs[second_ref_frame - 1].sf);
4395
      if (ref_scaled) continue;
4396
    }
4397
#endif
4398
    // Look at the reference frame of the best mode so far and set the
4399
    // skip mask to look at a subset of the remaining modes.
4400
18.1M
    if (ref_index > 2 && sf->mode_skip_start < MAX_MODES) {
4401
1.85M
      if (ref_index == 3) {
4402
617k
        switch (best_mbmode.ref_frame[0]) {
4403
478k
          case INTRA_FRAME: break;
4404
84.6k
          case LAST_FRAME:
4405
84.6k
            ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME);
4406
84.6k
            ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4407
84.6k
            break;
4408
43.1k
          case GOLDEN_FRAME:
4409
43.1k
            ref_frame_skip_mask[0] |= (1 << LAST_FRAME) | (1 << ALTREF_FRAME);
4410
43.1k
            ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4411
43.1k
            break;
4412
10.4k
          case ALTREF_FRAME:
4413
10.4k
            ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << LAST_FRAME);
4414
10.4k
            break;
4415
0
          case NO_REF_FRAME:
4416
0
          case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
4417
617k
        }
4418
617k
      }
4419
1.85M
    }
4420
4421
18.1M
    if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
4422
18.1M
        (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
4423
3.11M
      continue;
4424
4425
    // Test best rd so far against threshold for trying this mode.
4426
15.0M
    if (!internal_active_edge &&
4427
15.0M
        rd_less_than_thresh(best_rd,
4428
15.0M
                            rd_opt->threshes[segment_id][bsize][ref_index],
4429
15.0M
                            &rd_thresh_freq_fact[ref_index]))
4430
6.03M
      continue;
4431
4432
    // This is only used in motion vector unit test.
4433
8.98M
    if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
4434
4435
8.98M
    comp_pred = second_ref_frame > INTRA_FRAME;
4436
8.98M
    if (comp_pred) {
4437
0
      if (!cpi->allow_comp_inter_inter) continue;
4438
4439
0
      if (cm->ref_frame_sign_bias[ref_frame] ==
4440
0
          cm->ref_frame_sign_bias[second_ref_frame])
4441
0
        continue;
4442
4443
0
      if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
4444
0
        continue;
4445
      // Do not allow compound prediction if the segment level reference frame
4446
      // feature is in use as in this case there can only be one reference.
4447
0
      if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
4448
4449
0
      if ((sf->mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
4450
0
          best_mbmode.ref_frame[0] == INTRA_FRAME)
4451
0
        continue;
4452
0
    }
4453
4454
8.98M
    if (comp_pred)
4455
0
      mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
4456
8.98M
    else if (ref_frame != INTRA_FRAME)
4457
6.11M
      mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
4458
4459
    // If the segment reference frame feature is enabled....
4460
    // then do nothing if the current ref frame is not allowed..
4461
8.98M
    if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
4462
8.98M
        get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
4463
0
      continue;
4464
      // Disable this drop out case if the ref frame
4465
      // segment level feature is enabled for this segment. This is to
4466
      // prevent the possibility that we end up unable to pick any mode.
4467
8.98M
    } else if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
4468
      // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
4469
      // unless ARNR filtering is enabled in which case we want
4470
      // an unfiltered alternative. We allow near/nearest as well
4471
      // because they may result in zero-zero MVs but be cheaper.
4472
8.98M
      if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
4473
0
        continue;
4474
8.98M
    }
4475
4476
8.98M
    mi->tx_size = TX_4X4;
4477
8.98M
    mi->uv_mode = DC_PRED;
4478
8.98M
    mi->ref_frame[0] = ref_frame;
4479
8.98M
    mi->ref_frame[1] = second_ref_frame;
4480
    // Evaluate all sub-pel filters irrespective of whether we can use
4481
    // them for this frame.
4482
8.98M
    mi->interp_filter =
4483
8.98M
        cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
4484
8.98M
    x->skip = 0;
4485
8.98M
    set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
4486
4487
    // Select prediction reference frames.
4488
35.9M
    for (i = 0; i < MAX_MB_PLANE; i++) {
4489
26.9M
      xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
4490
26.9M
      if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
4491
26.9M
    }
4492
4493
8.98M
    if (ref_frame == INTRA_FRAME) {
4494
2.86M
      int rate;
4495
2.86M
      if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y, &distortion_y,
4496
2.86M
                                       best_rd) >= best_rd)
4497
631k
        continue;
4498
2.23M
      rate2 += rate;
4499
2.23M
      rate2 += intra_cost_penalty;
4500
2.23M
      distortion2 += distortion_y;
4501
4502
2.23M
      if (rate_uv_intra == INT_MAX) {
4503
2.23M
        choose_intra_uv_mode(cpi, x, ctx, bsize, TX_4X4, &rate_uv_intra,
4504
2.23M
                             &rate_uv_tokenonly, &dist_uv, &skip_uv, &mode_uv);
4505
2.23M
      }
4506
2.23M
      rate2 += rate_uv_intra;
4507
2.23M
      rate_uv = rate_uv_tokenonly;
4508
2.23M
      distortion2 += dist_uv;
4509
2.23M
      distortion_uv = dist_uv;
4510
2.23M
      mi->uv_mode = mode_uv;
4511
6.11M
    } else {
4512
6.11M
      int rate;
4513
6.11M
      int64_t distortion;
4514
6.11M
      int64_t this_rd_thresh;
4515
6.11M
      int64_t tmp_rd, tmp_best_rd = INT64_MAX, tmp_best_rdu = INT64_MAX;
4516
6.11M
      int tmp_best_rate = INT_MAX, tmp_best_ratey = INT_MAX;
4517
6.11M
      int64_t tmp_best_distortion = INT_MAX, tmp_best_sse, uv_sse;
4518
6.11M
      int tmp_best_skippable = 0;
4519
6.11M
      int switchable_filter_index;
4520
6.11M
      int_mv *second_ref =
4521
6.11M
          comp_pred ? &x->mbmi_ext->ref_mvs[second_ref_frame][0] : NULL;
4522
6.11M
      b_mode_info tmp_best_bmodes[16];
4523
6.11M
      MODE_INFO tmp_best_mbmode;
4524
6.11M
      BEST_SEG_INFO bsi[SWITCHABLE_FILTERS];
4525
6.11M
      int pred_exists = 0;
4526
6.11M
      int uv_skippable;
4527
4528
6.11M
      YV12_BUFFER_CONFIG *scaled_ref_frame[2] = { NULL, NULL };
4529
6.11M
      int ref;
4530
4531
18.3M
      for (ref = 0; ref < 2; ++ref) {
4532
12.2M
        scaled_ref_frame[ref] =
4533
12.2M
            mi->ref_frame[ref] > INTRA_FRAME
4534
12.2M
                ? vp9_get_scaled_ref_frame(cpi, mi->ref_frame[ref])
4535
12.2M
                : NULL;
4536
4537
12.2M
        if (scaled_ref_frame[ref]) {
4538
          // Swap out the reference frame for a version that's been scaled to
4539
          // match the resolution of the current frame, allowing the existing
4540
          // motion search code to be used without additional modifications.
4541
0
          for (i = 0; i < MAX_MB_PLANE; i++)
4542
0
            backup_yv12[ref][i] = xd->plane[i].pre[ref];
4543
0
          vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
4544
0
                               NULL);
4545
0
        }
4546
12.2M
      }
4547
4548
6.11M
      this_rd_thresh = (ref_frame == LAST_FRAME)
4549
6.11M
                           ? rd_opt->threshes[segment_id][bsize][THR_LAST]
4550
6.11M
                           : rd_opt->threshes[segment_id][bsize][THR_ALTR];
4551
6.11M
      this_rd_thresh = (ref_frame == GOLDEN_FRAME)
4552
6.11M
                           ? rd_opt->threshes[segment_id][bsize][THR_GOLD]
4553
6.11M
                           : this_rd_thresh;
4554
30.5M
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
4555
24.4M
        filter_cache[i] = INT64_MAX;
4556
4557
6.11M
      if (cm->interp_filter != BILINEAR) {
4558
6.11M
        tmp_best_filter = EIGHTTAP;
4559
6.11M
        if (x->source_variance < sf->disable_filter_search_var_thresh) {
4560
0
          tmp_best_filter = EIGHTTAP;
4561
6.11M
        } else if (sf->adaptive_pred_interp_filter == 1 &&
4562
6.11M
                   ctx->pred_interp_filter < SWITCHABLE) {
4563
6.11M
          tmp_best_filter = ctx->pred_interp_filter;
4564
6.11M
        } else if (sf->adaptive_pred_interp_filter == 2) {
4565
0
          tmp_best_filter = ctx->pred_interp_filter < SWITCHABLE
4566
0
                                ? ctx->pred_interp_filter
4567
0
                                : 0;
4568
0
        } else {
4569
0
          for (switchable_filter_index = 0;
4570
0
               switchable_filter_index < SWITCHABLE_FILTERS;
4571
0
               ++switchable_filter_index) {
4572
0
            int newbest, rs;
4573
0
            int64_t rs_rd;
4574
0
            MB_MODE_INFO_EXT *mbmi_ext = x->mbmi_ext;
4575
0
            mi->interp_filter = switchable_filter_index;
4576
0
            tmp_rd = rd_pick_best_sub8x8_mode(
4577
0
                cpi, x, &mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
4578
0
                &rate, &rate_y, &distortion, &skippable, &total_sse,
4579
0
                (int)this_rd_thresh, seg_mvs, bsi, switchable_filter_index,
4580
0
                mi_row, mi_col);
4581
4582
0
            if (tmp_rd == INT64_MAX) continue;
4583
0
            rs = vp9_get_switchable_rate(cpi, xd);
4584
0
            rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
4585
0
            filter_cache[switchable_filter_index] = tmp_rd;
4586
0
            filter_cache[SWITCHABLE_FILTERS] =
4587
0
                VPXMIN(filter_cache[SWITCHABLE_FILTERS], tmp_rd + rs_rd);
4588
0
            if (cm->interp_filter == SWITCHABLE) tmp_rd += rs_rd;
4589
4590
0
            mask_filter = VPXMAX(mask_filter, tmp_rd);
4591
4592
0
            newbest = (tmp_rd < tmp_best_rd);
4593
0
            if (newbest) {
4594
0
              tmp_best_filter = mi->interp_filter;
4595
0
              tmp_best_rd = tmp_rd;
4596
0
            }
4597
0
            if ((newbest && cm->interp_filter == SWITCHABLE) ||
4598
0
                (mi->interp_filter == cm->interp_filter &&
4599
0
                 cm->interp_filter != SWITCHABLE)) {
4600
0
              tmp_best_rdu = tmp_rd;
4601
0
              tmp_best_rate = rate;
4602
0
              tmp_best_ratey = rate_y;
4603
0
              tmp_best_distortion = distortion;
4604
0
              tmp_best_sse = total_sse;
4605
0
              tmp_best_skippable = skippable;
4606
0
              tmp_best_mbmode = *mi;
4607
0
              x->sum_y_eobs[TX_4X4] = 0;
4608
0
              for (i = 0; i < 4; i++) {
4609
0
                tmp_best_bmodes[i] = xd->mi[0]->bmi[i];
4610
0
                x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
4611
0
                x->sum_y_eobs[TX_4X4] += x->plane[0].eobs[i];
4612
0
              }
4613
0
              pred_exists = 1;
4614
0
              if (switchable_filter_index == 0 && sf->use_rd_breakout &&
4615
0
                  best_rd < INT64_MAX) {
4616
0
                if (tmp_best_rdu / 2 > best_rd) {
4617
                  // skip searching the other filters if the first is
4618
                  // already substantially larger than the best so far
4619
0
                  tmp_best_filter = mi->interp_filter;
4620
0
                  tmp_best_rdu = INT64_MAX;
4621
0
                  break;
4622
0
                }
4623
0
              }
4624
0
            }
4625
0
          }  // switchable_filter_index loop
4626
0
        }
4627
6.11M
      }
4628
4629
6.11M
      if (tmp_best_rdu == INT64_MAX && pred_exists) continue;
4630
4631
6.11M
      mi->interp_filter = (cm->interp_filter == SWITCHABLE ? tmp_best_filter
4632
6.11M
                                                           : cm->interp_filter);
4633
6.11M
      if (!pred_exists) {
4634
        // Handles the special case when a filter that is not in the
4635
        // switchable list (bilinear, 6-tap) is indicated at the frame level
4636
6.11M
        tmp_rd = rd_pick_best_sub8x8_mode(
4637
6.11M
            cpi, x, &x->mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
4638
6.11M
            &rate, &rate_y, &distortion, &skippable, &total_sse,
4639
6.11M
            (int)this_rd_thresh, seg_mvs, bsi, 0, mi_row, mi_col);
4640
6.11M
        if (tmp_rd == INT64_MAX) continue;
4641
3.91M
        x->sum_y_eobs[TX_4X4] = 0;
4642
19.5M
        for (i = 0; i < 4; i++) {
4643
15.6M
          x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
4644
15.6M
          x->sum_y_eobs[TX_4X4] += x->plane[0].eobs[i];
4645
15.6M
        }
4646
3.91M
      } else {
4647
0
        total_sse = tmp_best_sse;
4648
0
        rate = tmp_best_rate;
4649
0
        rate_y = tmp_best_ratey;
4650
0
        distortion = tmp_best_distortion;
4651
0
        skippable = tmp_best_skippable;
4652
0
        *mi = tmp_best_mbmode;
4653
0
        for (i = 0; i < 4; i++) xd->mi[0]->bmi[i] = tmp_best_bmodes[i];
4654
0
      }
4655
4656
3.91M
      rate2 += rate;
4657
3.91M
      distortion2 += distortion;
4658
4659
3.91M
      if (cm->interp_filter == SWITCHABLE)
4660
1.67M
        rate2 += vp9_get_switchable_rate(cpi, xd);
4661
4662
3.91M
      if (!mode_excluded)
4663
3.91M
        mode_excluded = comp_pred ? cm->reference_mode == SINGLE_REFERENCE
4664
3.91M
                                  : cm->reference_mode == COMPOUND_REFERENCE;
4665
4666
3.91M
      compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
4667
4668
3.91M
      tmp_best_rdu =
4669
3.91M
          best_rd - VPXMIN(RDCOST(x->rdmult, x->rddiv, rate2, distortion2),
4670
3.91M
                           RDCOST(x->rdmult, x->rddiv, 0, total_sse));
4671
4672
3.91M
      if (tmp_best_rdu > 0) {
4673
        // If even the 'Y' rd value of split is higher than best so far
4674
        // then don't bother looking at UV
4675
3.90M
        vp9_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col, BLOCK_8X8);
4676
3.90M
        memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
4677
3.90M
        if (!super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
4678
3.90M
                              &uv_sse, BLOCK_8X8, tmp_best_rdu)) {
4679
4.38M
          for (ref = 0; ref < 2; ++ref) {
4680
2.92M
            if (scaled_ref_frame[ref]) {
4681
0
              for (i = 0; i < MAX_MB_PLANE; ++i)
4682
0
                xd->plane[i].pre[ref] = backup_yv12[ref][i];
4683
0
            }
4684
2.92M
          }
4685
1.46M
          continue;
4686
1.46M
        }
4687
4688
2.44M
        rate2 += rate_uv;
4689
2.44M
        distortion2 += distortion_uv;
4690
2.44M
        skippable = skippable && uv_skippable;
4691
2.44M
        total_sse += uv_sse;
4692
2.44M
      }
4693
4694
7.34M
      for (ref = 0; ref < 2; ++ref) {
4695
4.89M
        if (scaled_ref_frame[ref]) {
4696
          // Restore the prediction frame pointers to their unscaled versions.
4697
0
          for (i = 0; i < MAX_MB_PLANE; ++i)
4698
0
            xd->plane[i].pre[ref] = backup_yv12[ref][i];
4699
0
        }
4700
4.89M
      }
4701
2.44M
    }
4702
4703
4.68M
    if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
4704
4705
    // Estimate the reference frame signaling cost and add it
4706
    // to the rolling cost variable.
4707
4.68M
    if (second_ref_frame > INTRA_FRAME) {
4708
0
      rate2 += ref_costs_comp[ref_frame];
4709
4.68M
    } else {
4710
4.68M
      rate2 += ref_costs_single[ref_frame];
4711
4.68M
    }
4712
4713
4.68M
    if (!disable_skip) {
4714
4.68M
      const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
4715
4.68M
      const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
4716
4.68M
      const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
4717
4718
      // Skip is never coded at the segment level for sub8x8 blocks and instead
4719
      // always coded in the bitstream at the mode info level.
4720
4.68M
      if (ref_frame != INTRA_FRAME && !xd->lossless) {
4721
2.26M
        if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
4722
2.26M
                   distortion2) <
4723
2.26M
            RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
4724
          // Add in the cost of the no skip flag.
4725
2.02M
          rate2 += skip_cost0;
4726
2.02M
        } else {
4727
          // FIXME(rbultje) make this work for splitmv also
4728
243k
          rate2 += skip_cost1;
4729
243k
          distortion2 = total_sse;
4730
243k
          assert(total_sse >= 0);
4731
243k
          rate2 -= (rate_y + rate_uv);
4732
243k
          rate_y = 0;
4733
243k
          rate_uv = 0;
4734
243k
          this_skip2 = 1;
4735
243k
        }
4736
2.41M
      } else {
4737
        // Add in the cost of the no skip flag.
4738
2.41M
        rate2 += skip_cost0;
4739
2.41M
      }
4740
4741
      // Calculate the final RD estimate for this mode.
4742
4.68M
      this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
4743
4.68M
    }
4744
4745
4.68M
    if (!disable_skip && ref_frame == INTRA_FRAME) {
4746
8.94M
      for (i = 0; i < REFERENCE_MODES; ++i)
4747
6.70M
        best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
4748
11.1M
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
4749
8.94M
        best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
4750
2.23M
    }
4751
4752
    // Did this mode help.. i.e. is it the new best mode
4753
4.68M
    if (this_rd < best_rd || x->skip) {
4754
1.32M
      if (!mode_excluded) {
4755
1.32M
        int max_plane = MAX_MB_PLANE;
4756
        // Note index of best mode so far
4757
1.32M
        best_ref_index = ref_index;
4758
4759
1.32M
        if (ref_frame == INTRA_FRAME) {
4760
          /* required for left and above block mv */
4761
822k
          mi->mv[0].as_int = 0;
4762
822k
          max_plane = 1;
4763
          // Initialize interp_filter here so we do not have to check for
4764
          // inter block modes in get_pred_context_switchable_interp()
4765
822k
          mi->interp_filter = SWITCHABLE_FILTERS;
4766
822k
        }
4767
4768
1.32M
        rd_cost->rate = rate2;
4769
1.32M
        rd_cost->dist = distortion2;
4770
1.32M
        rd_cost->rdcost = this_rd;
4771
1.32M
        best_rd = this_rd;
4772
1.32M
        best_yrd =
4773
1.32M
            best_rd - RDCOST(x->rdmult, x->rddiv, rate_uv, distortion_uv);
4774
1.32M
        best_mbmode = *mi;
4775
1.32M
        best_skip2 = this_skip2;
4776
1.32M
        if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
4777
1.32M
        memcpy(ctx->zcoeff_blk, x->zcoeff_blk[TX_4X4],
4778
1.32M
               sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
4779
1.32M
        ctx->sum_y_eobs = x->sum_y_eobs[TX_4X4];
4780
4781
6.60M
        for (i = 0; i < 4; i++) best_bmodes[i] = xd->mi[0]->bmi[i];
4782
4783
        // TODO(debargha): enhance this test with a better distortion prediction
4784
        // based on qp, activity mask and history
4785
1.32M
        if ((sf->mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
4786
1.32M
            (ref_index > MIN_EARLY_TERM_INDEX)) {
4787
0
          int qstep = xd->plane[0].dequant[1];
4788
          // TODO(debargha): Enhance this by specializing for each mode_index
4789
0
          int scale = 4;
4790
0
#if CONFIG_VP9_HIGHBITDEPTH
4791
0
          if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
4792
0
            qstep >>= (xd->bd - 8);
4793
0
          }
4794
0
#endif  // CONFIG_VP9_HIGHBITDEPTH
4795
0
          if (x->source_variance < UINT_MAX) {
4796
0
            const int var_adjust = (x->source_variance < 16);
4797
0
            scale -= var_adjust;
4798
0
          }
4799
0
          if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
4800
0
            early_term = 1;
4801
0
          }
4802
0
        }
4803
1.32M
      }
4804
1.32M
    }
4805
4806
    /* keep record of best compound/single-only prediction */
4807
4.68M
    if (!disable_skip && ref_frame != INTRA_FRAME) {
4808
2.44M
      int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
4809
4810
2.44M
      if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4811
0
        single_rate = rate2 - compmode_cost;
4812
0
        hybrid_rate = rate2;
4813
2.44M
      } else {
4814
2.44M
        single_rate = rate2;
4815
2.44M
        hybrid_rate = rate2 + compmode_cost;
4816
2.44M
      }
4817
4818
2.44M
      single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
4819
2.44M
      hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
4820
4821
2.44M
      if (!comp_pred && single_rd < best_pred_rd[SINGLE_REFERENCE])
4822
1.93M
        best_pred_rd[SINGLE_REFERENCE] = single_rd;
4823
510k
      else if (comp_pred && single_rd < best_pred_rd[COMPOUND_REFERENCE])
4824
0
        best_pred_rd[COMPOUND_REFERENCE] = single_rd;
4825
4826
2.44M
      if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
4827
1.93M
        best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
4828
2.44M
    }
4829
4830
    /* keep record of best filter type */
4831
4.68M
    if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
4832
4.68M
        cm->interp_filter != BILINEAR) {
4833
2.44M
      int64_t ref =
4834
2.44M
          filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
4835
2.44M
                                                       : cm->interp_filter];
4836
2.44M
      int64_t adj_rd;
4837
12.2M
      for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4838
9.79M
        if (ref == INT64_MAX)
4839
9.79M
          adj_rd = 0;
4840
0
        else if (filter_cache[i] == INT64_MAX)
4841
          // when early termination is triggered, the encoder does not have
4842
          // access to the rate-distortion cost. it only knows that the cost
4843
          // should be above the maximum valid value. hence it takes the known
4844
          // maximum plus an arbitrary constant as the rate-distortion cost.
4845
0
          adj_rd = mask_filter - ref + 10;
4846
0
        else
4847
0
          adj_rd = filter_cache[i] - ref;
4848
4849
9.79M
        adj_rd += this_rd;
4850
9.79M
        best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
4851
9.79M
      }
4852
2.44M
    }
4853
4854
4.68M
    if (early_term) break;
4855
4856
4.68M
    if (x->skip && !comp_pred) break;
4857
4.68M
  }
4858
4859
3.02M
  if (best_rd >= best_rd_so_far) {
4860
1.86M
    rd_cost->rate = INT_MAX;
4861
1.86M
    rd_cost->rdcost = INT64_MAX;
4862
1.86M
    return;
4863
1.86M
  }
4864
4865
  // If we used an estimate for the uv intra rd in the loop above...
4866
1.16M
  if (sf->use_uv_intra_rd_estimate) {
4867
    // Do Intra UV best rd mode selection if best mode choice above was intra.
4868
0
    if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
4869
0
      *mi = best_mbmode;
4870
0
      rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra, &rate_uv_tokenonly,
4871
0
                              &dist_uv, &skip_uv, BLOCK_8X8, TX_4X4);
4872
0
    }
4873
0
  }
4874
4875
1.16M
  if (best_rd == INT64_MAX) {
4876
0
    rd_cost->rate = INT_MAX;
4877
0
    rd_cost->dist = INT64_MAX;
4878
0
    rd_cost->rdcost = INT64_MAX;
4879
0
    return;
4880
0
  }
4881
4882
1.16M
  assert((cm->interp_filter == SWITCHABLE) ||
4883
1.16M
         (cm->interp_filter == best_mbmode.interp_filter) ||
4884
1.16M
         !is_inter_block(&best_mbmode));
4885
4886
1.16M
  vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact, sf->adaptive_rd_thresh,
4887
1.16M
                            bsize, best_ref_index);
4888
4889
  // macroblock modes
4890
1.16M
  *mi = best_mbmode;
4891
1.16M
  x->skip |= best_skip2;
4892
1.16M
  if (!is_inter_block(&best_mbmode)) {
4893
4.11M
    for (i = 0; i < 4; i++) xd->mi[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
4894
822k
  } else {
4895
1.69M
    for (i = 0; i < 4; ++i) xd->mi[0]->bmi[i] = best_bmodes[i];
4896
4897
338k
    mi->mv[0].as_int = xd->mi[0]->bmi[3].as_mv[0].as_int;
4898
338k
    mi->mv[1].as_int = xd->mi[0]->bmi[3].as_mv[1].as_int;
4899
338k
  }
4900
  // If the second reference does not exist, set the corresponding mv to zero.
4901
1.16M
  if (mi->ref_frame[1] == NO_REF_FRAME) {
4902
1.16M
    mi->mv[1].as_int = 0;
4903
5.80M
    for (i = 0; i < 4; ++i) {
4904
4.64M
      mi->bmi[i].as_mv[1].as_int = 0;
4905
4.64M
    }
4906
1.16M
  }
4907
4908
4.64M
  for (i = 0; i < REFERENCE_MODES; ++i) {
4909
3.48M
    if (best_pred_rd[i] == INT64_MAX)
4910
158k
      best_pred_diff[i] = INT_MIN;
4911
3.32M
    else
4912
3.32M
      best_pred_diff[i] = best_rd - best_pred_rd[i];
4913
3.48M
  }
4914
4915
1.16M
  if (!x->skip) {
4916
5.71M
    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4917
4.56M
      if (best_filter_rd[i] == INT64_MAX)
4918
0
        best_filter_diff[i] = 0;
4919
4.56M
      else
4920
4.56M
        best_filter_diff[i] = best_rd - best_filter_rd[i];
4921
4.56M
    }
4922
1.14M
    if (cm->interp_filter == SWITCHABLE)
4923
644k
      assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
4924
1.14M
  } else {
4925
18.7k
    vp9_zero(best_filter_diff);
4926
18.7k
  }
4927
4928
1.16M
  store_coding_context(x, ctx, best_ref_index, best_pred_diff, best_filter_diff,
4929
1.16M
                       0);
4930
1.16M
}
4931
#endif  // !CONFIG_REALTIME_ONLY