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