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 assert(!x->skip_block);
1112
1113 #if CONFIG_VP9_HIGHBITDEPTH
1114 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1115 for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1116 int64_t this_rd;
1117 int ratey = 0;
1118 int64_t distortion = 0;
1119 int rate = bmode_costs[mode];
1120
1121 if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
1122
1123 // Only do the oblique modes if the best so far is
1124 // one of the neighboring directional modes
1125 if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
1126 if (conditional_skipintra(mode, *best_mode)) continue;
1127 }
1128
1129 memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
1130 memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
1131
1132 for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
1133 for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
1134 const int block = (row + idy) * 2 + (col + idx);
1135 const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
1136 uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
1137 uint16_t *const dst16 = CONVERT_TO_SHORTPTR(dst);
1138 int16_t *const src_diff =
1139 vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
1140 tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
1141 tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
1142 tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
1143 uint16_t *const eob = &p->eobs[block];
1144 xd->mi[0]->bmi[block].as_mode = mode;
1145 vp9_predict_intra_block(xd, 1, TX_4X4, mode,
1146 x->skip_encode ? src : dst,
1147 x->skip_encode ? src_stride : dst_stride, dst,
1148 dst_stride, col + idx, row + idy, 0);
1149 vpx_highbd_subtract_block(4, 4, src_diff, 8, src, src_stride, dst,
1150 dst_stride, xd->bd);
1151 if (xd->lossless) {
1152 const scan_order *so = &vp9_default_scan_orders[TX_4X4];
1153 const int coeff_ctx =
1154 combine_entropy_contexts(tempa[idx], templ[idy]);
1155 vp9_highbd_fwht4x4(src_diff, coeff, 8);
1156 vpx_highbd_quantize_b(coeff, 4 * 4, p->zbin, p->round, p->quant,
1157 p->quant_shift, qcoeff, dqcoeff, pd->dequant,
1158 eob, so->scan, so->iscan);
1159 ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1160 so->neighbors, cpi->sf.use_fast_coef_costing);
1161 tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
1162 if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1163 goto next_highbd;
1164 vp9_highbd_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst16,
1165 dst_stride, p->eobs[block], xd->bd);
1166 } else {
1167 int64_t unused;
1168 const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
1169 const scan_order *so = &vp9_scan_orders[TX_4X4][tx_type];
1170 const int coeff_ctx =
1171 combine_entropy_contexts(tempa[idx], templ[idy]);
1172 if (tx_type == DCT_DCT)
1173 vpx_highbd_fdct4x4(src_diff, coeff, 8);
1174 else
1175 vp9_highbd_fht4x4(src_diff, coeff, 8, tx_type);
1176 vpx_highbd_quantize_b(coeff, 4 * 4, p->zbin, p->round, p->quant,
1177 p->quant_shift, qcoeff, dqcoeff, pd->dequant,
1178 eob, so->scan, so->iscan);
1179 ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1180 so->neighbors, cpi->sf.use_fast_coef_costing);
1181 distortion += vp9_highbd_block_error_dispatch(
1182 coeff, BLOCK_OFFSET(pd->dqcoeff, block), 16,
1183 &unused, xd->bd) >>
1184 2;
1185 tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
1186 if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1187 goto next_highbd;
1188 vp9_highbd_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block),
1189 dst16, dst_stride, p->eobs[block], xd->bd);
1190 }
1191 }
1192 }
1193
1194 rate += ratey;
1195 this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1196
1197 if (this_rd < best_rd) {
1198 *bestrate = rate;
1199 *bestratey = ratey;
1200 *bestdistortion = distortion;
1201 best_rd = this_rd;
1202 *best_mode = mode;
1203 memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
1204 memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
1205 for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
1206 memcpy(best_dst16 + idy * 8,
1207 CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
1208 num_4x4_blocks_wide * 4 * sizeof(uint16_t));
1209 }
1210 }
1211 next_highbd : {}
1212 }
1213 if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
1214
1215 for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
1216 memcpy(CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
1217 best_dst16 + idy * 8, num_4x4_blocks_wide * 4 * sizeof(uint16_t));
1218 }
1219
1220 return best_rd;
1221 }
1222 #endif // CONFIG_VP9_HIGHBITDEPTH
1223
1224 for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1225 int64_t this_rd;
1226 int ratey = 0;
1227 int64_t distortion = 0;
1228 int rate = bmode_costs[mode];
1229
1230 if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
1231
1232 // Only do the oblique modes if the best so far is
1233 // one of the neighboring directional modes
1234 if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
1235 if (conditional_skipintra(mode, *best_mode)) continue;
1236 }
1237
1238 memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
1239 memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
1240
1241 for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
1242 for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
1243 const int block = (row + idy) * 2 + (col + idx);
1244 const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
1245 uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
1246 int16_t *const src_diff =
1247 vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
1248 tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
1249 tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
1250 tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
1251 uint16_t *const eob = &p->eobs[block];
1252 xd->mi[0]->bmi[block].as_mode = mode;
1253 vp9_predict_intra_block(xd, 1, TX_4X4, mode, x->skip_encode ? src : dst,
1254 x->skip_encode ? src_stride : dst_stride, dst,
1255 dst_stride, col + idx, row + idy, 0);
1256 vpx_subtract_block(4, 4, src_diff, 8, src, src_stride, dst, dst_stride);
1257
1258 if (xd->lossless) {
1259 const scan_order *so = &vp9_default_scan_orders[TX_4X4];
1260 const int coeff_ctx =
1261 combine_entropy_contexts(tempa[idx], templ[idy]);
1262 vp9_fwht4x4(src_diff, coeff, 8);
1263 vpx_quantize_b(coeff, 4 * 4, p->zbin, p->round, p->quant,
1264 p->quant_shift, qcoeff, dqcoeff, pd->dequant, eob,
1265 so->scan, so->iscan);
1266 ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1267 so->neighbors, cpi->sf.use_fast_coef_costing);
1268 tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
1269 if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1270 goto next;
1271 vp9_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst, dst_stride,
1272 p->eobs[block]);
1273 } else {
1274 int64_t unused;
1275 const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
1276 const scan_order *so = &vp9_scan_orders[TX_4X4][tx_type];
1277 const int coeff_ctx =
1278 combine_entropy_contexts(tempa[idx], templ[idy]);
1279 vp9_fht4x4(src_diff, coeff, 8, tx_type);
1280 vpx_quantize_b(coeff, 4 * 4, p->zbin, p->round, p->quant,
1281 p->quant_shift, qcoeff, dqcoeff, pd->dequant, eob,
1282 so->scan, so->iscan);
1283 ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
1284 so->neighbors, cpi->sf.use_fast_coef_costing);
1285 tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
1286 distortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, block),
1287 16, &unused) >>
1288 2;
1289 if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
1290 goto next;
1291 vp9_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block), dst,
1292 dst_stride, p->eobs[block]);
1293 }
1294 }
1295 }
1296
1297 rate += ratey;
1298 this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
1299
1300 if (this_rd < best_rd) {
1301 *bestrate = rate;
1302 *bestratey = ratey;
1303 *bestdistortion = distortion;
1304 best_rd = this_rd;
1305 *best_mode = mode;
1306 memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
1307 memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
1308 for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
1309 memcpy(best_dst + idy * 8, dst_init + idy * dst_stride,
1310 num_4x4_blocks_wide * 4);
1311 }
1312 next : {}
1313 }
1314
1315 if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
1316
1317 for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
1318 memcpy(dst_init + idy * dst_stride, best_dst + idy * 8,
1319 num_4x4_blocks_wide * 4);
1320
1321 return best_rd;
1322 }
1323
rd_pick_intra_sub_8x8_y_mode(VP9_COMP * cpi,MACROBLOCK * mb,int * rate,int * rate_y,int64_t * distortion,int64_t best_rd)1324 static int64_t rd_pick_intra_sub_8x8_y_mode(VP9_COMP *cpi, MACROBLOCK *mb,
1325 int *rate, int *rate_y,
1326 int64_t *distortion,
1327 int64_t best_rd) {
1328 int i, j;
1329 const MACROBLOCKD *const xd = &mb->e_mbd;
1330 MODE_INFO *const mic = xd->mi[0];
1331 const MODE_INFO *above_mi = xd->above_mi;
1332 const MODE_INFO *left_mi = xd->left_mi;
1333 const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
1334 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1335 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1336 int idx, idy;
1337 int cost = 0;
1338 int64_t total_distortion = 0;
1339 int tot_rate_y = 0;
1340 int64_t total_rd = 0;
1341 const int *bmode_costs = cpi->mbmode_cost;
1342
1343 // Pick modes for each sub-block (of size 4x4, 4x8, or 8x4) in an 8x8 block.
1344 for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
1345 for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
1346 PREDICTION_MODE best_mode = DC_PRED;
1347 int r = INT_MAX, ry = INT_MAX;
1348 int64_t d = INT64_MAX, this_rd = INT64_MAX;
1349 i = idy * 2 + idx;
1350 if (cpi->common.frame_type == KEY_FRAME) {
1351 const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, i);
1352 const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, i);
1353
1354 bmode_costs = cpi->y_mode_costs[A][L];
1355 }
1356
1357 this_rd = rd_pick_intra4x4block(
1358 cpi, mb, idy, idx, &best_mode, bmode_costs,
1359 xd->plane[0].above_context + idx, xd->plane[0].left_context + idy, &r,
1360 &ry, &d, bsize, best_rd - total_rd);
1361
1362 if (this_rd >= best_rd - total_rd) return INT64_MAX;
1363
1364 total_rd += this_rd;
1365 cost += r;
1366 total_distortion += d;
1367 tot_rate_y += ry;
1368
1369 mic->bmi[i].as_mode = best_mode;
1370 for (j = 1; j < num_4x4_blocks_high; ++j)
1371 mic->bmi[i + j * 2].as_mode = best_mode;
1372 for (j = 1; j < num_4x4_blocks_wide; ++j)
1373 mic->bmi[i + j].as_mode = best_mode;
1374
1375 if (total_rd >= best_rd) return INT64_MAX;
1376 }
1377 }
1378
1379 *rate = cost;
1380 *rate_y = tot_rate_y;
1381 *distortion = total_distortion;
1382 mic->mode = mic->bmi[3].as_mode;
1383
1384 return RDCOST(mb->rdmult, mb->rddiv, cost, total_distortion);
1385 }
1386
1387 // 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)1388 static int64_t rd_pick_intra_sby_mode(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1389 int *rate_tokenonly, int64_t *distortion,
1390 int *skippable, BLOCK_SIZE bsize,
1391 int64_t best_rd) {
1392 PREDICTION_MODE mode;
1393 PREDICTION_MODE mode_selected = DC_PRED;
1394 MACROBLOCKD *const xd = &x->e_mbd;
1395 MODE_INFO *const mic = xd->mi[0];
1396 int this_rate, this_rate_tokenonly, s;
1397 int64_t this_distortion, this_rd;
1398 TX_SIZE best_tx = TX_4X4;
1399 int *bmode_costs;
1400 const MODE_INFO *above_mi = xd->above_mi;
1401 const MODE_INFO *left_mi = xd->left_mi;
1402 const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0);
1403 const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
1404 bmode_costs = cpi->y_mode_costs[A][L];
1405
1406 memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1407 /* Y Search for intra prediction mode */
1408 for (mode = DC_PRED; mode <= TM_PRED; mode++) {
1409 if (cpi->sf.use_nonrd_pick_mode) {
1410 // These speed features are turned on in hybrid non-RD and RD mode
1411 // for key frame coding in the context of real-time setting.
1412 if (conditional_skipintra(mode, mode_selected)) continue;
1413 if (*skippable) break;
1414 }
1415
1416 mic->mode = mode;
1417
1418 super_block_yrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s, NULL,
1419 bsize, best_rd, /*recon = */ 0);
1420
1421 if (this_rate_tokenonly == INT_MAX) continue;
1422
1423 this_rate = this_rate_tokenonly + bmode_costs[mode];
1424 this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
1425
1426 if (this_rd < best_rd) {
1427 mode_selected = mode;
1428 best_rd = this_rd;
1429 best_tx = mic->tx_size;
1430 *rate = this_rate;
1431 *rate_tokenonly = this_rate_tokenonly;
1432 *distortion = this_distortion;
1433 *skippable = s;
1434 }
1435 }
1436
1437 mic->mode = mode_selected;
1438 mic->tx_size = best_tx;
1439
1440 return best_rd;
1441 }
1442
1443 // Return value 0: early termination triggered, no valid rd cost available;
1444 // 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)1445 static int super_block_uvrd(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1446 int64_t *distortion, int *skippable, int64_t *sse,
1447 BLOCK_SIZE bsize, int64_t ref_best_rd) {
1448 MACROBLOCKD *const xd = &x->e_mbd;
1449 MODE_INFO *const mi = xd->mi[0];
1450 const TX_SIZE uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
1451 int plane;
1452 int pnrate = 0, pnskip = 1;
1453 int64_t pndist = 0, pnsse = 0;
1454 int is_cost_valid = 1;
1455
1456 if (ref_best_rd < 0) is_cost_valid = 0;
1457
1458 if (is_inter_block(mi) && is_cost_valid) {
1459 int plane;
1460 for (plane = 1; plane < MAX_MB_PLANE; ++plane)
1461 vp9_subtract_plane(x, bsize, plane);
1462 }
1463
1464 *rate = 0;
1465 *distortion = 0;
1466 *sse = 0;
1467 *skippable = 1;
1468
1469 for (plane = 1; plane < MAX_MB_PLANE; ++plane) {
1470 txfm_rd_in_plane(cpi, x, &pnrate, &pndist, &pnskip, &pnsse, ref_best_rd,
1471 plane, bsize, uv_tx_size, cpi->sf.use_fast_coef_costing,
1472 /*recon = */ 0);
1473 if (pnrate == INT_MAX) {
1474 is_cost_valid = 0;
1475 break;
1476 }
1477 *rate += pnrate;
1478 *distortion += pndist;
1479 *sse += pnsse;
1480 *skippable &= pnskip;
1481 }
1482
1483 if (!is_cost_valid) {
1484 // reset cost value
1485 *rate = INT_MAX;
1486 *distortion = INT64_MAX;
1487 *sse = INT64_MAX;
1488 *skippable = 0;
1489 }
1490
1491 return is_cost_valid;
1492 }
1493
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)1494 static int64_t rd_pick_intra_sbuv_mode(VP9_COMP *cpi, MACROBLOCK *x,
1495 PICK_MODE_CONTEXT *ctx, int *rate,
1496 int *rate_tokenonly, int64_t *distortion,
1497 int *skippable, BLOCK_SIZE bsize,
1498 TX_SIZE max_tx_size) {
1499 MACROBLOCKD *xd = &x->e_mbd;
1500 PREDICTION_MODE mode;
1501 PREDICTION_MODE mode_selected = DC_PRED;
1502 int64_t best_rd = INT64_MAX, this_rd;
1503 int this_rate_tokenonly, this_rate, s;
1504 int64_t this_distortion, this_sse;
1505
1506 memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1507 for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
1508 if (!(cpi->sf.intra_uv_mode_mask[max_tx_size] & (1 << mode))) continue;
1509 #if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
1510 if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
1511 (xd->above_mi == NULL || xd->left_mi == NULL) && need_top_left[mode])
1512 continue;
1513 #endif // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
1514
1515 xd->mi[0]->uv_mode = mode;
1516
1517 if (!super_block_uvrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s,
1518 &this_sse, bsize, best_rd))
1519 continue;
1520 this_rate =
1521 this_rate_tokenonly +
1522 cpi->intra_uv_mode_cost[cpi->common.frame_type][xd->mi[0]->mode][mode];
1523 this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
1524
1525 if (this_rd < best_rd) {
1526 mode_selected = mode;
1527 best_rd = this_rd;
1528 *rate = this_rate;
1529 *rate_tokenonly = this_rate_tokenonly;
1530 *distortion = this_distortion;
1531 *skippable = s;
1532 if (!x->select_tx_size) swap_block_ptr(x, ctx, 2, 0, 1, MAX_MB_PLANE);
1533 }
1534 }
1535
1536 xd->mi[0]->uv_mode = mode_selected;
1537 return best_rd;
1538 }
1539
1540 #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)1541 static int64_t rd_sbuv_dcpred(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
1542 int *rate_tokenonly, int64_t *distortion,
1543 int *skippable, BLOCK_SIZE bsize) {
1544 const VP9_COMMON *cm = &cpi->common;
1545 int64_t unused;
1546
1547 x->e_mbd.mi[0]->uv_mode = DC_PRED;
1548 memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
1549 super_block_uvrd(cpi, x, rate_tokenonly, distortion, skippable, &unused,
1550 bsize, INT64_MAX);
1551 *rate =
1552 *rate_tokenonly +
1553 cpi->intra_uv_mode_cost[cm->frame_type][x->e_mbd.mi[0]->mode][DC_PRED];
1554 return RDCOST(x->rdmult, x->rddiv, *rate, *distortion);
1555 }
1556
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)1557 static void choose_intra_uv_mode(VP9_COMP *cpi, MACROBLOCK *const x,
1558 PICK_MODE_CONTEXT *ctx, BLOCK_SIZE bsize,
1559 TX_SIZE max_tx_size, int *rate_uv,
1560 int *rate_uv_tokenonly, int64_t *dist_uv,
1561 int *skip_uv, PREDICTION_MODE *mode_uv) {
1562 // Use an estimated rd for uv_intra based on DC_PRED if the
1563 // appropriate speed flag is set.
1564 if (cpi->sf.use_uv_intra_rd_estimate) {
1565 rd_sbuv_dcpred(cpi, x, rate_uv, rate_uv_tokenonly, dist_uv, skip_uv,
1566 bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize);
1567 // Else do a proper rd search for each possible transform size that may
1568 // be considered in the main rd loop.
1569 } else {
1570 rd_pick_intra_sbuv_mode(cpi, x, ctx, rate_uv, rate_uv_tokenonly, dist_uv,
1571 skip_uv, bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
1572 max_tx_size);
1573 }
1574 *mode_uv = x->e_mbd.mi[0]->uv_mode;
1575 }
1576
cost_mv_ref(const VP9_COMP * cpi,PREDICTION_MODE mode,int mode_context)1577 static int cost_mv_ref(const VP9_COMP *cpi, PREDICTION_MODE mode,
1578 int mode_context) {
1579 assert(is_inter_mode(mode));
1580 return cpi->inter_mode_cost[mode_context][INTER_OFFSET(mode)];
1581 }
1582
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])1583 static int set_and_cost_bmi_mvs(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
1584 int i, PREDICTION_MODE mode, int_mv this_mv[2],
1585 int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1586 int_mv seg_mvs[MAX_REF_FRAMES],
1587 int_mv *best_ref_mv[2], const int *mvjcost,
1588 int *mvcost[2]) {
1589 MODE_INFO *const mi = xd->mi[0];
1590 const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
1591 int thismvcost = 0;
1592 int idx, idy;
1593 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[mi->sb_type];
1594 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[mi->sb_type];
1595 const int is_compound = has_second_ref(mi);
1596
1597 switch (mode) {
1598 case NEWMV:
1599 this_mv[0].as_int = seg_mvs[mi->ref_frame[0]].as_int;
1600 thismvcost += vp9_mv_bit_cost(&this_mv[0].as_mv, &best_ref_mv[0]->as_mv,
1601 mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1602 if (is_compound) {
1603 this_mv[1].as_int = seg_mvs[mi->ref_frame[1]].as_int;
1604 thismvcost += vp9_mv_bit_cost(&this_mv[1].as_mv, &best_ref_mv[1]->as_mv,
1605 mvjcost, mvcost, MV_COST_WEIGHT_SUB);
1606 }
1607 break;
1608 case NEARMV:
1609 case NEARESTMV:
1610 this_mv[0].as_int = frame_mv[mode][mi->ref_frame[0]].as_int;
1611 if (is_compound)
1612 this_mv[1].as_int = frame_mv[mode][mi->ref_frame[1]].as_int;
1613 break;
1614 default:
1615 assert(mode == ZEROMV);
1616 this_mv[0].as_int = 0;
1617 if (is_compound) this_mv[1].as_int = 0;
1618 break;
1619 }
1620
1621 mi->bmi[i].as_mv[0].as_int = this_mv[0].as_int;
1622 if (is_compound) mi->bmi[i].as_mv[1].as_int = this_mv[1].as_int;
1623
1624 mi->bmi[i].as_mode = mode;
1625
1626 for (idy = 0; idy < num_4x4_blocks_high; ++idy)
1627 for (idx = 0; idx < num_4x4_blocks_wide; ++idx)
1628 memmove(&mi->bmi[i + idy * 2 + idx], &mi->bmi[i], sizeof(mi->bmi[i]));
1629
1630 return cost_mv_ref(cpi, mode, mbmi_ext->mode_context[mi->ref_frame[0]]) +
1631 thismvcost;
1632 }
1633
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)1634 static int64_t encode_inter_mb_segment(VP9_COMP *cpi, MACROBLOCK *x,
1635 int64_t best_yrd, int i, int *labelyrate,
1636 int64_t *distortion, int64_t *sse,
1637 ENTROPY_CONTEXT *ta, ENTROPY_CONTEXT *tl,
1638 int mi_row, int mi_col) {
1639 int k;
1640 MACROBLOCKD *xd = &x->e_mbd;
1641 struct macroblockd_plane *const pd = &xd->plane[0];
1642 struct macroblock_plane *const p = &x->plane[0];
1643 MODE_INFO *const mi = xd->mi[0];
1644 const BLOCK_SIZE plane_bsize = get_plane_block_size(mi->sb_type, pd);
1645 const int width = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
1646 const int height = 4 * num_4x4_blocks_high_lookup[plane_bsize];
1647 int idx, idy;
1648
1649 const uint8_t *const src =
1650 &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1651 uint8_t *const dst =
1652 &pd->dst.buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->dst.stride)];
1653 int64_t thisdistortion = 0, thissse = 0;
1654 int thisrate = 0, ref;
1655 const scan_order *so = &vp9_default_scan_orders[TX_4X4];
1656 const int is_compound = has_second_ref(mi);
1657 const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
1658
1659 assert(!x->skip_block);
1660
1661 for (ref = 0; ref < 1 + is_compound; ++ref) {
1662 const int bw = b_width_log2_lookup[BLOCK_8X8];
1663 const int h = 4 * (i >> bw);
1664 const int w = 4 * (i & ((1 << bw) - 1));
1665 const struct scale_factors *sf = &xd->block_refs[ref]->sf;
1666 int y_stride = pd->pre[ref].stride;
1667 uint8_t *pre = pd->pre[ref].buf + (h * pd->pre[ref].stride + w);
1668
1669 if (vp9_is_scaled(sf)) {
1670 const int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
1671 const int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
1672
1673 y_stride = xd->block_refs[ref]->buf->y_stride;
1674 pre = xd->block_refs[ref]->buf->y_buffer;
1675 pre += scaled_buffer_offset(x_start + w, y_start + h, y_stride, sf);
1676 }
1677 #if CONFIG_VP9_HIGHBITDEPTH
1678 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1679 vp9_highbd_build_inter_predictor(
1680 CONVERT_TO_SHORTPTR(pre), y_stride, CONVERT_TO_SHORTPTR(dst),
1681 pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1682 &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1683 mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2),
1684 xd->bd);
1685 } else {
1686 vp9_build_inter_predictor(
1687 pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1688 &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1689 mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
1690 }
1691 #else
1692 vp9_build_inter_predictor(
1693 pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
1694 &xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
1695 mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
1696 #endif // CONFIG_VP9_HIGHBITDEPTH
1697 }
1698
1699 #if CONFIG_VP9_HIGHBITDEPTH
1700 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1701 vpx_highbd_subtract_block(
1702 height, width, vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1703 8, src, p->src.stride, dst, pd->dst.stride, xd->bd);
1704 } else {
1705 vpx_subtract_block(height, width,
1706 vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1707 8, src, p->src.stride, dst, pd->dst.stride);
1708 }
1709 #else
1710 vpx_subtract_block(height, width,
1711 vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
1712 8, src, p->src.stride, dst, pd->dst.stride);
1713 #endif // CONFIG_VP9_HIGHBITDEPTH
1714
1715 k = i;
1716 for (idy = 0; idy < height / 4; ++idy) {
1717 for (idx = 0; idx < width / 4; ++idx) {
1718 #if CONFIG_VP9_HIGHBITDEPTH
1719 const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
1720 #endif
1721 int64_t ssz, rd, rd1, rd2;
1722 tran_low_t *coeff, *qcoeff, *dqcoeff;
1723 uint16_t *eob;
1724 int coeff_ctx;
1725 k += (idy * 2 + idx);
1726 coeff_ctx = combine_entropy_contexts(ta[k & 1], tl[k >> 1]);
1727 coeff = BLOCK_OFFSET(p->coeff, k);
1728 qcoeff = BLOCK_OFFSET(p->qcoeff, k);
1729 dqcoeff = BLOCK_OFFSET(pd->dqcoeff, k);
1730 eob = &p->eobs[k];
1731
1732 x->fwd_txfm4x4(vp9_raster_block_offset_int16(BLOCK_8X8, k, p->src_diff),
1733 coeff, 8);
1734 #if CONFIG_VP9_HIGHBITDEPTH
1735 vpx_highbd_quantize_b(coeff, 4 * 4, p->zbin, p->round, p->quant,
1736 p->quant_shift, qcoeff, dqcoeff, pd->dequant, eob,
1737 so->scan, so->iscan);
1738 thisdistortion += vp9_highbd_block_error_dispatch(
1739 coeff, BLOCK_OFFSET(pd->dqcoeff, k), 16, &ssz, bd);
1740 #else
1741 vpx_quantize_b(coeff, 4 * 4, p->zbin, p->round, p->quant, p->quant_shift,
1742 qcoeff, dqcoeff, pd->dequant, eob, so->scan, so->iscan);
1743 thisdistortion +=
1744 vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, k), 16, &ssz);
1745 #endif // CONFIG_VP9_HIGHBITDEPTH
1746 thissse += ssz;
1747 thisrate += cost_coeffs(x, 0, k, TX_4X4, coeff_ctx, so->scan,
1748 so->neighbors, cpi->sf.use_fast_coef_costing);
1749 ta[k & 1] = tl[k >> 1] = (x->plane[0].eobs[k] > 0) ? 1 : 0;
1750 rd1 = RDCOST(x->rdmult, x->rddiv, thisrate, thisdistortion >> 2);
1751 rd2 = RDCOST(x->rdmult, x->rddiv, 0, thissse >> 2);
1752 rd = VPXMIN(rd1, rd2);
1753 if (rd >= best_yrd) return INT64_MAX;
1754 }
1755 }
1756
1757 *distortion = thisdistortion >> 2;
1758 *labelyrate = thisrate;
1759 *sse = thissse >> 2;
1760
1761 return RDCOST(x->rdmult, x->rddiv, *labelyrate, *distortion);
1762 }
1763 #endif // !CONFIG_REALTIME_ONLY
1764
1765 typedef struct {
1766 int eobs;
1767 int brate;
1768 int byrate;
1769 int64_t bdist;
1770 int64_t bsse;
1771 int64_t brdcost;
1772 int_mv mvs[2];
1773 ENTROPY_CONTEXT ta[2];
1774 ENTROPY_CONTEXT tl[2];
1775 } SEG_RDSTAT;
1776
1777 typedef struct {
1778 int_mv *ref_mv[2];
1779 int_mv mvp;
1780
1781 int64_t segment_rd;
1782 int r;
1783 int64_t d;
1784 int64_t sse;
1785 int segment_yrate;
1786 PREDICTION_MODE modes[4];
1787 SEG_RDSTAT rdstat[4][INTER_MODES];
1788 int mvthresh;
1789 } BEST_SEG_INFO;
1790
1791 #if !CONFIG_REALTIME_ONLY
mv_check_bounds(const MvLimits * mv_limits,const MV * mv)1792 static INLINE int mv_check_bounds(const MvLimits *mv_limits, const MV *mv) {
1793 return (mv->row >> 3) < mv_limits->row_min ||
1794 (mv->row >> 3) > mv_limits->row_max ||
1795 (mv->col >> 3) < mv_limits->col_min ||
1796 (mv->col >> 3) > mv_limits->col_max;
1797 }
1798
mi_buf_shift(MACROBLOCK * x,int i)1799 static INLINE void mi_buf_shift(MACROBLOCK *x, int i) {
1800 MODE_INFO *const mi = x->e_mbd.mi[0];
1801 struct macroblock_plane *const p = &x->plane[0];
1802 struct macroblockd_plane *const pd = &x->e_mbd.plane[0];
1803
1804 p->src.buf =
1805 &p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
1806 assert(((intptr_t)pd->pre[0].buf & 0x7) == 0);
1807 pd->pre[0].buf =
1808 &pd->pre[0].buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[0].stride)];
1809 if (has_second_ref(mi))
1810 pd->pre[1].buf =
1811 &pd->pre[1]
1812 .buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[1].stride)];
1813 }
1814
mi_buf_restore(MACROBLOCK * x,struct buf_2d orig_src,struct buf_2d orig_pre[2])1815 static INLINE void mi_buf_restore(MACROBLOCK *x, struct buf_2d orig_src,
1816 struct buf_2d orig_pre[2]) {
1817 MODE_INFO *mi = x->e_mbd.mi[0];
1818 x->plane[0].src = orig_src;
1819 x->e_mbd.plane[0].pre[0] = orig_pre[0];
1820 if (has_second_ref(mi)) x->e_mbd.plane[0].pre[1] = orig_pre[1];
1821 }
1822
mv_has_subpel(const MV * mv)1823 static INLINE int mv_has_subpel(const MV *mv) {
1824 return (mv->row & 0x0F) || (mv->col & 0x0F);
1825 }
1826
1827 // Check if NEARESTMV/NEARMV/ZEROMV is the cheapest way encode zero motion.
1828 // 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])1829 static int check_best_zero_mv(const VP9_COMP *cpi,
1830 const uint8_t mode_context[MAX_REF_FRAMES],
1831 int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
1832 int this_mode,
1833 const MV_REFERENCE_FRAME ref_frames[2]) {
1834 if ((this_mode == NEARMV || this_mode == NEARESTMV || this_mode == ZEROMV) &&
1835 frame_mv[this_mode][ref_frames[0]].as_int == 0 &&
1836 (ref_frames[1] == NONE ||
1837 frame_mv[this_mode][ref_frames[1]].as_int == 0)) {
1838 int rfc = mode_context[ref_frames[0]];
1839 int c1 = cost_mv_ref(cpi, NEARMV, rfc);
1840 int c2 = cost_mv_ref(cpi, NEARESTMV, rfc);
1841 int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
1842
1843 if (this_mode == NEARMV) {
1844 if (c1 > c3) return 0;
1845 } else if (this_mode == NEARESTMV) {
1846 if (c2 > c3) return 0;
1847 } else {
1848 assert(this_mode == ZEROMV);
1849 if (ref_frames[1] == NONE) {
1850 if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0) ||
1851 (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0))
1852 return 0;
1853 } else {
1854 if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0 &&
1855 frame_mv[NEARESTMV][ref_frames[1]].as_int == 0) ||
1856 (c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0 &&
1857 frame_mv[NEARMV][ref_frames[1]].as_int == 0))
1858 return 0;
1859 }
1860 }
1861 }
1862 return 1;
1863 }
1864
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)1865 static void joint_motion_search(VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
1866 int_mv *frame_mv, int mi_row, int mi_col,
1867 int_mv single_newmv[MAX_REF_FRAMES],
1868 int *rate_mv) {
1869 const VP9_COMMON *const cm = &cpi->common;
1870 const int pw = 4 * num_4x4_blocks_wide_lookup[bsize];
1871 const int ph = 4 * num_4x4_blocks_high_lookup[bsize];
1872 MACROBLOCKD *xd = &x->e_mbd;
1873 MODE_INFO *mi = xd->mi[0];
1874 const int refs[2] = { mi->ref_frame[0],
1875 mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1] };
1876 int_mv ref_mv[2];
1877 int ite, ref;
1878 const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
1879 struct scale_factors sf;
1880
1881 // Do joint motion search in compound mode to get more accurate mv.
1882 struct buf_2d backup_yv12[2][MAX_MB_PLANE];
1883 uint32_t last_besterr[2] = { UINT_MAX, UINT_MAX };
1884 const YV12_BUFFER_CONFIG *const scaled_ref_frame[2] = {
1885 vp9_get_scaled_ref_frame(cpi, mi->ref_frame[0]),
1886 vp9_get_scaled_ref_frame(cpi, mi->ref_frame[1])
1887 };
1888
1889 // Prediction buffer from second frame.
1890 #if CONFIG_VP9_HIGHBITDEPTH
1891 DECLARE_ALIGNED(16, uint16_t, second_pred_alloc_16[64 * 64]);
1892 uint8_t *second_pred;
1893 #else
1894 DECLARE_ALIGNED(16, uint8_t, second_pred[64 * 64]);
1895 #endif // CONFIG_VP9_HIGHBITDEPTH
1896
1897 for (ref = 0; ref < 2; ++ref) {
1898 ref_mv[ref] = x->mbmi_ext->ref_mvs[refs[ref]][0];
1899
1900 if (scaled_ref_frame[ref]) {
1901 int i;
1902 // Swap out the reference frame for a version that's been scaled to
1903 // match the resolution of the current frame, allowing the existing
1904 // motion search code to be used without additional modifications.
1905 for (i = 0; i < MAX_MB_PLANE; i++)
1906 backup_yv12[ref][i] = xd->plane[i].pre[ref];
1907 vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
1908 NULL);
1909 }
1910
1911 frame_mv[refs[ref]].as_int = single_newmv[refs[ref]].as_int;
1912 }
1913
1914 // Since we have scaled the reference frames to match the size of the current
1915 // frame we must use a unit scaling factor during mode selection.
1916 #if CONFIG_VP9_HIGHBITDEPTH
1917 vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
1918 cm->height, cm->use_highbitdepth);
1919 #else
1920 vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
1921 cm->height);
1922 #endif // CONFIG_VP9_HIGHBITDEPTH
1923
1924 // Allow joint search multiple times iteratively for each reference frame
1925 // and break out of the search loop if it couldn't find a better mv.
1926 for (ite = 0; ite < 4; ite++) {
1927 struct buf_2d ref_yv12[2];
1928 uint32_t bestsme = UINT_MAX;
1929 int sadpb = x->sadperbit16;
1930 MV tmp_mv;
1931 int search_range = 3;
1932
1933 const MvLimits tmp_mv_limits = x->mv_limits;
1934 int id = ite % 2; // Even iterations search in the first reference frame,
1935 // odd iterations search in the second. The predictor
1936 // found for the 'other' reference frame is factored in.
1937
1938 // Initialized here because of compiler problem in Visual Studio.
1939 ref_yv12[0] = xd->plane[0].pre[0];
1940 ref_yv12[1] = xd->plane[0].pre[1];
1941
1942 // Get the prediction block from the 'other' reference frame.
1943 #if CONFIG_VP9_HIGHBITDEPTH
1944 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1945 second_pred = CONVERT_TO_BYTEPTR(second_pred_alloc_16);
1946 vp9_highbd_build_inter_predictor(
1947 CONVERT_TO_SHORTPTR(ref_yv12[!id].buf), ref_yv12[!id].stride,
1948 second_pred_alloc_16, pw, &frame_mv[refs[!id]].as_mv, &sf, pw, ph, 0,
1949 kernel, MV_PRECISION_Q3, mi_col * MI_SIZE, mi_row * MI_SIZE, xd->bd);
1950 } else {
1951 second_pred = (uint8_t *)second_pred_alloc_16;
1952 vp9_build_inter_predictor(ref_yv12[!id].buf, ref_yv12[!id].stride,
1953 second_pred, pw, &frame_mv[refs[!id]].as_mv,
1954 &sf, pw, ph, 0, kernel, MV_PRECISION_Q3,
1955 mi_col * MI_SIZE, mi_row * MI_SIZE);
1956 }
1957 #else
1958 vp9_build_inter_predictor(ref_yv12[!id].buf, ref_yv12[!id].stride,
1959 second_pred, pw, &frame_mv[refs[!id]].as_mv, &sf,
1960 pw, ph, 0, kernel, MV_PRECISION_Q3,
1961 mi_col * MI_SIZE, mi_row * MI_SIZE);
1962 #endif // CONFIG_VP9_HIGHBITDEPTH
1963
1964 // Do compound motion search on the current reference frame.
1965 if (id) xd->plane[0].pre[0] = ref_yv12[id];
1966 vp9_set_mv_search_range(&x->mv_limits, &ref_mv[id].as_mv);
1967
1968 // Use the mv result from the single mode as mv predictor.
1969 tmp_mv = frame_mv[refs[id]].as_mv;
1970
1971 tmp_mv.col >>= 3;
1972 tmp_mv.row >>= 3;
1973
1974 // Small-range full-pixel motion search.
1975 bestsme = vp9_refining_search_8p_c(x, &tmp_mv, sadpb, search_range,
1976 &cpi->fn_ptr[bsize], &ref_mv[id].as_mv,
1977 second_pred);
1978 if (bestsme < UINT_MAX)
1979 bestsme = vp9_get_mvpred_av_var(x, &tmp_mv, &ref_mv[id].as_mv,
1980 second_pred, &cpi->fn_ptr[bsize], 1);
1981
1982 x->mv_limits = tmp_mv_limits;
1983
1984 if (bestsme < UINT_MAX) {
1985 uint32_t dis; /* TODO: use dis in distortion calculation later. */
1986 uint32_t sse;
1987 bestsme = cpi->find_fractional_mv_step(
1988 x, &tmp_mv, &ref_mv[id].as_mv, cpi->common.allow_high_precision_mv,
1989 x->errorperbit, &cpi->fn_ptr[bsize], 0,
1990 cpi->sf.mv.subpel_search_level, NULL, x->nmvjointcost, x->mvcost,
1991 &dis, &sse, second_pred, pw, ph, cpi->sf.use_accurate_subpel_search);
1992 }
1993
1994 // Restore the pointer to the first (possibly scaled) prediction buffer.
1995 if (id) xd->plane[0].pre[0] = ref_yv12[0];
1996
1997 if (bestsme < last_besterr[id]) {
1998 frame_mv[refs[id]].as_mv = tmp_mv;
1999 last_besterr[id] = bestsme;
2000 } else {
2001 break;
2002 }
2003 }
2004
2005 *rate_mv = 0;
2006
2007 for (ref = 0; ref < 2; ++ref) {
2008 if (scaled_ref_frame[ref]) {
2009 // Restore the prediction frame pointers to their unscaled versions.
2010 int i;
2011 for (i = 0; i < MAX_MB_PLANE; i++)
2012 xd->plane[i].pre[ref] = backup_yv12[ref][i];
2013 }
2014
2015 *rate_mv += vp9_mv_bit_cost(&frame_mv[refs[ref]].as_mv,
2016 &x->mbmi_ext->ref_mvs[refs[ref]][0].as_mv,
2017 x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2018 }
2019 }
2020
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)2021 static int64_t rd_pick_best_sub8x8_mode(
2022 VP9_COMP *cpi, MACROBLOCK *x, int_mv *best_ref_mv,
2023 int_mv *second_best_ref_mv, int64_t best_rd, int *returntotrate,
2024 int *returnyrate, int64_t *returndistortion, int *skippable, int64_t *psse,
2025 int mvthresh, int_mv seg_mvs[4][MAX_REF_FRAMES], BEST_SEG_INFO *bsi_buf,
2026 int filter_idx, int mi_row, int mi_col) {
2027 int i;
2028 BEST_SEG_INFO *bsi = bsi_buf + filter_idx;
2029 MACROBLOCKD *xd = &x->e_mbd;
2030 MODE_INFO *mi = xd->mi[0];
2031 int mode_idx;
2032 int k, br = 0, idx, idy;
2033 int64_t bd = 0, block_sse = 0;
2034 PREDICTION_MODE this_mode;
2035 VP9_COMMON *cm = &cpi->common;
2036 struct macroblock_plane *const p = &x->plane[0];
2037 struct macroblockd_plane *const pd = &xd->plane[0];
2038 const int label_count = 4;
2039 int64_t this_segment_rd = 0;
2040 int label_mv_thresh;
2041 int segmentyrate = 0;
2042 const BLOCK_SIZE bsize = mi->sb_type;
2043 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2044 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2045 const int pw = num_4x4_blocks_wide << 2;
2046 const int ph = num_4x4_blocks_high << 2;
2047 ENTROPY_CONTEXT t_above[2], t_left[2];
2048 int subpelmv = 1, have_ref = 0;
2049 SPEED_FEATURES *const sf = &cpi->sf;
2050 const int has_second_rf = has_second_ref(mi);
2051 const int inter_mode_mask = sf->inter_mode_mask[bsize];
2052 MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2053
2054 vp9_zero(*bsi);
2055
2056 bsi->segment_rd = best_rd;
2057 bsi->ref_mv[0] = best_ref_mv;
2058 bsi->ref_mv[1] = second_best_ref_mv;
2059 bsi->mvp.as_int = best_ref_mv->as_int;
2060 bsi->mvthresh = mvthresh;
2061
2062 for (i = 0; i < 4; i++) bsi->modes[i] = ZEROMV;
2063
2064 memcpy(t_above, pd->above_context, sizeof(t_above));
2065 memcpy(t_left, pd->left_context, sizeof(t_left));
2066
2067 // 64 makes this threshold really big effectively
2068 // making it so that we very rarely check mvs on
2069 // segments. setting this to 1 would make mv thresh
2070 // roughly equal to what it is for macroblocks
2071 label_mv_thresh = 1 * bsi->mvthresh / label_count;
2072
2073 // Segmentation method overheads
2074 for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
2075 for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
2076 // TODO(jingning,rbultje): rewrite the rate-distortion optimization
2077 // loop for 4x4/4x8/8x4 block coding. to be replaced with new rd loop
2078 int_mv mode_mv[MB_MODE_COUNT][2];
2079 int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
2080 PREDICTION_MODE mode_selected = ZEROMV;
2081 int64_t best_rd = INT64_MAX;
2082 const int i = idy * 2 + idx;
2083 int ref;
2084
2085 for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2086 const MV_REFERENCE_FRAME frame = mi->ref_frame[ref];
2087 frame_mv[ZEROMV][frame].as_int = 0;
2088 vp9_append_sub8x8_mvs_for_idx(
2089 cm, xd, i, ref, mi_row, mi_col, &frame_mv[NEARESTMV][frame],
2090 &frame_mv[NEARMV][frame], mbmi_ext->mode_context);
2091 }
2092
2093 // search for the best motion vector on this segment
2094 for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
2095 const struct buf_2d orig_src = x->plane[0].src;
2096 struct buf_2d orig_pre[2];
2097
2098 mode_idx = INTER_OFFSET(this_mode);
2099 bsi->rdstat[i][mode_idx].brdcost = INT64_MAX;
2100 if (!(inter_mode_mask & (1 << this_mode))) continue;
2101
2102 if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv,
2103 this_mode, mi->ref_frame))
2104 continue;
2105
2106 memcpy(orig_pre, pd->pre, sizeof(orig_pre));
2107 memcpy(bsi->rdstat[i][mode_idx].ta, t_above,
2108 sizeof(bsi->rdstat[i][mode_idx].ta));
2109 memcpy(bsi->rdstat[i][mode_idx].tl, t_left,
2110 sizeof(bsi->rdstat[i][mode_idx].tl));
2111
2112 // motion search for newmv (single predictor case only)
2113 if (!has_second_rf && this_mode == NEWMV &&
2114 seg_mvs[i][mi->ref_frame[0]].as_int == INVALID_MV) {
2115 MV *const new_mv = &mode_mv[NEWMV][0].as_mv;
2116 int step_param = 0;
2117 uint32_t bestsme = UINT_MAX;
2118 int sadpb = x->sadperbit4;
2119 MV mvp_full;
2120 int max_mv;
2121 int cost_list[5];
2122 const MvLimits tmp_mv_limits = x->mv_limits;
2123
2124 /* Is the best so far sufficiently good that we cant justify doing
2125 * and new motion search. */
2126 if (best_rd < label_mv_thresh) break;
2127
2128 if (cpi->oxcf.mode != BEST) {
2129 // use previous block's result as next block's MV predictor.
2130 if (i > 0) {
2131 bsi->mvp.as_int = mi->bmi[i - 1].as_mv[0].as_int;
2132 if (i == 2) bsi->mvp.as_int = mi->bmi[i - 2].as_mv[0].as_int;
2133 }
2134 }
2135 if (i == 0)
2136 max_mv = x->max_mv_context[mi->ref_frame[0]];
2137 else
2138 max_mv =
2139 VPXMAX(abs(bsi->mvp.as_mv.row), abs(bsi->mvp.as_mv.col)) >> 3;
2140
2141 if (sf->mv.auto_mv_step_size && cm->show_frame) {
2142 // Take wtd average of the step_params based on the last frame's
2143 // max mv magnitude and the best ref mvs of the current block for
2144 // the given reference.
2145 step_param =
2146 (vp9_init_search_range(max_mv) + cpi->mv_step_param) / 2;
2147 } else {
2148 step_param = cpi->mv_step_param;
2149 }
2150
2151 mvp_full.row = bsi->mvp.as_mv.row >> 3;
2152 mvp_full.col = bsi->mvp.as_mv.col >> 3;
2153
2154 if (sf->adaptive_motion_search) {
2155 if (x->pred_mv[mi->ref_frame[0]].row != INT16_MAX &&
2156 x->pred_mv[mi->ref_frame[0]].col != INT16_MAX) {
2157 mvp_full.row = x->pred_mv[mi->ref_frame[0]].row >> 3;
2158 mvp_full.col = x->pred_mv[mi->ref_frame[0]].col >> 3;
2159 }
2160 step_param = VPXMAX(step_param, 8);
2161 }
2162
2163 // adjust src pointer for this block
2164 mi_buf_shift(x, i);
2165
2166 vp9_set_mv_search_range(&x->mv_limits, &bsi->ref_mv[0]->as_mv);
2167
2168 bestsme = vp9_full_pixel_search(
2169 cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method,
2170 sadpb,
2171 sf->mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL,
2172 &bsi->ref_mv[0]->as_mv, new_mv, INT_MAX, 1);
2173
2174 x->mv_limits = tmp_mv_limits;
2175
2176 if (bestsme < UINT_MAX) {
2177 uint32_t distortion;
2178 cpi->find_fractional_mv_step(
2179 x, new_mv, &bsi->ref_mv[0]->as_mv, cm->allow_high_precision_mv,
2180 x->errorperbit, &cpi->fn_ptr[bsize], sf->mv.subpel_force_stop,
2181 sf->mv.subpel_search_level, cond_cost_list(cpi, cost_list),
2182 x->nmvjointcost, x->mvcost, &distortion,
2183 &x->pred_sse[mi->ref_frame[0]], NULL, pw, ph,
2184 cpi->sf.use_accurate_subpel_search);
2185
2186 // save motion search result for use in compound prediction
2187 seg_mvs[i][mi->ref_frame[0]].as_mv = *new_mv;
2188 }
2189
2190 x->pred_mv[mi->ref_frame[0]] = *new_mv;
2191
2192 // restore src pointers
2193 mi_buf_restore(x, orig_src, orig_pre);
2194 }
2195
2196 if (has_second_rf) {
2197 if (seg_mvs[i][mi->ref_frame[1]].as_int == INVALID_MV ||
2198 seg_mvs[i][mi->ref_frame[0]].as_int == INVALID_MV)
2199 continue;
2200 }
2201
2202 if (has_second_rf && this_mode == NEWMV &&
2203 mi->interp_filter == EIGHTTAP) {
2204 // adjust src pointers
2205 mi_buf_shift(x, i);
2206 if (sf->comp_inter_joint_search_thresh <= bsize) {
2207 int rate_mv;
2208 joint_motion_search(cpi, x, bsize, frame_mv[this_mode], mi_row,
2209 mi_col, seg_mvs[i], &rate_mv);
2210 seg_mvs[i][mi->ref_frame[0]].as_int =
2211 frame_mv[this_mode][mi->ref_frame[0]].as_int;
2212 seg_mvs[i][mi->ref_frame[1]].as_int =
2213 frame_mv[this_mode][mi->ref_frame[1]].as_int;
2214 }
2215 // restore src pointers
2216 mi_buf_restore(x, orig_src, orig_pre);
2217 }
2218
2219 bsi->rdstat[i][mode_idx].brate = set_and_cost_bmi_mvs(
2220 cpi, x, xd, i, this_mode, mode_mv[this_mode], frame_mv, seg_mvs[i],
2221 bsi->ref_mv, x->nmvjointcost, x->mvcost);
2222
2223 for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2224 bsi->rdstat[i][mode_idx].mvs[ref].as_int =
2225 mode_mv[this_mode][ref].as_int;
2226 if (num_4x4_blocks_wide > 1)
2227 bsi->rdstat[i + 1][mode_idx].mvs[ref].as_int =
2228 mode_mv[this_mode][ref].as_int;
2229 if (num_4x4_blocks_high > 1)
2230 bsi->rdstat[i + 2][mode_idx].mvs[ref].as_int =
2231 mode_mv[this_mode][ref].as_int;
2232 }
2233
2234 // Trap vectors that reach beyond the UMV borders
2235 if (mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][0].as_mv) ||
2236 (has_second_rf &&
2237 mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][1].as_mv)))
2238 continue;
2239
2240 if (filter_idx > 0) {
2241 BEST_SEG_INFO *ref_bsi = bsi_buf;
2242 subpelmv = 0;
2243 have_ref = 1;
2244
2245 for (ref = 0; ref < 1 + has_second_rf; ++ref) {
2246 subpelmv |= mv_has_subpel(&mode_mv[this_mode][ref].as_mv);
2247 have_ref &= mode_mv[this_mode][ref].as_int ==
2248 ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
2249 }
2250
2251 if (filter_idx > 1 && !subpelmv && !have_ref) {
2252 ref_bsi = bsi_buf + 1;
2253 have_ref = 1;
2254 for (ref = 0; ref < 1 + has_second_rf; ++ref)
2255 have_ref &= mode_mv[this_mode][ref].as_int ==
2256 ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
2257 }
2258
2259 if (!subpelmv && have_ref &&
2260 ref_bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
2261 memcpy(&bsi->rdstat[i][mode_idx], &ref_bsi->rdstat[i][mode_idx],
2262 sizeof(SEG_RDSTAT));
2263 if (num_4x4_blocks_wide > 1)
2264 bsi->rdstat[i + 1][mode_idx].eobs =
2265 ref_bsi->rdstat[i + 1][mode_idx].eobs;
2266 if (num_4x4_blocks_high > 1)
2267 bsi->rdstat[i + 2][mode_idx].eobs =
2268 ref_bsi->rdstat[i + 2][mode_idx].eobs;
2269
2270 if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
2271 mode_selected = this_mode;
2272 best_rd = bsi->rdstat[i][mode_idx].brdcost;
2273 }
2274 continue;
2275 }
2276 }
2277
2278 bsi->rdstat[i][mode_idx].brdcost = encode_inter_mb_segment(
2279 cpi, x, bsi->segment_rd - this_segment_rd, i,
2280 &bsi->rdstat[i][mode_idx].byrate, &bsi->rdstat[i][mode_idx].bdist,
2281 &bsi->rdstat[i][mode_idx].bsse, bsi->rdstat[i][mode_idx].ta,
2282 bsi->rdstat[i][mode_idx].tl, mi_row, mi_col);
2283 if (bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
2284 bsi->rdstat[i][mode_idx].brdcost +=
2285 RDCOST(x->rdmult, x->rddiv, bsi->rdstat[i][mode_idx].brate, 0);
2286 bsi->rdstat[i][mode_idx].brate += bsi->rdstat[i][mode_idx].byrate;
2287 bsi->rdstat[i][mode_idx].eobs = p->eobs[i];
2288 if (num_4x4_blocks_wide > 1)
2289 bsi->rdstat[i + 1][mode_idx].eobs = p->eobs[i + 1];
2290 if (num_4x4_blocks_high > 1)
2291 bsi->rdstat[i + 2][mode_idx].eobs = p->eobs[i + 2];
2292 }
2293
2294 if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
2295 mode_selected = this_mode;
2296 best_rd = bsi->rdstat[i][mode_idx].brdcost;
2297 }
2298 } /*for each 4x4 mode*/
2299
2300 if (best_rd == INT64_MAX) {
2301 int iy, midx;
2302 for (iy = i + 1; iy < 4; ++iy)
2303 for (midx = 0; midx < INTER_MODES; ++midx)
2304 bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2305 bsi->segment_rd = INT64_MAX;
2306 return INT64_MAX;
2307 }
2308
2309 mode_idx = INTER_OFFSET(mode_selected);
2310 memcpy(t_above, bsi->rdstat[i][mode_idx].ta, sizeof(t_above));
2311 memcpy(t_left, bsi->rdstat[i][mode_idx].tl, sizeof(t_left));
2312
2313 set_and_cost_bmi_mvs(cpi, x, xd, i, mode_selected, mode_mv[mode_selected],
2314 frame_mv, seg_mvs[i], bsi->ref_mv, x->nmvjointcost,
2315 x->mvcost);
2316
2317 br += bsi->rdstat[i][mode_idx].brate;
2318 bd += bsi->rdstat[i][mode_idx].bdist;
2319 block_sse += bsi->rdstat[i][mode_idx].bsse;
2320 segmentyrate += bsi->rdstat[i][mode_idx].byrate;
2321 this_segment_rd += bsi->rdstat[i][mode_idx].brdcost;
2322
2323 if (this_segment_rd > bsi->segment_rd) {
2324 int iy, midx;
2325 for (iy = i + 1; iy < 4; ++iy)
2326 for (midx = 0; midx < INTER_MODES; ++midx)
2327 bsi->rdstat[iy][midx].brdcost = INT64_MAX;
2328 bsi->segment_rd = INT64_MAX;
2329 return INT64_MAX;
2330 }
2331 }
2332 } /* for each label */
2333
2334 bsi->r = br;
2335 bsi->d = bd;
2336 bsi->segment_yrate = segmentyrate;
2337 bsi->segment_rd = this_segment_rd;
2338 bsi->sse = block_sse;
2339
2340 // update the coding decisions
2341 for (k = 0; k < 4; ++k) bsi->modes[k] = mi->bmi[k].as_mode;
2342
2343 if (bsi->segment_rd > best_rd) return INT64_MAX;
2344 /* set it to the best */
2345 for (i = 0; i < 4; i++) {
2346 mode_idx = INTER_OFFSET(bsi->modes[i]);
2347 mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int;
2348 if (has_second_ref(mi))
2349 mi->bmi[i].as_mv[1].as_int = bsi->rdstat[i][mode_idx].mvs[1].as_int;
2350 x->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
2351 mi->bmi[i].as_mode = bsi->modes[i];
2352 }
2353
2354 /*
2355 * used to set mbmi->mv.as_int
2356 */
2357 *returntotrate = bsi->r;
2358 *returndistortion = bsi->d;
2359 *returnyrate = bsi->segment_yrate;
2360 *skippable = vp9_is_skippable_in_plane(x, BLOCK_8X8, 0);
2361 *psse = bsi->sse;
2362 mi->mode = bsi->modes[3];
2363
2364 return bsi->segment_rd;
2365 }
2366
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)2367 static void estimate_ref_frame_costs(const VP9_COMMON *cm,
2368 const MACROBLOCKD *xd, int segment_id,
2369 unsigned int *ref_costs_single,
2370 unsigned int *ref_costs_comp,
2371 vpx_prob *comp_mode_p) {
2372 int seg_ref_active =
2373 segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME);
2374 if (seg_ref_active) {
2375 memset(ref_costs_single, 0, MAX_REF_FRAMES * sizeof(*ref_costs_single));
2376 memset(ref_costs_comp, 0, MAX_REF_FRAMES * sizeof(*ref_costs_comp));
2377 *comp_mode_p = 128;
2378 } else {
2379 vpx_prob intra_inter_p = vp9_get_intra_inter_prob(cm, xd);
2380 vpx_prob comp_inter_p = 128;
2381
2382 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
2383 comp_inter_p = vp9_get_reference_mode_prob(cm, xd);
2384 *comp_mode_p = comp_inter_p;
2385 } else {
2386 *comp_mode_p = 128;
2387 }
2388
2389 ref_costs_single[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
2390
2391 if (cm->reference_mode != COMPOUND_REFERENCE) {
2392 vpx_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
2393 vpx_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
2394 unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
2395
2396 if (cm->reference_mode == REFERENCE_MODE_SELECT)
2397 base_cost += vp9_cost_bit(comp_inter_p, 0);
2398
2399 ref_costs_single[LAST_FRAME] = ref_costs_single[GOLDEN_FRAME] =
2400 ref_costs_single[ALTREF_FRAME] = base_cost;
2401 ref_costs_single[LAST_FRAME] += vp9_cost_bit(ref_single_p1, 0);
2402 ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
2403 ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
2404 ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
2405 ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
2406 } else {
2407 ref_costs_single[LAST_FRAME] = 512;
2408 ref_costs_single[GOLDEN_FRAME] = 512;
2409 ref_costs_single[ALTREF_FRAME] = 512;
2410 }
2411 if (cm->reference_mode != SINGLE_REFERENCE) {
2412 vpx_prob ref_comp_p = vp9_get_pred_prob_comp_ref_p(cm, xd);
2413 unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
2414
2415 if (cm->reference_mode == REFERENCE_MODE_SELECT)
2416 base_cost += vp9_cost_bit(comp_inter_p, 1);
2417
2418 ref_costs_comp[LAST_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 0);
2419 ref_costs_comp[GOLDEN_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 1);
2420 } else {
2421 ref_costs_comp[LAST_FRAME] = 512;
2422 ref_costs_comp[GOLDEN_FRAME] = 512;
2423 }
2424 }
2425 }
2426
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)2427 static void store_coding_context(
2428 MACROBLOCK *x, PICK_MODE_CONTEXT *ctx, int mode_index,
2429 int64_t comp_pred_diff[REFERENCE_MODES],
2430 int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS], int skippable) {
2431 MACROBLOCKD *const xd = &x->e_mbd;
2432
2433 // Take a snapshot of the coding context so it can be
2434 // restored if we decide to encode this way
2435 ctx->skip = x->skip;
2436 ctx->skippable = skippable;
2437 ctx->best_mode_index = mode_index;
2438 ctx->mic = *xd->mi[0];
2439 ctx->mbmi_ext = *x->mbmi_ext;
2440 ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_REFERENCE];
2441 ctx->comp_pred_diff = (int)comp_pred_diff[COMPOUND_REFERENCE];
2442 ctx->hybrid_pred_diff = (int)comp_pred_diff[REFERENCE_MODE_SELECT];
2443
2444 memcpy(ctx->best_filter_diff, best_filter_diff,
2445 sizeof(*best_filter_diff) * SWITCHABLE_FILTER_CONTEXTS);
2446 }
2447
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])2448 static void setup_buffer_inter(VP9_COMP *cpi, MACROBLOCK *x,
2449 MV_REFERENCE_FRAME ref_frame,
2450 BLOCK_SIZE block_size, int mi_row, int mi_col,
2451 int_mv frame_nearest_mv[MAX_REF_FRAMES],
2452 int_mv frame_near_mv[MAX_REF_FRAMES],
2453 struct buf_2d yv12_mb[4][MAX_MB_PLANE]) {
2454 const VP9_COMMON *cm = &cpi->common;
2455 const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
2456 MACROBLOCKD *const xd = &x->e_mbd;
2457 MODE_INFO *const mi = xd->mi[0];
2458 int_mv *const candidates = x->mbmi_ext->ref_mvs[ref_frame];
2459 const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
2460 MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2461
2462 assert(yv12 != NULL);
2463
2464 // TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this
2465 // use the UV scaling factors.
2466 vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
2467
2468 // Gets an initial list of candidate vectors from neighbours and orders them
2469 vp9_find_mv_refs(cm, xd, mi, ref_frame, candidates, mi_row, mi_col,
2470 mbmi_ext->mode_context);
2471
2472 // Candidate refinement carried out at encoder and decoder
2473 vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
2474 &frame_nearest_mv[ref_frame],
2475 &frame_near_mv[ref_frame]);
2476
2477 // Further refinement that is encode side only to test the top few candidates
2478 // in full and choose the best as the centre point for subsequent searches.
2479 // The current implementation doesn't support scaling.
2480 if (!vp9_is_scaled(sf) && block_size >= BLOCK_8X8)
2481 vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride, ref_frame,
2482 block_size);
2483 }
2484
2485 #if CONFIG_NON_GREEDY_MV
ref_frame_to_gf_rf_idx(int ref_frame)2486 static int ref_frame_to_gf_rf_idx(int ref_frame) {
2487 if (ref_frame == GOLDEN_FRAME) {
2488 return 0;
2489 }
2490 if (ref_frame == LAST_FRAME) {
2491 return 1;
2492 }
2493 if (ref_frame == ALTREF_FRAME) {
2494 return 2;
2495 }
2496 assert(0);
2497 return -1;
2498 }
2499 #endif
2500
single_motion_search(VP9_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int mi_row,int mi_col,int_mv * tmp_mv,int * rate_mv)2501 static void single_motion_search(VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
2502 int mi_row, int mi_col, int_mv *tmp_mv,
2503 int *rate_mv) {
2504 MACROBLOCKD *xd = &x->e_mbd;
2505 const VP9_COMMON *cm = &cpi->common;
2506 MODE_INFO *mi = xd->mi[0];
2507 struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0 } };
2508 int step_param;
2509 MV mvp_full;
2510 int ref = mi->ref_frame[0];
2511 MV ref_mv = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2512 const MvLimits tmp_mv_limits = x->mv_limits;
2513 int cost_list[5];
2514 const int best_predmv_idx = x->mv_best_ref_index[ref];
2515 const YV12_BUFFER_CONFIG *scaled_ref_frame =
2516 vp9_get_scaled_ref_frame(cpi, ref);
2517 const int pw = num_4x4_blocks_wide_lookup[bsize] << 2;
2518 const int ph = num_4x4_blocks_high_lookup[bsize] << 2;
2519 MV pred_mv[3];
2520
2521 int bestsme = INT_MAX;
2522 #if CONFIG_NON_GREEDY_MV
2523 int gf_group_idx = cpi->twopass.gf_group.index;
2524 int gf_rf_idx = ref_frame_to_gf_rf_idx(ref);
2525 BLOCK_SIZE square_bsize = get_square_block_size(bsize);
2526 int_mv nb_full_mvs[NB_MVS_NUM] = { 0 };
2527 MotionField *motion_field = vp9_motion_field_info_get_motion_field(
2528 &cpi->motion_field_info, gf_group_idx, gf_rf_idx, square_bsize);
2529 const int nb_full_mv_num =
2530 vp9_prepare_nb_full_mvs(motion_field, mi_row, mi_col, nb_full_mvs);
2531 const int lambda = (pw * ph) / 4;
2532 assert(pw * ph == lambda << 2);
2533 #else // CONFIG_NON_GREEDY_MV
2534 int sadpb = x->sadperbit16;
2535 #endif // CONFIG_NON_GREEDY_MV
2536
2537 pred_mv[0] = x->mbmi_ext->ref_mvs[ref][0].as_mv;
2538 pred_mv[1] = x->mbmi_ext->ref_mvs[ref][1].as_mv;
2539 pred_mv[2] = x->pred_mv[ref];
2540
2541 if (scaled_ref_frame) {
2542 int i;
2543 // Swap out the reference frame for a version that's been scaled to
2544 // match the resolution of the current frame, allowing the existing
2545 // motion search code to be used without additional modifications.
2546 for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
2547
2548 vp9_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
2549 }
2550
2551 // Work out the size of the first step in the mv step search.
2552 // 0 here is maximum length first step. 1 is VPXMAX >> 1 etc.
2553 if (cpi->sf.mv.auto_mv_step_size && cm->show_frame) {
2554 // Take wtd average of the step_params based on the last frame's
2555 // max mv magnitude and that based on the best ref mvs of the current
2556 // block for the given reference.
2557 step_param =
2558 (vp9_init_search_range(x->max_mv_context[ref]) + cpi->mv_step_param) /
2559 2;
2560 } else {
2561 step_param = cpi->mv_step_param;
2562 }
2563
2564 if (cpi->sf.adaptive_motion_search && bsize < BLOCK_64X64) {
2565 const int boffset =
2566 2 * (b_width_log2_lookup[BLOCK_64X64] -
2567 VPXMIN(b_height_log2_lookup[bsize], b_width_log2_lookup[bsize]));
2568 step_param = VPXMAX(step_param, boffset);
2569 }
2570
2571 if (cpi->sf.adaptive_motion_search) {
2572 int bwl = b_width_log2_lookup[bsize];
2573 int bhl = b_height_log2_lookup[bsize];
2574 int tlevel = x->pred_mv_sad[ref] >> (bwl + bhl + 4);
2575
2576 if (tlevel < 5) step_param += 2;
2577
2578 // prev_mv_sad is not setup for dynamically scaled frames.
2579 if (cpi->oxcf.resize_mode != RESIZE_DYNAMIC) {
2580 int i;
2581 for (i = LAST_FRAME; i <= ALTREF_FRAME && cm->show_frame; ++i) {
2582 if ((x->pred_mv_sad[ref] >> 3) > x->pred_mv_sad[i]) {
2583 x->pred_mv[ref].row = INT16_MAX;
2584 x->pred_mv[ref].col = INT16_MAX;
2585 tmp_mv->as_int = INVALID_MV;
2586
2587 if (scaled_ref_frame) {
2588 int i;
2589 for (i = 0; i < MAX_MB_PLANE; ++i)
2590 xd->plane[i].pre[0] = backup_yv12[i];
2591 }
2592 return;
2593 }
2594 }
2595 }
2596 }
2597
2598 // Note: MV limits are modified here. Always restore the original values
2599 // after full-pixel motion search.
2600 vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
2601
2602 mvp_full = pred_mv[best_predmv_idx];
2603 mvp_full.col >>= 3;
2604 mvp_full.row >>= 3;
2605
2606 #if CONFIG_NON_GREEDY_MV
2607 bestsme = vp9_full_pixel_diamond_new(cpi, x, bsize, &mvp_full, step_param,
2608 lambda, 1, nb_full_mvs, nb_full_mv_num,
2609 &tmp_mv->as_mv);
2610 #else // CONFIG_NON_GREEDY_MV
2611 bestsme = vp9_full_pixel_search(
2612 cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method, sadpb,
2613 cond_cost_list(cpi, cost_list), &ref_mv, &tmp_mv->as_mv, INT_MAX, 1);
2614 #endif // CONFIG_NON_GREEDY_MV
2615
2616 if (cpi->sf.enhanced_full_pixel_motion_search) {
2617 int i;
2618 for (i = 0; i < 3; ++i) {
2619 int this_me;
2620 MV this_mv;
2621 int diff_row;
2622 int diff_col;
2623 int step;
2624
2625 if (pred_mv[i].row == INT16_MAX || pred_mv[i].col == INT16_MAX) continue;
2626 if (i == best_predmv_idx) continue;
2627
2628 diff_row = ((int)pred_mv[i].row -
2629 pred_mv[i > 0 ? (i - 1) : best_predmv_idx].row) >>
2630 3;
2631 diff_col = ((int)pred_mv[i].col -
2632 pred_mv[i > 0 ? (i - 1) : best_predmv_idx].col) >>
2633 3;
2634 if (diff_row == 0 && diff_col == 0) continue;
2635 if (diff_row < 0) diff_row = -diff_row;
2636 if (diff_col < 0) diff_col = -diff_col;
2637 step = get_msb((diff_row + diff_col + 1) >> 1);
2638 if (step <= 0) continue;
2639
2640 mvp_full = pred_mv[i];
2641 mvp_full.col >>= 3;
2642 mvp_full.row >>= 3;
2643 #if CONFIG_NON_GREEDY_MV
2644 this_me = vp9_full_pixel_diamond_new(
2645 cpi, x, bsize, &mvp_full,
2646 VPXMAX(step_param, MAX_MVSEARCH_STEPS - step), lambda, 1, nb_full_mvs,
2647 nb_full_mv_num, &this_mv);
2648 #else // CONFIG_NON_GREEDY_MV
2649 this_me = vp9_full_pixel_search(
2650 cpi, x, bsize, &mvp_full,
2651 VPXMAX(step_param, MAX_MVSEARCH_STEPS - step),
2652 cpi->sf.mv.search_method, sadpb, cond_cost_list(cpi, cost_list),
2653 &ref_mv, &this_mv, INT_MAX, 1);
2654 #endif // CONFIG_NON_GREEDY_MV
2655 if (this_me < bestsme) {
2656 tmp_mv->as_mv = this_mv;
2657 bestsme = this_me;
2658 }
2659 }
2660 }
2661
2662 x->mv_limits = tmp_mv_limits;
2663
2664 if (bestsme < INT_MAX) {
2665 uint32_t dis; /* TODO: use dis in distortion calculation later. */
2666 cpi->find_fractional_mv_step(
2667 x, &tmp_mv->as_mv, &ref_mv, cm->allow_high_precision_mv, x->errorperbit,
2668 &cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop,
2669 cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list),
2670 x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[ref], NULL, pw, ph,
2671 cpi->sf.use_accurate_subpel_search);
2672 }
2673 *rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv, x->nmvjointcost,
2674 x->mvcost, MV_COST_WEIGHT);
2675
2676 x->pred_mv[ref] = tmp_mv->as_mv;
2677
2678 if (scaled_ref_frame) {
2679 int i;
2680 for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
2681 }
2682 }
2683
restore_dst_buf(MACROBLOCKD * xd,uint8_t * orig_dst[MAX_MB_PLANE],int orig_dst_stride[MAX_MB_PLANE])2684 static INLINE void restore_dst_buf(MACROBLOCKD *xd,
2685 uint8_t *orig_dst[MAX_MB_PLANE],
2686 int orig_dst_stride[MAX_MB_PLANE]) {
2687 int i;
2688 for (i = 0; i < MAX_MB_PLANE; i++) {
2689 xd->plane[i].dst.buf = orig_dst[i];
2690 xd->plane[i].dst.stride = orig_dst_stride[i];
2691 }
2692 }
2693
2694 // In some situations we want to discount tha pparent cost of a new motion
2695 // vector. Where there is a subtle motion field and especially where there is
2696 // low spatial complexity then it can be hard to cover the cost of a new motion
2697 // vector in a single block, even if that motion vector reduces distortion.
2698 // However, once established that vector may be usable through the nearest and
2699 // near mv modes to reduce distortion in subsequent blocks and also improve
2700 // 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)2701 static int discount_newmv_test(VP9_COMP *cpi, int this_mode, int_mv this_mv,
2702 int_mv (*mode_mv)[MAX_REF_FRAMES], int ref_frame,
2703 int mi_row, int mi_col, BLOCK_SIZE bsize) {
2704 #if CONFIG_NON_GREEDY_MV
2705 (void)mode_mv;
2706 (void)this_mv;
2707 if (this_mode == NEWMV && bsize >= BLOCK_8X8 && cpi->tpl_ready) {
2708 const int gf_group_idx = cpi->twopass.gf_group.index;
2709 const int gf_rf_idx = ref_frame_to_gf_rf_idx(ref_frame);
2710 const TplDepFrame tpl_frame = cpi->tpl_stats[gf_group_idx];
2711 const MotionField *motion_field = vp9_motion_field_info_get_motion_field(
2712 &cpi->motion_field_info, gf_group_idx, gf_rf_idx, cpi->tpl_bsize);
2713 const int tpl_block_mi_h = num_8x8_blocks_high_lookup[cpi->tpl_bsize];
2714 const int tpl_block_mi_w = num_8x8_blocks_wide_lookup[cpi->tpl_bsize];
2715 const int tpl_mi_row = mi_row - (mi_row % tpl_block_mi_h);
2716 const int tpl_mi_col = mi_col - (mi_col % tpl_block_mi_w);
2717 const int mv_mode =
2718 tpl_frame
2719 .mv_mode_arr[gf_rf_idx][tpl_mi_row * tpl_frame.stride + tpl_mi_col];
2720 if (mv_mode == NEW_MV_MODE) {
2721 int_mv tpl_new_mv =
2722 vp9_motion_field_mi_get_mv(motion_field, tpl_mi_row, tpl_mi_col);
2723 int row_diff = abs(tpl_new_mv.as_mv.row - this_mv.as_mv.row);
2724 int col_diff = abs(tpl_new_mv.as_mv.col - this_mv.as_mv.col);
2725 if (VPXMAX(row_diff, col_diff) <= 8) {
2726 return 1;
2727 } else {
2728 return 0;
2729 }
2730 } else {
2731 return 0;
2732 }
2733 } else {
2734 return 0;
2735 }
2736 #else
2737 (void)mi_row;
2738 (void)mi_col;
2739 (void)bsize;
2740 return (!cpi->rc.is_src_frame_alt_ref && (this_mode == NEWMV) &&
2741 (this_mv.as_int != 0) &&
2742 ((mode_mv[NEARESTMV][ref_frame].as_int == 0) ||
2743 (mode_mv[NEARESTMV][ref_frame].as_int == INVALID_MV)) &&
2744 ((mode_mv[NEARMV][ref_frame].as_int == 0) ||
2745 (mode_mv[NEARMV][ref_frame].as_int == INVALID_MV)));
2746 #endif
2747 }
2748
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[])2749 static int64_t handle_inter_mode(
2750 VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int *rate2,
2751 int64_t *distortion, int *skippable, int *rate_y, int *rate_uv,
2752 struct buf_2d *recon, int *disable_skip, int_mv (*mode_mv)[MAX_REF_FRAMES],
2753 int mi_row, int mi_col, int_mv single_newmv[MAX_REF_FRAMES],
2754 INTERP_FILTER (*single_filter)[MAX_REF_FRAMES],
2755 int (*single_skippable)[MAX_REF_FRAMES], int64_t *psse,
2756 const int64_t ref_best_rd, int64_t *mask_filter, int64_t filter_cache[]) {
2757 VP9_COMMON *cm = &cpi->common;
2758 MACROBLOCKD *xd = &x->e_mbd;
2759 MODE_INFO *mi = xd->mi[0];
2760 MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2761 const int is_comp_pred = has_second_ref(mi);
2762 const int this_mode = mi->mode;
2763 int_mv *frame_mv = mode_mv[this_mode];
2764 int i;
2765 int refs[2] = { mi->ref_frame[0],
2766 (mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1]) };
2767 int_mv cur_mv[2];
2768 #if CONFIG_VP9_HIGHBITDEPTH
2769 DECLARE_ALIGNED(16, uint16_t, tmp_buf16[MAX_MB_PLANE * 64 * 64]);
2770 uint8_t *tmp_buf;
2771 #else
2772 DECLARE_ALIGNED(16, uint8_t, tmp_buf[MAX_MB_PLANE * 64 * 64]);
2773 #endif // CONFIG_VP9_HIGHBITDEPTH
2774 int pred_exists = 0;
2775 int intpel_mv;
2776 int64_t rd, tmp_rd, best_rd = INT64_MAX;
2777 int best_needs_copy = 0;
2778 uint8_t *orig_dst[MAX_MB_PLANE];
2779 int orig_dst_stride[MAX_MB_PLANE];
2780 int rs = 0;
2781 INTERP_FILTER best_filter = SWITCHABLE;
2782 uint8_t skip_txfm[MAX_MB_PLANE << 2] = { 0 };
2783 int64_t bsse[MAX_MB_PLANE << 2] = { 0 };
2784
2785 int bsl = mi_width_log2_lookup[bsize];
2786 int pred_filter_search =
2787 cpi->sf.cb_pred_filter_search
2788 ? (((mi_row + mi_col) >> bsl) +
2789 get_chessboard_index(cm->current_video_frame)) &
2790 0x1
2791 : 0;
2792
2793 int skip_txfm_sb = 0;
2794 int64_t skip_sse_sb = INT64_MAX;
2795 int64_t distortion_y = 0, distortion_uv = 0;
2796
2797 #if CONFIG_VP9_HIGHBITDEPTH
2798 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2799 tmp_buf = CONVERT_TO_BYTEPTR(tmp_buf16);
2800 } else {
2801 tmp_buf = (uint8_t *)tmp_buf16;
2802 }
2803 #endif // CONFIG_VP9_HIGHBITDEPTH
2804
2805 if (pred_filter_search) {
2806 INTERP_FILTER af = SWITCHABLE, lf = SWITCHABLE;
2807 if (xd->above_mi && is_inter_block(xd->above_mi))
2808 af = xd->above_mi->interp_filter;
2809 if (xd->left_mi && is_inter_block(xd->left_mi))
2810 lf = xd->left_mi->interp_filter;
2811
2812 if ((this_mode != NEWMV) || (af == lf)) best_filter = af;
2813 }
2814
2815 if (is_comp_pred) {
2816 if (frame_mv[refs[0]].as_int == INVALID_MV ||
2817 frame_mv[refs[1]].as_int == INVALID_MV)
2818 return INT64_MAX;
2819
2820 if (cpi->sf.adaptive_mode_search) {
2821 if (single_filter[this_mode][refs[0]] ==
2822 single_filter[this_mode][refs[1]])
2823 best_filter = single_filter[this_mode][refs[0]];
2824 }
2825 }
2826
2827 if (this_mode == NEWMV) {
2828 int rate_mv;
2829 if (is_comp_pred) {
2830 // Initialize mv using single prediction mode result.
2831 frame_mv[refs[0]].as_int = single_newmv[refs[0]].as_int;
2832 frame_mv[refs[1]].as_int = single_newmv[refs[1]].as_int;
2833
2834 if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
2835 joint_motion_search(cpi, x, bsize, frame_mv, mi_row, mi_col,
2836 single_newmv, &rate_mv);
2837 } else {
2838 rate_mv = vp9_mv_bit_cost(&frame_mv[refs[0]].as_mv,
2839 &x->mbmi_ext->ref_mvs[refs[0]][0].as_mv,
2840 x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2841 rate_mv += vp9_mv_bit_cost(&frame_mv[refs[1]].as_mv,
2842 &x->mbmi_ext->ref_mvs[refs[1]][0].as_mv,
2843 x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
2844 }
2845 *rate2 += rate_mv;
2846 } else {
2847 int_mv tmp_mv;
2848 single_motion_search(cpi, x, bsize, mi_row, mi_col, &tmp_mv, &rate_mv);
2849 if (tmp_mv.as_int == INVALID_MV) return INT64_MAX;
2850
2851 frame_mv[refs[0]].as_int = xd->mi[0]->bmi[0].as_mv[0].as_int =
2852 tmp_mv.as_int;
2853 single_newmv[refs[0]].as_int = tmp_mv.as_int;
2854
2855 // Estimate the rate implications of a new mv but discount this
2856 // under certain circumstances where we want to help initiate a weak
2857 // motion field, where the distortion gain for a single block may not
2858 // be enough to overcome the cost of a new mv.
2859 if (discount_newmv_test(cpi, this_mode, tmp_mv, mode_mv, refs[0], mi_row,
2860 mi_col, bsize)) {
2861 *rate2 += VPXMAX((rate_mv / NEW_MV_DISCOUNT_FACTOR), 1);
2862 } else {
2863 *rate2 += rate_mv;
2864 }
2865 }
2866 }
2867
2868 for (i = 0; i < is_comp_pred + 1; ++i) {
2869 cur_mv[i] = frame_mv[refs[i]];
2870 // Clip "next_nearest" so that it does not extend to far out of image
2871 if (this_mode != NEWMV) clamp_mv2(&cur_mv[i].as_mv, xd);
2872
2873 if (mv_check_bounds(&x->mv_limits, &cur_mv[i].as_mv)) return INT64_MAX;
2874 mi->mv[i].as_int = cur_mv[i].as_int;
2875 }
2876
2877 // do first prediction into the destination buffer. Do the next
2878 // prediction into a temporary buffer. Then keep track of which one
2879 // of these currently holds the best predictor, and use the other
2880 // one for future predictions. In the end, copy from tmp_buf to
2881 // dst if necessary.
2882 for (i = 0; i < MAX_MB_PLANE; i++) {
2883 orig_dst[i] = xd->plane[i].dst.buf;
2884 orig_dst_stride[i] = xd->plane[i].dst.stride;
2885 }
2886
2887 // We don't include the cost of the second reference here, because there
2888 // are only two options: Last/ARF or Golden/ARF; The second one is always
2889 // known, which is ARF.
2890 //
2891 // Under some circumstances we discount the cost of new mv mode to encourage
2892 // initiation of a motion field.
2893 if (discount_newmv_test(cpi, this_mode, frame_mv[refs[0]], mode_mv, refs[0],
2894 mi_row, mi_col, bsize)) {
2895 *rate2 +=
2896 VPXMIN(cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]),
2897 cost_mv_ref(cpi, NEARESTMV, mbmi_ext->mode_context[refs[0]]));
2898 } else {
2899 *rate2 += cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]);
2900 }
2901
2902 if (RDCOST(x->rdmult, x->rddiv, *rate2, 0) > ref_best_rd &&
2903 mi->mode != NEARESTMV)
2904 return INT64_MAX;
2905
2906 pred_exists = 0;
2907 // Are all MVs integer pel for Y and UV
2908 intpel_mv = !mv_has_subpel(&mi->mv[0].as_mv);
2909 if (is_comp_pred) intpel_mv &= !mv_has_subpel(&mi->mv[1].as_mv);
2910
2911 // Search for best switchable filter by checking the variance of
2912 // pred error irrespective of whether the filter will be used
2913 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
2914
2915 if (cm->interp_filter != BILINEAR) {
2916 if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
2917 best_filter = EIGHTTAP;
2918 } else if (best_filter == SWITCHABLE) {
2919 int newbest;
2920 int tmp_rate_sum = 0;
2921 int64_t tmp_dist_sum = 0;
2922
2923 for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
2924 int j;
2925 int64_t rs_rd;
2926 int tmp_skip_sb = 0;
2927 int64_t tmp_skip_sse = INT64_MAX;
2928
2929 mi->interp_filter = i;
2930 rs = vp9_get_switchable_rate(cpi, xd);
2931 rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
2932
2933 if (i > 0 && intpel_mv) {
2934 rd = RDCOST(x->rdmult, x->rddiv, tmp_rate_sum, tmp_dist_sum);
2935 filter_cache[i] = rd;
2936 filter_cache[SWITCHABLE_FILTERS] =
2937 VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
2938 if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
2939 *mask_filter = VPXMAX(*mask_filter, rd);
2940 } else {
2941 int rate_sum = 0;
2942 int64_t dist_sum = 0;
2943 if (i > 0 && cpi->sf.adaptive_interp_filter_search &&
2944 (cpi->sf.interp_filter_search_mask & (1 << i))) {
2945 rate_sum = INT_MAX;
2946 dist_sum = INT64_MAX;
2947 continue;
2948 }
2949
2950 if ((cm->interp_filter == SWITCHABLE && (!i || best_needs_copy)) ||
2951 (cm->interp_filter != SWITCHABLE &&
2952 (cm->interp_filter == mi->interp_filter ||
2953 (i == 0 && intpel_mv)))) {
2954 restore_dst_buf(xd, orig_dst, orig_dst_stride);
2955 } else {
2956 for (j = 0; j < MAX_MB_PLANE; j++) {
2957 xd->plane[j].dst.buf = tmp_buf + j * 64 * 64;
2958 xd->plane[j].dst.stride = 64;
2959 }
2960 }
2961 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
2962 model_rd_for_sb(cpi, bsize, x, xd, &rate_sum, &dist_sum, &tmp_skip_sb,
2963 &tmp_skip_sse);
2964
2965 rd = RDCOST(x->rdmult, x->rddiv, rate_sum, dist_sum);
2966 filter_cache[i] = rd;
2967 filter_cache[SWITCHABLE_FILTERS] =
2968 VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
2969 if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
2970 *mask_filter = VPXMAX(*mask_filter, rd);
2971
2972 if (i == 0 && intpel_mv) {
2973 tmp_rate_sum = rate_sum;
2974 tmp_dist_sum = dist_sum;
2975 }
2976 }
2977
2978 if (i == 0 && cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
2979 if (rd / 2 > ref_best_rd) {
2980 restore_dst_buf(xd, orig_dst, orig_dst_stride);
2981 return INT64_MAX;
2982 }
2983 }
2984 newbest = i == 0 || rd < best_rd;
2985
2986 if (newbest) {
2987 best_rd = rd;
2988 best_filter = mi->interp_filter;
2989 if (cm->interp_filter == SWITCHABLE && i && !intpel_mv)
2990 best_needs_copy = !best_needs_copy;
2991 }
2992
2993 if ((cm->interp_filter == SWITCHABLE && newbest) ||
2994 (cm->interp_filter != SWITCHABLE &&
2995 cm->interp_filter == mi->interp_filter)) {
2996 pred_exists = 1;
2997 tmp_rd = best_rd;
2998
2999 skip_txfm_sb = tmp_skip_sb;
3000 skip_sse_sb = tmp_skip_sse;
3001 memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
3002 memcpy(bsse, x->bsse, sizeof(bsse));
3003 }
3004 }
3005 restore_dst_buf(xd, orig_dst, orig_dst_stride);
3006 }
3007 }
3008 // Set the appropriate filter
3009 mi->interp_filter =
3010 cm->interp_filter != SWITCHABLE ? cm->interp_filter : best_filter;
3011 rs = cm->interp_filter == SWITCHABLE ? vp9_get_switchable_rate(cpi, xd) : 0;
3012
3013 if (pred_exists) {
3014 if (best_needs_copy) {
3015 // again temporarily set the buffers to local memory to prevent a memcpy
3016 for (i = 0; i < MAX_MB_PLANE; i++) {
3017 xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
3018 xd->plane[i].dst.stride = 64;
3019 }
3020 }
3021 rd = tmp_rd + RDCOST(x->rdmult, x->rddiv, rs, 0);
3022 } else {
3023 int tmp_rate;
3024 int64_t tmp_dist;
3025 // Handles the special case when a filter that is not in the
3026 // switchable list (ex. bilinear) is indicated at the frame level, or
3027 // skip condition holds.
3028 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
3029 model_rd_for_sb(cpi, bsize, x, xd, &tmp_rate, &tmp_dist, &skip_txfm_sb,
3030 &skip_sse_sb);
3031 rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
3032 memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
3033 memcpy(bsse, x->bsse, sizeof(bsse));
3034 }
3035
3036 if (!is_comp_pred) single_filter[this_mode][refs[0]] = mi->interp_filter;
3037
3038 if (cpi->sf.adaptive_mode_search)
3039 if (is_comp_pred)
3040 if (single_skippable[this_mode][refs[0]] &&
3041 single_skippable[this_mode][refs[1]])
3042 memset(skip_txfm, SKIP_TXFM_AC_DC, sizeof(skip_txfm));
3043
3044 if (cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
3045 // if current pred_error modeled rd is substantially more than the best
3046 // so far, do not bother doing full rd
3047 if (rd / 2 > ref_best_rd) {
3048 restore_dst_buf(xd, orig_dst, orig_dst_stride);
3049 return INT64_MAX;
3050 }
3051 }
3052
3053 if (cm->interp_filter == SWITCHABLE) *rate2 += rs;
3054
3055 memcpy(x->skip_txfm, skip_txfm, sizeof(skip_txfm));
3056 memcpy(x->bsse, bsse, sizeof(bsse));
3057
3058 if (!skip_txfm_sb || xd->lossless) {
3059 int skippable_y, skippable_uv;
3060 int64_t sseuv = INT64_MAX;
3061 int64_t rdcosty = INT64_MAX;
3062
3063 // Y cost and distortion
3064 vp9_subtract_plane(x, bsize, 0);
3065 super_block_yrd(cpi, x, rate_y, &distortion_y, &skippable_y, psse, bsize,
3066 ref_best_rd, recon);
3067
3068 if (*rate_y == INT_MAX) {
3069 *rate2 = INT_MAX;
3070 *distortion = INT64_MAX;
3071 restore_dst_buf(xd, orig_dst, orig_dst_stride);
3072 return INT64_MAX;
3073 }
3074
3075 *rate2 += *rate_y;
3076 *distortion += distortion_y;
3077
3078 rdcosty = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
3079 rdcosty = VPXMIN(rdcosty, RDCOST(x->rdmult, x->rddiv, 0, *psse));
3080
3081 if (!super_block_uvrd(cpi, x, rate_uv, &distortion_uv, &skippable_uv,
3082 &sseuv, bsize, ref_best_rd - rdcosty)) {
3083 *rate2 = INT_MAX;
3084 *distortion = INT64_MAX;
3085 restore_dst_buf(xd, orig_dst, orig_dst_stride);
3086 return INT64_MAX;
3087 }
3088
3089 *psse += sseuv;
3090 *rate2 += *rate_uv;
3091 *distortion += distortion_uv;
3092 *skippable = skippable_y && skippable_uv;
3093 } else {
3094 x->skip = 1;
3095 *disable_skip = 1;
3096
3097 // The cost of skip bit needs to be added.
3098 *rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
3099
3100 *distortion = skip_sse_sb;
3101 }
3102
3103 if (!is_comp_pred) single_skippable[this_mode][refs[0]] = *skippable;
3104
3105 restore_dst_buf(xd, orig_dst, orig_dst_stride);
3106 return 0; // The rate-distortion cost will be re-calculated by caller.
3107 }
3108 #endif // !CONFIG_REALTIME_ONLY
3109
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)3110 void vp9_rd_pick_intra_mode_sb(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *rd_cost,
3111 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
3112 int64_t best_rd) {
3113 VP9_COMMON *const cm = &cpi->common;
3114 MACROBLOCKD *const xd = &x->e_mbd;
3115 struct macroblockd_plane *const pd = xd->plane;
3116 int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0;
3117 int y_skip = 0, uv_skip = 0;
3118 int64_t dist_y = 0, dist_uv = 0;
3119 TX_SIZE max_uv_tx_size;
3120 x->skip_encode = 0;
3121 ctx->skip = 0;
3122 xd->mi[0]->ref_frame[0] = INTRA_FRAME;
3123 xd->mi[0]->ref_frame[1] = NONE;
3124 // Initialize interp_filter here so we do not have to check for inter block
3125 // modes in get_pred_context_switchable_interp()
3126 xd->mi[0]->interp_filter = SWITCHABLE_FILTERS;
3127
3128 if (bsize >= BLOCK_8X8) {
3129 if (rd_pick_intra_sby_mode(cpi, x, &rate_y, &rate_y_tokenonly, &dist_y,
3130 &y_skip, bsize, best_rd) >= best_rd) {
3131 rd_cost->rate = INT_MAX;
3132 return;
3133 }
3134 } else {
3135 y_skip = 0;
3136 if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate_y, &rate_y_tokenonly,
3137 &dist_y, best_rd) >= best_rd) {
3138 rd_cost->rate = INT_MAX;
3139 return;
3140 }
3141 }
3142 max_uv_tx_size = uv_txsize_lookup[bsize][xd->mi[0]->tx_size]
3143 [pd[1].subsampling_x][pd[1].subsampling_y];
3144 rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly, &dist_uv,
3145 &uv_skip, VPXMAX(BLOCK_8X8, bsize), max_uv_tx_size);
3146
3147 if (y_skip && uv_skip) {
3148 rd_cost->rate = rate_y + rate_uv - rate_y_tokenonly - rate_uv_tokenonly +
3149 vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
3150 rd_cost->dist = dist_y + dist_uv;
3151 } else {
3152 rd_cost->rate =
3153 rate_y + rate_uv + vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
3154 rd_cost->dist = dist_y + dist_uv;
3155 }
3156
3157 ctx->mic = *xd->mi[0];
3158 ctx->mbmi_ext = *x->mbmi_ext;
3159 rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
3160 }
3161
3162 #if !CONFIG_REALTIME_ONLY
3163 // This function is designed to apply a bias or adjustment to an rd value based
3164 // on the relative variance of the source and reconstruction.
3165 #define LOW_VAR_THRESH 250
3166 #define VAR_MULT 250
3167 static unsigned int max_var_adjust[VP9E_CONTENT_INVALID] = { 16, 16, 250 };
3168
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)3169 static void rd_variance_adjustment(VP9_COMP *cpi, MACROBLOCK *x,
3170 BLOCK_SIZE bsize, int64_t *this_rd,
3171 struct buf_2d *recon,
3172 MV_REFERENCE_FRAME ref_frame,
3173 MV_REFERENCE_FRAME second_ref_frame,
3174 PREDICTION_MODE this_mode) {
3175 MACROBLOCKD *const xd = &x->e_mbd;
3176 unsigned int rec_variance;
3177 unsigned int src_variance;
3178 unsigned int src_rec_min;
3179 unsigned int var_diff = 0;
3180 unsigned int var_factor = 0;
3181 unsigned int adj_max;
3182 unsigned int low_var_thresh = LOW_VAR_THRESH;
3183 const int bw = num_8x8_blocks_wide_lookup[bsize];
3184 const int bh = num_8x8_blocks_high_lookup[bsize];
3185 vp9e_tune_content content_type = cpi->oxcf.content;
3186
3187 if (*this_rd == INT64_MAX) return;
3188
3189 #if CONFIG_VP9_HIGHBITDEPTH
3190 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3191 rec_variance = vp9_high_get_sby_variance(cpi, recon, bsize, xd->bd);
3192 src_variance =
3193 vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, xd->bd);
3194 } else {
3195 rec_variance = vp9_get_sby_variance(cpi, recon, bsize);
3196 src_variance = vp9_get_sby_variance(cpi, &x->plane[0].src, bsize);
3197 }
3198 #else
3199 rec_variance = vp9_get_sby_variance(cpi, recon, bsize);
3200 src_variance = vp9_get_sby_variance(cpi, &x->plane[0].src, bsize);
3201 #endif // CONFIG_VP9_HIGHBITDEPTH
3202
3203 // Scale based on area in 8x8 blocks
3204 rec_variance /= (bw * bh);
3205 src_variance /= (bw * bh);
3206
3207 if (content_type == VP9E_CONTENT_FILM) {
3208 if (cpi->oxcf.pass == 2) {
3209 // Adjust low variance threshold based on estimated group noise enegry.
3210 double noise_factor =
3211 (double)cpi->twopass.gf_group.group_noise_energy / SECTION_NOISE_DEF;
3212 low_var_thresh = (unsigned int)(low_var_thresh * noise_factor);
3213
3214 if (ref_frame == INTRA_FRAME) {
3215 low_var_thresh *= 2;
3216 if (this_mode == DC_PRED) low_var_thresh *= 5;
3217 } else if (second_ref_frame > INTRA_FRAME) {
3218 low_var_thresh *= 2;
3219 }
3220 }
3221 } else {
3222 low_var_thresh = LOW_VAR_THRESH / 2;
3223 }
3224
3225 // Lower of source (raw per pixel value) and recon variance. Note that
3226 // if the source per pixel is 0 then the recon value here will not be per
3227 // pixel (see above) so will likely be much larger.
3228 src_rec_min = VPXMIN(src_variance, rec_variance);
3229
3230 if (src_rec_min > low_var_thresh) return;
3231
3232 // We care more when the reconstruction has lower variance so give this case
3233 // a stronger weighting.
3234 var_diff = (src_variance > rec_variance) ? (src_variance - rec_variance) * 2
3235 : (rec_variance - src_variance) / 2;
3236
3237 adj_max = max_var_adjust[content_type];
3238
3239 var_factor =
3240 (unsigned int)((int64_t)VAR_MULT * var_diff) / VPXMAX(1, src_variance);
3241 var_factor = VPXMIN(adj_max, var_factor);
3242
3243 if ((content_type == VP9E_CONTENT_FILM) &&
3244 ((ref_frame == INTRA_FRAME) || (second_ref_frame > INTRA_FRAME))) {
3245 var_factor *= 2;
3246 }
3247
3248 *this_rd += (*this_rd * var_factor) / 100;
3249
3250 (void)xd;
3251 }
3252 #endif // !CONFIG_REALTIME_ONLY
3253
3254 // Do we have an internal image edge (e.g. formatting bars).
vp9_internal_image_edge(VP9_COMP * cpi)3255 int vp9_internal_image_edge(VP9_COMP *cpi) {
3256 return (cpi->oxcf.pass == 2) &&
3257 ((cpi->twopass.this_frame_stats.inactive_zone_rows > 0) ||
3258 (cpi->twopass.this_frame_stats.inactive_zone_cols > 0));
3259 }
3260
3261 // Checks to see if a super block is on a horizontal image edge.
3262 // In most cases this is the "real" edge unless there are formatting
3263 // bars embedded in the stream.
vp9_active_h_edge(VP9_COMP * cpi,int mi_row,int mi_step)3264 int vp9_active_h_edge(VP9_COMP *cpi, int mi_row, int mi_step) {
3265 int top_edge = 0;
3266 int bottom_edge = cpi->common.mi_rows;
3267 int is_active_h_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 vpx_clear_system_state();
3273
3274 // The inactive region is specified in MBs not mi units.
3275 // The image edge is in the following MB row.
3276 top_edge += (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
3277
3278 bottom_edge -= (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
3279 bottom_edge = VPXMAX(top_edge, bottom_edge);
3280 }
3281
3282 if (((top_edge >= mi_row) && (top_edge < (mi_row + mi_step))) ||
3283 ((bottom_edge >= mi_row) && (bottom_edge < (mi_row + mi_step)))) {
3284 is_active_h_edge = 1;
3285 }
3286 return is_active_h_edge;
3287 }
3288
3289 // Checks to see if a super block is on a vertical image edge.
3290 // In most cases this is the "real" edge unless there are formatting
3291 // bars embedded in the stream.
vp9_active_v_edge(VP9_COMP * cpi,int mi_col,int mi_step)3292 int vp9_active_v_edge(VP9_COMP *cpi, int mi_col, int mi_step) {
3293 int left_edge = 0;
3294 int right_edge = cpi->common.mi_cols;
3295 int is_active_v_edge = 0;
3296
3297 // For two pass account for any formatting bars detected.
3298 if (cpi->oxcf.pass == 2) {
3299 TWO_PASS *twopass = &cpi->twopass;
3300 vpx_clear_system_state();
3301
3302 // The inactive region is specified in MBs not mi units.
3303 // The image edge is in the following MB row.
3304 left_edge += (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
3305
3306 right_edge -= (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
3307 right_edge = VPXMAX(left_edge, right_edge);
3308 }
3309
3310 if (((left_edge >= mi_col) && (left_edge < (mi_col + mi_step))) ||
3311 ((right_edge >= mi_col) && (right_edge < (mi_col + mi_step)))) {
3312 is_active_v_edge = 1;
3313 }
3314 return is_active_v_edge;
3315 }
3316
3317 // Checks to see if a super block is at the edge of the active image.
3318 // In most cases this is the "real" edge unless there are formatting
3319 // bars embedded in the stream.
vp9_active_edge_sb(VP9_COMP * cpi,int mi_row,int mi_col)3320 int vp9_active_edge_sb(VP9_COMP *cpi, int mi_row, int mi_col) {
3321 return vp9_active_h_edge(cpi, mi_row, MI_BLOCK_SIZE) ||
3322 vp9_active_v_edge(cpi, mi_col, MI_BLOCK_SIZE);
3323 }
3324
3325 #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)3326 void vp9_rd_pick_inter_mode_sb(VP9_COMP *cpi, TileDataEnc *tile_data,
3327 MACROBLOCK *x, int mi_row, int mi_col,
3328 RD_COST *rd_cost, BLOCK_SIZE bsize,
3329 PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far) {
3330 VP9_COMMON *const cm = &cpi->common;
3331 TileInfo *const tile_info = &tile_data->tile_info;
3332 RD_OPT *const rd_opt = &cpi->rd;
3333 SPEED_FEATURES *const sf = &cpi->sf;
3334 MACROBLOCKD *const xd = &x->e_mbd;
3335 MODE_INFO *const mi = xd->mi[0];
3336 MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
3337 const struct segmentation *const seg = &cm->seg;
3338 PREDICTION_MODE this_mode;
3339 MV_REFERENCE_FRAME ref_frame, second_ref_frame;
3340 unsigned char segment_id = mi->segment_id;
3341 int comp_pred, i, k;
3342 int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
3343 struct buf_2d yv12_mb[4][MAX_MB_PLANE];
3344 int_mv single_newmv[MAX_REF_FRAMES] = { { 0 } };
3345 INTERP_FILTER single_inter_filter[MB_MODE_COUNT][MAX_REF_FRAMES];
3346 int single_skippable[MB_MODE_COUNT][MAX_REF_FRAMES];
3347 int64_t best_rd = best_rd_so_far;
3348 int64_t best_pred_diff[REFERENCE_MODES];
3349 int64_t best_pred_rd[REFERENCE_MODES];
3350 int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
3351 int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
3352 MODE_INFO best_mbmode;
3353 int best_mode_skippable = 0;
3354 int midx, best_mode_index = -1;
3355 unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
3356 vpx_prob comp_mode_p;
3357 int64_t best_intra_rd = INT64_MAX;
3358 unsigned int best_pred_sse = UINT_MAX;
3359 PREDICTION_MODE best_intra_mode = DC_PRED;
3360 int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
3361 int64_t dist_uv[TX_SIZES];
3362 int skip_uv[TX_SIZES];
3363 PREDICTION_MODE mode_uv[TX_SIZES];
3364 const int intra_cost_penalty =
3365 vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
3366 int best_skip2 = 0;
3367 uint8_t ref_frame_skip_mask[2] = { 0, 1 };
3368 uint16_t mode_skip_mask[MAX_REF_FRAMES] = { 0 };
3369 int mode_skip_start = sf->mode_skip_start + 1;
3370 const int *const rd_threshes = rd_opt->threshes[segment_id][bsize];
3371 const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
3372 int64_t mode_threshold[MAX_MODES];
3373 int8_t *tile_mode_map = tile_data->mode_map[bsize];
3374 int8_t mode_map[MAX_MODES]; // Maintain mode_map information locally to avoid
3375 // lock mechanism involved with reads from
3376 // tile_mode_map
3377 const int mode_search_skip_flags = sf->mode_search_skip_flags;
3378 const int is_rect_partition =
3379 num_4x4_blocks_wide_lookup[bsize] != num_4x4_blocks_high_lookup[bsize];
3380 int64_t mask_filter = 0;
3381 int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
3382
3383 struct buf_2d *recon;
3384 struct buf_2d recon_buf;
3385 #if CONFIG_VP9_HIGHBITDEPTH
3386 DECLARE_ALIGNED(16, uint16_t, recon16[64 * 64]);
3387 recon_buf.buf = xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH
3388 ? CONVERT_TO_BYTEPTR(recon16)
3389 : (uint8_t *)recon16;
3390 #else
3391 DECLARE_ALIGNED(16, uint8_t, recon8[64 * 64]);
3392 recon_buf.buf = recon8;
3393 #endif // CONFIG_VP9_HIGHBITDEPTH
3394 recon_buf.stride = 64;
3395 recon = cpi->oxcf.content == VP9E_CONTENT_FILM ? &recon_buf : 0;
3396
3397 vp9_zero(best_mbmode);
3398
3399 x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
3400
3401 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
3402
3403 estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
3404 &comp_mode_p);
3405
3406 for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
3407 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3408 best_filter_rd[i] = INT64_MAX;
3409 for (i = 0; i < TX_SIZES; i++) rate_uv_intra[i] = INT_MAX;
3410 for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
3411 for (i = 0; i < MB_MODE_COUNT; ++i) {
3412 for (k = 0; k < MAX_REF_FRAMES; ++k) {
3413 single_inter_filter[i][k] = SWITCHABLE;
3414 single_skippable[i][k] = 0;
3415 }
3416 }
3417
3418 rd_cost->rate = INT_MAX;
3419
3420 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3421 x->pred_mv_sad[ref_frame] = INT_MAX;
3422 if ((cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) &&
3423 !(is_rect_partition && (ctx->skip_ref_frame_mask & (1 << ref_frame)))) {
3424 assert(get_ref_frame_buffer(cpi, ref_frame) != NULL);
3425 setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
3426 frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
3427 }
3428 frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
3429 frame_mv[ZEROMV][ref_frame].as_int = 0;
3430 }
3431
3432 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3433 if (!(cpi->ref_frame_flags & ref_frame_to_flag(ref_frame))) {
3434 // Skip checking missing references in both single and compound reference
3435 // modes. Note that a mode will be skipped if both reference frames
3436 // are masked out.
3437 ref_frame_skip_mask[0] |= (1 << ref_frame);
3438 ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3439 } else if (sf->reference_masking) {
3440 for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
3441 // Skip fixed mv modes for poor references
3442 if ((x->pred_mv_sad[ref_frame] >> 2) > x->pred_mv_sad[i]) {
3443 mode_skip_mask[ref_frame] |= INTER_NEAREST_NEAR_ZERO;
3444 break;
3445 }
3446 }
3447 }
3448 // If the segment reference frame feature is enabled....
3449 // then do nothing if the current ref frame is not allowed..
3450 if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
3451 get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
3452 ref_frame_skip_mask[0] |= (1 << ref_frame);
3453 ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
3454 }
3455 }
3456
3457 // Disable this drop out case if the ref frame
3458 // segment level feature is enabled for this segment. This is to
3459 // prevent the possibility that we end up unable to pick any mode.
3460 if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
3461 // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
3462 // unless ARNR filtering is enabled in which case we want
3463 // an unfiltered alternative. We allow near/nearest as well
3464 // because they may result in zero-zero MVs but be cheaper.
3465 if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0)) {
3466 ref_frame_skip_mask[0] = (1 << LAST_FRAME) | (1 << GOLDEN_FRAME);
3467 ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
3468 mode_skip_mask[ALTREF_FRAME] = ~INTER_NEAREST_NEAR_ZERO;
3469 if (frame_mv[NEARMV][ALTREF_FRAME].as_int != 0)
3470 mode_skip_mask[ALTREF_FRAME] |= (1 << NEARMV);
3471 if (frame_mv[NEARESTMV][ALTREF_FRAME].as_int != 0)
3472 mode_skip_mask[ALTREF_FRAME] |= (1 << NEARESTMV);
3473 }
3474 }
3475
3476 if (cpi->rc.is_src_frame_alt_ref) {
3477 if (sf->alt_ref_search_fp) {
3478 mode_skip_mask[ALTREF_FRAME] = 0;
3479 ref_frame_skip_mask[0] = ~(1 << ALTREF_FRAME) & 0xff;
3480 ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
3481 }
3482 }
3483
3484 if (sf->alt_ref_search_fp)
3485 if (!cm->show_frame && x->pred_mv_sad[GOLDEN_FRAME] < INT_MAX)
3486 if (x->pred_mv_sad[ALTREF_FRAME] > (x->pred_mv_sad[GOLDEN_FRAME] << 1))
3487 mode_skip_mask[ALTREF_FRAME] |= INTER_ALL;
3488
3489 if (sf->adaptive_mode_search) {
3490 if (cm->show_frame && !cpi->rc.is_src_frame_alt_ref &&
3491 cpi->rc.frames_since_golden >= 3)
3492 if (x->pred_mv_sad[GOLDEN_FRAME] > (x->pred_mv_sad[LAST_FRAME] << 1))
3493 mode_skip_mask[GOLDEN_FRAME] |= INTER_ALL;
3494 }
3495
3496 if (bsize > sf->max_intra_bsize) {
3497 ref_frame_skip_mask[0] |= (1 << INTRA_FRAME);
3498 ref_frame_skip_mask[1] |= (1 << INTRA_FRAME);
3499 }
3500
3501 mode_skip_mask[INTRA_FRAME] |=
3502 (uint16_t) ~(sf->intra_y_mode_mask[max_txsize_lookup[bsize]]);
3503
3504 for (i = 0; i <= LAST_NEW_MV_INDEX; ++i) mode_threshold[i] = 0;
3505
3506 for (i = LAST_NEW_MV_INDEX + 1; i < MAX_MODES; ++i)
3507 mode_threshold[i] = ((int64_t)rd_threshes[i] * rd_thresh_freq_fact[i]) >> 5;
3508
3509 midx = sf->schedule_mode_search ? mode_skip_start : 0;
3510
3511 while (midx > 4) {
3512 uint8_t end_pos = 0;
3513 for (i = 5; i < midx; ++i) {
3514 if (mode_threshold[tile_mode_map[i - 1]] >
3515 mode_threshold[tile_mode_map[i]]) {
3516 uint8_t tmp = tile_mode_map[i];
3517 tile_mode_map[i] = tile_mode_map[i - 1];
3518 tile_mode_map[i - 1] = tmp;
3519 end_pos = i;
3520 }
3521 }
3522 midx = end_pos;
3523 }
3524
3525 memcpy(mode_map, tile_mode_map, sizeof(mode_map));
3526
3527 for (midx = 0; midx < MAX_MODES; ++midx) {
3528 int mode_index = mode_map[midx];
3529 int mode_excluded = 0;
3530 int64_t this_rd = INT64_MAX;
3531 int disable_skip = 0;
3532 int compmode_cost = 0;
3533 int rate2 = 0, rate_y = 0, rate_uv = 0;
3534 int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
3535 int skippable = 0;
3536 int this_skip2 = 0;
3537 int64_t total_sse = INT64_MAX;
3538 int early_term = 0;
3539
3540 this_mode = vp9_mode_order[mode_index].mode;
3541 ref_frame = vp9_mode_order[mode_index].ref_frame[0];
3542 second_ref_frame = vp9_mode_order[mode_index].ref_frame[1];
3543
3544 vp9_zero(x->sum_y_eobs);
3545
3546 if (is_rect_partition) {
3547 if (ctx->skip_ref_frame_mask & (1 << ref_frame)) continue;
3548 if (second_ref_frame > 0 &&
3549 (ctx->skip_ref_frame_mask & (1 << second_ref_frame)))
3550 continue;
3551 }
3552
3553 // Look at the reference frame of the best mode so far and set the
3554 // skip mask to look at a subset of the remaining modes.
3555 if (midx == mode_skip_start && best_mode_index >= 0) {
3556 switch (best_mbmode.ref_frame[0]) {
3557 case INTRA_FRAME: break;
3558 case LAST_FRAME: ref_frame_skip_mask[0] |= LAST_FRAME_MODE_MASK; break;
3559 case GOLDEN_FRAME:
3560 ref_frame_skip_mask[0] |= GOLDEN_FRAME_MODE_MASK;
3561 break;
3562 case ALTREF_FRAME: ref_frame_skip_mask[0] |= ALT_REF_MODE_MASK; break;
3563 case NONE:
3564 case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
3565 }
3566 }
3567
3568 if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
3569 (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
3570 continue;
3571
3572 if (mode_skip_mask[ref_frame] & (1 << this_mode)) continue;
3573
3574 // Test best rd so far against threshold for trying this mode.
3575 if (best_mode_skippable && sf->schedule_mode_search)
3576 mode_threshold[mode_index] <<= 1;
3577
3578 if (best_rd < mode_threshold[mode_index]) continue;
3579
3580 // This is only used in motion vector unit test.
3581 if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
3582
3583 if (sf->motion_field_mode_search) {
3584 const int mi_width = VPXMIN(num_8x8_blocks_wide_lookup[bsize],
3585 tile_info->mi_col_end - mi_col);
3586 const int mi_height = VPXMIN(num_8x8_blocks_high_lookup[bsize],
3587 tile_info->mi_row_end - mi_row);
3588 const int bsl = mi_width_log2_lookup[bsize];
3589 int cb_partition_search_ctrl =
3590 (((mi_row + mi_col) >> bsl) +
3591 get_chessboard_index(cm->current_video_frame)) &
3592 0x1;
3593 MODE_INFO *ref_mi;
3594 int const_motion = 1;
3595 int skip_ref_frame = !cb_partition_search_ctrl;
3596 MV_REFERENCE_FRAME rf = NONE;
3597 int_mv ref_mv;
3598 ref_mv.as_int = INVALID_MV;
3599
3600 if ((mi_row - 1) >= tile_info->mi_row_start) {
3601 ref_mv = xd->mi[-xd->mi_stride]->mv[0];
3602 rf = xd->mi[-xd->mi_stride]->ref_frame[0];
3603 for (i = 0; i < mi_width; ++i) {
3604 ref_mi = xd->mi[-xd->mi_stride + i];
3605 const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
3606 (ref_frame == ref_mi->ref_frame[0]);
3607 skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
3608 }
3609 }
3610
3611 if ((mi_col - 1) >= tile_info->mi_col_start) {
3612 if (ref_mv.as_int == INVALID_MV) ref_mv = xd->mi[-1]->mv[0];
3613 if (rf == NONE) rf = xd->mi[-1]->ref_frame[0];
3614 for (i = 0; i < mi_height; ++i) {
3615 ref_mi = xd->mi[i * xd->mi_stride - 1];
3616 const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
3617 (ref_frame == ref_mi->ref_frame[0]);
3618 skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
3619 }
3620 }
3621
3622 if (skip_ref_frame && this_mode != NEARESTMV && this_mode != NEWMV)
3623 if (rf > INTRA_FRAME)
3624 if (ref_frame != rf) continue;
3625
3626 if (const_motion)
3627 if (this_mode == NEARMV || this_mode == ZEROMV) continue;
3628 }
3629
3630 comp_pred = second_ref_frame > INTRA_FRAME;
3631 if (comp_pred) {
3632 if (!cpi->allow_comp_inter_inter) continue;
3633
3634 if (cm->ref_frame_sign_bias[ref_frame] ==
3635 cm->ref_frame_sign_bias[second_ref_frame])
3636 continue;
3637
3638 // Skip compound inter modes if ARF is not available.
3639 if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
3640 continue;
3641
3642 // Do not allow compound prediction if the segment level reference frame
3643 // feature is in use as in this case there can only be one reference.
3644 if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
3645
3646 if ((mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
3647 best_mode_index >= 0 && best_mbmode.ref_frame[0] == INTRA_FRAME)
3648 continue;
3649
3650 mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
3651 } else {
3652 if (ref_frame != INTRA_FRAME)
3653 mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
3654 }
3655
3656 if (ref_frame == INTRA_FRAME) {
3657 if (sf->adaptive_mode_search)
3658 if ((x->source_variance << num_pels_log2_lookup[bsize]) > best_pred_sse)
3659 continue;
3660
3661 if (this_mode != DC_PRED) {
3662 // Disable intra modes other than DC_PRED for blocks with low variance
3663 // Threshold for intra skipping based on source variance
3664 // TODO(debargha): Specialize the threshold for super block sizes
3665 const unsigned int skip_intra_var_thresh =
3666 (cpi->oxcf.content == VP9E_CONTENT_FILM) ? 0 : 64;
3667 if ((mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
3668 x->source_variance < skip_intra_var_thresh)
3669 continue;
3670 // Only search the oblique modes if the best so far is
3671 // one of the neighboring directional modes
3672 if ((mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
3673 (this_mode >= D45_PRED && this_mode <= TM_PRED)) {
3674 if (best_mode_index >= 0 && best_mbmode.ref_frame[0] > INTRA_FRAME)
3675 continue;
3676 }
3677 if (mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
3678 if (conditional_skipintra(this_mode, best_intra_mode)) continue;
3679 }
3680 }
3681 } else {
3682 const MV_REFERENCE_FRAME ref_frames[2] = { ref_frame, second_ref_frame };
3683 if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv, this_mode,
3684 ref_frames))
3685 continue;
3686 }
3687
3688 mi->mode = this_mode;
3689 mi->uv_mode = DC_PRED;
3690 mi->ref_frame[0] = ref_frame;
3691 mi->ref_frame[1] = second_ref_frame;
3692 // Evaluate all sub-pel filters irrespective of whether we can use
3693 // them for this frame.
3694 mi->interp_filter =
3695 cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
3696 mi->mv[0].as_int = mi->mv[1].as_int = 0;
3697
3698 x->skip = 0;
3699 set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
3700
3701 // Select prediction reference frames.
3702 for (i = 0; i < MAX_MB_PLANE; i++) {
3703 xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
3704 if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
3705 }
3706
3707 if (ref_frame == INTRA_FRAME) {
3708 TX_SIZE uv_tx;
3709 struct macroblockd_plane *const pd = &xd->plane[1];
3710 memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
3711 super_block_yrd(cpi, x, &rate_y, &distortion_y, &skippable, NULL, bsize,
3712 best_rd, recon);
3713 if (rate_y == INT_MAX) continue;
3714
3715 uv_tx = uv_txsize_lookup[bsize][mi->tx_size][pd->subsampling_x]
3716 [pd->subsampling_y];
3717 if (rate_uv_intra[uv_tx] == INT_MAX) {
3718 choose_intra_uv_mode(cpi, x, ctx, bsize, uv_tx, &rate_uv_intra[uv_tx],
3719 &rate_uv_tokenonly[uv_tx], &dist_uv[uv_tx],
3720 &skip_uv[uv_tx], &mode_uv[uv_tx]);
3721 }
3722
3723 rate_uv = rate_uv_tokenonly[uv_tx];
3724 distortion_uv = dist_uv[uv_tx];
3725 skippable = skippable && skip_uv[uv_tx];
3726 mi->uv_mode = mode_uv[uv_tx];
3727
3728 rate2 = rate_y + cpi->mbmode_cost[mi->mode] + rate_uv_intra[uv_tx];
3729 if (this_mode != DC_PRED && this_mode != TM_PRED)
3730 rate2 += intra_cost_penalty;
3731 distortion2 = distortion_y + distortion_uv;
3732 } else {
3733 this_rd = handle_inter_mode(
3734 cpi, x, bsize, &rate2, &distortion2, &skippable, &rate_y, &rate_uv,
3735 recon, &disable_skip, frame_mv, mi_row, mi_col, single_newmv,
3736 single_inter_filter, single_skippable, &total_sse, best_rd,
3737 &mask_filter, filter_cache);
3738 if (this_rd == INT64_MAX) continue;
3739
3740 compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
3741
3742 if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
3743 }
3744
3745 // Estimate the reference frame signaling cost and add it
3746 // to the rolling cost variable.
3747 if (comp_pred) {
3748 rate2 += ref_costs_comp[ref_frame];
3749 } else {
3750 rate2 += ref_costs_single[ref_frame];
3751 }
3752
3753 if (!disable_skip) {
3754 const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
3755 const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
3756 const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
3757
3758 if (skippable) {
3759 // Back out the coefficient coding costs
3760 rate2 -= (rate_y + rate_uv);
3761
3762 // Cost the skip mb case
3763 rate2 += skip_cost1;
3764 } else if (ref_frame != INTRA_FRAME && !xd->lossless &&
3765 !cpi->oxcf.sharpness) {
3766 if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
3767 distortion2) <
3768 RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
3769 // Add in the cost of the no skip flag.
3770 rate2 += skip_cost0;
3771 } else {
3772 // FIXME(rbultje) make this work for splitmv also
3773 assert(total_sse >= 0);
3774
3775 rate2 += skip_cost1;
3776 distortion2 = total_sse;
3777 rate2 -= (rate_y + rate_uv);
3778 this_skip2 = 1;
3779 }
3780 } else {
3781 // Add in the cost of the no skip flag.
3782 rate2 += skip_cost0;
3783 }
3784
3785 // Calculate the final RD estimate for this mode.
3786 this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
3787 }
3788
3789 if (recon) {
3790 // In film mode bias against DC pred and other intra if there is a
3791 // significant difference between the variance of the sub blocks in the
3792 // the source. Also apply some bias against compound modes which also
3793 // tend to blur fine texture such as film grain over time.
3794 //
3795 // The sub block test here acts in the case where one or more sub
3796 // blocks have high relatively variance but others relatively low
3797 // variance. Here the high variance sub blocks may push the
3798 // total variance for the current block size over the thresholds
3799 // used in rd_variance_adjustment() below.
3800 if (cpi->oxcf.content == VP9E_CONTENT_FILM) {
3801 if (bsize >= BLOCK_16X16) {
3802 int min_energy, max_energy;
3803 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3804 &max_energy);
3805 if (max_energy > min_energy) {
3806 if (ref_frame == INTRA_FRAME) {
3807 if (this_mode == DC_PRED)
3808 this_rd += (this_rd * (max_energy - min_energy));
3809 else
3810 this_rd += (this_rd * (max_energy - min_energy)) / 4;
3811 } else if (second_ref_frame > INTRA_FRAME) {
3812 this_rd += this_rd / 4;
3813 }
3814 }
3815 }
3816 }
3817 // Apply an adjustment to the rd value based on the similarity of the
3818 // source variance and reconstructed variance.
3819 rd_variance_adjustment(cpi, x, bsize, &this_rd, recon, ref_frame,
3820 second_ref_frame, this_mode);
3821 }
3822
3823 if (ref_frame == INTRA_FRAME) {
3824 // Keep record of best intra rd
3825 if (this_rd < best_intra_rd) {
3826 best_intra_rd = this_rd;
3827 best_intra_mode = mi->mode;
3828 }
3829 }
3830
3831 if (!disable_skip && ref_frame == INTRA_FRAME) {
3832 for (i = 0; i < REFERENCE_MODES; ++i)
3833 best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
3834 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
3835 best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
3836 }
3837
3838 // Did this mode help.. i.e. is it the new best mode
3839 if (this_rd < best_rd || x->skip) {
3840 int max_plane = MAX_MB_PLANE;
3841 if (!mode_excluded) {
3842 // Note index of best mode so far
3843 best_mode_index = mode_index;
3844
3845 if (ref_frame == INTRA_FRAME) {
3846 /* required for left and above block mv */
3847 mi->mv[0].as_int = 0;
3848 max_plane = 1;
3849 // Initialize interp_filter here so we do not have to check for
3850 // inter block modes in get_pred_context_switchable_interp()
3851 mi->interp_filter = SWITCHABLE_FILTERS;
3852 } else {
3853 best_pred_sse = x->pred_sse[ref_frame];
3854 }
3855
3856 rd_cost->rate = rate2;
3857 rd_cost->dist = distortion2;
3858 rd_cost->rdcost = this_rd;
3859 best_rd = this_rd;
3860 best_mbmode = *mi;
3861 best_skip2 = this_skip2;
3862 best_mode_skippable = skippable;
3863
3864 if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
3865 memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mi->tx_size],
3866 sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
3867 ctx->sum_y_eobs = x->sum_y_eobs[mi->tx_size];
3868
3869 // TODO(debargha): enhance this test with a better distortion prediction
3870 // based on qp, activity mask and history
3871 if ((mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
3872 (mode_index > MIN_EARLY_TERM_INDEX)) {
3873 int qstep = xd->plane[0].dequant[1];
3874 // TODO(debargha): Enhance this by specializing for each mode_index
3875 int scale = 4;
3876 #if CONFIG_VP9_HIGHBITDEPTH
3877 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3878 qstep >>= (xd->bd - 8);
3879 }
3880 #endif // CONFIG_VP9_HIGHBITDEPTH
3881 if (x->source_variance < UINT_MAX) {
3882 const int var_adjust = (x->source_variance < 16);
3883 scale -= var_adjust;
3884 }
3885 if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
3886 early_term = 1;
3887 }
3888 }
3889 }
3890 }
3891
3892 /* keep record of best compound/single-only prediction */
3893 if (!disable_skip && ref_frame != INTRA_FRAME) {
3894 int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
3895
3896 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
3897 single_rate = rate2 - compmode_cost;
3898 hybrid_rate = rate2;
3899 } else {
3900 single_rate = rate2;
3901 hybrid_rate = rate2 + compmode_cost;
3902 }
3903
3904 single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
3905 hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
3906
3907 if (!comp_pred) {
3908 if (single_rd < best_pred_rd[SINGLE_REFERENCE])
3909 best_pred_rd[SINGLE_REFERENCE] = single_rd;
3910 } else {
3911 if (single_rd < best_pred_rd[COMPOUND_REFERENCE])
3912 best_pred_rd[COMPOUND_REFERENCE] = single_rd;
3913 }
3914 if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
3915 best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
3916
3917 /* keep record of best filter type */
3918 if (!mode_excluded && cm->interp_filter != BILINEAR) {
3919 int64_t ref =
3920 filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
3921 : cm->interp_filter];
3922
3923 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
3924 int64_t adj_rd;
3925 if (ref == INT64_MAX)
3926 adj_rd = 0;
3927 else if (filter_cache[i] == INT64_MAX)
3928 // when early termination is triggered, the encoder does not have
3929 // access to the rate-distortion cost. it only knows that the cost
3930 // should be above the maximum valid value. hence it takes the known
3931 // maximum plus an arbitrary constant as the rate-distortion cost.
3932 adj_rd = mask_filter - ref + 10;
3933 else
3934 adj_rd = filter_cache[i] - ref;
3935
3936 adj_rd += this_rd;
3937 best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
3938 }
3939 }
3940 }
3941
3942 if (early_term) break;
3943
3944 if (x->skip && !comp_pred) break;
3945 }
3946
3947 // The inter modes' rate costs are not calculated precisely in some cases.
3948 // Therefore, sometimes, NEWMV is chosen instead of NEARESTMV, NEARMV, and
3949 // ZEROMV. Here, checks are added for those cases, and the mode decisions
3950 // are corrected.
3951 if (best_mbmode.mode == NEWMV) {
3952 const MV_REFERENCE_FRAME refs[2] = { best_mbmode.ref_frame[0],
3953 best_mbmode.ref_frame[1] };
3954 int comp_pred_mode = refs[1] > INTRA_FRAME;
3955
3956 if (frame_mv[NEARESTMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
3957 ((comp_pred_mode &&
3958 frame_mv[NEARESTMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
3959 !comp_pred_mode))
3960 best_mbmode.mode = NEARESTMV;
3961 else if (frame_mv[NEARMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
3962 ((comp_pred_mode &&
3963 frame_mv[NEARMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
3964 !comp_pred_mode))
3965 best_mbmode.mode = NEARMV;
3966 else if (best_mbmode.mv[0].as_int == 0 &&
3967 ((comp_pred_mode && best_mbmode.mv[1].as_int == 0) ||
3968 !comp_pred_mode))
3969 best_mbmode.mode = ZEROMV;
3970 }
3971
3972 if (best_mode_index < 0 || best_rd >= best_rd_so_far) {
3973 // If adaptive interp filter is enabled, then the current leaf node of 8x8
3974 // data is needed for sub8x8. Hence preserve the context.
3975 #if CONFIG_CONSISTENT_RECODE
3976 if (bsize == BLOCK_8X8) ctx->mic = *xd->mi[0];
3977 #else
3978 if (cpi->row_mt && bsize == BLOCK_8X8) ctx->mic = *xd->mi[0];
3979 #endif
3980 rd_cost->rate = INT_MAX;
3981 rd_cost->rdcost = INT64_MAX;
3982 return;
3983 }
3984
3985 // If we used an estimate for the uv intra rd in the loop above...
3986 if (sf->use_uv_intra_rd_estimate) {
3987 // Do Intra UV best rd mode selection if best mode choice above was intra.
3988 if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
3989 TX_SIZE uv_tx_size;
3990 *mi = best_mbmode;
3991 uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
3992 rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
3993 &rate_uv_tokenonly[uv_tx_size],
3994 &dist_uv[uv_tx_size], &skip_uv[uv_tx_size],
3995 bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
3996 uv_tx_size);
3997 }
3998 }
3999
4000 assert((cm->interp_filter == SWITCHABLE) ||
4001 (cm->interp_filter == best_mbmode.interp_filter) ||
4002 !is_inter_block(&best_mbmode));
4003
4004 if (!cpi->rc.is_src_frame_alt_ref)
4005 vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
4006 sf->adaptive_rd_thresh, bsize, best_mode_index);
4007
4008 // macroblock modes
4009 *mi = best_mbmode;
4010 x->skip |= best_skip2;
4011
4012 for (i = 0; i < REFERENCE_MODES; ++i) {
4013 if (best_pred_rd[i] == INT64_MAX)
4014 best_pred_diff[i] = INT_MIN;
4015 else
4016 best_pred_diff[i] = best_rd - best_pred_rd[i];
4017 }
4018
4019 if (!x->skip) {
4020 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4021 if (best_filter_rd[i] == INT64_MAX)
4022 best_filter_diff[i] = 0;
4023 else
4024 best_filter_diff[i] = best_rd - best_filter_rd[i];
4025 }
4026 if (cm->interp_filter == SWITCHABLE)
4027 assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
4028 } else {
4029 vp9_zero(best_filter_diff);
4030 }
4031
4032 // TODO(yunqingwang): Moving this line in front of the above best_filter_diff
4033 // updating code causes PSNR loss. Need to figure out the confliction.
4034 x->skip |= best_mode_skippable;
4035
4036 if (!x->skip && !x->select_tx_size) {
4037 int has_high_freq_coeff = 0;
4038 int plane;
4039 int max_plane = is_inter_block(xd->mi[0]) ? MAX_MB_PLANE : 1;
4040 for (plane = 0; plane < max_plane; ++plane) {
4041 x->plane[plane].eobs = ctx->eobs_pbuf[plane][1];
4042 has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
4043 }
4044
4045 for (plane = max_plane; plane < MAX_MB_PLANE; ++plane) {
4046 x->plane[plane].eobs = ctx->eobs_pbuf[plane][2];
4047 has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
4048 }
4049
4050 best_mode_skippable |= !has_high_freq_coeff;
4051 }
4052
4053 assert(best_mode_index >= 0);
4054
4055 store_coding_context(x, ctx, best_mode_index, best_pred_diff,
4056 best_filter_diff, best_mode_skippable);
4057 }
4058
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)4059 void vp9_rd_pick_inter_mode_sb_seg_skip(VP9_COMP *cpi, TileDataEnc *tile_data,
4060 MACROBLOCK *x, RD_COST *rd_cost,
4061 BLOCK_SIZE bsize,
4062 PICK_MODE_CONTEXT *ctx,
4063 int64_t best_rd_so_far) {
4064 VP9_COMMON *const cm = &cpi->common;
4065 MACROBLOCKD *const xd = &x->e_mbd;
4066 MODE_INFO *const mi = xd->mi[0];
4067 unsigned char segment_id = mi->segment_id;
4068 const int comp_pred = 0;
4069 int i;
4070 int64_t best_pred_diff[REFERENCE_MODES];
4071 int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
4072 unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
4073 vpx_prob comp_mode_p;
4074 INTERP_FILTER best_filter = SWITCHABLE;
4075 int64_t this_rd = INT64_MAX;
4076 int rate2 = 0;
4077 const int64_t distortion2 = 0;
4078
4079 x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
4080
4081 estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
4082 &comp_mode_p);
4083
4084 for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
4085 for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i) x->pred_mv_sad[i] = INT_MAX;
4086
4087 rd_cost->rate = INT_MAX;
4088
4089 assert(segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP));
4090
4091 mi->mode = ZEROMV;
4092 mi->uv_mode = DC_PRED;
4093 mi->ref_frame[0] = LAST_FRAME;
4094 mi->ref_frame[1] = NONE;
4095 mi->mv[0].as_int = 0;
4096 x->skip = 1;
4097
4098 ctx->sum_y_eobs = 0;
4099
4100 if (cm->interp_filter != BILINEAR) {
4101 best_filter = EIGHTTAP;
4102 if (cm->interp_filter == SWITCHABLE &&
4103 x->source_variance >= cpi->sf.disable_filter_search_var_thresh) {
4104 int rs;
4105 int best_rs = INT_MAX;
4106 for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
4107 mi->interp_filter = i;
4108 rs = vp9_get_switchable_rate(cpi, xd);
4109 if (rs < best_rs) {
4110 best_rs = rs;
4111 best_filter = mi->interp_filter;
4112 }
4113 }
4114 }
4115 }
4116 // Set the appropriate filter
4117 if (cm->interp_filter == SWITCHABLE) {
4118 mi->interp_filter = best_filter;
4119 rate2 += vp9_get_switchable_rate(cpi, xd);
4120 } else {
4121 mi->interp_filter = cm->interp_filter;
4122 }
4123
4124 if (cm->reference_mode == REFERENCE_MODE_SELECT)
4125 rate2 += vp9_cost_bit(comp_mode_p, comp_pred);
4126
4127 // Estimate the reference frame signaling cost and add it
4128 // to the rolling cost variable.
4129 rate2 += ref_costs_single[LAST_FRAME];
4130 this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
4131
4132 rd_cost->rate = rate2;
4133 rd_cost->dist = distortion2;
4134 rd_cost->rdcost = this_rd;
4135
4136 if (this_rd >= best_rd_so_far) {
4137 rd_cost->rate = INT_MAX;
4138 rd_cost->rdcost = INT64_MAX;
4139 return;
4140 }
4141
4142 assert((cm->interp_filter == SWITCHABLE) ||
4143 (cm->interp_filter == mi->interp_filter));
4144
4145 vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
4146 cpi->sf.adaptive_rd_thresh, bsize, THR_ZEROMV);
4147
4148 vp9_zero(best_pred_diff);
4149 vp9_zero(best_filter_diff);
4150
4151 if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, MAX_MB_PLANE);
4152 store_coding_context(x, ctx, THR_ZEROMV, best_pred_diff, best_filter_diff, 0);
4153 }
4154
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)4155 void vp9_rd_pick_inter_mode_sub8x8(VP9_COMP *cpi, TileDataEnc *tile_data,
4156 MACROBLOCK *x, int mi_row, int mi_col,
4157 RD_COST *rd_cost, BLOCK_SIZE bsize,
4158 PICK_MODE_CONTEXT *ctx,
4159 int64_t best_rd_so_far) {
4160 VP9_COMMON *const cm = &cpi->common;
4161 RD_OPT *const rd_opt = &cpi->rd;
4162 SPEED_FEATURES *const sf = &cpi->sf;
4163 MACROBLOCKD *const xd = &x->e_mbd;
4164 MODE_INFO *const mi = xd->mi[0];
4165 const struct segmentation *const seg = &cm->seg;
4166 MV_REFERENCE_FRAME ref_frame, second_ref_frame;
4167 unsigned char segment_id = mi->segment_id;
4168 int comp_pred, i;
4169 int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
4170 struct buf_2d yv12_mb[4][MAX_MB_PLANE];
4171 int64_t best_rd = best_rd_so_far;
4172 int64_t best_yrd = best_rd_so_far; // FIXME(rbultje) more precise
4173 int64_t best_pred_diff[REFERENCE_MODES];
4174 int64_t best_pred_rd[REFERENCE_MODES];
4175 int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
4176 int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
4177 MODE_INFO best_mbmode;
4178 int ref_index, best_ref_index = 0;
4179 unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
4180 vpx_prob comp_mode_p;
4181 INTERP_FILTER tmp_best_filter = SWITCHABLE;
4182 int rate_uv_intra, rate_uv_tokenonly;
4183 int64_t dist_uv;
4184 int skip_uv;
4185 PREDICTION_MODE mode_uv = DC_PRED;
4186 const int intra_cost_penalty =
4187 vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
4188 int_mv seg_mvs[4][MAX_REF_FRAMES];
4189 b_mode_info best_bmodes[4];
4190 int best_skip2 = 0;
4191 int ref_frame_skip_mask[2] = { 0 };
4192 int64_t mask_filter = 0;
4193 int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
4194 int internal_active_edge =
4195 vp9_active_edge_sb(cpi, mi_row, mi_col) && vp9_internal_image_edge(cpi);
4196 const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
4197
4198 x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
4199 memset(x->zcoeff_blk[TX_4X4], 0, 4);
4200 vp9_zero(best_mbmode);
4201
4202 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
4203
4204 for (i = 0; i < 4; i++) {
4205 int j;
4206 for (j = 0; j < MAX_REF_FRAMES; j++) seg_mvs[i][j].as_int = INVALID_MV;
4207 }
4208
4209 estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
4210 &comp_mode_p);
4211
4212 for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
4213 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
4214 best_filter_rd[i] = INT64_MAX;
4215 rate_uv_intra = INT_MAX;
4216
4217 rd_cost->rate = INT_MAX;
4218
4219 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
4220 if (cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) {
4221 setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
4222 frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
4223 } else {
4224 ref_frame_skip_mask[0] |= (1 << ref_frame);
4225 ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4226 }
4227 frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
4228 frame_mv[ZEROMV][ref_frame].as_int = 0;
4229 }
4230
4231 for (ref_index = 0; ref_index < MAX_REFS; ++ref_index) {
4232 int mode_excluded = 0;
4233 int64_t this_rd = INT64_MAX;
4234 int disable_skip = 0;
4235 int compmode_cost = 0;
4236 int rate2 = 0, rate_y = 0, rate_uv = 0;
4237 int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
4238 int skippable = 0;
4239 int i;
4240 int this_skip2 = 0;
4241 int64_t total_sse = INT_MAX;
4242 int early_term = 0;
4243 struct buf_2d backup_yv12[2][MAX_MB_PLANE];
4244
4245 ref_frame = vp9_ref_order[ref_index].ref_frame[0];
4246 second_ref_frame = vp9_ref_order[ref_index].ref_frame[1];
4247
4248 vp9_zero(x->sum_y_eobs);
4249
4250 #if CONFIG_BETTER_HW_COMPATIBILITY
4251 // forbid 8X4 and 4X8 partitions if any reference frame is scaled.
4252 if (bsize == BLOCK_8X4 || bsize == BLOCK_4X8) {
4253 int ref_scaled = ref_frame > INTRA_FRAME &&
4254 vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf);
4255 if (second_ref_frame > INTRA_FRAME)
4256 ref_scaled += vp9_is_scaled(&cm->frame_refs[second_ref_frame - 1].sf);
4257 if (ref_scaled) continue;
4258 }
4259 #endif
4260 // Look at the reference frame of the best mode so far and set the
4261 // skip mask to look at a subset of the remaining modes.
4262 if (ref_index > 2 && sf->mode_skip_start < MAX_MODES) {
4263 if (ref_index == 3) {
4264 switch (best_mbmode.ref_frame[0]) {
4265 case INTRA_FRAME: break;
4266 case LAST_FRAME:
4267 ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME);
4268 ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4269 break;
4270 case GOLDEN_FRAME:
4271 ref_frame_skip_mask[0] |= (1 << LAST_FRAME) | (1 << ALTREF_FRAME);
4272 ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
4273 break;
4274 case ALTREF_FRAME:
4275 ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << LAST_FRAME);
4276 break;
4277 case NONE:
4278 case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
4279 }
4280 }
4281 }
4282
4283 if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
4284 (ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
4285 continue;
4286
4287 // Test best rd so far against threshold for trying this mode.
4288 if (!internal_active_edge &&
4289 rd_less_than_thresh(best_rd,
4290 rd_opt->threshes[segment_id][bsize][ref_index],
4291 &rd_thresh_freq_fact[ref_index]))
4292 continue;
4293
4294 // This is only used in motion vector unit test.
4295 if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
4296
4297 comp_pred = second_ref_frame > INTRA_FRAME;
4298 if (comp_pred) {
4299 if (!cpi->allow_comp_inter_inter) continue;
4300
4301 if (cm->ref_frame_sign_bias[ref_frame] ==
4302 cm->ref_frame_sign_bias[second_ref_frame])
4303 continue;
4304
4305 if (!(cpi->ref_frame_flags & ref_frame_to_flag(second_ref_frame)))
4306 continue;
4307 // Do not allow compound prediction if the segment level reference frame
4308 // feature is in use as in this case there can only be one reference.
4309 if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
4310
4311 if ((sf->mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
4312 best_mbmode.ref_frame[0] == INTRA_FRAME)
4313 continue;
4314 }
4315
4316 if (comp_pred)
4317 mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
4318 else if (ref_frame != INTRA_FRAME)
4319 mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
4320
4321 // If the segment reference frame feature is enabled....
4322 // then do nothing if the current ref frame is not allowed..
4323 if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
4324 get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
4325 continue;
4326 // Disable this drop out case if the ref frame
4327 // segment level feature is enabled for this segment. This is to
4328 // prevent the possibility that we end up unable to pick any mode.
4329 } else if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
4330 // Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
4331 // unless ARNR filtering is enabled in which case we want
4332 // an unfiltered alternative. We allow near/nearest as well
4333 // because they may result in zero-zero MVs but be cheaper.
4334 if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
4335 continue;
4336 }
4337
4338 mi->tx_size = TX_4X4;
4339 mi->uv_mode = DC_PRED;
4340 mi->ref_frame[0] = ref_frame;
4341 mi->ref_frame[1] = second_ref_frame;
4342 // Evaluate all sub-pel filters irrespective of whether we can use
4343 // them for this frame.
4344 mi->interp_filter =
4345 cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
4346 x->skip = 0;
4347 set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
4348
4349 // Select prediction reference frames.
4350 for (i = 0; i < MAX_MB_PLANE; i++) {
4351 xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
4352 if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
4353 }
4354
4355 if (ref_frame == INTRA_FRAME) {
4356 int rate;
4357 if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y, &distortion_y,
4358 best_rd) >= best_rd)
4359 continue;
4360 rate2 += rate;
4361 rate2 += intra_cost_penalty;
4362 distortion2 += distortion_y;
4363
4364 if (rate_uv_intra == INT_MAX) {
4365 choose_intra_uv_mode(cpi, x, ctx, bsize, TX_4X4, &rate_uv_intra,
4366 &rate_uv_tokenonly, &dist_uv, &skip_uv, &mode_uv);
4367 }
4368 rate2 += rate_uv_intra;
4369 rate_uv = rate_uv_tokenonly;
4370 distortion2 += dist_uv;
4371 distortion_uv = dist_uv;
4372 mi->uv_mode = mode_uv;
4373 } else {
4374 int rate;
4375 int64_t distortion;
4376 int64_t this_rd_thresh;
4377 int64_t tmp_rd, tmp_best_rd = INT64_MAX, tmp_best_rdu = INT64_MAX;
4378 int tmp_best_rate = INT_MAX, tmp_best_ratey = INT_MAX;
4379 int64_t tmp_best_distortion = INT_MAX, tmp_best_sse, uv_sse;
4380 int tmp_best_skippable = 0;
4381 int switchable_filter_index;
4382 int_mv *second_ref =
4383 comp_pred ? &x->mbmi_ext->ref_mvs[second_ref_frame][0] : NULL;
4384 b_mode_info tmp_best_bmodes[16];
4385 MODE_INFO tmp_best_mbmode;
4386 BEST_SEG_INFO bsi[SWITCHABLE_FILTERS];
4387 int pred_exists = 0;
4388 int uv_skippable;
4389
4390 YV12_BUFFER_CONFIG *scaled_ref_frame[2] = { NULL, NULL };
4391 int ref;
4392
4393 for (ref = 0; ref < 2; ++ref) {
4394 scaled_ref_frame[ref] =
4395 mi->ref_frame[ref] > INTRA_FRAME
4396 ? vp9_get_scaled_ref_frame(cpi, mi->ref_frame[ref])
4397 : NULL;
4398
4399 if (scaled_ref_frame[ref]) {
4400 int i;
4401 // Swap out the reference frame for a version that's been scaled to
4402 // match the resolution of the current frame, allowing the existing
4403 // motion search code to be used without additional modifications.
4404 for (i = 0; i < MAX_MB_PLANE; i++)
4405 backup_yv12[ref][i] = xd->plane[i].pre[ref];
4406 vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
4407 NULL);
4408 }
4409 }
4410
4411 this_rd_thresh = (ref_frame == LAST_FRAME)
4412 ? rd_opt->threshes[segment_id][bsize][THR_LAST]
4413 : rd_opt->threshes[segment_id][bsize][THR_ALTR];
4414 this_rd_thresh = (ref_frame == GOLDEN_FRAME)
4415 ? rd_opt->threshes[segment_id][bsize][THR_GOLD]
4416 : this_rd_thresh;
4417 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
4418 filter_cache[i] = INT64_MAX;
4419
4420 if (cm->interp_filter != BILINEAR) {
4421 tmp_best_filter = EIGHTTAP;
4422 if (x->source_variance < sf->disable_filter_search_var_thresh) {
4423 tmp_best_filter = EIGHTTAP;
4424 } else if (sf->adaptive_pred_interp_filter == 1 &&
4425 ctx->pred_interp_filter < SWITCHABLE) {
4426 tmp_best_filter = ctx->pred_interp_filter;
4427 } else if (sf->adaptive_pred_interp_filter == 2) {
4428 tmp_best_filter = ctx->pred_interp_filter < SWITCHABLE
4429 ? ctx->pred_interp_filter
4430 : 0;
4431 } else {
4432 for (switchable_filter_index = 0;
4433 switchable_filter_index < SWITCHABLE_FILTERS;
4434 ++switchable_filter_index) {
4435 int newbest, rs;
4436 int64_t rs_rd;
4437 MB_MODE_INFO_EXT *mbmi_ext = x->mbmi_ext;
4438 mi->interp_filter = switchable_filter_index;
4439 tmp_rd = rd_pick_best_sub8x8_mode(
4440 cpi, x, &mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
4441 &rate, &rate_y, &distortion, &skippable, &total_sse,
4442 (int)this_rd_thresh, seg_mvs, bsi, switchable_filter_index,
4443 mi_row, mi_col);
4444
4445 if (tmp_rd == INT64_MAX) continue;
4446 rs = vp9_get_switchable_rate(cpi, xd);
4447 rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
4448 filter_cache[switchable_filter_index] = tmp_rd;
4449 filter_cache[SWITCHABLE_FILTERS] =
4450 VPXMIN(filter_cache[SWITCHABLE_FILTERS], tmp_rd + rs_rd);
4451 if (cm->interp_filter == SWITCHABLE) tmp_rd += rs_rd;
4452
4453 mask_filter = VPXMAX(mask_filter, tmp_rd);
4454
4455 newbest = (tmp_rd < tmp_best_rd);
4456 if (newbest) {
4457 tmp_best_filter = mi->interp_filter;
4458 tmp_best_rd = tmp_rd;
4459 }
4460 if ((newbest && cm->interp_filter == SWITCHABLE) ||
4461 (mi->interp_filter == cm->interp_filter &&
4462 cm->interp_filter != SWITCHABLE)) {
4463 tmp_best_rdu = tmp_rd;
4464 tmp_best_rate = rate;
4465 tmp_best_ratey = rate_y;
4466 tmp_best_distortion = distortion;
4467 tmp_best_sse = total_sse;
4468 tmp_best_skippable = skippable;
4469 tmp_best_mbmode = *mi;
4470 x->sum_y_eobs[TX_4X4] = 0;
4471 for (i = 0; i < 4; i++) {
4472 tmp_best_bmodes[i] = xd->mi[0]->bmi[i];
4473 x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
4474 x->sum_y_eobs[TX_4X4] += x->plane[0].eobs[i];
4475 }
4476 pred_exists = 1;
4477 if (switchable_filter_index == 0 && sf->use_rd_breakout &&
4478 best_rd < INT64_MAX) {
4479 if (tmp_best_rdu / 2 > best_rd) {
4480 // skip searching the other filters if the first is
4481 // already substantially larger than the best so far
4482 tmp_best_filter = mi->interp_filter;
4483 tmp_best_rdu = INT64_MAX;
4484 break;
4485 }
4486 }
4487 }
4488 } // switchable_filter_index loop
4489 }
4490 }
4491
4492 if (tmp_best_rdu == INT64_MAX && pred_exists) continue;
4493
4494 mi->interp_filter = (cm->interp_filter == SWITCHABLE ? tmp_best_filter
4495 : cm->interp_filter);
4496 if (!pred_exists) {
4497 // Handles the special case when a filter that is not in the
4498 // switchable list (bilinear, 6-tap) is indicated at the frame level
4499 tmp_rd = rd_pick_best_sub8x8_mode(
4500 cpi, x, &x->mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
4501 &rate, &rate_y, &distortion, &skippable, &total_sse,
4502 (int)this_rd_thresh, seg_mvs, bsi, 0, mi_row, mi_col);
4503 if (tmp_rd == INT64_MAX) continue;
4504 x->sum_y_eobs[TX_4X4] = 0;
4505 for (i = 0; i < 4; i++) {
4506 x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
4507 x->sum_y_eobs[TX_4X4] += x->plane[0].eobs[i];
4508 }
4509 } else {
4510 total_sse = tmp_best_sse;
4511 rate = tmp_best_rate;
4512 rate_y = tmp_best_ratey;
4513 distortion = tmp_best_distortion;
4514 skippable = tmp_best_skippable;
4515 *mi = tmp_best_mbmode;
4516 for (i = 0; i < 4; i++) xd->mi[0]->bmi[i] = tmp_best_bmodes[i];
4517 }
4518
4519 rate2 += rate;
4520 distortion2 += distortion;
4521
4522 if (cm->interp_filter == SWITCHABLE)
4523 rate2 += vp9_get_switchable_rate(cpi, xd);
4524
4525 if (!mode_excluded)
4526 mode_excluded = comp_pred ? cm->reference_mode == SINGLE_REFERENCE
4527 : cm->reference_mode == COMPOUND_REFERENCE;
4528
4529 compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
4530
4531 tmp_best_rdu =
4532 best_rd - VPXMIN(RDCOST(x->rdmult, x->rddiv, rate2, distortion2),
4533 RDCOST(x->rdmult, x->rddiv, 0, total_sse));
4534
4535 if (tmp_best_rdu > 0) {
4536 // If even the 'Y' rd value of split is higher than best so far
4537 // then dont bother looking at UV
4538 vp9_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col, BLOCK_8X8);
4539 memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
4540 if (!super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
4541 &uv_sse, BLOCK_8X8, tmp_best_rdu)) {
4542 for (ref = 0; ref < 2; ++ref) {
4543 if (scaled_ref_frame[ref]) {
4544 int i;
4545 for (i = 0; i < MAX_MB_PLANE; ++i)
4546 xd->plane[i].pre[ref] = backup_yv12[ref][i];
4547 }
4548 }
4549 continue;
4550 }
4551
4552 rate2 += rate_uv;
4553 distortion2 += distortion_uv;
4554 skippable = skippable && uv_skippable;
4555 total_sse += uv_sse;
4556 }
4557
4558 for (ref = 0; ref < 2; ++ref) {
4559 if (scaled_ref_frame[ref]) {
4560 // Restore the prediction frame pointers to their unscaled versions.
4561 int i;
4562 for (i = 0; i < MAX_MB_PLANE; ++i)
4563 xd->plane[i].pre[ref] = backup_yv12[ref][i];
4564 }
4565 }
4566 }
4567
4568 if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
4569
4570 // Estimate the reference frame signaling cost and add it
4571 // to the rolling cost variable.
4572 if (second_ref_frame > INTRA_FRAME) {
4573 rate2 += ref_costs_comp[ref_frame];
4574 } else {
4575 rate2 += ref_costs_single[ref_frame];
4576 }
4577
4578 if (!disable_skip) {
4579 const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
4580 const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
4581 const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
4582
4583 // Skip is never coded at the segment level for sub8x8 blocks and instead
4584 // always coded in the bitstream at the mode info level.
4585 if (ref_frame != INTRA_FRAME && !xd->lossless) {
4586 if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
4587 distortion2) <
4588 RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
4589 // Add in the cost of the no skip flag.
4590 rate2 += skip_cost0;
4591 } else {
4592 // FIXME(rbultje) make this work for splitmv also
4593 rate2 += skip_cost1;
4594 distortion2 = total_sse;
4595 assert(total_sse >= 0);
4596 rate2 -= (rate_y + rate_uv);
4597 rate_y = 0;
4598 rate_uv = 0;
4599 this_skip2 = 1;
4600 }
4601 } else {
4602 // Add in the cost of the no skip flag.
4603 rate2 += skip_cost0;
4604 }
4605
4606 // Calculate the final RD estimate for this mode.
4607 this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
4608 }
4609
4610 if (!disable_skip && ref_frame == INTRA_FRAME) {
4611 for (i = 0; i < REFERENCE_MODES; ++i)
4612 best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
4613 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
4614 best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
4615 }
4616
4617 // Did this mode help.. i.e. is it the new best mode
4618 if (this_rd < best_rd || x->skip) {
4619 if (!mode_excluded) {
4620 int max_plane = MAX_MB_PLANE;
4621 // Note index of best mode so far
4622 best_ref_index = ref_index;
4623
4624 if (ref_frame == INTRA_FRAME) {
4625 /* required for left and above block mv */
4626 mi->mv[0].as_int = 0;
4627 max_plane = 1;
4628 // Initialize interp_filter here so we do not have to check for
4629 // inter block modes in get_pred_context_switchable_interp()
4630 mi->interp_filter = SWITCHABLE_FILTERS;
4631 }
4632
4633 rd_cost->rate = rate2;
4634 rd_cost->dist = distortion2;
4635 rd_cost->rdcost = this_rd;
4636 best_rd = this_rd;
4637 best_yrd =
4638 best_rd - RDCOST(x->rdmult, x->rddiv, rate_uv, distortion_uv);
4639 best_mbmode = *mi;
4640 best_skip2 = this_skip2;
4641 if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
4642 memcpy(ctx->zcoeff_blk, x->zcoeff_blk[TX_4X4],
4643 sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
4644 ctx->sum_y_eobs = x->sum_y_eobs[TX_4X4];
4645
4646 for (i = 0; i < 4; i++) best_bmodes[i] = xd->mi[0]->bmi[i];
4647
4648 // TODO(debargha): enhance this test with a better distortion prediction
4649 // based on qp, activity mask and history
4650 if ((sf->mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
4651 (ref_index > MIN_EARLY_TERM_INDEX)) {
4652 int qstep = xd->plane[0].dequant[1];
4653 // TODO(debargha): Enhance this by specializing for each mode_index
4654 int scale = 4;
4655 #if CONFIG_VP9_HIGHBITDEPTH
4656 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
4657 qstep >>= (xd->bd - 8);
4658 }
4659 #endif // CONFIG_VP9_HIGHBITDEPTH
4660 if (x->source_variance < UINT_MAX) {
4661 const int var_adjust = (x->source_variance < 16);
4662 scale -= var_adjust;
4663 }
4664 if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
4665 early_term = 1;
4666 }
4667 }
4668 }
4669 }
4670
4671 /* keep record of best compound/single-only prediction */
4672 if (!disable_skip && ref_frame != INTRA_FRAME) {
4673 int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
4674
4675 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4676 single_rate = rate2 - compmode_cost;
4677 hybrid_rate = rate2;
4678 } else {
4679 single_rate = rate2;
4680 hybrid_rate = rate2 + compmode_cost;
4681 }
4682
4683 single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
4684 hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
4685
4686 if (!comp_pred && single_rd < best_pred_rd[SINGLE_REFERENCE])
4687 best_pred_rd[SINGLE_REFERENCE] = single_rd;
4688 else if (comp_pred && single_rd < best_pred_rd[COMPOUND_REFERENCE])
4689 best_pred_rd[COMPOUND_REFERENCE] = single_rd;
4690
4691 if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
4692 best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
4693 }
4694
4695 /* keep record of best filter type */
4696 if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
4697 cm->interp_filter != BILINEAR) {
4698 int64_t ref =
4699 filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
4700 : cm->interp_filter];
4701 int64_t adj_rd;
4702 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4703 if (ref == INT64_MAX)
4704 adj_rd = 0;
4705 else if (filter_cache[i] == INT64_MAX)
4706 // when early termination is triggered, the encoder does not have
4707 // access to the rate-distortion cost. it only knows that the cost
4708 // should be above the maximum valid value. hence it takes the known
4709 // maximum plus an arbitrary constant as the rate-distortion cost.
4710 adj_rd = mask_filter - ref + 10;
4711 else
4712 adj_rd = filter_cache[i] - ref;
4713
4714 adj_rd += this_rd;
4715 best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
4716 }
4717 }
4718
4719 if (early_term) break;
4720
4721 if (x->skip && !comp_pred) break;
4722 }
4723
4724 if (best_rd >= best_rd_so_far) {
4725 rd_cost->rate = INT_MAX;
4726 rd_cost->rdcost = INT64_MAX;
4727 return;
4728 }
4729
4730 // If we used an estimate for the uv intra rd in the loop above...
4731 if (sf->use_uv_intra_rd_estimate) {
4732 // Do Intra UV best rd mode selection if best mode choice above was intra.
4733 if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
4734 *mi = best_mbmode;
4735 rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra, &rate_uv_tokenonly,
4736 &dist_uv, &skip_uv, BLOCK_8X8, TX_4X4);
4737 }
4738 }
4739
4740 if (best_rd == INT64_MAX) {
4741 rd_cost->rate = INT_MAX;
4742 rd_cost->dist = INT64_MAX;
4743 rd_cost->rdcost = INT64_MAX;
4744 return;
4745 }
4746
4747 assert((cm->interp_filter == SWITCHABLE) ||
4748 (cm->interp_filter == best_mbmode.interp_filter) ||
4749 !is_inter_block(&best_mbmode));
4750
4751 vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact, sf->adaptive_rd_thresh,
4752 bsize, best_ref_index);
4753
4754 // macroblock modes
4755 *mi = best_mbmode;
4756 x->skip |= best_skip2;
4757 if (!is_inter_block(&best_mbmode)) {
4758 for (i = 0; i < 4; i++) xd->mi[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
4759 } else {
4760 for (i = 0; i < 4; ++i)
4761 memcpy(&xd->mi[0]->bmi[i], &best_bmodes[i], sizeof(b_mode_info));
4762
4763 mi->mv[0].as_int = xd->mi[0]->bmi[3].as_mv[0].as_int;
4764 mi->mv[1].as_int = xd->mi[0]->bmi[3].as_mv[1].as_int;
4765 }
4766 // If the second reference does not exist, set the corresponding mv to zero.
4767 if (mi->ref_frame[1] == NONE) {
4768 mi->mv[1].as_int = 0;
4769 for (i = 0; i < 4; ++i) {
4770 mi->bmi[i].as_mv[1].as_int = 0;
4771 }
4772 }
4773
4774 for (i = 0; i < REFERENCE_MODES; ++i) {
4775 if (best_pred_rd[i] == INT64_MAX)
4776 best_pred_diff[i] = INT_MIN;
4777 else
4778 best_pred_diff[i] = best_rd - best_pred_rd[i];
4779 }
4780
4781 if (!x->skip) {
4782 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
4783 if (best_filter_rd[i] == INT64_MAX)
4784 best_filter_diff[i] = 0;
4785 else
4786 best_filter_diff[i] = best_rd - best_filter_rd[i];
4787 }
4788 if (cm->interp_filter == SWITCHABLE)
4789 assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
4790 } else {
4791 vp9_zero(best_filter_diff);
4792 }
4793
4794 store_coding_context(x, ctx, best_ref_index, best_pred_diff, best_filter_diff,
4795 0);
4796 }
4797 #endif // !CONFIG_REALTIME_ONLY
4798