2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
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.
16 #include "./vp9_rtcd.h"
17 #include "./vpx_dsp_rtcd.h"
18 #include "./vpx_config.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_ports/mem.h"
22 #include "vpx_ports/vpx_timer.h"
23 #include "vpx_ports/system_state.h"
25 #include "vp9/common/vp9_common.h"
26 #include "vp9/common/vp9_entropy.h"
27 #include "vp9/common/vp9_entropymode.h"
28 #include "vp9/common/vp9_idct.h"
29 #include "vp9/common/vp9_mvref_common.h"
30 #include "vp9/common/vp9_pred_common.h"
31 #include "vp9/common/vp9_quant_common.h"
32 #include "vp9/common/vp9_reconintra.h"
33 #include "vp9/common/vp9_reconinter.h"
34 #include "vp9/common/vp9_seg_common.h"
35 #include "vp9/common/vp9_tile_common.h"
37 #include "vp9/encoder/vp9_aq_360.h"
38 #include "vp9/encoder/vp9_aq_complexity.h"
39 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
40 #include "vp9/encoder/vp9_aq_variance.h"
41 #include "vp9/encoder/vp9_encodeframe.h"
42 #include "vp9/encoder/vp9_encodemb.h"
43 #include "vp9/encoder/vp9_encodemv.h"
44 #include "vp9/encoder/vp9_ethread.h"
45 #include "vp9/encoder/vp9_extend.h"
46 #include "vp9/encoder/vp9_multi_thread.h"
47 #include "vp9/encoder/vp9_partition_models.h"
48 #include "vp9/encoder/vp9_pickmode.h"
49 #include "vp9/encoder/vp9_rd.h"
50 #include "vp9/encoder/vp9_rdopt.h"
51 #include "vp9/encoder/vp9_segmentation.h"
52 #include "vp9/encoder/vp9_tokenize.h"
54 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
55 int output_enabled, int mi_row, int mi_col,
56 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx);
58 // This is used as a reference when computing the source variance for the
59 // purpose of activity masking.
60 // Eventually this should be replaced by custom no-reference routines,
61 // which will be faster.
62 static const uint8_t VP9_VAR_OFFS[64] = {
63 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
64 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
65 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
66 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
67 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
70 #if CONFIG_VP9_HIGHBITDEPTH
71 static const uint16_t VP9_HIGH_VAR_OFFS_8[64] = {
72 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
73 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
74 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
75 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
76 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
79 static const uint16_t VP9_HIGH_VAR_OFFS_10[64] = {
80 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
81 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
82 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
83 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
84 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
85 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
86 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
87 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4
90 static const uint16_t VP9_HIGH_VAR_OFFS_12[64] = {
91 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
92 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
93 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
94 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
95 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
96 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
97 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
98 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
99 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
102 #endif // CONFIG_VP9_HIGHBITDEPTH
104 unsigned int vp9_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
107 const unsigned int var =
108 cpi->fn_ptr[bs].vf(ref->buf, ref->stride, VP9_VAR_OFFS, 0, &sse);
112 #if CONFIG_VP9_HIGHBITDEPTH
113 unsigned int vp9_high_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
114 BLOCK_SIZE bs, int bd) {
115 unsigned int var, sse;
119 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
120 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10), 0, &sse);
124 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
125 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12), 0, &sse);
130 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
131 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8), 0, &sse);
136 #endif // CONFIG_VP9_HIGHBITDEPTH
138 unsigned int vp9_get_sby_perpixel_variance(VP9_COMP *cpi,
139 const struct buf_2d *ref,
141 return ROUND_POWER_OF_TWO(vp9_get_sby_variance(cpi, ref, bs),
142 num_pels_log2_lookup[bs]);
145 #if CONFIG_VP9_HIGHBITDEPTH
146 unsigned int vp9_high_get_sby_perpixel_variance(VP9_COMP *cpi,
147 const struct buf_2d *ref,
148 BLOCK_SIZE bs, int bd) {
149 return (unsigned int)ROUND64_POWER_OF_TWO(
150 (int64_t)vp9_high_get_sby_variance(cpi, ref, bs, bd),
151 num_pels_log2_lookup[bs]);
153 #endif // CONFIG_VP9_HIGHBITDEPTH
155 static unsigned int get_sby_perpixel_diff_variance(VP9_COMP *cpi,
156 const struct buf_2d *ref,
157 int mi_row, int mi_col,
159 unsigned int sse, var;
161 const YV12_BUFFER_CONFIG *last = get_ref_frame_buffer(cpi, LAST_FRAME);
163 assert(last != NULL);
165 &last->y_buffer[mi_row * MI_SIZE * last->y_stride + mi_col * MI_SIZE];
166 var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride, last_y, last->y_stride, &sse);
167 return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
170 static BLOCK_SIZE get_rd_var_based_fixed_partition(VP9_COMP *cpi, MACROBLOCK *x,
171 int mi_row, int mi_col) {
172 unsigned int var = get_sby_perpixel_diff_variance(
173 cpi, &x->plane[0].src, mi_row, mi_col, BLOCK_64X64);
184 static void set_segment_index(VP9_COMP *cpi, MACROBLOCK *const x, int mi_row,
185 int mi_col, BLOCK_SIZE bsize, int segment_index) {
186 VP9_COMMON *const cm = &cpi->common;
187 const struct segmentation *const seg = &cm->seg;
188 MACROBLOCKD *const xd = &x->e_mbd;
189 MODE_INFO *mi = xd->mi[0];
191 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
192 const uint8_t *const map =
193 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
195 // Initialize the segmentation index as 0.
198 // Skip the rest if AQ mode is disabled.
199 if (!seg->enabled) return;
202 case CYCLIC_REFRESH_AQ:
203 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
206 if (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
207 cpi->force_update_segmentation ||
208 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
211 // Get sub block energy range
212 if (bsize >= BLOCK_32X32) {
213 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
216 min_energy = bsize <= BLOCK_16X16 ? x->mb_energy
217 : vp9_block_energy(cpi, x, bsize);
219 mi->segment_id = vp9_vaq_segment_id(min_energy);
221 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
225 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
228 if (cm->frame_type == KEY_FRAME || cpi->force_update_segmentation)
229 mi->segment_id = vp9_360aq_segment_id(mi_row, cm->mi_rows);
231 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
233 case PSNR_AQ: mi->segment_id = segment_index; break;
239 // Set segment index from ROI map if it's enabled.
240 if (cpi->roi.enabled)
241 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
243 if (cpi->sf.enable_wiener_variance) mi->segment_id = x->segment_id;
245 vp9_init_plane_quantizers(cpi, x);
248 // Lighter version of set_offsets that only sets the mode info
250 static INLINE void set_mode_info_offsets(VP9_COMMON *const cm,
252 MACROBLOCKD *const xd, int mi_row,
254 const int idx_str = xd->mi_stride * mi_row + mi_col;
255 xd->mi = cm->mi_grid_visible + idx_str;
256 xd->mi[0] = cm->mi + idx_str;
257 x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
260 static double get_ssim_rdmult_scaling_factor(VP9_COMP *const cpi, int mi_row,
262 const VP9_COMMON *const cm = &cpi->common;
264 // SSIM rdmult scaling factors are currently 64x64 based.
265 const int num_8x8_w = 8;
266 const int num_8x8_h = 8;
267 const int num_cols = (cm->mi_cols + num_8x8_w - 1) / num_8x8_w;
268 const int row = mi_row / num_8x8_h;
269 const int col = mi_col / num_8x8_w;
270 const int index = row * num_cols + col;
272 assert(cpi->oxcf.tuning == VP8_TUNE_SSIM);
273 vpx_clear_system_state();
274 return cpi->mi_ssim_rdmult_scaling_factors[index];
277 static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
278 MACROBLOCK *const x, int mi_row, int mi_col,
280 VP9_COMMON *const cm = &cpi->common;
281 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
282 MACROBLOCKD *const xd = &x->e_mbd;
283 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
284 const int mi_height = num_8x8_blocks_high_lookup[bsize];
285 MvLimits *const mv_limits = &x->mv_limits;
287 set_skip_context(xd, mi_row, mi_col);
289 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
291 // Set up destination pointers.
292 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
294 // Set up limit values for MV components.
295 // Mv beyond the range do not produce new/different prediction block.
296 mv_limits->row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
297 mv_limits->col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
298 mv_limits->row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
299 mv_limits->col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
301 // Set up distance of MB to edge of frame in 1/8th pel units.
302 assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
303 set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width, cm->mi_rows,
306 // Set up source buffers.
307 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
310 x->rddiv = cpi->rd.RDDIV;
311 x->rdmult = cpi->rd.RDMULT;
312 if (oxcf->tuning == VP8_TUNE_SSIM) {
313 const double ssim_factor =
314 get_ssim_rdmult_scaling_factor(cpi, mi_row, mi_col);
315 x->rdmult = (int)(ssim_factor * x->rdmult);
316 vpx_clear_system_state();
319 // required by vp9_append_sub8x8_mvs_for_idx() and vp9_find_best_ref_mvs()
323 static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
324 int mi_row, int mi_col,
326 const int block_width =
327 VPXMIN(num_8x8_blocks_wide_lookup[bsize], cm->mi_cols - mi_col);
328 const int block_height =
329 VPXMIN(num_8x8_blocks_high_lookup[bsize], cm->mi_rows - mi_row);
330 const int mi_stride = xd->mi_stride;
331 MODE_INFO *const src_mi = xd->mi[0];
334 for (j = 0; j < block_height; ++j)
335 for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
338 static void set_block_size(VP9_COMP *const cpi, MACROBLOCK *const x,
339 MACROBLOCKD *const xd, int mi_row, int mi_col,
341 if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
342 set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
343 xd->mi[0]->sb_type = bsize;
348 // This struct is used for computing variance in choose_partitioning(), where
349 // the max number of samples within a superblock is 16x16 (with 4x4 avg). Even
350 // in high bitdepth, uint32_t is enough for sum_square_error (2^12 * 2^12 * 16
352 uint32_t sum_square_error;
362 } partition_variance;
365 partition_variance part_variances;
370 partition_variance part_variances;
375 partition_variance part_variances;
380 partition_variance part_variances;
385 partition_variance part_variances;
390 partition_variance *part_variances;
400 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
402 node->part_variances = NULL;
405 v64x64 *vt = (v64x64 *)data;
406 node->part_variances = &vt->part_variances;
407 for (i = 0; i < 4; i++)
408 node->split[i] = &vt->split[i].part_variances.none;
412 v32x32 *vt = (v32x32 *)data;
413 node->part_variances = &vt->part_variances;
414 for (i = 0; i < 4; i++)
415 node->split[i] = &vt->split[i].part_variances.none;
419 v16x16 *vt = (v16x16 *)data;
420 node->part_variances = &vt->part_variances;
421 for (i = 0; i < 4; i++)
422 node->split[i] = &vt->split[i].part_variances.none;
426 v8x8 *vt = (v8x8 *)data;
427 node->part_variances = &vt->part_variances;
428 for (i = 0; i < 4; i++)
429 node->split[i] = &vt->split[i].part_variances.none;
433 v4x4 *vt = (v4x4 *)data;
434 assert(bsize == BLOCK_4X4);
435 node->part_variances = &vt->part_variances;
436 for (i = 0; i < 4; i++) node->split[i] = &vt->split[i];
442 // Set variance values given sum square error, sum error, count.
443 static void fill_variance(uint32_t s2, int32_t s, int c, var *v) {
444 v->sum_square_error = s2;
449 static void get_variance(var *v) {
451 (int)(256 * (v->sum_square_error -
452 (uint32_t)(((int64_t)v->sum_error * v->sum_error) >>
457 static void sum_2_variances(const var *a, const var *b, var *r) {
458 assert(a->log2_count == b->log2_count);
459 fill_variance(a->sum_square_error + b->sum_square_error,
460 a->sum_error + b->sum_error, a->log2_count + 1, r);
463 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
465 memset(&node, 0, sizeof(node));
466 tree_to_node(data, bsize, &node);
467 sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
468 sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
469 sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
470 sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
471 sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
472 &node.part_variances->none);
475 static int set_vt_partitioning(VP9_COMP *cpi, MACROBLOCK *const x,
476 MACROBLOCKD *const xd, void *data,
477 BLOCK_SIZE bsize, int mi_row, int mi_col,
478 int64_t threshold, BLOCK_SIZE bsize_min,
480 VP9_COMMON *const cm = &cpi->common;
482 const int block_width = num_8x8_blocks_wide_lookup[bsize];
483 const int block_height = num_8x8_blocks_high_lookup[bsize];
485 assert(block_height == block_width);
486 tree_to_node(data, bsize, &vt);
488 if (force_split == 1) return 0;
490 // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
491 // variance is below threshold, otherwise split will be selected.
492 // No check for vert/horiz split as too few samples for variance.
493 if (bsize == bsize_min) {
494 // Variance already computed to set the force_split.
495 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
496 if (mi_col + block_width / 2 < cm->mi_cols &&
497 mi_row + block_height / 2 < cm->mi_rows &&
498 vt.part_variances->none.variance < threshold) {
499 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
503 } else if (bsize > bsize_min) {
504 // Variance already computed to set the force_split.
505 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
506 // For key frame: take split for bsize above 32X32 or very high variance.
507 if (frame_is_intra_only(cm) &&
508 (bsize > BLOCK_32X32 ||
509 vt.part_variances->none.variance > (threshold << 4))) {
512 // If variance is low, take the bsize (no split).
513 if (mi_col + block_width / 2 < cm->mi_cols &&
514 mi_row + block_height / 2 < cm->mi_rows &&
515 vt.part_variances->none.variance < threshold) {
516 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
520 // Check vertical split.
521 if (mi_row + block_height / 2 < cm->mi_rows) {
522 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
523 get_variance(&vt.part_variances->vert[0]);
524 get_variance(&vt.part_variances->vert[1]);
525 if (vt.part_variances->vert[0].variance < threshold &&
526 vt.part_variances->vert[1].variance < threshold &&
527 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
528 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
529 set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
533 // Check horizontal split.
534 if (mi_col + block_width / 2 < cm->mi_cols) {
535 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
536 get_variance(&vt.part_variances->horz[0]);
537 get_variance(&vt.part_variances->horz[1]);
538 if (vt.part_variances->horz[0].variance < threshold &&
539 vt.part_variances->horz[1].variance < threshold &&
540 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
541 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
542 set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
552 static int64_t scale_part_thresh_sumdiff(int64_t threshold_base, int speed,
553 int width, int height,
556 if (width <= 640 && height <= 480)
557 return (5 * threshold_base) >> 2;
558 else if ((content_state == kLowSadLowSumdiff) ||
559 (content_state == kHighSadLowSumdiff) ||
560 (content_state == kLowVarHighSumdiff))
561 return (5 * threshold_base) >> 2;
562 } else if (speed == 7) {
563 if ((content_state == kLowSadLowSumdiff) ||
564 (content_state == kHighSadLowSumdiff) ||
565 (content_state == kLowVarHighSumdiff)) {
566 return (5 * threshold_base) >> 2;
569 return threshold_base;
572 // Set the variance split thresholds for following the block sizes:
573 // 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
574 // 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
575 // currently only used on key frame.
576 static void set_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q,
578 VP9_COMMON *const cm = &cpi->common;
579 const int is_key_frame = frame_is_intra_only(cm);
580 const int threshold_multiplier =
581 is_key_frame ? 20 : cpi->sf.variance_part_thresh_mult;
582 int64_t threshold_base =
583 (int64_t)(threshold_multiplier * cpi->y_dequant[q][1]);
586 thresholds[0] = threshold_base;
587 thresholds[1] = threshold_base >> 2;
588 thresholds[2] = threshold_base >> 2;
589 thresholds[3] = threshold_base << 2;
591 // Increase base variance threshold based on estimated noise level.
592 if (cpi->noise_estimate.enabled && cm->width >= 640 && cm->height >= 480) {
593 NOISE_LEVEL noise_level =
594 vp9_noise_estimate_extract_level(&cpi->noise_estimate);
595 if (noise_level == kHigh)
596 threshold_base = 3 * threshold_base;
597 else if (noise_level == kMedium)
598 threshold_base = threshold_base << 1;
599 else if (noise_level < kLow)
600 threshold_base = (7 * threshold_base) >> 3;
602 #if CONFIG_VP9_TEMPORAL_DENOISING
603 if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
604 cpi->oxcf.speed > 5 && cpi->denoiser.denoising_level >= kDenLow)
606 vp9_scale_part_thresh(threshold_base, cpi->denoiser.denoising_level,
607 content_state, cpi->svc.temporal_layer_id);
610 scale_part_thresh_sumdiff(threshold_base, cpi->oxcf.speed, cm->width,
611 cm->height, content_state);
613 // Increase base variance threshold based on content_state/sum_diff level.
614 threshold_base = scale_part_thresh_sumdiff(
615 threshold_base, cpi->oxcf.speed, cm->width, cm->height, content_state);
617 thresholds[0] = threshold_base;
618 thresholds[2] = threshold_base << cpi->oxcf.speed;
619 if (cm->width >= 1280 && cm->height >= 720 && cpi->oxcf.speed < 7)
620 thresholds[2] = thresholds[2] << 1;
621 if (cm->width <= 352 && cm->height <= 288) {
622 thresholds[0] = threshold_base >> 3;
623 thresholds[1] = threshold_base >> 1;
624 thresholds[2] = threshold_base << 3;
625 } else if (cm->width < 1280 && cm->height < 720) {
626 thresholds[1] = (5 * threshold_base) >> 2;
627 } else if (cm->width < 1920 && cm->height < 1080) {
628 thresholds[1] = threshold_base << 1;
630 thresholds[1] = (5 * threshold_base) >> 1;
632 if (cpi->sf.disable_16x16part_nonkey) thresholds[2] = INT64_MAX;
636 void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q,
638 VP9_COMMON *const cm = &cpi->common;
639 SPEED_FEATURES *const sf = &cpi->sf;
640 const int is_key_frame = frame_is_intra_only(cm);
641 if (sf->partition_search_type != VAR_BASED_PARTITION &&
642 sf->partition_search_type != REFERENCE_PARTITION) {
645 set_vbp_thresholds(cpi, cpi->vbp_thresholds, q, content_state);
646 // The thresholds below are not changed locally.
648 cpi->vbp_threshold_sad = 0;
649 cpi->vbp_threshold_copy = 0;
650 cpi->vbp_bsize_min = BLOCK_8X8;
652 if (cm->width <= 352 && cm->height <= 288)
653 cpi->vbp_threshold_sad = 10;
655 cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000
656 ? (cpi->y_dequant[q][1] << 1)
658 cpi->vbp_bsize_min = BLOCK_16X16;
659 if (cm->width <= 352 && cm->height <= 288)
660 cpi->vbp_threshold_copy = 4000;
661 else if (cm->width <= 640 && cm->height <= 360)
662 cpi->vbp_threshold_copy = 8000;
664 cpi->vbp_threshold_copy = (cpi->y_dequant[q][1] << 3) > 8000
665 ? (cpi->y_dequant[q][1] << 3)
667 if (cpi->rc.high_source_sad ||
668 (cpi->use_svc && cpi->svc.high_source_sad_superframe)) {
669 cpi->vbp_threshold_sad = 0;
670 cpi->vbp_threshold_copy = 0;
673 cpi->vbp_threshold_minmax = 15 + (q >> 3);
677 // Compute the minmax over the 8x8 subblocks.
678 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
679 int dp, int x16_idx, int y16_idx,
680 #if CONFIG_VP9_HIGHBITDEPTH
683 int pixels_wide, int pixels_high) {
686 int minmax_min = 255;
687 // Loop over the 4 8x8 subblocks.
688 for (k = 0; k < 4; k++) {
689 int x8_idx = x16_idx + ((k & 1) << 3);
690 int y8_idx = y16_idx + ((k >> 1) << 3);
693 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
694 #if CONFIG_VP9_HIGHBITDEPTH
695 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
696 vpx_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
697 d + y8_idx * dp + x8_idx, dp, &min, &max);
699 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx,
703 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx, dp,
706 if ((max - min) > minmax_max) minmax_max = (max - min);
707 if ((max - min) < minmax_min) minmax_min = (max - min);
710 return (minmax_max - minmax_min);
713 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
714 int dp, int x8_idx, int y8_idx, v8x8 *vst,
715 #if CONFIG_VP9_HIGHBITDEPTH
718 int pixels_wide, int pixels_high,
721 for (k = 0; k < 4; k++) {
722 int x4_idx = x8_idx + ((k & 1) << 2);
723 int y4_idx = y8_idx + ((k >> 1) << 2);
724 unsigned int sse = 0;
726 if (x4_idx < pixels_wide && y4_idx < pixels_high) {
729 #if CONFIG_VP9_HIGHBITDEPTH
730 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
731 s_avg = vpx_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
733 d_avg = vpx_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
735 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
736 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
739 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
740 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
745 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
749 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
750 int dp, int x16_idx, int y16_idx, v16x16 *vst,
751 #if CONFIG_VP9_HIGHBITDEPTH
754 int pixels_wide, int pixels_high,
757 for (k = 0; k < 4; k++) {
758 int x8_idx = x16_idx + ((k & 1) << 3);
759 int y8_idx = y16_idx + ((k >> 1) << 3);
760 unsigned int sse = 0;
762 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
765 #if CONFIG_VP9_HIGHBITDEPTH
766 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
767 s_avg = vpx_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
769 d_avg = vpx_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
771 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
772 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
775 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
776 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
781 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
785 // Check if most of the superblock is skin content, and if so, force split to
786 // 32x32, and set x->sb_is_skin for use in mode selection.
787 static int skin_sb_split(VP9_COMP *cpi, MACROBLOCK *x, const int low_res,
788 int mi_row, int mi_col, int *force_split) {
789 VP9_COMMON *const cm = &cpi->common;
790 #if CONFIG_VP9_HIGHBITDEPTH
791 if (cm->use_highbitdepth) return 0;
793 // Avoid checking superblocks on/near boundary and avoid low resolutions.
794 // Note superblock may still pick 64X64 if y_sad is very small
795 // (i.e., y_sad < cpi->vbp_threshold_sad) below. For now leave this as is.
796 if (!low_res && (mi_col >= 8 && mi_col + 8 < cm->mi_cols && mi_row >= 8 &&
797 mi_row + 8 < cm->mi_rows)) {
798 int num_16x16_skin = 0;
799 int num_16x16_nonskin = 0;
800 uint8_t *ysignal = x->plane[0].src.buf;
801 uint8_t *usignal = x->plane[1].src.buf;
802 uint8_t *vsignal = x->plane[2].src.buf;
803 int sp = x->plane[0].src.stride;
804 int spuv = x->plane[1].src.stride;
805 const int block_index = mi_row * cm->mi_cols + mi_col;
806 const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
807 const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
808 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
809 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
810 // Loop through the 16x16 sub-blocks.
812 for (i = 0; i < ymis; i += 2) {
813 for (j = 0; j < xmis; j += 2) {
814 int bl_index = block_index + i * cm->mi_cols + j;
815 int is_skin = cpi->skin_map[bl_index];
816 num_16x16_skin += is_skin;
817 num_16x16_nonskin += (1 - is_skin);
818 if (num_16x16_nonskin > 3) {
819 // Exit loop if at least 4 of the 16x16 blocks are not skin.
827 ysignal += (sp << 4) - 64;
828 usignal += (spuv << 3) - 32;
829 vsignal += (spuv << 3) - 32;
831 if (num_16x16_skin > 12) {
839 static void set_low_temp_var_flag(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
840 v64x64 *vt, int64_t thresholds[],
841 MV_REFERENCE_FRAME ref_frame_partition,
842 int mi_col, int mi_row) {
844 VP9_COMMON *const cm = &cpi->common;
845 const int mv_thr = cm->width > 640 ? 8 : 4;
846 // Check temporal variance for bsize >= 16x16, if LAST_FRAME was selected and
847 // int_pro mv is small. If the temporal variance is small set the flag
848 // variance_low for the block. The variance threshold can be adjusted, the
849 // higher the more aggressive.
850 if (ref_frame_partition == LAST_FRAME &&
851 (cpi->sf.short_circuit_low_temp_var == 1 ||
852 (xd->mi[0]->mv[0].as_mv.col < mv_thr &&
853 xd->mi[0]->mv[0].as_mv.col > -mv_thr &&
854 xd->mi[0]->mv[0].as_mv.row < mv_thr &&
855 xd->mi[0]->mv[0].as_mv.row > -mv_thr))) {
856 if (xd->mi[0]->sb_type == BLOCK_64X64) {
857 if ((vt->part_variances).none.variance < (thresholds[0] >> 1))
858 x->variance_low[0] = 1;
859 } else if (xd->mi[0]->sb_type == BLOCK_64X32) {
860 for (i = 0; i < 2; i++) {
861 if (vt->part_variances.horz[i].variance < (thresholds[0] >> 2))
862 x->variance_low[i + 1] = 1;
864 } else if (xd->mi[0]->sb_type == BLOCK_32X64) {
865 for (i = 0; i < 2; i++) {
866 if (vt->part_variances.vert[i].variance < (thresholds[0] >> 2))
867 x->variance_low[i + 3] = 1;
870 for (i = 0; i < 4; i++) {
871 const int idx[4][2] = { { 0, 0 }, { 0, 4 }, { 4, 0 }, { 4, 4 } };
873 cm->mi_stride * (mi_row + idx[i][0]) + mi_col + idx[i][1];
874 MODE_INFO **this_mi = cm->mi_grid_visible + idx_str;
876 if (cm->mi_cols <= mi_col + idx[i][1] ||
877 cm->mi_rows <= mi_row + idx[i][0])
880 if ((*this_mi)->sb_type == BLOCK_32X32) {
881 int64_t threshold_32x32 = (cpi->sf.short_circuit_low_temp_var == 1 ||
882 cpi->sf.short_circuit_low_temp_var == 3)
883 ? ((5 * thresholds[1]) >> 3)
884 : (thresholds[1] >> 1);
885 if (vt->split[i].part_variances.none.variance < threshold_32x32)
886 x->variance_low[i + 5] = 1;
887 } else if (cpi->sf.short_circuit_low_temp_var >= 2) {
888 // For 32x16 and 16x32 blocks, the flag is set on each 16x16 block
890 if ((*this_mi)->sb_type == BLOCK_16X16 ||
891 (*this_mi)->sb_type == BLOCK_32X16 ||
892 (*this_mi)->sb_type == BLOCK_16X32) {
893 for (j = 0; j < 4; j++) {
894 if (vt->split[i].split[j].part_variances.none.variance <
895 (thresholds[2] >> 8))
896 x->variance_low[(i << 2) + j + 9] = 1;
905 static void copy_partitioning_helper(VP9_COMP *cpi, MACROBLOCK *x,
906 MACROBLOCKD *xd, BLOCK_SIZE bsize,
907 int mi_row, int mi_col) {
908 VP9_COMMON *const cm = &cpi->common;
909 BLOCK_SIZE *prev_part = cpi->prev_partition;
910 int start_pos = mi_row * cm->mi_stride + mi_col;
912 const int bsl = b_width_log2_lookup[bsize];
913 const int bs = (1 << bsl) >> 2;
915 PARTITION_TYPE partition;
917 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
919 partition = partition_lookup[bsl][prev_part[start_pos]];
920 subsize = get_subsize(bsize, partition);
922 if (subsize < BLOCK_8X8) {
923 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
927 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
930 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
931 set_block_size(cpi, x, xd, mi_row + bs, mi_col, subsize);
934 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
935 set_block_size(cpi, x, xd, mi_row, mi_col + bs, subsize);
938 assert(partition == PARTITION_SPLIT);
939 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col);
940 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col);
941 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col + bs);
942 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col + bs);
948 static int copy_partitioning(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
949 int mi_row, int mi_col, int segment_id,
951 int svc_copy_allowed = 1;
952 int frames_since_key_thresh = 1;
954 // For SVC, don't allow copy if base spatial layer is key frame, or if
955 // frame is not a temporal enhancement layer frame.
956 int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
957 cpi->svc.number_temporal_layers);
958 const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
959 if (lc->is_key_frame || !cpi->svc.non_reference_frame) svc_copy_allowed = 0;
960 frames_since_key_thresh = cpi->svc.number_spatial_layers << 1;
962 if (cpi->rc.frames_since_key > frames_since_key_thresh && svc_copy_allowed &&
963 !cpi->resize_pending && segment_id == CR_SEGMENT_ID_BASE &&
964 cpi->prev_segment_id[sb_offset] == CR_SEGMENT_ID_BASE &&
965 cpi->copied_frame_cnt[sb_offset] < cpi->max_copied_frame) {
966 if (cpi->prev_partition != NULL) {
967 copy_partitioning_helper(cpi, x, xd, BLOCK_64X64, mi_row, mi_col);
968 cpi->copied_frame_cnt[sb_offset] += 1;
969 memcpy(x->variance_low, &(cpi->prev_variance_low[sb_offset * 25]),
970 sizeof(x->variance_low));
978 static int scale_partitioning_svc(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
979 BLOCK_SIZE bsize, int mi_row, int mi_col,
980 int mi_row_high, int mi_col_high) {
981 VP9_COMMON *const cm = &cpi->common;
982 SVC *const svc = &cpi->svc;
983 BLOCK_SIZE *prev_part = svc->prev_partition_svc;
984 // Variables with _high are for higher resolution.
986 int subsize_high = 0;
987 const int bsl_high = b_width_log2_lookup[bsize];
988 const int bs_high = (1 << bsl_high) >> 2;
989 const int has_rows = (mi_row_high + bs_high) < cm->mi_rows;
990 const int has_cols = (mi_col_high + bs_high) < cm->mi_cols;
992 const int row_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 1, 0,
995 const int col_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 2, 2,
999 BLOCK_SIZE bsize_low;
1000 PARTITION_TYPE partition_high;
1002 if (mi_row_high >= cm->mi_rows || mi_col_high >= cm->mi_cols) return 0;
1003 if (mi_row >= svc->mi_rows[svc->spatial_layer_id - 1] ||
1004 mi_col >= svc->mi_cols[svc->spatial_layer_id - 1])
1007 // Find corresponding (mi_col/mi_row) block down-scaled by 2x2.
1008 start_pos = mi_row * (svc->mi_stride[svc->spatial_layer_id - 1]) + mi_col;
1009 bsize_low = prev_part[start_pos];
1010 // The block size is too big for boundaries. Do variance based partitioning.
1011 if ((!has_rows || !has_cols) && bsize_low > BLOCK_16X16) return 1;
1013 // For reference frames: return 1 (do variance-based partitioning) if the
1014 // superblock is not low source sad and lower-resoln bsize is below 32x32.
1015 if (!cpi->svc.non_reference_frame && !x->skip_low_source_sad &&
1016 bsize_low < BLOCK_32X32)
1019 // Scale up block size by 2x2. Force 64x64 for size larger than 32x32.
1020 if (bsize_low < BLOCK_32X32) {
1021 bsize_high = bsize_low + 3;
1022 } else if (bsize_low >= BLOCK_32X32) {
1023 bsize_high = BLOCK_64X64;
1025 // Scale up blocks on boundary.
1026 if (!has_cols && has_rows) {
1027 bsize_high = bsize_low + row_boundary_block_scale_factor[bsize_low];
1028 } else if (has_cols && !has_rows) {
1029 bsize_high = bsize_low + col_boundary_block_scale_factor[bsize_low];
1030 } else if (!has_cols && !has_rows) {
1031 bsize_high = bsize_low;
1034 partition_high = partition_lookup[bsl_high][bsize_high];
1035 subsize_high = get_subsize(bsize, partition_high);
1037 if (subsize_high < BLOCK_8X8) {
1038 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1040 const int bsl = b_width_log2_lookup[bsize];
1041 const int bs = (1 << bsl) >> 2;
1042 switch (partition_high) {
1043 case PARTITION_NONE:
1044 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1046 case PARTITION_HORZ:
1047 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1048 if (subsize_high < BLOCK_64X64)
1049 set_block_size(cpi, x, xd, mi_row_high + bs_high, mi_col_high,
1052 case PARTITION_VERT:
1053 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1054 if (subsize_high < BLOCK_64X64)
1055 set_block_size(cpi, x, xd, mi_row_high, mi_col_high + bs_high,
1059 assert(partition_high == PARTITION_SPLIT);
1060 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row, mi_col,
1061 mi_row_high, mi_col_high))
1063 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1064 mi_col, mi_row_high + bs_high, mi_col_high))
1066 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row,
1067 mi_col + (bs >> 1), mi_row_high,
1068 mi_col_high + bs_high))
1070 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1071 mi_col + (bs >> 1), mi_row_high + bs_high,
1072 mi_col_high + bs_high))
1081 static void update_partition_svc(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
1083 VP9_COMMON *const cm = &cpi->common;
1084 BLOCK_SIZE *prev_part = cpi->svc.prev_partition_svc;
1085 int start_pos = mi_row * cm->mi_stride + mi_col;
1086 const int bsl = b_width_log2_lookup[bsize];
1087 const int bs = (1 << bsl) >> 2;
1089 PARTITION_TYPE partition;
1090 const MODE_INFO *mi = NULL;
1093 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1095 mi = cm->mi_grid_visible[start_pos];
1096 partition = partition_lookup[bsl][mi->sb_type];
1097 subsize = get_subsize(bsize, partition);
1098 if (subsize < BLOCK_8X8) {
1099 prev_part[start_pos] = bsize;
1101 switch (partition) {
1102 case PARTITION_NONE:
1103 prev_part[start_pos] = bsize;
1104 if (bsize == BLOCK_64X64) {
1105 for (xx = 0; xx < 8; xx += 4)
1106 for (yy = 0; yy < 8; yy += 4) {
1107 if ((mi_row + xx < cm->mi_rows) && (mi_col + yy < cm->mi_cols))
1108 prev_part[start_pos + xx * cm->mi_stride + yy] = bsize;
1112 case PARTITION_HORZ:
1113 prev_part[start_pos] = subsize;
1114 if (mi_row + bs < cm->mi_rows)
1115 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1117 case PARTITION_VERT:
1118 prev_part[start_pos] = subsize;
1119 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1122 assert(partition == PARTITION_SPLIT);
1123 update_partition_svc(cpi, subsize, mi_row, mi_col);
1124 update_partition_svc(cpi, subsize, mi_row + bs, mi_col);
1125 update_partition_svc(cpi, subsize, mi_row, mi_col + bs);
1126 update_partition_svc(cpi, subsize, mi_row + bs, mi_col + bs);
1132 static void update_prev_partition_helper(VP9_COMP *cpi, BLOCK_SIZE bsize,
1133 int mi_row, int mi_col) {
1134 VP9_COMMON *const cm = &cpi->common;
1135 BLOCK_SIZE *prev_part = cpi->prev_partition;
1136 int start_pos = mi_row * cm->mi_stride + mi_col;
1137 const int bsl = b_width_log2_lookup[bsize];
1138 const int bs = (1 << bsl) >> 2;
1140 PARTITION_TYPE partition;
1141 const MODE_INFO *mi = NULL;
1143 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1145 mi = cm->mi_grid_visible[start_pos];
1146 partition = partition_lookup[bsl][mi->sb_type];
1147 subsize = get_subsize(bsize, partition);
1148 if (subsize < BLOCK_8X8) {
1149 prev_part[start_pos] = bsize;
1151 switch (partition) {
1152 case PARTITION_NONE: prev_part[start_pos] = bsize; break;
1153 case PARTITION_HORZ:
1154 prev_part[start_pos] = subsize;
1155 if (mi_row + bs < cm->mi_rows)
1156 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1158 case PARTITION_VERT:
1159 prev_part[start_pos] = subsize;
1160 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1163 assert(partition == PARTITION_SPLIT);
1164 update_prev_partition_helper(cpi, subsize, mi_row, mi_col);
1165 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col);
1166 update_prev_partition_helper(cpi, subsize, mi_row, mi_col + bs);
1167 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col + bs);
1173 static void update_prev_partition(VP9_COMP *cpi, MACROBLOCK *x, int segment_id,
1174 int mi_row, int mi_col, int sb_offset) {
1175 update_prev_partition_helper(cpi, BLOCK_64X64, mi_row, mi_col);
1176 cpi->prev_segment_id[sb_offset] = segment_id;
1177 memcpy(&(cpi->prev_variance_low[sb_offset * 25]), x->variance_low,
1178 sizeof(x->variance_low));
1179 // Reset the counter for copy partitioning
1180 cpi->copied_frame_cnt[sb_offset] = 0;
1183 static void chroma_check(VP9_COMP *cpi, MACROBLOCK *x, int bsize,
1184 unsigned int y_sad, int is_key_frame) {
1186 MACROBLOCKD *xd = &x->e_mbd;
1188 if (is_key_frame) return;
1190 // For speed >= 8, avoid the chroma check if y_sad is above threshold.
1191 if (cpi->oxcf.speed >= 8) {
1192 if (y_sad > cpi->vbp_thresholds[1] &&
1193 (!cpi->noise_estimate.enabled ||
1194 vp9_noise_estimate_extract_level(&cpi->noise_estimate) < kMedium))
1198 for (i = 1; i <= 2; ++i) {
1199 unsigned int uv_sad = UINT_MAX;
1200 struct macroblock_plane *p = &x->plane[i];
1201 struct macroblockd_plane *pd = &xd->plane[i];
1202 const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
1204 if (bs != BLOCK_INVALID)
1205 uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride, pd->dst.buf,
1208 // TODO(marpan): Investigate if we should lower this threshold if
1209 // superblock is detected as skin.
1210 x->color_sensitivity[i - 1] = uv_sad > (y_sad >> 2);
1214 static uint64_t avg_source_sad(VP9_COMP *cpi, MACROBLOCK *x, int shift,
1216 unsigned int tmp_sse;
1218 unsigned int tmp_variance;
1219 const BLOCK_SIZE bsize = BLOCK_64X64;
1220 uint8_t *src_y = cpi->Source->y_buffer;
1221 int src_ystride = cpi->Source->y_stride;
1222 uint8_t *last_src_y = cpi->Last_Source->y_buffer;
1223 int last_src_ystride = cpi->Last_Source->y_stride;
1224 uint64_t avg_source_sad_threshold = 10000;
1225 uint64_t avg_source_sad_threshold2 = 12000;
1226 #if CONFIG_VP9_HIGHBITDEPTH
1227 if (cpi->common.use_highbitdepth) return 0;
1230 last_src_y += shift;
1232 cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y, last_src_ystride);
1233 tmp_variance = vpx_variance64x64(src_y, src_ystride, last_src_y,
1234 last_src_ystride, &tmp_sse);
1235 // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1236 if (tmp_sad < avg_source_sad_threshold)
1237 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kLowSadLowSumdiff
1238 : kLowSadHighSumdiff;
1240 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kHighSadLowSumdiff
1241 : kHighSadHighSumdiff;
1243 // Detect large lighting change.
1244 if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
1245 cpi->oxcf.rc_mode == VPX_CBR && tmp_variance < (tmp_sse >> 3) &&
1246 (tmp_sse - tmp_variance) > 10000)
1247 x->content_state_sb = kLowVarHighSumdiff;
1248 else if (tmp_sad > (avg_source_sad_threshold << 1))
1249 x->content_state_sb = kVeryHighSad;
1251 if (cpi->content_state_sb_fd != NULL) {
1252 if (tmp_sad < avg_source_sad_threshold2) {
1253 // Cap the increment to 255.
1254 if (cpi->content_state_sb_fd[sb_offset] < 255)
1255 cpi->content_state_sb_fd[sb_offset]++;
1257 cpi->content_state_sb_fd[sb_offset] = 0;
1260 if (tmp_sad == 0) x->zero_temp_sad_source = 1;
1264 // This function chooses partitioning based on the variance between source and
1265 // reconstructed last, where variance is computed for down-sampled inputs.
1266 static int choose_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1267 MACROBLOCK *x, int mi_row, int mi_col) {
1268 VP9_COMMON *const cm = &cpi->common;
1269 MACROBLOCKD *xd = &x->e_mbd;
1273 int force_split[21];
1275 int max_var_32x32 = 0;
1276 int min_var_32x32 = INT_MAX;
1279 int maxvar_16x16[4];
1280 int minvar_16x16[4];
1281 int64_t threshold_4x4avg;
1282 NOISE_LEVEL noise_level = kLow;
1283 int content_state = 0;
1288 int compute_minmax_variance = 1;
1289 unsigned int y_sad = UINT_MAX;
1290 BLOCK_SIZE bsize = BLOCK_64X64;
1291 // Ref frame used in partitioning.
1292 MV_REFERENCE_FRAME ref_frame_partition = LAST_FRAME;
1293 int pixels_wide = 64, pixels_high = 64;
1294 int64_t thresholds[4] = { cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
1295 cpi->vbp_thresholds[2], cpi->vbp_thresholds[3] };
1296 int force_64_split = cpi->rc.high_source_sad ||
1297 (cpi->use_svc && cpi->svc.high_source_sad_superframe) ||
1298 (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1299 cpi->compute_source_sad_onepass &&
1300 cpi->sf.use_source_sad && !x->zero_temp_sad_source);
1302 // For the variance computation under SVC mode, we treat the frame as key if
1303 // the reference (base layer frame) is key frame (i.e., is_key_frame == 1).
1305 (frame_is_intra_only(cm) ||
1306 (is_one_pass_cbr_svc(cpi) &&
1307 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame));
1308 // Always use 4x4 partition for key frame.
1309 const int use_4x4_partition = frame_is_intra_only(cm);
1310 const int low_res = (cm->width <= 352 && cm->height <= 288);
1311 int variance4x4downsample[16];
1313 int sb_offset = (cm->mi_stride >> 3) * (mi_row >> 3) + (mi_col >> 3);
1315 // For SVC: check if LAST frame is NULL or if the resolution of LAST is
1316 // different than the current frame resolution, and if so, treat this frame
1317 // as a key frame, for the purpose of the superblock partitioning.
1318 // LAST == NULL can happen in some cases where enhancement spatial layers are
1319 // enabled dyanmically in the stream and the only reference is the spatial
1320 // reference (GOLDEN).
1322 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, LAST_FRAME);
1323 if (ref == NULL || ref->y_crop_height != cm->height ||
1324 ref->y_crop_width != cm->width)
1328 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
1329 set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
1330 segment_id = xd->mi[0]->segment_id;
1332 if (cpi->oxcf.speed >= 8 || (cpi->use_svc && cpi->svc.non_reference_frame))
1333 compute_minmax_variance = 0;
1335 memset(x->variance_low, 0, sizeof(x->variance_low));
1337 if (cpi->sf.use_source_sad && !is_key_frame) {
1338 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1339 content_state = x->content_state_sb;
1340 x->skip_low_source_sad = (content_state == kLowSadLowSumdiff ||
1341 content_state == kLowSadHighSumdiff)
1344 x->lowvar_highsumdiff = (content_state == kLowVarHighSumdiff) ? 1 : 0;
1345 if (cpi->content_state_sb_fd != NULL)
1346 x->last_sb_high_content = cpi->content_state_sb_fd[sb_offset2];
1348 // For SVC on top spatial layer: use/scale the partition from
1349 // the lower spatial resolution if svc_use_lowres_part is enabled.
1350 if (cpi->sf.svc_use_lowres_part &&
1351 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1352 cpi->svc.prev_partition_svc != NULL && content_state != kVeryHighSad) {
1353 if (!scale_partitioning_svc(cpi, x, xd, BLOCK_64X64, mi_row >> 1,
1354 mi_col >> 1, mi_row, mi_col)) {
1355 if (cpi->sf.copy_partition_flag) {
1356 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1361 // If source_sad is low copy the partition without computing the y_sad.
1362 if (x->skip_low_source_sad && cpi->sf.copy_partition_flag &&
1364 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1365 x->sb_use_mv_part = 1;
1366 if (cpi->sf.svc_use_lowres_part &&
1367 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1368 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1373 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
1374 cyclic_refresh_segment_id_boosted(segment_id)) {
1375 int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
1376 set_vbp_thresholds(cpi, thresholds, q, content_state);
1378 set_vbp_thresholds(cpi, thresholds, cm->base_qindex, content_state);
1380 // Decrease 32x32 split threshold for screen on base layer, for scene
1381 // change/high motion frames.
1382 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1383 cpi->svc.spatial_layer_id == 0 && force_64_split)
1384 thresholds[1] = 3 * thresholds[1] >> 2;
1386 // For non keyframes, disable 4x4 average for low resolution when speed = 8
1387 threshold_4x4avg = (cpi->oxcf.speed < 8) ? thresholds[1] << 1 : INT64_MAX;
1389 if (xd->mb_to_right_edge < 0) pixels_wide += (xd->mb_to_right_edge >> 3);
1390 if (xd->mb_to_bottom_edge < 0) pixels_high += (xd->mb_to_bottom_edge >> 3);
1392 s = x->plane[0].src.buf;
1393 sp = x->plane[0].src.stride;
1395 // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
1396 // 5-20 for the 16x16 blocks.
1397 force_split[0] = force_64_split;
1399 if (!is_key_frame) {
1400 // In the case of spatial/temporal scalable coding, the assumption here is
1401 // that the temporal reference frame will always be of type LAST_FRAME.
1402 // TODO(marpan): If that assumption is broken, we need to revisit this code.
1403 MODE_INFO *mi = xd->mi[0];
1404 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1406 const YV12_BUFFER_CONFIG *yv12_g = NULL;
1407 unsigned int y_sad_g, y_sad_thr, y_sad_last;
1408 bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
1409 (mi_row + 4 < cm->mi_rows);
1411 assert(yv12 != NULL);
1413 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
1414 cpi->svc.use_gf_temporal_ref_current_layer) {
1415 // For now, GOLDEN will not be used for non-zero spatial layers, since
1416 // it may not be a temporal reference.
1417 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1420 // Only compute y_sad_g (sad for golden reference) for speed < 8.
1421 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
1422 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
1423 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1424 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1425 y_sad_g = cpi->fn_ptr[bsize].sdf(
1426 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1427 xd->plane[0].pre[0].stride);
1432 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
1433 cpi->rc.is_src_frame_alt_ref) {
1434 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
1435 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1436 &cm->frame_refs[ALTREF_FRAME - 1].sf);
1437 mi->ref_frame[0] = ALTREF_FRAME;
1440 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1441 &cm->frame_refs[LAST_FRAME - 1].sf);
1442 mi->ref_frame[0] = LAST_FRAME;
1444 mi->ref_frame[1] = NONE;
1445 mi->sb_type = BLOCK_64X64;
1446 mi->mv[0].as_int = 0;
1447 mi->interp_filter = BILINEAR;
1449 if (cpi->oxcf.speed >= 8 && !low_res &&
1450 x->content_state_sb != kVeryHighSad) {
1451 y_sad = cpi->fn_ptr[bsize].sdf(
1452 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1453 xd->plane[0].pre[0].stride);
1455 const MV dummy_mv = { 0, 0 };
1456 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
1458 x->sb_use_mv_part = 1;
1459 x->sb_mvcol_part = mi->mv[0].as_mv.col;
1460 x->sb_mvrow_part = mi->mv[0].as_mv.row;
1461 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1462 cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
1463 cpi->svc.high_num_blocks_with_motion && !x->zero_temp_sad_source &&
1464 cm->width > 640 && cm->height > 480) {
1465 // Disable split below 16x16 block size when scroll motion (horz or
1466 // vert) is detected.
1467 // TODO(marpan/jianj): Improve this condition: issue is that search
1468 // range is hard-coded/limited in vp9_int_pro_motion_estimation() so
1469 // scroll motion may not be detected here.
1470 if (((abs(x->sb_mvrow_part) >= 48 && abs(x->sb_mvcol_part) <= 8) ||
1471 (abs(x->sb_mvcol_part) >= 48 && abs(x->sb_mvrow_part) <= 8)) &&
1473 compute_minmax_variance = 0;
1474 thresholds[2] = INT64_MAX;
1480 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
1481 // are close if short_circuit_low_temp_var is on.
1482 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
1483 if (y_sad_g < y_sad_thr) {
1484 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1485 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1486 mi->ref_frame[0] = GOLDEN_FRAME;
1487 mi->mv[0].as_int = 0;
1489 ref_frame_partition = GOLDEN_FRAME;
1491 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
1492 ref_frame_partition = LAST_FRAME;
1495 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
1496 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
1498 if (cpi->use_skin_detection)
1500 skin_sb_split(cpi, x, low_res, mi_row, mi_col, force_split);
1502 d = xd->plane[0].dst.buf;
1503 dp = xd->plane[0].dst.stride;
1505 // If the y_sad is very small, take 64x64 as partition and exit.
1506 // Don't check on boosted segment for now, as 64x64 is suppressed there.
1507 if (segment_id == CR_SEGMENT_ID_BASE && y_sad < cpi->vbp_threshold_sad) {
1508 const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
1509 const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
1510 if (mi_col + block_width / 2 < cm->mi_cols &&
1511 mi_row + block_height / 2 < cm->mi_rows) {
1512 set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
1513 x->variance_low[0] = 1;
1514 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1515 if (cpi->sf.svc_use_lowres_part &&
1516 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1517 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1518 if (cpi->sf.copy_partition_flag) {
1519 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1525 // If the y_sad is small enough, copy the partition of the superblock in the
1526 // last frame to current frame only if the last frame is not a keyframe.
1527 // Stop the copy every cpi->max_copied_frame to refresh the partition.
1528 // TODO(jianj) : tune the threshold.
1529 if (cpi->sf.copy_partition_flag && y_sad_last < cpi->vbp_threshold_copy &&
1530 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1531 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1532 if (cpi->sf.svc_use_lowres_part &&
1533 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1534 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1540 #if CONFIG_VP9_HIGHBITDEPTH
1541 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1543 case 10: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10); break;
1544 case 12: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12); break;
1546 default: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8); break;
1549 #endif // CONFIG_VP9_HIGHBITDEPTH
1552 if (low_res && threshold_4x4avg < INT64_MAX)
1553 CHECK_MEM_ERROR(cm, vt2, vpx_calloc(16, sizeof(*vt2)));
1554 // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
1556 for (i = 0; i < 4; i++) {
1557 const int x32_idx = ((i & 1) << 5);
1558 const int y32_idx = ((i >> 1) << 5);
1559 const int i2 = i << 2;
1560 force_split[i + 1] = 0;
1562 maxvar_16x16[i] = 0;
1563 minvar_16x16[i] = INT_MAX;
1564 for (j = 0; j < 4; j++) {
1565 const int x16_idx = x32_idx + ((j & 1) << 4);
1566 const int y16_idx = y32_idx + ((j >> 1) << 4);
1567 const int split_index = 5 + i2 + j;
1568 v16x16 *vst = &vt.split[i].split[j];
1569 force_split[split_index] = 0;
1570 variance4x4downsample[i2 + j] = 0;
1571 if (!is_key_frame) {
1572 fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
1573 #if CONFIG_VP9_HIGHBITDEPTH
1576 pixels_wide, pixels_high, is_key_frame);
1577 fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1578 get_variance(&vt.split[i].split[j].part_variances.none);
1579 avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance;
1580 if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i])
1581 minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1582 if (vt.split[i].split[j].part_variances.none.variance > maxvar_16x16[i])
1583 maxvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1584 if (vt.split[i].split[j].part_variances.none.variance > thresholds[2]) {
1585 // 16X16 variance is above threshold for split, so force split to 8x8
1586 // for this 16x16 block (this also forces splits for upper levels).
1587 force_split[split_index] = 1;
1588 force_split[i + 1] = 1;
1590 } else if (compute_minmax_variance &&
1591 vt.split[i].split[j].part_variances.none.variance >
1593 !cyclic_refresh_segment_id_boosted(segment_id)) {
1594 // We have some nominal amount of 16x16 variance (based on average),
1595 // compute the minmax over the 8x8 sub-blocks, and if above threshold,
1596 // force split to 8x8 block for this 16x16 block.
1597 int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
1598 #if CONFIG_VP9_HIGHBITDEPTH
1601 pixels_wide, pixels_high);
1602 int thresh_minmax = (int)cpi->vbp_threshold_minmax;
1603 if (x->content_state_sb == kVeryHighSad)
1604 thresh_minmax = thresh_minmax << 1;
1605 if (minmax > thresh_minmax) {
1606 force_split[split_index] = 1;
1607 force_split[i + 1] = 1;
1613 (low_res && vt.split[i].split[j].part_variances.none.variance >
1614 threshold_4x4avg)) {
1615 force_split[split_index] = 0;
1616 // Go down to 4x4 down-sampling for variance.
1617 variance4x4downsample[i2 + j] = 1;
1618 for (k = 0; k < 4; k++) {
1619 int x8_idx = x16_idx + ((k & 1) << 3);
1620 int y8_idx = y16_idx + ((k >> 1) << 3);
1621 v8x8 *vst2 = is_key_frame ? &vst->split[k] : &vt2[i2 + j].split[k];
1622 fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
1623 #if CONFIG_VP9_HIGHBITDEPTH
1626 pixels_wide, pixels_high, is_key_frame);
1631 if (cpi->noise_estimate.enabled)
1632 noise_level = vp9_noise_estimate_extract_level(&cpi->noise_estimate);
1633 // Fill the rest of the variance tree by summing split partition values.
1635 for (i = 0; i < 4; i++) {
1636 const int i2 = i << 2;
1637 for (j = 0; j < 4; j++) {
1638 if (variance4x4downsample[i2 + j] == 1) {
1639 v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] : &vt.split[i].split[j];
1640 for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
1641 fill_variance_tree(vtemp, BLOCK_16X16);
1642 // If variance of this 16x16 block is above the threshold, force block
1643 // to split. This also forces a split on the upper levels.
1644 get_variance(&vtemp->part_variances.none);
1645 if (vtemp->part_variances.none.variance > thresholds[2]) {
1646 force_split[5 + i2 + j] = 1;
1647 force_split[i + 1] = 1;
1652 fill_variance_tree(&vt.split[i], BLOCK_32X32);
1653 // If variance of this 32x32 block is above the threshold, or if its above
1654 // (some threshold of) the average variance over the sub-16x16 blocks, then
1655 // force this block to split. This also forces a split on the upper
1657 if (!force_split[i + 1]) {
1658 get_variance(&vt.split[i].part_variances.none);
1659 var_32x32 = vt.split[i].part_variances.none.variance;
1660 max_var_32x32 = VPXMAX(var_32x32, max_var_32x32);
1661 min_var_32x32 = VPXMIN(var_32x32, min_var_32x32);
1662 if (vt.split[i].part_variances.none.variance > thresholds[1] ||
1664 vt.split[i].part_variances.none.variance > (thresholds[1] >> 1) &&
1665 vt.split[i].part_variances.none.variance > (avg_16x16[i] >> 1))) {
1666 force_split[i + 1] = 1;
1668 } else if (!is_key_frame && noise_level < kLow && cm->height <= 360 &&
1669 (maxvar_16x16[i] - minvar_16x16[i]) > (thresholds[1] >> 1) &&
1670 maxvar_16x16[i] > thresholds[1]) {
1671 force_split[i + 1] = 1;
1674 avg_32x32 += var_32x32;
1677 if (!force_split[0]) {
1678 fill_variance_tree(&vt, BLOCK_64X64);
1679 get_variance(&vt.part_variances.none);
1680 // If variance of this 64x64 block is above (some threshold of) the average
1681 // variance over the sub-32x32 blocks, then force this block to split.
1682 // Only checking this for noise level >= medium for now.
1683 if (!is_key_frame && noise_level >= kMedium &&
1684 vt.part_variances.none.variance > (9 * avg_32x32) >> 5)
1686 // Else if the maximum 32x32 variance minus the miniumum 32x32 variance in
1687 // a 64x64 block is greater than threshold and the maximum 32x32 variance is
1688 // above a miniumum threshold, then force the split of a 64x64 block
1689 // Only check this for low noise.
1690 else if (!is_key_frame && noise_level < kMedium &&
1691 (max_var_32x32 - min_var_32x32) > 3 * (thresholds[0] >> 3) &&
1692 max_var_32x32 > thresholds[0] >> 1)
1696 // Now go through the entire structure, splitting every block size until
1697 // we get to one that's got a variance lower than our threshold.
1698 if (mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
1699 !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
1700 thresholds[0], BLOCK_16X16, force_split[0])) {
1701 for (i = 0; i < 4; ++i) {
1702 const int x32_idx = ((i & 1) << 2);
1703 const int y32_idx = ((i >> 1) << 2);
1704 const int i2 = i << 2;
1705 if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
1706 (mi_row + y32_idx), (mi_col + x32_idx),
1707 thresholds[1], BLOCK_16X16,
1708 force_split[i + 1])) {
1709 for (j = 0; j < 4; ++j) {
1710 const int x16_idx = ((j & 1) << 1);
1711 const int y16_idx = ((j >> 1) << 1);
1712 // For inter frames: if variance4x4downsample[] == 1 for this 16x16
1713 // block, then the variance is based on 4x4 down-sampling, so use vt2
1714 // in set_vt_partioning(), otherwise use vt.
1715 v16x16 *vtemp = (!is_key_frame && variance4x4downsample[i2 + j] == 1)
1717 : &vt.split[i].split[j];
1718 if (!set_vt_partitioning(
1719 cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx,
1720 mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min,
1721 force_split[5 + i2 + j])) {
1722 for (k = 0; k < 4; ++k) {
1723 const int x8_idx = (k & 1);
1724 const int y8_idx = (k >> 1);
1725 if (use_4x4_partition) {
1726 if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
1728 mi_row + y32_idx + y16_idx + y8_idx,
1729 mi_col + x32_idx + x16_idx + x8_idx,
1730 thresholds[3], BLOCK_8X8, 0)) {
1732 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1733 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_4X4);
1737 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1738 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_8X8);
1747 if (!frame_is_intra_only(cm) && cpi->sf.copy_partition_flag) {
1748 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1751 if (!frame_is_intra_only(cm) && cpi->sf.svc_use_lowres_part &&
1752 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1753 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1755 if (cpi->sf.short_circuit_low_temp_var) {
1756 set_low_temp_var_flag(cpi, x, xd, &vt, thresholds, ref_frame_partition,
1760 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1761 if (vt2) vpx_free(vt2);
1765 static void update_state(VP9_COMP *cpi, ThreadData *td, PICK_MODE_CONTEXT *ctx,
1766 int mi_row, int mi_col, BLOCK_SIZE bsize,
1767 int output_enabled) {
1769 VP9_COMMON *const cm = &cpi->common;
1770 RD_COUNTS *const rdc = &td->rd_counts;
1771 MACROBLOCK *const x = &td->mb;
1772 MACROBLOCKD *const xd = &x->e_mbd;
1773 struct macroblock_plane *const p = x->plane;
1774 struct macroblockd_plane *const pd = xd->plane;
1775 MODE_INFO *mi = &ctx->mic;
1776 MODE_INFO *const xdmi = xd->mi[0];
1777 MODE_INFO *mi_addr = xd->mi[0];
1778 const struct segmentation *const seg = &cm->seg;
1779 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
1780 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
1781 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1782 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1783 MV_REF *const frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1786 const int mis = cm->mi_stride;
1787 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
1788 const int mi_height = num_8x8_blocks_high_lookup[bsize];
1791 assert(mi->sb_type == bsize);
1794 *x->mbmi_ext = ctx->mbmi_ext;
1796 // If segmentation in use
1798 // For in frame complexity AQ copy the segment id from the segment map.
1799 if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1800 const uint8_t *const map =
1801 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1802 mi_addr->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1804 // Else for cyclic refresh mode update the segment map, set the segment id
1805 // and then update the quantizer.
1806 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1807 vp9_cyclic_refresh_update_segment(cpi, xd->mi[0], mi_row, mi_col, bsize,
1808 ctx->rate, ctx->dist, x->skip, p);
1812 max_plane = is_inter_block(xdmi) ? MAX_MB_PLANE : 1;
1813 for (i = 0; i < max_plane; ++i) {
1814 p[i].coeff = ctx->coeff_pbuf[i][1];
1815 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1816 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1817 p[i].eobs = ctx->eobs_pbuf[i][1];
1820 for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1821 p[i].coeff = ctx->coeff_pbuf[i][2];
1822 p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1823 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1824 p[i].eobs = ctx->eobs_pbuf[i][2];
1827 // Restore the coding context of the MB to that that was in place
1828 // when the mode was picked for it
1829 for (y = 0; y < mi_height; y++)
1830 for (x_idx = 0; x_idx < mi_width; x_idx++)
1831 if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx &&
1832 (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1833 xd->mi[x_idx + y * mis] = mi_addr;
1836 if (cpi->oxcf.aq_mode != NO_AQ) vp9_init_plane_quantizers(cpi, x);
1838 if (is_inter_block(xdmi) && xdmi->sb_type < BLOCK_8X8) {
1839 xdmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1840 xdmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1843 x->skip = ctx->skip;
1844 memcpy(x->zcoeff_blk[xdmi->tx_size], ctx->zcoeff_blk,
1845 sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1847 if (!output_enabled) return;
1849 #if CONFIG_INTERNAL_STATS
1850 if (frame_is_intra_only(cm)) {
1851 static const int kf_mode_index[] = {
1852 THR_DC /*DC_PRED*/, THR_V_PRED /*V_PRED*/,
1853 THR_H_PRED /*H_PRED*/, THR_D45_PRED /*D45_PRED*/,
1854 THR_D135_PRED /*D135_PRED*/, THR_D117_PRED /*D117_PRED*/,
1855 THR_D153_PRED /*D153_PRED*/, THR_D207_PRED /*D207_PRED*/,
1856 THR_D63_PRED /*D63_PRED*/, THR_TM /*TM_PRED*/,
1858 ++cpi->mode_chosen_counts[kf_mode_index[xdmi->mode]];
1860 // Note how often each mode chosen as best
1861 ++cpi->mode_chosen_counts[ctx->best_mode_index];
1864 if (!frame_is_intra_only(cm)) {
1865 if (is_inter_block(xdmi)) {
1866 vp9_update_mv_count(td);
1868 if (cm->interp_filter == SWITCHABLE) {
1869 const int ctx = get_pred_context_switchable_interp(xd);
1870 ++td->counts->switchable_interp[ctx][xdmi->interp_filter];
1874 rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1875 rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1876 rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1878 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1879 rdc->filter_diff[i] += ctx->best_filter_diff[i];
1882 for (h = 0; h < y_mis; ++h) {
1883 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1884 for (w = 0; w < x_mis; ++w) {
1885 MV_REF *const mv = frame_mv + w;
1886 mv->ref_frame[0] = mi->ref_frame[0];
1887 mv->ref_frame[1] = mi->ref_frame[1];
1888 mv->mv[0].as_int = mi->mv[0].as_int;
1889 mv->mv[1].as_int = mi->mv[1].as_int;
1894 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1895 int mi_row, int mi_col) {
1896 uint8_t *const buffers[3] = { src->y_buffer, src->u_buffer, src->v_buffer };
1897 const int strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
1900 // Set current frame pointer.
1901 x->e_mbd.cur_buf = src;
1903 for (i = 0; i < MAX_MB_PLANE; i++)
1904 setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1905 NULL, x->e_mbd.plane[i].subsampling_x,
1906 x->e_mbd.plane[i].subsampling_y);
1909 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1910 RD_COST *rd_cost, BLOCK_SIZE bsize) {
1911 MACROBLOCKD *const xd = &x->e_mbd;
1912 MODE_INFO *const mi = xd->mi[0];
1913 INTERP_FILTER filter_ref;
1915 filter_ref = get_pred_context_switchable_interp(xd);
1916 if (filter_ref == SWITCHABLE_FILTERS) filter_ref = EIGHTTAP;
1918 mi->sb_type = bsize;
1921 VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[tx_mode]);
1923 mi->uv_mode = DC_PRED;
1924 mi->ref_frame[0] = LAST_FRAME;
1925 mi->ref_frame[1] = NONE;
1926 mi->mv[0].as_int = 0;
1927 mi->interp_filter = filter_ref;
1929 xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1932 vp9_rd_cost_init(rd_cost);
1935 static void set_segment_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
1936 int mi_row, int mi_col, BLOCK_SIZE bsize,
1938 VP9_COMMON *const cm = &cpi->common;
1939 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1940 const uint8_t *const map =
1941 cm->seg.update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1943 vp9_init_plane_quantizers(cpi, x);
1944 vpx_clear_system_state();
1946 if (aq_mode == NO_AQ || aq_mode == PSNR_AQ) {
1947 if (cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance)
1948 x->rdmult = x->cb_rdmult;
1949 } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1950 // If segment is boosted, use rdmult for that segment.
1951 if (cyclic_refresh_segment_id_boosted(
1952 get_segment_id(cm, map, bsize, mi_row, mi_col)))
1953 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1955 x->rdmult = vp9_compute_rd_mult(cpi, cm->base_qindex + cm->y_dc_delta_q);
1956 if (cpi->sf.enable_wiener_variance && cm->show_frame) {
1957 if (cm->seg.enabled)
1958 x->rdmult = vp9_compute_rd_mult(
1959 cpi, vp9_get_qindex(&cm->seg, x->e_mbd.mi[0]->segment_id,
1964 if (oxcf->tuning == VP8_TUNE_SSIM) {
1965 const double ssim_factor =
1966 get_ssim_rdmult_scaling_factor(cpi, mi_row, mi_col);
1967 x->rdmult = (int)(ssim_factor * x->rdmult);
1968 vpx_clear_system_state();
1972 static void rd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
1973 MACROBLOCK *const x, int mi_row, int mi_col,
1974 RD_COST *rd_cost, BLOCK_SIZE bsize,
1975 PICK_MODE_CONTEXT *ctx, int64_t best_rd) {
1976 VP9_COMMON *const cm = &cpi->common;
1977 TileInfo *const tile_info = &tile_data->tile_info;
1978 MACROBLOCKD *const xd = &x->e_mbd;
1980 struct macroblock_plane *const p = x->plane;
1981 struct macroblockd_plane *const pd = xd->plane;
1982 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1985 vpx_clear_system_state();
1987 // Use the lower precision, but faster, 32x32 fdct for mode selection.
1988 x->use_lp32x32fdct = 1;
1990 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1992 mi->sb_type = bsize;
1994 for (i = 0; i < MAX_MB_PLANE; ++i) {
1995 p[i].coeff = ctx->coeff_pbuf[i][0];
1996 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1997 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1998 p[i].eobs = ctx->eobs_pbuf[i][0];
2002 ctx->pred_pixel_ready = 0;
2005 // Set to zero to make sure we do not use the previous encoded frame stats
2008 #if CONFIG_VP9_HIGHBITDEPTH
2009 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2010 x->source_variance = vp9_high_get_sby_perpixel_variance(
2011 cpi, &x->plane[0].src, bsize, xd->bd);
2013 x->source_variance =
2014 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2017 x->source_variance =
2018 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2019 #endif // CONFIG_VP9_HIGHBITDEPTH
2021 // Save rdmult before it might be changed, so it can be restored later.
2022 orig_rdmult = x->rdmult;
2024 if ((cpi->sf.tx_domain_thresh > 0.0) || (cpi->sf.quant_opt_thresh > 0.0)) {
2025 double logvar = vp9_log_block_var(cpi, x, bsize);
2026 // Check block complexity as part of descision on using pixel or transform
2027 // domain distortion in rd tests.
2028 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion &&
2029 (logvar >= cpi->sf.tx_domain_thresh);
2031 // Check block complexity as part of descision on using quantized
2032 // coefficient optimisation inside the rd loop.
2033 x->block_qcoeff_opt =
2034 cpi->sf.allow_quant_coeff_opt && (logvar <= cpi->sf.quant_opt_thresh);
2036 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion;
2037 x->block_qcoeff_opt = cpi->sf.allow_quant_coeff_opt;
2040 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
2041 set_segment_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode);
2043 // Find best coding mode & reconstruct the MB so it is available
2044 // as a predictor for MBs that follow in the SB
2045 if (frame_is_intra_only(cm)) {
2046 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
2048 if (bsize >= BLOCK_8X8) {
2049 if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
2050 vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
2053 vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2054 bsize, ctx, best_rd);
2056 vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2057 bsize, ctx, best_rd);
2061 // Examine the resulting rate and for AQ mode 2 make a segment choice.
2062 if ((rd_cost->rate != INT_MAX) && (aq_mode == COMPLEXITY_AQ) &&
2063 (bsize >= BLOCK_16X16) &&
2064 (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
2065 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
2066 vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
2069 // TODO(jingning) The rate-distortion optimization flow needs to be
2070 // refactored to provide proper exit/return handle.
2071 if (rd_cost->rate == INT_MAX)
2072 rd_cost->rdcost = INT64_MAX;
2074 rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2076 x->rdmult = orig_rdmult;
2078 ctx->rate = rd_cost->rate;
2079 ctx->dist = rd_cost->dist;
2082 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
2083 const MACROBLOCK *x = &td->mb;
2084 const MACROBLOCKD *const xd = &x->e_mbd;
2085 const MODE_INFO *const mi = xd->mi[0];
2086 const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2087 const BLOCK_SIZE bsize = mi->sb_type;
2089 if (!frame_is_intra_only(cm)) {
2090 FRAME_COUNTS *const counts = td->counts;
2091 const int inter_block = is_inter_block(mi);
2092 const int seg_ref_active =
2093 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_REF_FRAME);
2094 if (!seg_ref_active) {
2095 counts->intra_inter[get_intra_inter_context(xd)][inter_block]++;
2096 // If the segment reference feature is enabled we have only a single
2097 // reference frame allowed for the segment so exclude it from
2098 // the reference frame counts used to work out probabilities.
2100 const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
2101 if (cm->reference_mode == REFERENCE_MODE_SELECT)
2102 counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
2103 [has_second_ref(mi)]++;
2105 if (has_second_ref(mi)) {
2106 const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
2107 const int ctx = vp9_get_pred_context_comp_ref_p(cm, xd);
2108 const int bit = mi->ref_frame[!idx] == cm->comp_var_ref[1];
2109 counts->comp_ref[ctx][bit]++;
2111 counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
2112 [ref0 != LAST_FRAME]++;
2113 if (ref0 != LAST_FRAME)
2114 counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
2115 [ref0 != GOLDEN_FRAME]++;
2120 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP)) {
2121 const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
2122 if (bsize >= BLOCK_8X8) {
2123 const PREDICTION_MODE mode = mi->mode;
2124 ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
2126 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2127 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2129 for (idy = 0; idy < 2; idy += num_4x4_h) {
2130 for (idx = 0; idx < 2; idx += num_4x4_w) {
2131 const int j = idy * 2 + idx;
2132 const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
2133 ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
2141 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
2142 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2143 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2144 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2146 MACROBLOCKD *const xd = &x->e_mbd;
2148 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2149 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2150 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2151 int mi_height = num_8x8_blocks_high_lookup[bsize];
2152 for (p = 0; p < MAX_MB_PLANE; p++) {
2153 memcpy(xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
2154 a + num_4x4_blocks_wide * p,
2155 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2156 xd->plane[p].subsampling_x);
2157 memcpy(xd->left_context[p] +
2158 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2159 l + num_4x4_blocks_high * p,
2160 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2161 xd->plane[p].subsampling_y);
2163 memcpy(xd->above_seg_context + mi_col, sa,
2164 sizeof(*xd->above_seg_context) * mi_width);
2165 memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
2166 sizeof(xd->left_seg_context[0]) * mi_height);
2169 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
2170 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2171 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2172 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2174 const MACROBLOCKD *const xd = &x->e_mbd;
2176 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2177 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2178 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2179 int mi_height = num_8x8_blocks_high_lookup[bsize];
2181 // buffer the above/left context information of the block in search.
2182 for (p = 0; p < MAX_MB_PLANE; ++p) {
2183 memcpy(a + num_4x4_blocks_wide * p,
2184 xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
2185 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2186 xd->plane[p].subsampling_x);
2187 memcpy(l + num_4x4_blocks_high * p,
2188 xd->left_context[p] +
2189 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2190 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2191 xd->plane[p].subsampling_y);
2193 memcpy(sa, xd->above_seg_context + mi_col,
2194 sizeof(*xd->above_seg_context) * mi_width);
2195 memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
2196 sizeof(xd->left_seg_context[0]) * mi_height);
2199 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile, ThreadData *td,
2200 TOKENEXTRA **tp, int mi_row, int mi_col,
2201 int output_enabled, BLOCK_SIZE bsize,
2202 PICK_MODE_CONTEXT *ctx) {
2203 MACROBLOCK *const x = &td->mb;
2204 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2206 if ((cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance) &&
2207 cpi->oxcf.aq_mode == NO_AQ) {
2208 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2209 x->rdmult = x->cb_rdmult;
2210 if (oxcf->tuning == VP8_TUNE_SSIM) {
2211 const double ssim_factor =
2212 get_ssim_rdmult_scaling_factor(cpi, mi_row, mi_col);
2213 x->rdmult = (int)(ssim_factor * x->rdmult);
2214 vpx_clear_system_state();
2218 update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
2219 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2221 if (output_enabled) {
2222 update_stats(&cpi->common, td);
2224 (*tp)->token = EOSB_TOKEN;
2229 static void encode_sb(VP9_COMP *cpi, ThreadData *td, const TileInfo *const tile,
2230 TOKENEXTRA **tp, int mi_row, int mi_col,
2231 int output_enabled, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2232 VP9_COMMON *const cm = &cpi->common;
2233 MACROBLOCK *const x = &td->mb;
2234 MACROBLOCKD *const xd = &x->e_mbd;
2236 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2238 PARTITION_TYPE partition;
2239 BLOCK_SIZE subsize = bsize;
2241 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2243 if (bsize >= BLOCK_8X8) {
2244 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2245 subsize = get_subsize(bsize, pc_tree->partitioning);
2248 subsize = BLOCK_4X4;
2251 partition = partition_lookup[bsl][subsize];
2252 if (output_enabled && bsize != BLOCK_4X4)
2253 td->counts->partition[ctx][partition]++;
2255 switch (partition) {
2256 case PARTITION_NONE:
2257 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2260 case PARTITION_VERT:
2261 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2262 &pc_tree->vertical[0]);
2263 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2264 encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
2265 subsize, &pc_tree->vertical[1]);
2268 case PARTITION_HORZ:
2269 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2270 &pc_tree->horizontal[0]);
2271 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2272 encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
2273 subsize, &pc_tree->horizontal[1]);
2277 assert(partition == PARTITION_SPLIT);
2278 if (bsize == BLOCK_8X8) {
2279 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2280 pc_tree->leaf_split[0]);
2282 encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2284 encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2285 subsize, pc_tree->split[1]);
2286 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2287 subsize, pc_tree->split[2]);
2288 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
2289 subsize, pc_tree->split[3]);
2294 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2295 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2298 // Check to see if the given partition size is allowed for a specified number
2299 // of 8x8 block rows and columns remaining in the image.
2300 // If not then return the largest allowed partition size
2301 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
2302 int cols_left, int *bh, int *bw) {
2303 if (rows_left <= 0 || cols_left <= 0) {
2304 return VPXMIN(bsize, BLOCK_8X8);
2306 for (; bsize > 0; bsize -= 3) {
2307 *bh = num_8x8_blocks_high_lookup[bsize];
2308 *bw = num_8x8_blocks_wide_lookup[bsize];
2309 if ((*bh <= rows_left) && (*bw <= cols_left)) {
2317 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis, int bh_in,
2318 int bw_in, int row8x8_remaining,
2319 int col8x8_remaining, BLOCK_SIZE bsize,
2320 MODE_INFO **mi_8x8) {
2323 for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
2325 for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
2326 const int index = r * mis + c;
2327 mi_8x8[index] = mi + index;
2328 mi_8x8[index]->sb_type = find_partition_size(
2329 bsize, row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
2334 // This function attempts to set all mode info entries in a given SB64
2335 // to the same block partition size.
2336 // However, at the bottom and right borders of the image the requested size
2337 // may not be allowed in which case this code attempts to choose the largest
2338 // allowable partition.
2339 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
2340 MODE_INFO **mi_8x8, int mi_row, int mi_col,
2342 VP9_COMMON *const cm = &cpi->common;
2343 const int mis = cm->mi_stride;
2344 const int row8x8_remaining = tile->mi_row_end - mi_row;
2345 const int col8x8_remaining = tile->mi_col_end - mi_col;
2346 int block_row, block_col;
2347 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2348 int bh = num_8x8_blocks_high_lookup[bsize];
2349 int bw = num_8x8_blocks_wide_lookup[bsize];
2351 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2353 // Apply the requested partition size to the SB64 if it is all "in image"
2354 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2355 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2356 for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
2357 for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
2358 int index = block_row * mis + block_col;
2359 mi_8x8[index] = mi_upper_left + index;
2360 mi_8x8[index]->sb_type = bsize;
2364 // Else this is a partial SB64.
2365 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2366 col8x8_remaining, bsize, mi_8x8);
2370 static const struct {
2373 } coord_lookup[16] = {
2396 static void set_source_var_based_partition(VP9_COMP *cpi,
2397 const TileInfo *const tile,
2398 MACROBLOCK *const x,
2399 MODE_INFO **mi_8x8, int mi_row,
2401 VP9_COMMON *const cm = &cpi->common;
2402 const int mis = cm->mi_stride;
2403 const int row8x8_remaining = tile->mi_row_end - mi_row;
2404 const int col8x8_remaining = tile->mi_col_end - mi_col;
2405 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2407 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
2409 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2412 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2413 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2417 const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
2418 int is_larger_better = 0;
2420 unsigned int thr = cpi->source_var_thresh;
2422 memset(d32, 0, 4 * sizeof(diff));
2424 for (i = 0; i < 4; i++) {
2427 for (j = 0; j < 4; j++) {
2428 int b_mi_row = coord_lookup[i * 4 + j].row;
2429 int b_mi_col = coord_lookup[i * 4 + j].col;
2430 int boffset = b_mi_row / 2 * cm->mb_cols + b_mi_col / 2;
2432 d16[j] = cpi->source_diff_var + offset + boffset;
2434 index = b_mi_row * mis + b_mi_col;
2435 mi_8x8[index] = mi_upper_left + index;
2436 mi_8x8[index]->sb_type = BLOCK_16X16;
2438 // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
2439 // size to further improve quality.
2442 is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
2443 (d16[2]->var < thr) && (d16[3]->var < thr);
2445 // Use 32x32 partition
2446 if (is_larger_better) {
2449 for (j = 0; j < 4; j++) {
2450 d32[i].sse += d16[j]->sse;
2451 d32[i].sum += d16[j]->sum;
2455 (unsigned int)(d32[i].sse -
2456 (unsigned int)(((int64_t)d32[i].sum * d32[i].sum) >>
2459 index = coord_lookup[i * 4].row * mis + coord_lookup[i * 4].col;
2460 mi_8x8[index] = mi_upper_left + index;
2461 mi_8x8[index]->sb_type = BLOCK_32X32;
2465 if (use32x32 == 4) {
2467 is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
2468 (d32[2].var < thr) && (d32[3].var < thr);
2470 // Use 64x64 partition
2471 if (is_larger_better) {
2472 mi_8x8[0] = mi_upper_left;
2473 mi_8x8[0]->sb_type = BLOCK_64X64;
2476 } else { // partial in-image SB64
2477 int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
2478 int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
2479 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2480 col8x8_remaining, BLOCK_16X16, mi_8x8);
2484 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
2485 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
2487 VP9_COMMON *const cm = &cpi->common;
2488 MACROBLOCK *const x = &td->mb;
2489 MACROBLOCKD *const xd = &x->e_mbd;
2490 MODE_INFO *const mi = xd->mi[0];
2491 struct macroblock_plane *const p = x->plane;
2492 const struct segmentation *const seg = &cm->seg;
2493 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
2494 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
2495 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
2496 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
2498 *(xd->mi[0]) = ctx->mic;
2499 *(x->mbmi_ext) = ctx->mbmi_ext;
2501 if (seg->enabled && (cpi->oxcf.aq_mode != NO_AQ || cpi->roi.enabled)) {
2502 // Setting segmentation map for cyclic_refresh.
2503 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
2504 vp9_cyclic_refresh_update_segment(cpi, mi, mi_row, mi_col, bsize,
2505 ctx->rate, ctx->dist, x->skip, p);
2507 const uint8_t *const map =
2508 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
2509 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
2511 vp9_init_plane_quantizers(cpi, x);
2514 if (is_inter_block(mi)) {
2515 vp9_update_mv_count(td);
2516 if (cm->interp_filter == SWITCHABLE) {
2517 const int pred_ctx = get_pred_context_switchable_interp(xd);
2518 ++td->counts->switchable_interp[pred_ctx][mi->interp_filter];
2521 if (mi->sb_type < BLOCK_8X8) {
2522 mi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
2523 mi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
2527 if (cm->use_prev_frame_mvs || !cm->error_resilient_mode ||
2528 (cpi->svc.use_base_mv && cpi->svc.number_spatial_layers > 1 &&
2529 cpi->svc.spatial_layer_id != cpi->svc.number_spatial_layers - 1)) {
2530 MV_REF *const frame_mvs =
2531 cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
2534 for (h = 0; h < y_mis; ++h) {
2535 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
2536 for (w = 0; w < x_mis; ++w) {
2537 MV_REF *const mv = frame_mv + w;
2538 mv->ref_frame[0] = mi->ref_frame[0];
2539 mv->ref_frame[1] = mi->ref_frame[1];
2540 mv->mv[0].as_int = mi->mv[0].as_int;
2541 mv->mv[1].as_int = mi->mv[1].as_int;
2546 x->skip = ctx->skip;
2547 x->skip_txfm[0] = (mi->segment_id || xd->lossless) ? 0 : ctx->skip_txfm[0];
2550 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
2551 const TileInfo *const tile, TOKENEXTRA **tp, int mi_row,
2552 int mi_col, int output_enabled, BLOCK_SIZE bsize,
2553 PICK_MODE_CONTEXT *ctx) {
2554 MACROBLOCK *const x = &td->mb;
2555 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2556 update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
2558 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2559 update_stats(&cpi->common, td);
2561 (*tp)->token = EOSB_TOKEN;
2565 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
2566 const TileInfo *const tile, TOKENEXTRA **tp,
2567 int mi_row, int mi_col, int output_enabled,
2568 BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2569 VP9_COMMON *const cm = &cpi->common;
2570 MACROBLOCK *const x = &td->mb;
2571 MACROBLOCKD *const xd = &x->e_mbd;
2573 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2575 PARTITION_TYPE partition;
2578 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2580 if (bsize >= BLOCK_8X8) {
2581 const int idx_str = xd->mi_stride * mi_row + mi_col;
2582 MODE_INFO **mi_8x8 = cm->mi_grid_visible + idx_str;
2583 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2584 subsize = mi_8x8[0]->sb_type;
2587 subsize = BLOCK_4X4;
2590 partition = partition_lookup[bsl][subsize];
2591 if (output_enabled && bsize != BLOCK_4X4)
2592 td->counts->partition[ctx][partition]++;
2594 switch (partition) {
2595 case PARTITION_NONE:
2596 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2599 case PARTITION_VERT:
2600 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2601 &pc_tree->vertical[0]);
2602 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2603 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2604 subsize, &pc_tree->vertical[1]);
2607 case PARTITION_HORZ:
2608 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2609 &pc_tree->horizontal[0]);
2610 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2611 encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2612 subsize, &pc_tree->horizontal[1]);
2616 assert(partition == PARTITION_SPLIT);
2617 subsize = get_subsize(bsize, PARTITION_SPLIT);
2618 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2620 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2621 subsize, pc_tree->split[1]);
2622 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2623 subsize, pc_tree->split[2]);
2624 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
2625 output_enabled, subsize, pc_tree->split[3]);
2629 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2630 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2633 static void rd_use_partition(VP9_COMP *cpi, ThreadData *td,
2634 TileDataEnc *tile_data, MODE_INFO **mi_8x8,
2635 TOKENEXTRA **tp, int mi_row, int mi_col,
2636 BLOCK_SIZE bsize, int *rate, int64_t *dist,
2637 int do_recon, PC_TREE *pc_tree) {
2638 VP9_COMMON *const cm = &cpi->common;
2639 TileInfo *const tile_info = &tile_data->tile_info;
2640 MACROBLOCK *const x = &td->mb;
2641 MACROBLOCKD *const xd = &x->e_mbd;
2642 const int mis = cm->mi_stride;
2643 const int bsl = b_width_log2_lookup[bsize];
2644 const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
2645 const int bss = (1 << bsl) / 4;
2647 PARTITION_TYPE partition = PARTITION_NONE;
2649 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2650 PARTITION_CONTEXT sl[8], sa[8];
2651 RD_COST last_part_rdc, none_rdc, chosen_rdc;
2652 BLOCK_SIZE sub_subsize = BLOCK_4X4;
2653 int splits_below = 0;
2654 BLOCK_SIZE bs_type = mi_8x8[0]->sb_type;
2655 int do_partition_search = 1;
2656 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2658 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2660 assert(num_4x4_blocks_wide_lookup[bsize] ==
2661 num_4x4_blocks_high_lookup[bsize]);
2663 vp9_rd_cost_reset(&last_part_rdc);
2664 vp9_rd_cost_reset(&none_rdc);
2665 vp9_rd_cost_reset(&chosen_rdc);
2667 partition = partition_lookup[bsl][bs_type];
2668 subsize = get_subsize(bsize, partition);
2670 pc_tree->partitioning = partition;
2671 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2673 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ) {
2674 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2675 x->mb_energy = vp9_block_energy(cpi, x, bsize);
2678 if (do_partition_search &&
2679 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2680 cpi->sf.adjust_partitioning_from_last_frame) {
2681 // Check if any of the sub blocks are further split.
2682 if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
2683 sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
2685 for (i = 0; i < 4; i++) {
2686 int jj = i >> 1, ii = i & 0x01;
2687 MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
2688 if (this_mi && this_mi->sb_type >= sub_subsize) {
2694 // If partition is not none try none unless each of the 4 splits are split
2696 if (partition != PARTITION_NONE && !splits_below &&
2697 mi_row + (mi_step >> 1) < cm->mi_rows &&
2698 mi_col + (mi_step >> 1) < cm->mi_cols) {
2699 pc_tree->partitioning = PARTITION_NONE;
2700 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize, ctx,
2703 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2705 if (none_rdc.rate < INT_MAX) {
2706 none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2708 RDCOST(x->rdmult, x->rddiv, none_rdc.rate, none_rdc.dist);
2711 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2712 mi_8x8[0]->sb_type = bs_type;
2713 pc_tree->partitioning = partition;
2717 switch (partition) {
2718 case PARTITION_NONE:
2719 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc, bsize,
2722 case PARTITION_HORZ:
2723 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
2724 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2725 subsize, &pc_tree->horizontal[0], INT64_MAX);
2726 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2727 mi_row + (mi_step >> 1) < cm->mi_rows) {
2729 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2730 vp9_rd_cost_init(&tmp_rdc);
2731 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2732 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2733 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
2734 rd_pick_sb_modes(cpi, tile_data, x, mi_row + (mi_step >> 1), mi_col,
2735 &tmp_rdc, subsize, &pc_tree->horizontal[1], INT64_MAX);
2736 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2737 vp9_rd_cost_reset(&last_part_rdc);
2740 last_part_rdc.rate += tmp_rdc.rate;
2741 last_part_rdc.dist += tmp_rdc.dist;
2742 last_part_rdc.rdcost += tmp_rdc.rdcost;
2745 case PARTITION_VERT:
2746 pc_tree->vertical[0].skip_ref_frame_mask = 0;
2747 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2748 subsize, &pc_tree->vertical[0], INT64_MAX);
2749 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2750 mi_col + (mi_step >> 1) < cm->mi_cols) {
2752 PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
2753 vp9_rd_cost_init(&tmp_rdc);
2754 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2755 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2756 pc_tree->vertical[bsize > BLOCK_8X8].skip_ref_frame_mask = 0;
2757 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + (mi_step >> 1),
2759 &pc_tree->vertical[bsize > BLOCK_8X8], INT64_MAX);
2760 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2761 vp9_rd_cost_reset(&last_part_rdc);
2764 last_part_rdc.rate += tmp_rdc.rate;
2765 last_part_rdc.dist += tmp_rdc.dist;
2766 last_part_rdc.rdcost += tmp_rdc.rdcost;
2770 assert(partition == PARTITION_SPLIT);
2771 if (bsize == BLOCK_8X8) {
2772 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2773 subsize, pc_tree->leaf_split[0], INT64_MAX);
2776 last_part_rdc.rate = 0;
2777 last_part_rdc.dist = 0;
2778 last_part_rdc.rdcost = 0;
2779 for (i = 0; i < 4; i++) {
2780 int x_idx = (i & 1) * (mi_step >> 1);
2781 int y_idx = (i >> 1) * (mi_step >> 1);
2782 int jj = i >> 1, ii = i & 0x01;
2784 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2787 vp9_rd_cost_init(&tmp_rdc);
2788 rd_use_partition(cpi, td, tile_data, mi_8x8 + jj * bss * mis + ii * bss,
2789 tp, mi_row + y_idx, mi_col + x_idx, subsize,
2790 &tmp_rdc.rate, &tmp_rdc.dist, i != 3,
2792 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2793 vp9_rd_cost_reset(&last_part_rdc);
2796 last_part_rdc.rate += tmp_rdc.rate;
2797 last_part_rdc.dist += tmp_rdc.dist;
2802 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2803 if (last_part_rdc.rate < INT_MAX) {
2804 last_part_rdc.rate += cpi->partition_cost[pl][partition];
2805 last_part_rdc.rdcost =
2806 RDCOST(x->rdmult, x->rddiv, last_part_rdc.rate, last_part_rdc.dist);
2809 if (do_partition_search && cpi->sf.adjust_partitioning_from_last_frame &&
2810 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2811 partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
2812 (mi_row + mi_step < cm->mi_rows ||
2813 mi_row + (mi_step >> 1) == cm->mi_rows) &&
2814 (mi_col + mi_step < cm->mi_cols ||
2815 mi_col + (mi_step >> 1) == cm->mi_cols)) {
2816 BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2817 chosen_rdc.rate = 0;
2818 chosen_rdc.dist = 0;
2819 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2820 pc_tree->partitioning = PARTITION_SPLIT;
2823 for (i = 0; i < 4; i++) {
2824 int x_idx = (i & 1) * (mi_step >> 1);
2825 int y_idx = (i >> 1) * (mi_step >> 1);
2827 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2828 PARTITION_CONTEXT sl[8], sa[8];
2830 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2833 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2834 pc_tree->split[i]->partitioning = PARTITION_NONE;
2835 rd_pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2836 &tmp_rdc, split_subsize, &pc_tree->split[i]->none,
2839 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2841 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2842 vp9_rd_cost_reset(&chosen_rdc);
2846 chosen_rdc.rate += tmp_rdc.rate;
2847 chosen_rdc.dist += tmp_rdc.dist;
2850 encode_sb(cpi, td, tile_info, tp, mi_row + y_idx, mi_col + x_idx, 0,
2851 split_subsize, pc_tree->split[i]);
2853 pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2855 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2857 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2858 if (chosen_rdc.rate < INT_MAX) {
2859 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2861 RDCOST(x->rdmult, x->rddiv, chosen_rdc.rate, chosen_rdc.dist);
2865 // If last_part is better set the partitioning to that.
2866 if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2867 mi_8x8[0]->sb_type = bsize;
2868 if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2869 chosen_rdc = last_part_rdc;
2871 // If none was better set the partitioning to that.
2872 if (none_rdc.rdcost < chosen_rdc.rdcost) {
2873 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2874 chosen_rdc = none_rdc;
2877 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2879 // We must have chosen a partitioning and encoding or we'll fail later on.
2880 // No other opportunities for success.
2881 if (bsize == BLOCK_64X64)
2882 assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2885 int output_enabled = (bsize == BLOCK_64X64);
2886 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2890 *rate = chosen_rdc.rate;
2891 *dist = chosen_rdc.dist;
2894 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2895 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2896 BLOCK_4X4, BLOCK_8X8, BLOCK_8X8, BLOCK_8X8, BLOCK_16X16,
2897 BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
2900 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2901 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2902 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2903 BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
2906 // Look at all the mode_info entries for blocks that are part of this
2907 // partition and find the min and max values for sb_type.
2908 // At the moment this is designed to work on a 64x64 SB but could be
2909 // adjusted to use a size parameter.
2911 // The min and max are assumed to have been initialized prior to calling this
2912 // function so repeat calls can accumulate a min and max of more than one sb64.
2913 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2914 BLOCK_SIZE *min_block_size,
2915 BLOCK_SIZE *max_block_size,
2916 int bs_hist[BLOCK_SIZES]) {
2917 int sb_width_in_blocks = MI_BLOCK_SIZE;
2918 int sb_height_in_blocks = MI_BLOCK_SIZE;
2922 // Check the sb_type for each block that belongs to this region.
2923 for (i = 0; i < sb_height_in_blocks; ++i) {
2924 for (j = 0; j < sb_width_in_blocks; ++j) {
2925 MODE_INFO *mi = mi_8x8[index + j];
2926 BLOCK_SIZE sb_type = mi ? mi->sb_type : 0;
2928 *min_block_size = VPXMIN(*min_block_size, sb_type);
2929 *max_block_size = VPXMAX(*max_block_size, sb_type);
2931 index += xd->mi_stride;
2935 // Next square block size less or equal than current block size.
2936 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2937 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_8X8, BLOCK_8X8,
2938 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2939 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64
2942 // Look at neighboring blocks and set a min and max partition size based on
2944 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2945 MACROBLOCKD *const xd, int mi_row,
2946 int mi_col, BLOCK_SIZE *min_block_size,
2947 BLOCK_SIZE *max_block_size) {
2948 VP9_COMMON *const cm = &cpi->common;
2949 MODE_INFO **mi = xd->mi;
2950 const int left_in_image = !!xd->left_mi;
2951 const int above_in_image = !!xd->above_mi;
2952 const int row8x8_remaining = tile->mi_row_end - mi_row;
2953 const int col8x8_remaining = tile->mi_col_end - mi_col;
2955 BLOCK_SIZE min_size = BLOCK_4X4;
2956 BLOCK_SIZE max_size = BLOCK_64X64;
2957 int bs_hist[BLOCK_SIZES] = { 0 };
2959 // Trap case where we do not have a prediction.
2960 if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2961 // Default "min to max" and "max to min"
2962 min_size = BLOCK_64X64;
2963 max_size = BLOCK_4X4;
2965 // NOTE: each call to get_sb_partition_size_range() uses the previous
2966 // passed in values for min and max as a starting point.
2967 // Find the min and max partition used in previous frame at this location
2968 if (cm->frame_type != KEY_FRAME) {
2969 MODE_INFO **prev_mi =
2970 &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2971 get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2973 // Find the min and max partition sizes used in the left SB64
2974 if (left_in_image) {
2975 MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2976 get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2979 // Find the min and max partition sizes used in the above SB64.
2980 if (above_in_image) {
2981 MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2982 get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2986 // Adjust observed min and max for "relaxed" auto partition case.
2987 if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2988 min_size = min_partition_size[min_size];
2989 max_size = max_partition_size[max_size];
2993 // Check border cases where max and min from neighbors may not be legal.
2994 max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
2996 // Test for blocks at the edge of the active image.
2997 // This may be the actual edge of the image or where there are formatting
2999 if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
3000 min_size = BLOCK_4X4;
3003 VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
3006 // When use_square_partition_only is true, make sure at least one square
3007 // partition is allowed by selecting the next smaller square size as
3009 if (cpi->sf.use_square_partition_only &&
3010 next_square_size[max_size] < min_size) {
3011 min_size = next_square_size[max_size];
3014 *min_block_size = min_size;
3015 *max_block_size = max_size;
3018 // TODO(jingning) refactor functions setting partition search range
3019 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd, int mi_row,
3020 int mi_col, BLOCK_SIZE bsize,
3021 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
3022 int mi_width = num_8x8_blocks_wide_lookup[bsize];
3023 int mi_height = num_8x8_blocks_high_lookup[bsize];
3027 const int idx_str = cm->mi_stride * mi_row + mi_col;
3028 MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
3029 BLOCK_SIZE bs, min_size, max_size;
3031 min_size = BLOCK_64X64;
3032 max_size = BLOCK_4X4;
3035 for (idy = 0; idy < mi_height; ++idy) {
3036 for (idx = 0; idx < mi_width; ++idx) {
3037 mi = prev_mi[idy * cm->mi_stride + idx];
3038 bs = mi ? mi->sb_type : bsize;
3039 min_size = VPXMIN(min_size, bs);
3040 max_size = VPXMAX(max_size, bs);
3046 for (idy = 0; idy < mi_height; ++idy) {
3047 mi = xd->mi[idy * cm->mi_stride - 1];
3048 bs = mi ? mi->sb_type : bsize;
3049 min_size = VPXMIN(min_size, bs);
3050 max_size = VPXMAX(max_size, bs);
3055 for (idx = 0; idx < mi_width; ++idx) {
3056 mi = xd->mi[idx - cm->mi_stride];
3057 bs = mi ? mi->sb_type : bsize;
3058 min_size = VPXMIN(min_size, bs);
3059 max_size = VPXMAX(max_size, bs);
3063 if (min_size == max_size) {
3064 min_size = min_partition_size[min_size];
3065 max_size = max_partition_size[max_size];
3072 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3073 memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
3076 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3077 memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
3080 #if CONFIG_FP_MB_STATS
3081 const int num_16x16_blocks_wide_lookup[BLOCK_SIZES] = { 1, 1, 1, 1, 1, 1, 1,
3083 const int num_16x16_blocks_high_lookup[BLOCK_SIZES] = { 1, 1, 1, 1, 1, 1, 1,
3085 const int qindex_skip_threshold_lookup[BLOCK_SIZES] = { 0, 10, 10, 30, 40,
3088 const int qindex_split_threshold_lookup[BLOCK_SIZES] = { 0, 3, 3, 7, 15,
3091 const int complexity_16x16_blocks_threshold[BLOCK_SIZES] = { 1, 1, 1, 1, 1,
3104 static INLINE MOTION_DIRECTION get_motion_direction_fp(uint8_t fp_byte) {
3105 if (fp_byte & FPMB_MOTION_ZERO_MASK) {
3107 } else if (fp_byte & FPMB_MOTION_LEFT_MASK) {
3109 } else if (fp_byte & FPMB_MOTION_RIGHT_MASK) {
3111 } else if (fp_byte & FPMB_MOTION_UP_MASK) {
3118 static INLINE int get_motion_inconsistency(MOTION_DIRECTION this_mv,
3119 MOTION_DIRECTION that_mv) {
3120 if (this_mv == that_mv) {
3123 return abs(this_mv - that_mv) == 2 ? 2 : 1;
3128 // Calculate prediction based on the given input features and neural net config.
3129 // Assume there are no more than NN_MAX_NODES_PER_LAYER nodes in each hidden
3131 static void nn_predict(const float *features, const NN_CONFIG *nn_config,
3133 int num_input_nodes = nn_config->num_inputs;
3135 float buf[2][NN_MAX_NODES_PER_LAYER];
3136 const float *input_nodes = features;
3138 // Propagate hidden layers.
3139 const int num_layers = nn_config->num_hidden_layers;
3141 assert(num_layers <= NN_MAX_HIDDEN_LAYERS);
3142 for (layer = 0; layer < num_layers; ++layer) {
3143 const float *weights = nn_config->weights[layer];
3144 const float *bias = nn_config->bias[layer];
3145 float *output_nodes = buf[buf_index];
3146 const int num_output_nodes = nn_config->num_hidden_nodes[layer];
3147 assert(num_output_nodes < NN_MAX_NODES_PER_LAYER);
3148 for (node = 0; node < num_output_nodes; ++node) {
3150 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3152 // ReLU as activation function.
3153 val = VPXMAX(val, 0.0f);
3154 output_nodes[node] = val;
3155 weights += num_input_nodes;
3157 num_input_nodes = num_output_nodes;
3158 input_nodes = output_nodes;
3159 buf_index = 1 - buf_index;
3162 // Final output layer.
3164 const float *weights = nn_config->weights[num_layers];
3165 for (node = 0; node < nn_config->num_outputs; ++node) {
3166 const float *bias = nn_config->bias[num_layers];
3168 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3169 output[node] = val + bias[node];
3170 weights += num_input_nodes;
3176 // Machine-learning based partition search early termination.
3177 // Return 1 to skip split and rect partitions.
3178 static int ml_pruning_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
3179 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
3182 abs(ctx->mic.mv[0].as_mv.col) + abs(ctx->mic.mv[0].as_mv.row);
3183 const int left_in_image = !!xd->left_mi;
3184 const int above_in_image = !!xd->above_mi;
3185 MODE_INFO **prev_mi =
3186 &cm->prev_mi_grid_visible[mi_col + cm->mi_stride * mi_row];
3187 int above_par = 0; // above_partitioning
3188 int left_par = 0; // left_partitioning
3189 int last_par = 0; // last_partitioning
3192 BLOCK_SIZE context_size;
3193 const NN_CONFIG *nn_config = NULL;
3194 const float *mean, *sd, *linear_weights;
3195 float nn_score, linear_score;
3196 float features[FEATURES];
3198 assert(b_width_log2_lookup[bsize] == b_height_log2_lookup[bsize]);
3199 vpx_clear_system_state();
3204 nn_config = &vp9_partition_nnconfig_64x64;
3208 nn_config = &vp9_partition_nnconfig_32x32;
3212 nn_config = &vp9_partition_nnconfig_16x16;
3214 default: assert(0 && "Unexpected block size."); return 0;
3217 if (above_in_image) {
3218 context_size = xd->above_mi->sb_type;
3219 if (context_size < bsize)
3221 else if (context_size == bsize)
3225 if (left_in_image) {
3226 context_size = xd->left_mi->sb_type;
3227 if (context_size < bsize)
3229 else if (context_size == bsize)
3234 context_size = prev_mi[0]->sb_type;
3235 if (context_size < bsize)
3237 else if (context_size == bsize)
3241 mean = &vp9_partition_feature_mean[offset];
3242 sd = &vp9_partition_feature_std[offset];
3243 features[0] = ((float)ctx->rate - mean[0]) / sd[0];
3244 features[1] = ((float)ctx->dist - mean[1]) / sd[1];
3245 features[2] = ((float)mag_mv / 2 - mean[2]) * sd[2];
3246 features[3] = ((float)(left_par + above_par) / 2 - mean[3]) * sd[3];
3247 features[4] = ((float)ctx->sum_y_eobs - mean[4]) / sd[4];
3248 features[5] = ((float)cm->base_qindex - mean[5]) * sd[5];
3249 features[6] = ((float)last_par - mean[6]) * sd[6];
3251 // Predict using linear model.
3252 linear_weights = &vp9_partition_linear_weights[offset];
3253 linear_score = linear_weights[FEATURES];
3254 for (i = 0; i < FEATURES; ++i)
3255 linear_score += linear_weights[i] * features[i];
3256 if (linear_score > 0.1f) return 0;
3258 // Predict using neural net model.
3259 nn_predict(features, nn_config, &nn_score);
3261 if (linear_score < -0.0f && nn_score < 0.1f) return 1;
3262 if (nn_score < -0.0f && linear_score < 0.1f) return 1;
3268 // ML-based partition search breakout.
3269 static int ml_predict_breakout(VP9_COMP *const cpi, BLOCK_SIZE bsize,
3270 const MACROBLOCK *const x,
3271 const RD_COST *const rd_cost) {
3272 DECLARE_ALIGNED(16, static const uint8_t, vp9_64_zeros[64]) = { 0 };
3273 const VP9_COMMON *const cm = &cpi->common;
3274 float features[FEATURES];
3275 const float *linear_weights = NULL; // Linear model weights.
3276 float linear_score = 0.0f;
3277 const int qindex = cm->base_qindex;
3278 const int q_ctx = qindex >= 200 ? 0 : (qindex >= 150 ? 1 : 2);
3279 const int is_720p_or_larger = VPXMIN(cm->width, cm->height) >= 720;
3280 const int resolution_ctx = is_720p_or_larger ? 1 : 0;
3284 linear_weights = vp9_partition_breakout_weights_64[resolution_ctx][q_ctx];
3287 linear_weights = vp9_partition_breakout_weights_32[resolution_ctx][q_ctx];
3290 linear_weights = vp9_partition_breakout_weights_16[resolution_ctx][q_ctx];
3293 linear_weights = vp9_partition_breakout_weights_8[resolution_ctx][q_ctx];
3295 default: assert(0 && "Unexpected block size."); return 0;
3297 if (!linear_weights) return 0;
3299 { // Generate feature values.
3300 #if CONFIG_VP9_HIGHBITDEPTH
3302 vp9_ac_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3304 const int ac_q = vp9_ac_quant(qindex, 0, cm->bit_depth);
3305 #endif // CONFIG_VP9_HIGHBITDEPTH
3306 const int num_pels_log2 = num_pels_log2_lookup[bsize];
3307 int feature_index = 0;
3308 unsigned int var, sse;
3309 float rate_f, dist_f;
3311 #if CONFIG_VP9_HIGHBITDEPTH
3312 if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3314 vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, x->e_mbd.bd);
3316 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3317 vp9_64_zeros, 0, &sse);
3320 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3321 vp9_64_zeros, 0, &sse);
3323 var = var >> num_pels_log2;
3325 vpx_clear_system_state();
3327 rate_f = (float)VPXMIN(rd_cost->rate, INT_MAX);
3328 dist_f = (float)(VPXMIN(rd_cost->dist, INT_MAX) >> num_pels_log2);
3330 ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
3333 features[feature_index++] = rate_f;
3334 features[feature_index++] = dist_f;
3335 features[feature_index++] = (float)var;
3336 features[feature_index++] = (float)ac_q;
3337 assert(feature_index == FEATURES);
3340 { // Calculate the output score.
3342 linear_score = linear_weights[FEATURES];
3343 for (i = 0; i < FEATURES; ++i)
3344 linear_score += linear_weights[i] * features[i];
3347 return linear_score >= cpi->sf.rd_ml_partition.search_breakout_thresh[q_ctx];
3353 static void ml_prune_rect_partition(VP9_COMP *const cpi, MACROBLOCK *const x,
3355 const PC_TREE *const pc_tree,
3356 int *allow_horz, int *allow_vert,
3358 const NN_CONFIG *nn_config = NULL;
3359 float score[LABELS] = {
3366 if (ref_rd <= 0 || ref_rd > 1000000000) return;
3369 case BLOCK_8X8: break;
3371 nn_config = &vp9_rect_part_nnconfig_16;
3372 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[1];
3375 nn_config = &vp9_rect_part_nnconfig_32;
3376 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[2];
3379 nn_config = &vp9_rect_part_nnconfig_64;
3380 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[3];
3382 default: assert(0 && "Unexpected block size."); return;
3384 if (!nn_config || thresh < 0) return;
3386 // Feature extraction and model score calculation.
3388 const VP9_COMMON *const cm = &cpi->common;
3389 #if CONFIG_VP9_HIGHBITDEPTH
3391 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3393 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3394 #endif // CONFIG_VP9_HIGHBITDEPTH
3395 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3396 int feature_index = 0;
3397 float features[FEATURES];
3399 features[feature_index++] = logf((float)dc_q + 1.0f);
3400 features[feature_index++] =
3401 (float)(pc_tree->partitioning == PARTITION_NONE);
3402 features[feature_index++] = logf((float)ref_rd / bs / bs + 1.0f);
3405 const float norm_factor = 1.0f / ((float)ref_rd + 1.0f);
3406 const int64_t none_rdcost = pc_tree->none.rdcost;
3407 float rd_ratio = 2.0f;
3408 if (none_rdcost > 0 && none_rdcost < 1000000000)
3409 rd_ratio = (float)none_rdcost * norm_factor;
3410 features[feature_index++] = VPXMIN(rd_ratio, 2.0f);
3412 for (i = 0; i < 4; ++i) {
3413 const int64_t this_rd = pc_tree->split[i]->none.rdcost;
3414 const int rd_valid = this_rd > 0 && this_rd < 1000000000;
3415 // Ratio between sub-block RD and whole block RD.
3416 features[feature_index++] =
3417 rd_valid ? (float)this_rd * norm_factor : 1.0f;
3421 assert(feature_index == FEATURES);
3422 nn_predict(features, nn_config, score);
3425 // Make decisions based on the model score.
3427 int max_score = -1000;
3428 int horz = 0, vert = 0;
3429 int int_score[LABELS];
3430 for (i = 0; i < LABELS; ++i) {
3431 int_score[i] = (int)(100 * score[i]);
3432 max_score = VPXMAX(int_score[i], max_score);
3434 thresh = max_score - thresh;
3435 for (i = 0; i < LABELS; ++i) {
3436 if (int_score[i] >= thresh) {
3437 if ((i >> 0) & 1) horz = 1;
3438 if ((i >> 1) & 1) vert = 1;
3441 *allow_horz = *allow_horz && horz;
3442 *allow_vert = *allow_vert && vert;
3448 // Perform fast and coarse motion search for the given block. This is a
3449 // pre-processing step for the ML based partition search speedup.
3450 static void simple_motion_search(const VP9_COMP *const cpi, MACROBLOCK *const x,
3451 BLOCK_SIZE bsize, int mi_row, int mi_col,
3452 MV ref_mv, MV_REFERENCE_FRAME ref,
3453 uint8_t *const pred_buf) {
3454 const VP9_COMMON *const cm = &cpi->common;
3455 MACROBLOCKD *const xd = &x->e_mbd;
3456 MODE_INFO *const mi = xd->mi[0];
3457 const YV12_BUFFER_CONFIG *const yv12 = get_ref_frame_buffer(cpi, ref);
3458 const int step_param = 1;
3459 const MvLimits tmp_mv_limits = x->mv_limits;
3460 const SEARCH_METHODS search_method = NSTEP;
3461 const int sadpb = x->sadperbit16;
3462 MV ref_mv_full = { ref_mv.row >> 3, ref_mv.col >> 3 };
3463 MV best_mv = { 0, 0 };
3466 assert(yv12 != NULL);
3468 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
3469 &cm->frame_refs[ref - 1].sf);
3470 mi->ref_frame[0] = ref;
3471 mi->ref_frame[1] = NONE;
3472 mi->sb_type = bsize;
3473 vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
3474 vp9_full_pixel_search(cpi, x, bsize, &ref_mv_full, step_param, search_method,
3475 sadpb, cond_cost_list(cpi, cost_list), &ref_mv,
3479 x->mv_limits = tmp_mv_limits;
3480 mi->mv[0].as_mv = best_mv;
3482 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3483 xd->plane[0].dst.buf = pred_buf;
3484 xd->plane[0].dst.stride = 64;
3485 vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
3488 // Use a neural net model to prune partition-none and partition-split search.
3489 // Features used: QP; spatial block size contexts; variance of prediction
3490 // residue after simple_motion_search.
3492 static void ml_predict_var_rd_paritioning(const VP9_COMP *const cpi,
3493 MACROBLOCK *const x,
3494 PC_TREE *const pc_tree,
3495 BLOCK_SIZE bsize, int mi_row,
3496 int mi_col, int *none, int *split) {
3497 const VP9_COMMON *const cm = &cpi->common;
3498 const NN_CONFIG *nn_config = NULL;
3499 #if CONFIG_VP9_HIGHBITDEPTH
3500 MACROBLOCKD *xd = &x->e_mbd;
3501 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64 * 2]);
3502 uint8_t *const pred_buf = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
3503 ? (CONVERT_TO_BYTEPTR(pred_buffer))
3506 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64]);
3507 uint8_t *const pred_buf = pred_buffer;
3508 #endif // CONFIG_VP9_HIGHBITDEPTH
3509 const int speed = cpi->oxcf.speed;
3510 float thresh = 0.0f;
3514 nn_config = &vp9_part_split_nnconfig_64;
3515 thresh = speed > 0 ? 2.8f : 3.0f;
3518 nn_config = &vp9_part_split_nnconfig_32;
3519 thresh = speed > 0 ? 3.5f : 3.0f;
3522 nn_config = &vp9_part_split_nnconfig_16;
3523 thresh = speed > 0 ? 3.8f : 4.0f;
3526 nn_config = &vp9_part_split_nnconfig_8;
3527 if (cm->width >= 720 && cm->height >= 720)
3528 thresh = speed > 0 ? 2.5f : 2.0f;
3530 thresh = speed > 0 ? 3.8f : 2.0f;
3532 default: assert(0 && "Unexpected block size."); return;
3535 if (!nn_config) return;
3537 // Do a simple single motion search to find a prediction for current block.
3538 // The variance of the residue will be used as input features.
3541 const MV_REFERENCE_FRAME ref =
3542 cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
3543 // If bsize is 64x64, use zero MV as reference; otherwise, use MV result
3544 // of previous(larger) block as reference.
3545 if (bsize == BLOCK_64X64)
3546 ref_mv.row = ref_mv.col = 0;
3548 ref_mv = pc_tree->mv;
3549 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
3550 simple_motion_search(cpi, x, bsize, mi_row, mi_col, ref_mv, ref, pred_buf);
3551 pc_tree->mv = x->e_mbd.mi[0]->mv[0].as_mv;
3554 vpx_clear_system_state();
3557 float features[FEATURES] = { 0.0f };
3558 #if CONFIG_VP9_HIGHBITDEPTH
3560 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (xd->bd - 8);
3562 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3563 #endif // CONFIG_VP9_HIGHBITDEPTH
3564 int feature_idx = 0;
3567 // Generate model input features.
3568 features[feature_idx++] = logf((float)dc_q + 1.0f);
3570 // Get the variance of the residue as input features.
3572 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3573 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3574 const uint8_t *pred = pred_buf;
3575 const uint8_t *src = x->plane[0].src.buf;
3576 const int src_stride = x->plane[0].src.stride;
3577 const int pred_stride = 64;
3579 // Variance of whole block.
3580 const unsigned int var =
3581 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
3582 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
3583 const MACROBLOCKD *const xd = &x->e_mbd;
3584 const int has_above = !!xd->above_mi;
3585 const int has_left = !!xd->left_mi;
3586 const BLOCK_SIZE above_bsize = has_above ? xd->above_mi->sb_type : bsize;
3587 const BLOCK_SIZE left_bsize = has_left ? xd->left_mi->sb_type : bsize;
3590 features[feature_idx++] = (float)has_above;
3591 features[feature_idx++] = (float)b_width_log2_lookup[above_bsize];
3592 features[feature_idx++] = (float)b_height_log2_lookup[above_bsize];
3593 features[feature_idx++] = (float)has_left;
3594 features[feature_idx++] = (float)b_width_log2_lookup[left_bsize];
3595 features[feature_idx++] = (float)b_height_log2_lookup[left_bsize];
3596 features[feature_idx++] = logf((float)var + 1.0f);
3597 for (i = 0; i < 4; ++i) {
3598 const int x_idx = (i & 1) * bs / 2;
3599 const int y_idx = (i >> 1) * bs / 2;
3600 const int src_offset = y_idx * src_stride + x_idx;
3601 const int pred_offset = y_idx * pred_stride + x_idx;
3602 // Variance of quarter block.
3603 const unsigned int sub_var =
3604 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
3605 pred + pred_offset, pred_stride, &sse);
3606 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
3607 features[feature_idx++] = var_ratio;
3610 assert(feature_idx == FEATURES);
3612 // Feed the features into the model to get the confidence score.
3613 nn_predict(features, nn_config, &score);
3615 // Higher score means that the model has higher confidence that the split
3616 // partition is better than the non-split partition. So if the score is
3617 // high enough, we skip the none-split partition search; if the score is
3618 // low enough, we skip the split partition search.
3619 if (score > thresh) *none = 0;
3620 if (score < -thresh) *split = 0;
3625 static double log_wiener_var(int64_t wiener_variance) {
3626 return log(1.0 + wiener_variance) / log(2.0);
3629 static void build_kmeans_segmentation(VP9_COMP *cpi) {
3630 VP9_COMMON *cm = &cpi->common;
3631 BLOCK_SIZE bsize = BLOCK_64X64;
3632 KMEANS_DATA *kmeans_data;
3634 vp9_disable_segmentation(&cm->seg);
3635 if (cm->show_frame) {
3637 cpi->kmeans_data_size = 0;
3638 cpi->kmeans_ctr_num = 8;
3640 for (mi_row = 0; mi_row < cm->mi_rows; mi_row += MI_BLOCK_SIZE) {
3641 for (mi_col = 0; mi_col < cm->mi_cols; mi_col += MI_BLOCK_SIZE) {
3642 int mb_row_start = mi_row >> 1;
3643 int mb_col_start = mi_col >> 1;
3644 int mb_row_end = VPXMIN(
3645 (mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3646 int mb_col_end = VPXMIN(
3647 (mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3649 int64_t wiener_variance = 0;
3651 for (row = mb_row_start; row < mb_row_end; ++row)
3652 for (col = mb_col_start; col < mb_col_end; ++col)
3653 wiener_variance += cpi->mb_wiener_variance[row * cm->mb_cols + col];
3656 (mb_row_end - mb_row_start) * (mb_col_end - mb_col_start);
3658 #if CONFIG_MULTITHREAD
3659 pthread_mutex_lock(&cpi->kmeans_mutex);
3660 #endif // CONFIG_MULTITHREAD
3662 kmeans_data = &cpi->kmeans_data_arr[cpi->kmeans_data_size++];
3663 kmeans_data->value = log_wiener_var(wiener_variance);
3664 kmeans_data->pos = mi_row * cpi->kmeans_data_stride + mi_col;
3665 #if CONFIG_MULTITHREAD
3666 pthread_mutex_unlock(&cpi->kmeans_mutex);
3667 #endif // CONFIG_MULTITHREAD
3671 vp9_kmeans(cpi->kmeans_ctr_ls, cpi->kmeans_boundary_ls,
3672 cpi->kmeans_count_ls, cpi->kmeans_ctr_num, cpi->kmeans_data_arr,
3673 cpi->kmeans_data_size);
3675 vp9_perceptual_aq_mode_setup(cpi, &cm->seg);
3679 static int wiener_var_segment(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3681 VP9_COMMON *cm = &cpi->common;
3682 int mb_row_start = mi_row >> 1;
3683 int mb_col_start = mi_col >> 1;
3685 VPXMIN((mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3687 VPXMIN((mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3689 int64_t wiener_variance = 0;
3691 int8_t seg_hist[MAX_SEGMENTS] = { 0 };
3692 int8_t max_count = 0, max_index = -1;
3694 vpx_clear_system_state();
3696 assert(cpi->norm_wiener_variance > 0);
3698 for (row = mb_row_start; row < mb_row_end; ++row) {
3699 for (col = mb_col_start; col < mb_col_end; ++col) {
3700 wiener_variance = cpi->mb_wiener_variance[row * cm->mb_cols + col];
3702 vp9_get_group_idx(log_wiener_var(wiener_variance),
3703 cpi->kmeans_boundary_ls, cpi->kmeans_ctr_num);
3704 ++seg_hist[segment_id];
3708 for (idx = 0; idx < cpi->kmeans_ctr_num; ++idx) {
3709 if (seg_hist[idx] > max_count) {
3710 max_count = seg_hist[idx];
3715 assert(max_index >= 0);
3716 segment_id = max_index;
3721 static int get_rdmult_delta(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3722 int mi_col, int orig_rdmult) {
3723 const int gf_group_index = cpi->twopass.gf_group.index;
3724 TplDepFrame *tpl_frame = &cpi->tpl_stats[gf_group_index];
3725 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
3726 int tpl_stride = tpl_frame->stride;
3727 int64_t intra_cost = 0;
3728 int64_t mc_dep_cost = 0;
3729 int mi_wide = num_8x8_blocks_wide_lookup[bsize];
3730 int mi_high = num_8x8_blocks_high_lookup[bsize];
3735 double r0, rk, beta;
3737 if (tpl_frame->is_valid == 0) return orig_rdmult;
3739 if (cpi->twopass.gf_group.layer_depth[gf_group_index] > 1) return orig_rdmult;
3741 if (gf_group_index >= MAX_ARF_GOP_SIZE) return orig_rdmult;
3743 for (row = mi_row; row < mi_row + mi_high; ++row) {
3744 for (col = mi_col; col < mi_col + mi_wide; ++col) {
3745 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
3747 if (row >= cpi->common.mi_rows || col >= cpi->common.mi_cols) continue;
3749 intra_cost += this_stats->intra_cost;
3750 mc_dep_cost += this_stats->mc_dep_cost;
3756 vpx_clear_system_state();
3759 rk = (double)intra_cost / mc_dep_cost;
3761 dr = vp9_get_adaptive_rdmult(cpi, beta);
3763 dr = VPXMIN(dr, orig_rdmult * 3 / 2);
3764 dr = VPXMAX(dr, orig_rdmult * 1 / 2);
3771 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
3772 // unlikely to be selected depending on previous rate-distortion optimization
3773 // results, for encoding speed-up.
3774 static void rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3775 TileDataEnc *tile_data, TOKENEXTRA **tp,
3776 int mi_row, int mi_col, BLOCK_SIZE bsize,
3777 RD_COST *rd_cost, int64_t best_rd,
3779 VP9_COMMON *const cm = &cpi->common;
3780 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3781 TileInfo *const tile_info = &tile_data->tile_info;
3782 MACROBLOCK *const x = &td->mb;
3783 MACROBLOCKD *const xd = &x->e_mbd;
3784 const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
3785 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
3786 PARTITION_CONTEXT sl[8], sa[8];
3787 TOKENEXTRA *tp_orig = *tp;
3788 PICK_MODE_CONTEXT *const ctx = &pc_tree->none;
3790 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3792 RD_COST this_rdc, sum_rdc, best_rdc;
3793 int do_split = bsize >= BLOCK_8X8;
3795 INTERP_FILTER pred_interp_filter;
3797 // Override skipping rectangular partition operations for edge blocks
3798 const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
3799 const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
3800 const int xss = x->e_mbd.plane[1].subsampling_x;
3801 const int yss = x->e_mbd.plane[1].subsampling_y;
3803 BLOCK_SIZE min_size = x->min_partition_size;
3804 BLOCK_SIZE max_size = x->max_partition_size;
3806 #if CONFIG_FP_MB_STATS
3807 unsigned int src_diff_var = UINT_MAX;
3808 int none_complexity = 0;
3811 int partition_none_allowed = !force_horz_split && !force_vert_split;
3812 int partition_horz_allowed =
3813 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
3814 int partition_vert_allowed =
3815 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
3817 int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_thr.dist;
3818 int rate_breakout_thr = cpi->sf.partition_search_breakout_thr.rate;
3821 // Ref frames picked in the [i_th] quarter subblock during square partition
3822 // RD search. It may be used to prune ref frame selection of rect partitions.
3823 uint8_t ref_frames_used[4] = { 0, 0, 0, 0 };
3825 int partition_mul = x->cb_rdmult;
3826 if (oxcf->tuning == VP8_TUNE_SSIM) {
3827 const double ssim_factor =
3828 get_ssim_rdmult_scaling_factor(cpi, mi_row, mi_col);
3829 partition_mul = (int)(ssim_factor * partition_mul);
3830 vpx_clear_system_state();
3835 assert(num_8x8_blocks_wide_lookup[bsize] ==
3836 num_8x8_blocks_high_lookup[bsize]);
3838 dist_breakout_thr >>=
3839 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
3841 rate_breakout_thr *= num_pels_log2_lookup[bsize];
3843 vp9_rd_cost_init(&this_rdc);
3844 vp9_rd_cost_init(&sum_rdc);
3845 vp9_rd_cost_reset(&best_rdc);
3846 best_rdc.rdcost = best_rd;
3848 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3850 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ &&
3851 cpi->oxcf.aq_mode != LOOKAHEAD_AQ)
3852 x->mb_energy = vp9_block_energy(cpi, x, bsize);
3854 if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
3855 int cb_partition_search_ctrl =
3856 ((pc_tree->index == 0 || pc_tree->index == 3) +
3857 get_chessboard_index(cm->current_video_frame)) &
3860 if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
3861 set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
3864 // Get sub block energy range
3865 if (bsize >= BLOCK_16X16) {
3866 int min_energy, max_energy;
3867 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3869 must_split = (min_energy < -3) && (max_energy - min_energy > 2);
3872 // Determine partition types in search according to the speed features.
3873 // The threshold set here has to be of square block size.
3874 if (cpi->sf.auto_min_max_partition_size) {
3875 partition_none_allowed &= (bsize <= max_size);
3876 partition_horz_allowed &=
3877 ((bsize <= max_size && bsize > min_size) || force_horz_split);
3878 partition_vert_allowed &=
3879 ((bsize <= max_size && bsize > min_size) || force_vert_split);
3880 do_split &= bsize > min_size;
3883 if (cpi->sf.use_square_partition_only &&
3884 (bsize > cpi->sf.use_square_only_thresh_high ||
3885 bsize < cpi->sf.use_square_only_thresh_low)) {
3887 if (!vp9_active_h_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3888 partition_horz_allowed &= force_horz_split;
3889 if (!vp9_active_v_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3890 partition_vert_allowed &= force_vert_split;
3892 partition_horz_allowed &= force_horz_split;
3893 partition_vert_allowed &= force_vert_split;
3897 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3899 #if CONFIG_FP_MB_STATS
3900 if (cpi->use_fp_mb_stats) {
3901 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3902 src_diff_var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src, mi_row,
3907 #if CONFIG_FP_MB_STATS
3908 // Decide whether we shall split directly and skip searching NONE by using
3909 // the first pass block statistics
3910 if (cpi->use_fp_mb_stats && bsize >= BLOCK_32X32 && do_split &&
3911 partition_none_allowed && src_diff_var > 4 &&
3912 cm->base_qindex < qindex_split_threshold_lookup[bsize]) {
3913 int mb_row = mi_row >> 1;
3914 int mb_col = mi_col >> 1;
3916 VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
3918 VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
3921 // compute a complexity measure, basically measure inconsistency of motion
3922 // vectors obtained from the first pass in the current block
3923 for (r = mb_row; r < mb_row_end; r++) {
3924 for (c = mb_col; c < mb_col_end; c++) {
3925 const int mb_index = r * cm->mb_cols + c;
3927 MOTION_DIRECTION this_mv;
3928 MOTION_DIRECTION right_mv;
3929 MOTION_DIRECTION bottom_mv;
3932 get_motion_direction_fp(cpi->twopass.this_frame_mb_stats[mb_index]);
3935 if (c != mb_col_end - 1) {
3936 right_mv = get_motion_direction_fp(
3937 cpi->twopass.this_frame_mb_stats[mb_index + 1]);
3938 none_complexity += get_motion_inconsistency(this_mv, right_mv);
3942 if (r != mb_row_end - 1) {
3943 bottom_mv = get_motion_direction_fp(
3944 cpi->twopass.this_frame_mb_stats[mb_index + cm->mb_cols]);
3945 none_complexity += get_motion_inconsistency(this_mv, bottom_mv);
3948 // do not count its left and top neighbors to avoid double counting
3952 if (none_complexity > complexity_16x16_blocks_threshold[bsize]) {
3953 partition_none_allowed = 0;
3958 pc_tree->partitioning = PARTITION_NONE;
3960 if (cpi->sf.rd_ml_partition.var_pruning && !frame_is_intra_only(cm)) {
3961 const int do_rd_ml_partition_var_pruning =
3962 partition_none_allowed && do_split &&
3963 mi_row + num_8x8_blocks_high_lookup[bsize] <= cm->mi_rows &&
3964 mi_col + num_8x8_blocks_wide_lookup[bsize] <= cm->mi_cols;
3965 if (do_rd_ml_partition_var_pruning) {
3966 ml_predict_var_rd_paritioning(cpi, x, pc_tree, bsize, mi_row, mi_col,
3967 &partition_none_allowed, &do_split);
3969 vp9_zero(pc_tree->mv);
3971 if (bsize > BLOCK_8X8) { // Store MV result as reference for subblocks.
3972 for (i = 0; i < 4; ++i) pc_tree->split[i]->mv = pc_tree->mv;
3977 if (partition_none_allowed) {
3978 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize, ctx,
3980 ctx->rdcost = this_rdc.rdcost;
3981 if (this_rdc.rate != INT_MAX) {
3982 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
3983 const int ref1 = ctx->mic.ref_frame[0];
3984 const int ref2 = ctx->mic.ref_frame[1];
3985 for (i = 0; i < 4; ++i) {
3986 ref_frames_used[i] |= (1 << ref1);
3987 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3990 if (bsize >= BLOCK_8X8) {
3991 this_rdc.rdcost += RDCOST(partition_mul, x->rddiv,
3992 cpi->partition_cost[pl][PARTITION_NONE], 0);
3993 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3996 if (this_rdc.rdcost < best_rdc.rdcost) {
3997 MODE_INFO *mi = xd->mi[0];
3999 best_rdc = this_rdc;
4000 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4002 if (cpi->sf.rd_ml_partition.search_early_termination) {
4003 // Currently, the machine-learning based partition search early
4004 // termination is only used while bsize is 16x16, 32x32 or 64x64,
4005 // VPXMIN(cm->width, cm->height) >= 480, and speed = 0.
4006 if (!x->e_mbd.lossless &&
4007 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP) &&
4008 ctx->mic.mode >= INTRA_MODES && bsize >= BLOCK_16X16) {
4009 if (ml_pruning_partition(cm, xd, ctx, mi_row, mi_col, bsize)) {
4016 if ((do_split || do_rect) && !x->e_mbd.lossless && ctx->skippable) {
4017 const int use_ml_based_breakout =
4018 cpi->sf.rd_ml_partition.search_breakout && cm->base_qindex >= 100;
4019 if (use_ml_based_breakout) {
4020 if (ml_predict_breakout(cpi, bsize, x, &this_rdc)) {
4025 if (!cpi->sf.rd_ml_partition.search_early_termination) {
4026 if ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4027 (best_rdc.dist < dist_breakout_thr &&
4028 best_rdc.rate < rate_breakout_thr)) {
4036 #if CONFIG_FP_MB_STATS
4037 // Check if every 16x16 first pass block statistics has zero
4038 // motion and the corresponding first pass residue is small enough.
4039 // If that is the case, check the difference variance between the
4040 // current frame and the last frame. If the variance is small enough,
4041 // stop further splitting in RD optimization
4042 if (cpi->use_fp_mb_stats && do_split != 0 &&
4043 cm->base_qindex > qindex_skip_threshold_lookup[bsize]) {
4044 int mb_row = mi_row >> 1;
4045 int mb_col = mi_col >> 1;
4047 VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
4049 VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
4053 for (r = mb_row; r < mb_row_end; r++) {
4054 for (c = mb_col; c < mb_col_end; c++) {
4055 const int mb_index = r * cm->mb_cols + c;
4056 if (!(cpi->twopass.this_frame_mb_stats[mb_index] &
4057 FPMB_MOTION_ZERO_MASK) ||
4058 !(cpi->twopass.this_frame_mb_stats[mb_index] &
4059 FPMB_ERROR_SMALL_MASK)) {
4070 if (src_diff_var == UINT_MAX) {
4071 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4072 src_diff_var = get_sby_perpixel_diff_variance(
4073 cpi, &x->plane[0].src, mi_row, mi_col, bsize);
4075 if (src_diff_var < 8) {
4084 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4086 vp9_zero(ctx->pred_mv);
4087 ctx->mic.interp_filter = EIGHTTAP;
4090 // store estimated motion vector
4091 store_pred_mv(x, ctx);
4093 // If the interp_filter is marked as SWITCHABLE_FILTERS, it was for an
4094 // intra block and used for context purposes.
4095 if (ctx->mic.interp_filter == SWITCHABLE_FILTERS) {
4096 pred_interp_filter = EIGHTTAP;
4098 pred_interp_filter = ctx->mic.interp_filter;
4102 // TODO(jingning): use the motion vectors given by the above search as
4103 // the starting point of motion search in the following partition type check.
4104 pc_tree->split[0]->none.rdcost = 0;
4105 pc_tree->split[1]->none.rdcost = 0;
4106 pc_tree->split[2]->none.rdcost = 0;
4107 pc_tree->split[3]->none.rdcost = 0;
4108 if (do_split || must_split) {
4109 subsize = get_subsize(bsize, PARTITION_SPLIT);
4110 load_pred_mv(x, ctx);
4111 if (bsize == BLOCK_8X8) {
4113 if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
4114 pc_tree->leaf_split[0]->pred_interp_filter = pred_interp_filter;
4115 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4116 pc_tree->leaf_split[0], best_rdc.rdcost);
4117 if (sum_rdc.rate == INT_MAX) {
4118 sum_rdc.rdcost = INT64_MAX;
4120 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4121 const int ref1 = pc_tree->leaf_split[0]->mic.ref_frame[0];
4122 const int ref2 = pc_tree->leaf_split[0]->mic.ref_frame[1];
4123 for (i = 0; i < 4; ++i) {
4124 ref_frames_used[i] |= (1 << ref1);
4125 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4130 for (i = 0; (i < 4) && ((sum_rdc.rdcost < best_rdc.rdcost) || must_split);
4132 const int x_idx = (i & 1) * mi_step;
4133 const int y_idx = (i >> 1) * mi_step;
4135 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4138 pc_tree->split[i]->index = i;
4139 if (cpi->sf.prune_ref_frame_for_rect_partitions)
4140 pc_tree->split[i]->none.rate = INT_MAX;
4141 rd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4142 mi_col + x_idx, subsize, &this_rdc,
4143 // A must split test here increases the number of sub
4144 // partitions but hurts metrics results quite a bit,
4145 // so this extra test is commented out pending
4146 // further tests on whether it adds much in terms of
4148 // (must_split) ? best_rdc.rdcost
4149 // : best_rdc.rdcost - sum_rdc.rdcost,
4150 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4152 if (this_rdc.rate == INT_MAX) {
4153 sum_rdc.rdcost = INT64_MAX;
4156 if (cpi->sf.prune_ref_frame_for_rect_partitions &&
4157 pc_tree->split[i]->none.rate != INT_MAX) {
4158 const int ref1 = pc_tree->split[i]->none.mic.ref_frame[0];
4159 const int ref2 = pc_tree->split[i]->none.mic.ref_frame[1];
4160 ref_frames_used[i] |= (1 << ref1);
4161 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4163 sum_rdc.rate += this_rdc.rate;
4164 sum_rdc.dist += this_rdc.dist;
4165 sum_rdc.rdcost += this_rdc.rdcost;
4170 if (((sum_rdc.rdcost < best_rdc.rdcost) || must_split) && i == 4) {
4171 sum_rdc.rdcost += RDCOST(partition_mul, x->rddiv,
4172 cpi->partition_cost[pl][PARTITION_SPLIT], 0);
4173 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4175 if ((sum_rdc.rdcost < best_rdc.rdcost) ||
4176 (must_split && (sum_rdc.dist < best_rdc.dist))) {
4178 pc_tree->partitioning = PARTITION_SPLIT;
4180 // Rate and distortion based partition search termination clause.
4181 if (!cpi->sf.rd_ml_partition.search_early_termination &&
4182 !x->e_mbd.lossless &&
4183 ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4184 (best_rdc.dist < dist_breakout_thr &&
4185 best_rdc.rate < rate_breakout_thr))) {
4190 // skip rectangular partition test when larger block size
4191 // gives better rd cost
4192 if (cpi->sf.less_rectangular_check &&
4193 (bsize > cpi->sf.use_square_only_thresh_high ||
4194 best_rdc.dist < dist_breakout_thr))
4195 do_rect &= !partition_none_allowed;
4197 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4200 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
4201 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
4202 pc_tree->vertical[0].skip_ref_frame_mask = 0;
4203 pc_tree->vertical[1].skip_ref_frame_mask = 0;
4204 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4205 uint8_t used_frames;
4206 used_frames = ref_frames_used[0] | ref_frames_used[1];
4207 if (used_frames) pc_tree->horizontal[0].skip_ref_frame_mask = ~used_frames;
4208 used_frames = ref_frames_used[2] | ref_frames_used[3];
4209 if (used_frames) pc_tree->horizontal[1].skip_ref_frame_mask = ~used_frames;
4210 used_frames = ref_frames_used[0] | ref_frames_used[2];
4211 if (used_frames) pc_tree->vertical[0].skip_ref_frame_mask = ~used_frames;
4212 used_frames = ref_frames_used[1] | ref_frames_used[3];
4213 if (used_frames) pc_tree->vertical[1].skip_ref_frame_mask = ~used_frames;
4217 const int do_ml_rect_partition_pruning =
4218 !frame_is_intra_only(cm) && !force_horz_split && !force_vert_split &&
4219 (partition_horz_allowed || partition_vert_allowed) && bsize > BLOCK_8X8;
4220 if (do_ml_rect_partition_pruning) {
4221 ml_prune_rect_partition(cpi, x, bsize, pc_tree, &partition_horz_allowed,
4222 &partition_vert_allowed, best_rdc.rdcost);
4227 if (partition_horz_allowed &&
4228 (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
4229 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_HORZ];
4230 const int64_t part_mode_rdcost =
4231 RDCOST(partition_mul, x->rddiv, part_mode_rate, 0);
4232 subsize = get_subsize(bsize, PARTITION_HORZ);
4233 load_pred_mv(x, ctx);
4234 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4235 partition_none_allowed)
4236 pc_tree->horizontal[0].pred_interp_filter = pred_interp_filter;
4237 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4238 &pc_tree->horizontal[0],
4239 best_rdc.rdcost - part_mode_rdcost);
4240 if (sum_rdc.rdcost < INT64_MAX) {
4241 sum_rdc.rdcost += part_mode_rdcost;
4242 sum_rdc.rate += part_mode_rate;
4245 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
4246 bsize > BLOCK_8X8) {
4247 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
4248 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
4249 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
4250 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4251 partition_none_allowed)
4252 pc_tree->horizontal[1].pred_interp_filter = pred_interp_filter;
4253 rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col, &this_rdc,
4254 subsize, &pc_tree->horizontal[1],
4255 best_rdc.rdcost - sum_rdc.rdcost);
4256 if (this_rdc.rate == INT_MAX) {
4257 sum_rdc.rdcost = INT64_MAX;
4259 sum_rdc.rate += this_rdc.rate;
4260 sum_rdc.dist += this_rdc.dist;
4261 sum_rdc.rdcost += this_rdc.rdcost;
4265 if (sum_rdc.rdcost < best_rdc.rdcost) {
4267 pc_tree->partitioning = PARTITION_HORZ;
4269 if (cpi->sf.less_rectangular_check &&
4270 bsize > cpi->sf.use_square_only_thresh_high)
4273 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4277 if (partition_vert_allowed &&
4278 (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
4279 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_VERT];
4280 const int64_t part_mode_rdcost =
4281 RDCOST(partition_mul, x->rddiv, part_mode_rate, 0);
4282 subsize = get_subsize(bsize, PARTITION_VERT);
4283 load_pred_mv(x, ctx);
4284 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4285 partition_none_allowed)
4286 pc_tree->vertical[0].pred_interp_filter = pred_interp_filter;
4287 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4288 &pc_tree->vertical[0], best_rdc.rdcost - part_mode_rdcost);
4289 if (sum_rdc.rdcost < INT64_MAX) {
4290 sum_rdc.rdcost += part_mode_rdcost;
4291 sum_rdc.rate += part_mode_rate;
4294 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
4295 bsize > BLOCK_8X8) {
4296 update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
4297 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
4298 &pc_tree->vertical[0]);
4299 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4300 partition_none_allowed)
4301 pc_tree->vertical[1].pred_interp_filter = pred_interp_filter;
4302 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step, &this_rdc,
4303 subsize, &pc_tree->vertical[1],
4304 best_rdc.rdcost - sum_rdc.rdcost);
4305 if (this_rdc.rate == INT_MAX) {
4306 sum_rdc.rdcost = INT64_MAX;
4308 sum_rdc.rate += this_rdc.rate;
4309 sum_rdc.dist += this_rdc.dist;
4310 sum_rdc.rdcost += this_rdc.rdcost;
4314 if (sum_rdc.rdcost < best_rdc.rdcost) {
4316 pc_tree->partitioning = PARTITION_VERT;
4318 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4321 // TODO(jbb): This code added so that we avoid static analysis
4322 // warning related to the fact that best_rd isn't used after this
4323 // point. This code should be refactored so that the duplicate
4324 // checks occur in some sub function and thus are used...
4326 *rd_cost = best_rdc;
4328 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX &&
4329 pc_tree->index != 3) {
4330 int output_enabled = (bsize == BLOCK_64X64);
4331 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4335 if (bsize == BLOCK_64X64) {
4336 assert(tp_orig < *tp);
4337 assert(best_rdc.rate < INT_MAX);
4338 assert(best_rdc.dist < INT64_MAX);
4340 assert(tp_orig == *tp);
4344 static void encode_rd_sb_row(VP9_COMP *cpi, ThreadData *td,
4345 TileDataEnc *tile_data, int mi_row,
4347 VP9_COMMON *const cm = &cpi->common;
4348 TileInfo *const tile_info = &tile_data->tile_info;
4349 MACROBLOCK *const x = &td->mb;
4350 MACROBLOCKD *const xd = &x->e_mbd;
4351 SPEED_FEATURES *const sf = &cpi->sf;
4352 const int mi_col_start = tile_info->mi_col_start;
4353 const int mi_col_end = tile_info->mi_col_end;
4355 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
4356 const int num_sb_cols =
4357 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
4360 // Initialize the left context for the new SB row
4361 memset(&xd->left_context, 0, sizeof(xd->left_context));
4362 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
4364 // Code each SB in the row
4365 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
4366 mi_col += MI_BLOCK_SIZE, sb_col_in_tile++) {
4367 const struct segmentation *const seg = &cm->seg;
4373 int orig_rdmult = cpi->rd.RDMULT;
4375 const int idx_str = cm->mi_stride * mi_row + mi_col;
4376 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
4378 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
4381 if (sf->adaptive_pred_interp_filter) {
4382 for (i = 0; i < 64; ++i) td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
4384 for (i = 0; i < 64; ++i) {
4385 td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
4386 td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
4387 td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
4388 td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
4392 for (i = 0; i < MAX_REF_FRAMES; ++i) {
4393 x->pred_mv[i].row = INT16_MAX;
4394 x->pred_mv[i].col = INT16_MAX;
4396 td->pc_root->index = 0;
4399 const uint8_t *const map =
4400 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
4401 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
4402 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
4405 x->source_variance = UINT_MAX;
4407 x->cb_rdmult = orig_rdmult;
4409 if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
4410 const BLOCK_SIZE bsize =
4411 seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
4412 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4413 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4414 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4415 &dummy_rate, &dummy_dist, 1, td->pc_root);
4416 } else if (cpi->partition_search_skippable_frame) {
4418 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4419 bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col);
4420 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4421 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4422 &dummy_rate, &dummy_dist, 1, td->pc_root);
4423 } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
4424 cm->frame_type != KEY_FRAME) {
4425 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
4426 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4427 &dummy_rate, &dummy_dist, 1, td->pc_root);
4429 if (cpi->twopass.gf_group.index > 0 && cpi->sf.enable_tpl_model) {
4431 get_rdmult_delta(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4435 if (cpi->sf.enable_wiener_variance && cm->show_frame) {
4436 x->segment_id = wiener_var_segment(cpi, BLOCK_64X64, mi_row, mi_col);
4437 x->cb_rdmult = vp9_compute_rd_mult(
4438 cpi, vp9_get_qindex(&cm->seg, x->segment_id, cm->base_qindex));
4441 // If required set upper and lower partition size limits
4442 if (sf->auto_min_max_partition_size) {
4443 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4444 rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
4445 &x->min_partition_size, &x->max_partition_size);
4447 td->pc_root->none.rdcost = 0;
4448 rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
4449 &dummy_rdc, INT64_MAX, td->pc_root);
4451 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
4452 sb_col_in_tile, num_sb_cols);
4456 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
4457 MACROBLOCK *const x = &cpi->td.mb;
4458 VP9_COMMON *const cm = &cpi->common;
4459 MACROBLOCKD *const xd = &x->e_mbd;
4460 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
4462 // Copy data over into macro block data structures.
4463 vp9_setup_src_planes(x, cpi->Source, 0, 0);
4465 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
4467 // Note: this memset assumes above_context[0], [1] and [2]
4468 // are allocated as part of the same buffer.
4469 memset(xd->above_context[0], 0,
4470 sizeof(*xd->above_context[0]) * 2 * aligned_mi_cols * MAX_MB_PLANE);
4471 memset(xd->above_seg_context, 0,
4472 sizeof(*xd->above_seg_context) * aligned_mi_cols);
4475 static int check_dual_ref_flags(VP9_COMP *cpi) {
4476 const int ref_flags = cpi->ref_frame_flags;
4478 if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
4481 return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG) +
4482 !!(ref_flags & VP9_ALT_FLAG)) >= 2;
4486 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
4488 const int mis = cm->mi_stride;
4489 MODE_INFO **mi_ptr = cm->mi_grid_visible;
4491 for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
4492 for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
4493 if (mi_ptr[mi_col]->tx_size > max_tx_size)
4494 mi_ptr[mi_col]->tx_size = max_tx_size;
4499 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
4500 if (frame_is_intra_only(&cpi->common))
4502 else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
4503 return ALTREF_FRAME;
4504 else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
4505 return GOLDEN_FRAME;
4510 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
4511 if (xd->lossless) return ONLY_4X4;
4512 if (cpi->common.frame_type == KEY_FRAME && cpi->sf.use_nonrd_pick_mode)
4514 if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
4516 else if (cpi->sf.tx_size_search_method == USE_FULL_RD ||
4517 cpi->sf.tx_size_search_method == USE_TX_8X8)
4518 return TX_MODE_SELECT;
4520 return cpi->common.tx_mode;
4523 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
4524 RD_COST *rd_cost, BLOCK_SIZE bsize,
4525 PICK_MODE_CONTEXT *ctx) {
4526 if (!cpi->sf.nonrd_keyframe && bsize < BLOCK_16X16)
4527 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4529 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4532 static void hybrid_search_svc_baseiskey(VP9_COMP *cpi, MACROBLOCK *const x,
4533 RD_COST *rd_cost, BLOCK_SIZE bsize,
4534 PICK_MODE_CONTEXT *ctx,
4535 TileDataEnc *tile_data, int mi_row,
4537 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4538 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4540 if (cpi->svc.disable_inter_layer_pred == INTER_LAYER_PRED_OFF)
4541 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4542 else if (bsize >= BLOCK_8X8)
4543 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4546 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4550 static void hybrid_search_scene_change(VP9_COMP *cpi, MACROBLOCK *const x,
4551 RD_COST *rd_cost, BLOCK_SIZE bsize,
4552 PICK_MODE_CONTEXT *ctx,
4553 TileDataEnc *tile_data, int mi_row,
4555 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4556 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4558 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize, ctx);
4562 static void nonrd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
4563 MACROBLOCK *const x, int mi_row, int mi_col,
4564 RD_COST *rd_cost, BLOCK_SIZE bsize,
4565 PICK_MODE_CONTEXT *ctx) {
4566 VP9_COMMON *const cm = &cpi->common;
4567 TileInfo *const tile_info = &tile_data->tile_info;
4568 MACROBLOCKD *const xd = &x->e_mbd;
4570 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
4571 BLOCK_SIZE bs = VPXMAX(bsize, BLOCK_8X8); // processing unit block size
4572 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bs];
4573 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bs];
4576 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4578 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
4581 mi->sb_type = bsize;
4583 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4584 struct macroblockd_plane *pd = &xd->plane[plane];
4585 memcpy(a + num_4x4_blocks_wide * plane, pd->above_context,
4586 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4587 memcpy(l + num_4x4_blocks_high * plane, pd->left_context,
4588 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4591 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
4592 if (cyclic_refresh_segment_id_boosted(mi->segment_id))
4593 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
4595 if (frame_is_intra_only(cm))
4596 hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
4597 else if (cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
4598 hybrid_search_svc_baseiskey(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4600 else if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
4601 set_mode_info_seg_skip(x, cm->tx_mode, rd_cost, bsize);
4602 else if (bsize >= BLOCK_8X8) {
4603 if (cpi->rc.hybrid_intra_scene_change)
4604 hybrid_search_scene_change(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4607 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4610 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4613 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4615 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4616 struct macroblockd_plane *pd = &xd->plane[plane];
4617 memcpy(pd->above_context, a + num_4x4_blocks_wide * plane,
4618 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4619 memcpy(pd->left_context, l + num_4x4_blocks_high * plane,
4620 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4623 if (rd_cost->rate == INT_MAX) vp9_rd_cost_reset(rd_cost);
4625 ctx->rate = rd_cost->rate;
4626 ctx->dist = rd_cost->dist;
4629 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x, int mi_row,
4630 int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4631 MACROBLOCKD *xd = &x->e_mbd;
4632 int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4633 PARTITION_TYPE partition = pc_tree->partitioning;
4634 BLOCK_SIZE subsize = get_subsize(bsize, partition);
4636 assert(bsize >= BLOCK_8X8);
4638 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4640 switch (partition) {
4641 case PARTITION_NONE:
4642 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4643 *(xd->mi[0]) = pc_tree->none.mic;
4644 *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
4645 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4647 case PARTITION_VERT:
4648 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4649 *(xd->mi[0]) = pc_tree->vertical[0].mic;
4650 *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
4651 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4653 if (mi_col + hbs < cm->mi_cols) {
4654 set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
4655 *(xd->mi[0]) = pc_tree->vertical[1].mic;
4656 *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
4657 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
4660 case PARTITION_HORZ:
4661 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4662 *(xd->mi[0]) = pc_tree->horizontal[0].mic;
4663 *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
4664 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4665 if (mi_row + hbs < cm->mi_rows) {
4666 set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
4667 *(xd->mi[0]) = pc_tree->horizontal[1].mic;
4668 *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
4669 duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
4672 case PARTITION_SPLIT: {
4673 fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
4674 fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
4676 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
4678 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
4686 // Reset the prediction pixel ready flag recursively.
4687 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
4688 pc_tree->none.pred_pixel_ready = 0;
4689 pc_tree->horizontal[0].pred_pixel_ready = 0;
4690 pc_tree->horizontal[1].pred_pixel_ready = 0;
4691 pc_tree->vertical[0].pred_pixel_ready = 0;
4692 pc_tree->vertical[1].pred_pixel_ready = 0;
4694 if (bsize > BLOCK_8X8) {
4695 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4697 for (i = 0; i < 4; ++i) pred_pixel_ready_reset(pc_tree->split[i], subsize);
4703 static int ml_predict_var_paritioning(VP9_COMP *cpi, MACROBLOCK *x,
4704 BLOCK_SIZE bsize, int mi_row,
4706 VP9_COMMON *const cm = &cpi->common;
4707 const NN_CONFIG *nn_config = NULL;
4710 case BLOCK_64X64: nn_config = &vp9_var_part_nnconfig_64; break;
4711 case BLOCK_32X32: nn_config = &vp9_var_part_nnconfig_32; break;
4712 case BLOCK_16X16: nn_config = &vp9_var_part_nnconfig_16; break;
4713 case BLOCK_8X8: break;
4714 default: assert(0 && "Unexpected block size."); return -1;
4717 if (!nn_config) return -1;
4719 vpx_clear_system_state();
4722 const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
4723 float features[FEATURES] = { 0.0f };
4724 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
4725 int feature_idx = 0;
4726 float score[LABELS];
4728 features[feature_idx++] = logf((float)(dc_q * dc_q) / 256.0f + 1.0f);
4729 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
4731 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
4732 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4733 const int sb_offset_row = 8 * (mi_row & 7);
4734 const int sb_offset_col = 8 * (mi_col & 7);
4735 const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
4736 const uint8_t *src = x->plane[0].src.buf;
4737 const int src_stride = x->plane[0].src.stride;
4738 const int pred_stride = 64;
4741 // Variance of whole block.
4742 const unsigned int var =
4743 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
4744 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
4746 features[feature_idx++] = logf((float)var + 1.0f);
4747 for (i = 0; i < 4; ++i) {
4748 const int x_idx = (i & 1) * bs / 2;
4749 const int y_idx = (i >> 1) * bs / 2;
4750 const int src_offset = y_idx * src_stride + x_idx;
4751 const int pred_offset = y_idx * pred_stride + x_idx;
4752 // Variance of quarter block.
4753 const unsigned int sub_var =
4754 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
4755 pred + pred_offset, pred_stride, &sse);
4756 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
4757 features[feature_idx++] = var_ratio;
4761 assert(feature_idx == FEATURES);
4762 nn_predict(features, nn_config, score);
4763 if (score[0] > thresh) return PARTITION_SPLIT;
4764 if (score[0] < -thresh) return PARTITION_NONE;
4771 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
4772 TileDataEnc *tile_data, TOKENEXTRA **tp,
4773 int mi_row, int mi_col, BLOCK_SIZE bsize,
4774 RD_COST *rd_cost, int do_recon,
4775 int64_t best_rd, PC_TREE *pc_tree) {
4776 const SPEED_FEATURES *const sf = &cpi->sf;
4777 VP9_COMMON *const cm = &cpi->common;
4778 TileInfo *const tile_info = &tile_data->tile_info;
4779 MACROBLOCK *const x = &td->mb;
4780 MACROBLOCKD *const xd = &x->e_mbd;
4781 const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
4782 TOKENEXTRA *tp_orig = *tp;
4783 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
4785 BLOCK_SIZE subsize = bsize;
4786 RD_COST this_rdc, sum_rdc, best_rdc;
4787 int do_split = bsize >= BLOCK_8X8;
4789 // Override skipping rectangular partition operations for edge blocks
4790 const int force_horz_split = (mi_row + ms >= cm->mi_rows);
4791 const int force_vert_split = (mi_col + ms >= cm->mi_cols);
4792 const int xss = x->e_mbd.plane[1].subsampling_x;
4793 const int yss = x->e_mbd.plane[1].subsampling_y;
4795 int partition_none_allowed = !force_horz_split && !force_vert_split;
4796 int partition_horz_allowed =
4797 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
4798 int partition_vert_allowed =
4799 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
4800 const int use_ml_based_partitioning =
4801 sf->partition_search_type == ML_BASED_PARTITION;
4805 // Avoid checking for rectangular partitions for speed >= 6.
4806 if (cpi->oxcf.speed >= 6) do_rect = 0;
4808 assert(num_8x8_blocks_wide_lookup[bsize] ==
4809 num_8x8_blocks_high_lookup[bsize]);
4811 vp9_rd_cost_init(&sum_rdc);
4812 vp9_rd_cost_reset(&best_rdc);
4813 best_rdc.rdcost = best_rd;
4815 // Determine partition types in search according to the speed features.
4816 // The threshold set here has to be of square block size.
4817 if (sf->auto_min_max_partition_size) {
4818 partition_none_allowed &=
4819 (bsize <= x->max_partition_size && bsize >= x->min_partition_size);
4820 partition_horz_allowed &=
4821 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4823 partition_vert_allowed &=
4824 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4826 do_split &= bsize > x->min_partition_size;
4828 if (sf->use_square_partition_only) {
4829 partition_horz_allowed &= force_horz_split;
4830 partition_vert_allowed &= force_vert_split;
4833 if (use_ml_based_partitioning) {
4834 if (partition_none_allowed || do_split) do_rect = 0;
4835 if (partition_none_allowed && do_split) {
4836 const int ml_predicted_partition =
4837 ml_predict_var_paritioning(cpi, x, bsize, mi_row, mi_col);
4838 if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
4839 if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
4843 if (!partition_none_allowed && !do_split) do_rect = 1;
4845 ctx->pred_pixel_ready =
4846 !(partition_vert_allowed || partition_horz_allowed || do_split);
4849 if (partition_none_allowed) {
4850 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
4852 ctx->mic = *xd->mi[0];
4853 ctx->mbmi_ext = *x->mbmi_ext;
4854 ctx->skip_txfm[0] = x->skip_txfm[0];
4855 ctx->skip = x->skip;
4857 if (this_rdc.rate != INT_MAX) {
4858 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4859 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4861 RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
4862 if (this_rdc.rdcost < best_rdc.rdcost) {
4863 best_rdc = this_rdc;
4864 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4866 if (!use_ml_based_partitioning) {
4867 int64_t dist_breakout_thr = sf->partition_search_breakout_thr.dist;
4868 int64_t rate_breakout_thr = sf->partition_search_breakout_thr.rate;
4869 dist_breakout_thr >>=
4870 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4871 rate_breakout_thr *= num_pels_log2_lookup[bsize];
4872 if (!x->e_mbd.lossless && this_rdc.rate < rate_breakout_thr &&
4873 this_rdc.dist < dist_breakout_thr) {
4882 // store estimated motion vector
4883 store_pred_mv(x, ctx);
4887 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4888 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4889 sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4890 subsize = get_subsize(bsize, PARTITION_SPLIT);
4891 for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
4892 const int x_idx = (i & 1) * ms;
4893 const int y_idx = (i >> 1) * ms;
4895 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4897 load_pred_mv(x, ctx);
4898 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4899 mi_col + x_idx, subsize, &this_rdc, 0,
4900 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4902 if (this_rdc.rate == INT_MAX) {
4903 vp9_rd_cost_reset(&sum_rdc);
4905 sum_rdc.rate += this_rdc.rate;
4906 sum_rdc.dist += this_rdc.dist;
4907 sum_rdc.rdcost += this_rdc.rdcost;
4911 if (sum_rdc.rdcost < best_rdc.rdcost) {
4913 pc_tree->partitioning = PARTITION_SPLIT;
4915 // skip rectangular partition test when larger block size
4916 // gives better rd cost
4917 if (sf->less_rectangular_check) do_rect &= !partition_none_allowed;
4922 if (partition_horz_allowed && do_rect) {
4923 subsize = get_subsize(bsize, PARTITION_HORZ);
4924 load_pred_mv(x, ctx);
4925 pc_tree->horizontal[0].pred_pixel_ready = 1;
4926 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4927 &pc_tree->horizontal[0]);
4929 pc_tree->horizontal[0].mic = *xd->mi[0];
4930 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4931 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4932 pc_tree->horizontal[0].skip = x->skip;
4934 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
4935 load_pred_mv(x, ctx);
4936 pc_tree->horizontal[1].pred_pixel_ready = 1;
4937 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc,
4938 subsize, &pc_tree->horizontal[1]);
4940 pc_tree->horizontal[1].mic = *xd->mi[0];
4941 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
4942 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
4943 pc_tree->horizontal[1].skip = x->skip;
4945 if (this_rdc.rate == INT_MAX) {
4946 vp9_rd_cost_reset(&sum_rdc);
4948 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4949 this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
4950 sum_rdc.rate += this_rdc.rate;
4951 sum_rdc.dist += this_rdc.dist;
4953 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4957 if (sum_rdc.rdcost < best_rdc.rdcost) {
4959 pc_tree->partitioning = PARTITION_HORZ;
4961 pred_pixel_ready_reset(pc_tree, bsize);
4966 if (partition_vert_allowed && do_rect) {
4967 subsize = get_subsize(bsize, PARTITION_VERT);
4968 load_pred_mv(x, ctx);
4969 pc_tree->vertical[0].pred_pixel_ready = 1;
4970 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4971 &pc_tree->vertical[0]);
4972 pc_tree->vertical[0].mic = *xd->mi[0];
4973 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4974 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4975 pc_tree->vertical[0].skip = x->skip;
4977 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
4978 load_pred_mv(x, ctx);
4979 pc_tree->vertical[1].pred_pixel_ready = 1;
4980 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc,
4981 subsize, &pc_tree->vertical[1]);
4982 pc_tree->vertical[1].mic = *xd->mi[0];
4983 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4984 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4985 pc_tree->vertical[1].skip = x->skip;
4987 if (this_rdc.rate == INT_MAX) {
4988 vp9_rd_cost_reset(&sum_rdc);
4990 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4991 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
4992 sum_rdc.rate += this_rdc.rate;
4993 sum_rdc.dist += this_rdc.dist;
4995 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4999 if (sum_rdc.rdcost < best_rdc.rdcost) {
5001 pc_tree->partitioning = PARTITION_VERT;
5003 pred_pixel_ready_reset(pc_tree, bsize);
5007 *rd_cost = best_rdc;
5009 if (best_rdc.rate == INT_MAX) {
5010 vp9_rd_cost_reset(rd_cost);
5014 // update mode info array
5015 fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
5017 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
5018 int output_enabled = (bsize == BLOCK_64X64);
5019 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
5023 if (bsize == BLOCK_64X64 && do_recon) {
5024 assert(tp_orig < *tp);
5025 assert(best_rdc.rate < INT_MAX);
5026 assert(best_rdc.dist < INT64_MAX);
5028 assert(tp_orig == *tp);
5032 static void nonrd_select_partition(VP9_COMP *cpi, ThreadData *td,
5033 TileDataEnc *tile_data, MODE_INFO **mi,
5034 TOKENEXTRA **tp, int mi_row, int mi_col,
5035 BLOCK_SIZE bsize, int output_enabled,
5036 RD_COST *rd_cost, PC_TREE *pc_tree) {
5037 VP9_COMMON *const cm = &cpi->common;
5038 TileInfo *const tile_info = &tile_data->tile_info;
5039 MACROBLOCK *const x = &td->mb;
5040 MACROBLOCKD *const xd = &x->e_mbd;
5041 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5042 const int mis = cm->mi_stride;
5043 PARTITION_TYPE partition;
5046 BLOCK_SIZE subsize_ref =
5047 (cpi->sf.adapt_partition_source_sad) ? BLOCK_8X8 : BLOCK_16X16;
5049 vp9_rd_cost_reset(&this_rdc);
5050 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5052 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5053 partition = partition_lookup[bsl][subsize];
5055 if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
5056 x->max_partition_size = BLOCK_32X32;
5057 x->min_partition_size = BLOCK_16X16;
5058 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5059 0, INT64_MAX, pc_tree);
5060 } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
5061 subsize >= subsize_ref) {
5062 x->max_partition_size = BLOCK_32X32;
5063 x->min_partition_size = BLOCK_8X8;
5064 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5065 0, INT64_MAX, pc_tree);
5066 } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
5067 x->max_partition_size = BLOCK_16X16;
5068 x->min_partition_size = BLOCK_8X8;
5069 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5070 0, INT64_MAX, pc_tree);
5072 switch (partition) {
5073 case PARTITION_NONE:
5074 pc_tree->none.pred_pixel_ready = 1;
5075 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5077 pc_tree->none.mic = *xd->mi[0];
5078 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5079 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5080 pc_tree->none.skip = x->skip;
5082 case PARTITION_VERT:
5083 pc_tree->vertical[0].pred_pixel_ready = 1;
5084 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5085 &pc_tree->vertical[0]);
5086 pc_tree->vertical[0].mic = *xd->mi[0];
5087 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5088 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5089 pc_tree->vertical[0].skip = x->skip;
5090 if (mi_col + hbs < cm->mi_cols) {
5091 pc_tree->vertical[1].pred_pixel_ready = 1;
5092 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
5093 &this_rdc, subsize, &pc_tree->vertical[1]);
5094 pc_tree->vertical[1].mic = *xd->mi[0];
5095 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5096 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5097 pc_tree->vertical[1].skip = x->skip;
5098 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5099 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5100 rd_cost->rate += this_rdc.rate;
5101 rd_cost->dist += this_rdc.dist;
5105 case PARTITION_HORZ:
5106 pc_tree->horizontal[0].pred_pixel_ready = 1;
5107 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5108 &pc_tree->horizontal[0]);
5109 pc_tree->horizontal[0].mic = *xd->mi[0];
5110 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5111 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5112 pc_tree->horizontal[0].skip = x->skip;
5113 if (mi_row + hbs < cm->mi_rows) {
5114 pc_tree->horizontal[1].pred_pixel_ready = 1;
5115 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
5116 &this_rdc, subsize, &pc_tree->horizontal[1]);
5117 pc_tree->horizontal[1].mic = *xd->mi[0];
5118 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5119 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5120 pc_tree->horizontal[1].skip = x->skip;
5121 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5122 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5123 rd_cost->rate += this_rdc.rate;
5124 rd_cost->dist += this_rdc.dist;
5129 assert(partition == PARTITION_SPLIT);
5130 subsize = get_subsize(bsize, PARTITION_SPLIT);
5131 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5132 subsize, output_enabled, rd_cost,
5134 nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5135 mi_col + hbs, subsize, output_enabled, &this_rdc,
5137 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5138 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5139 rd_cost->rate += this_rdc.rate;
5140 rd_cost->dist += this_rdc.dist;
5142 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5143 mi_row + hbs, mi_col, subsize, output_enabled,
5144 &this_rdc, pc_tree->split[2]);
5145 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5146 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5147 rd_cost->rate += this_rdc.rate;
5148 rd_cost->dist += this_rdc.dist;
5150 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5151 mi_row + hbs, mi_col + hbs, subsize,
5152 output_enabled, &this_rdc, pc_tree->split[3]);
5153 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5154 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5155 rd_cost->rate += this_rdc.rate;
5156 rd_cost->dist += this_rdc.dist;
5162 if (bsize == BLOCK_64X64 && output_enabled)
5163 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
5166 static void nonrd_use_partition(VP9_COMP *cpi, ThreadData *td,
5167 TileDataEnc *tile_data, MODE_INFO **mi,
5168 TOKENEXTRA **tp, int mi_row, int mi_col,
5169 BLOCK_SIZE bsize, int output_enabled,
5170 RD_COST *dummy_cost, PC_TREE *pc_tree) {
5171 VP9_COMMON *const cm = &cpi->common;
5172 TileInfo *tile_info = &tile_data->tile_info;
5173 MACROBLOCK *const x = &td->mb;
5174 MACROBLOCKD *const xd = &x->e_mbd;
5175 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5176 const int mis = cm->mi_stride;
5177 PARTITION_TYPE partition;
5180 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5182 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5183 partition = partition_lookup[bsl][subsize];
5185 if (output_enabled && bsize != BLOCK_4X4) {
5186 int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
5187 td->counts->partition[ctx][partition]++;
5190 switch (partition) {
5191 case PARTITION_NONE:
5192 pc_tree->none.pred_pixel_ready = 1;
5193 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5194 subsize, &pc_tree->none);
5195 pc_tree->none.mic = *xd->mi[0];
5196 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5197 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5198 pc_tree->none.skip = x->skip;
5199 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5200 subsize, &pc_tree->none);
5202 case PARTITION_VERT:
5203 pc_tree->vertical[0].pred_pixel_ready = 1;
5204 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5205 subsize, &pc_tree->vertical[0]);
5206 pc_tree->vertical[0].mic = *xd->mi[0];
5207 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5208 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5209 pc_tree->vertical[0].skip = x->skip;
5210 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5211 subsize, &pc_tree->vertical[0]);
5212 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
5213 pc_tree->vertical[1].pred_pixel_ready = 1;
5214 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost,
5215 subsize, &pc_tree->vertical[1]);
5216 pc_tree->vertical[1].mic = *xd->mi[0];
5217 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5218 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5219 pc_tree->vertical[1].skip = x->skip;
5220 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
5221 output_enabled, subsize, &pc_tree->vertical[1]);
5224 case PARTITION_HORZ:
5225 pc_tree->horizontal[0].pred_pixel_ready = 1;
5226 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5227 subsize, &pc_tree->horizontal[0]);
5228 pc_tree->horizontal[0].mic = *xd->mi[0];
5229 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5230 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5231 pc_tree->horizontal[0].skip = x->skip;
5232 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5233 subsize, &pc_tree->horizontal[0]);
5235 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
5236 pc_tree->horizontal[1].pred_pixel_ready = 1;
5237 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost,
5238 subsize, &pc_tree->horizontal[1]);
5239 pc_tree->horizontal[1].mic = *xd->mi[0];
5240 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5241 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5242 pc_tree->horizontal[1].skip = x->skip;
5243 encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
5244 output_enabled, subsize, &pc_tree->horizontal[1]);
5248 assert(partition == PARTITION_SPLIT);
5249 subsize = get_subsize(bsize, PARTITION_SPLIT);
5250 if (bsize == BLOCK_8X8) {
5251 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5252 subsize, pc_tree->leaf_split[0]);
5253 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5254 subsize, pc_tree->leaf_split[0]);
5256 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, subsize,
5257 output_enabled, dummy_cost, pc_tree->split[0]);
5258 nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5259 mi_col + hbs, subsize, output_enabled, dummy_cost,
5261 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5262 mi_row + hbs, mi_col, subsize, output_enabled,
5263 dummy_cost, pc_tree->split[2]);
5264 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5265 mi_row + hbs, mi_col + hbs, subsize, output_enabled,
5266 dummy_cost, pc_tree->split[3]);
5271 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
5272 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
5275 // Get a prediction(stored in x->est_pred) for the whole 64x64 superblock.
5276 static void get_estimated_pred(VP9_COMP *cpi, const TileInfo *const tile,
5277 MACROBLOCK *x, int mi_row, int mi_col) {
5278 VP9_COMMON *const cm = &cpi->common;
5279 const int is_key_frame = frame_is_intra_only(cm);
5280 MACROBLOCKD *xd = &x->e_mbd;
5282 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
5284 if (!is_key_frame) {
5285 MODE_INFO *mi = xd->mi[0];
5286 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
5287 const YV12_BUFFER_CONFIG *yv12_g = NULL;
5288 const BLOCK_SIZE bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
5289 (mi_row + 4 < cm->mi_rows);
5290 unsigned int y_sad_g, y_sad_thr;
5291 unsigned int y_sad = UINT_MAX;
5293 assert(yv12 != NULL);
5295 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
5296 cpi->svc.use_gf_temporal_ref_current_layer) {
5297 // For now, GOLDEN will not be used for non-zero spatial layers, since
5298 // it may not be a temporal reference.
5299 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
5302 // Only compute y_sad_g (sad for golden reference) for speed < 8.
5303 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
5304 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
5305 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5306 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5307 y_sad_g = cpi->fn_ptr[bsize].sdf(
5308 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
5309 xd->plane[0].pre[0].stride);
5314 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
5315 cpi->rc.is_src_frame_alt_ref) {
5316 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
5317 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5318 &cm->frame_refs[ALTREF_FRAME - 1].sf);
5319 mi->ref_frame[0] = ALTREF_FRAME;
5322 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5323 &cm->frame_refs[LAST_FRAME - 1].sf);
5324 mi->ref_frame[0] = LAST_FRAME;
5326 mi->ref_frame[1] = NONE;
5327 mi->sb_type = BLOCK_64X64;
5328 mi->mv[0].as_int = 0;
5329 mi->interp_filter = BILINEAR;
5332 const MV dummy_mv = { 0, 0 };
5333 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
5335 x->sb_use_mv_part = 1;
5336 x->sb_mvcol_part = mi->mv[0].as_mv.col;
5337 x->sb_mvrow_part = mi->mv[0].as_mv.row;
5340 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
5341 // are close if short_circuit_low_temp_var is on.
5342 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
5343 if (y_sad_g < y_sad_thr) {
5344 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5345 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5346 mi->ref_frame[0] = GOLDEN_FRAME;
5347 mi->mv[0].as_int = 0;
5349 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
5352 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
5353 xd->plane[0].dst.buf = x->est_pred;
5354 xd->plane[0].dst.stride = 64;
5355 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
5357 #if CONFIG_VP9_HIGHBITDEPTH
5359 case 8: memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); break;
5361 memset(x->est_pred, 128 * 4, 64 * 64 * sizeof(x->est_pred[0]));
5364 memset(x->est_pred, 128 * 16, 64 * 64 * sizeof(x->est_pred[0]));
5368 memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0]));
5369 #endif // CONFIG_VP9_HIGHBITDEPTH
5373 static void encode_nonrd_sb_row(VP9_COMP *cpi, ThreadData *td,
5374 TileDataEnc *tile_data, int mi_row,
5376 SPEED_FEATURES *const sf = &cpi->sf;
5377 VP9_COMMON *const cm = &cpi->common;
5378 TileInfo *const tile_info = &tile_data->tile_info;
5379 MACROBLOCK *const x = &td->mb;
5380 MACROBLOCKD *const xd = &x->e_mbd;
5381 const int mi_col_start = tile_info->mi_col_start;
5382 const int mi_col_end = tile_info->mi_col_end;
5384 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
5385 const int num_sb_cols =
5386 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
5389 // Initialize the left context for the new SB row
5390 memset(&xd->left_context, 0, sizeof(xd->left_context));
5391 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
5393 // Code each SB in the row
5394 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
5395 mi_col += MI_BLOCK_SIZE, ++sb_col_in_tile) {
5396 const struct segmentation *const seg = &cm->seg;
5398 const int idx_str = cm->mi_stride * mi_row + mi_col;
5399 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
5400 PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
5401 BLOCK_SIZE bsize = BLOCK_64X64;
5405 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
5408 if (cpi->use_skin_detection) {
5409 vp9_compute_skin_sb(cpi, BLOCK_16X16, mi_row, mi_col);
5412 x->source_variance = UINT_MAX;
5413 for (i = 0; i < MAX_REF_FRAMES; ++i) {
5414 x->pred_mv[i].row = INT16_MAX;
5415 x->pred_mv[i].col = INT16_MAX;
5417 vp9_rd_cost_init(&dummy_rdc);
5418 x->color_sensitivity[0] = 0;
5419 x->color_sensitivity[1] = 0;
5421 x->skip_low_source_sad = 0;
5422 x->lowvar_highsumdiff = 0;
5423 x->content_state_sb = 0;
5424 x->zero_temp_sad_source = 0;
5425 x->sb_use_mv_part = 0;
5426 x->sb_mvcol_part = 0;
5427 x->sb_mvrow_part = 0;
5428 x->sb_pickmode_part = 0;
5429 x->arf_frame_usage = 0;
5430 x->lastgolden_frame_usage = 0;
5433 const uint8_t *const map =
5434 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
5435 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
5436 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
5438 partition_search_type = FIXED_PARTITION;
5442 if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
5443 int shift = cpi->Source->y_stride * (mi_row << 3) + (mi_col << 3);
5444 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5445 int64_t source_sad = avg_source_sad(cpi, x, shift, sb_offset2);
5446 if (sf->adapt_partition_source_sad &&
5447 (cpi->oxcf.rc_mode == VPX_VBR && !cpi->rc.is_src_frame_alt_ref &&
5448 source_sad > sf->adapt_partition_thresh &&
5449 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)))
5450 partition_search_type = REFERENCE_PARTITION;
5453 // Set the partition type of the 64X64 block
5454 switch (partition_search_type) {
5455 case VAR_BASED_PARTITION:
5456 // TODO(jingning, marpan): The mode decision and encoding process
5457 // support both intra and inter sub8x8 block coding for RTC mode.
5458 // Tune the thresholds accordingly to use sub8x8 block coding for
5459 // coding performance improvement.
5460 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5461 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5462 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5464 case ML_BASED_PARTITION:
5465 get_estimated_pred(cpi, tile_info, x, mi_row, mi_col);
5466 x->max_partition_size = BLOCK_64X64;
5467 x->min_partition_size = BLOCK_8X8;
5468 x->sb_pickmode_part = 1;
5469 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5470 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5473 case SOURCE_VAR_BASED_PARTITION:
5474 set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
5475 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5476 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5478 case FIXED_PARTITION:
5479 if (!seg_skip) bsize = sf->always_this_block_size;
5480 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
5481 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5482 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5485 assert(partition_search_type == REFERENCE_PARTITION);
5486 x->sb_pickmode_part = 1;
5487 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
5488 // Use nonrd_pick_partition on scene-cut for VBR mode.
5489 // nonrd_pick_partition does not support 4x4 partition, so avoid it
5490 // on key frame for now.
5491 if ((cpi->oxcf.rc_mode == VPX_VBR && cpi->rc.high_source_sad &&
5492 cpi->oxcf.speed < 6 && !frame_is_intra_only(cm) &&
5493 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
5494 // Use lower max_partition_size for low resoultions.
5495 if (cm->width <= 352 && cm->height <= 288)
5496 x->max_partition_size = BLOCK_32X32;
5498 x->max_partition_size = BLOCK_64X64;
5499 x->min_partition_size = BLOCK_8X8;
5500 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5501 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5504 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5505 // TODO(marpan): Seems like nonrd_select_partition does not support
5506 // 4x4 partition. Since 4x4 is used on key frame, use this switch
5508 if (frame_is_intra_only(cm))
5509 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5510 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5512 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5513 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5519 // Update ref_frame usage for inter frame if this group is ARF group.
5520 if (!cpi->rc.is_src_frame_alt_ref && !cpi->refresh_golden_frame &&
5521 !cpi->refresh_alt_ref_frame && cpi->rc.alt_ref_gf_group &&
5522 cpi->sf.use_altref_onepass) {
5523 int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5524 if (cpi->count_arf_frame_usage != NULL)
5525 cpi->count_arf_frame_usage[sboffset] = x->arf_frame_usage;
5526 if (cpi->count_lastgolden_frame_usage != NULL)
5527 cpi->count_lastgolden_frame_usage[sboffset] = x->lastgolden_frame_usage;
5530 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
5531 sb_col_in_tile, num_sb_cols);
5534 // end RTC play code
5536 static INLINE uint32_t variance(const diff *const d) {
5537 return d->sse - (uint32_t)(((int64_t)d->sum * d->sum) >> 8);
5540 #if CONFIG_VP9_HIGHBITDEPTH
5541 static INLINE uint32_t variance_highbd(diff *const d) {
5542 const int64_t var = (int64_t)d->sse - (((int64_t)d->sum * d->sum) >> 8);
5543 return (var >= 0) ? (uint32_t)var : 0;
5545 #endif // CONFIG_VP9_HIGHBITDEPTH
5547 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
5548 const SPEED_FEATURES *const sf = &cpi->sf;
5549 const VP9_COMMON *const cm = &cpi->common;
5551 const uint8_t *src = cpi->Source->y_buffer;
5552 const uint8_t *last_src = cpi->Last_Source->y_buffer;
5553 const int src_stride = cpi->Source->y_stride;
5554 const int last_stride = cpi->Last_Source->y_stride;
5556 // Pick cutoff threshold
5557 const int cutoff = (VPXMIN(cm->width, cm->height) >= 720)
5558 ? (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100)
5559 : (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
5560 DECLARE_ALIGNED(16, int, hist[VAR_HIST_BINS]);
5561 diff *var16 = cpi->source_diff_var;
5566 memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
5568 for (i = 0; i < cm->mb_rows; i++) {
5569 for (j = 0; j < cm->mb_cols; j++) {
5570 #if CONFIG_VP9_HIGHBITDEPTH
5571 if (cm->use_highbitdepth) {
5572 switch (cm->bit_depth) {
5574 vpx_highbd_8_get16x16var(src, src_stride, last_src, last_stride,
5575 &var16->sse, &var16->sum);
5576 var16->var = variance(var16);
5579 vpx_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
5580 &var16->sse, &var16->sum);
5581 var16->var = variance_highbd(var16);
5584 assert(cm->bit_depth == VPX_BITS_12);
5585 vpx_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
5586 &var16->sse, &var16->sum);
5587 var16->var = variance_highbd(var16);
5591 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5593 var16->var = variance(var16);
5596 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5598 var16->var = variance(var16);
5599 #endif // CONFIG_VP9_HIGHBITDEPTH
5601 if (var16->var >= VAR_HIST_MAX_BG_VAR)
5602 hist[VAR_HIST_BINS - 1]++;
5604 hist[var16->var / VAR_HIST_FACTOR]++;
5611 src = src - cm->mb_cols * 16 + 16 * src_stride;
5612 last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
5615 cpi->source_var_thresh = 0;
5617 if (hist[VAR_HIST_BINS - 1] < cutoff) {
5618 for (i = 0; i < VAR_HIST_BINS - 1; i++) {
5622 cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
5628 return sf->search_type_check_frequency;
5631 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
5632 VP9_COMMON *const cm = &cpi->common;
5633 SPEED_FEATURES *const sf = &cpi->sf;
5635 if (cm->frame_type == KEY_FRAME) {
5636 // For key frame, use SEARCH_PARTITION.
5637 sf->partition_search_type = SEARCH_PARTITION;
5638 } else if (cm->intra_only) {
5639 sf->partition_search_type = FIXED_PARTITION;
5641 if (cm->last_width != cm->width || cm->last_height != cm->height) {
5642 if (cpi->source_diff_var) vpx_free(cpi->source_diff_var);
5644 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
5645 vpx_calloc(cm->MBs, sizeof(diff)));
5648 if (!cpi->frames_till_next_var_check)
5649 cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
5651 if (cpi->frames_till_next_var_check > 0) {
5652 sf->partition_search_type = FIXED_PARTITION;
5653 cpi->frames_till_next_var_check--;
5658 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
5659 unsigned int intra_count = 0, inter_count = 0;
5662 for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
5663 intra_count += td->counts->intra_inter[j][0];
5664 inter_count += td->counts->intra_inter[j][1];
5667 return (intra_count << 2) < inter_count && cm->frame_type != KEY_FRAME &&
5671 void vp9_init_tile_data(VP9_COMP *cpi) {
5672 VP9_COMMON *const cm = &cpi->common;
5673 const int tile_cols = 1 << cm->log2_tile_cols;
5674 const int tile_rows = 1 << cm->log2_tile_rows;
5675 int tile_col, tile_row;
5676 TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
5677 TOKENLIST *tplist = cpi->tplist[0][0];
5679 int tplist_count = 0;
5681 if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
5682 if (cpi->tile_data != NULL) vpx_free(cpi->tile_data);
5685 vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
5686 cpi->allocated_tiles = tile_cols * tile_rows;
5688 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5689 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5690 TileDataEnc *tile_data =
5691 &cpi->tile_data[tile_row * tile_cols + tile_col];
5693 for (i = 0; i < BLOCK_SIZES; ++i) {
5694 for (j = 0; j < MAX_MODES; ++j) {
5695 tile_data->thresh_freq_fact[i][j] = RD_THRESH_INIT_FACT;
5696 #if CONFIG_CONSISTENT_RECODE
5697 tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5699 tile_data->mode_map[i][j] = j;
5702 #if CONFIG_MULTITHREAD
5703 tile_data->row_base_thresh_freq_fact = NULL;
5708 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
5709 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5710 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5711 TileInfo *tile_info = &this_tile->tile_info;
5712 if (cpi->sf.adaptive_rd_thresh_row_mt &&
5713 this_tile->row_base_thresh_freq_fact == NULL)
5714 vp9_row_mt_alloc_rd_thresh(cpi, this_tile);
5715 vp9_tile_init(tile_info, cm, tile_row, tile_col);
5717 cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
5718 pre_tok = cpi->tile_tok[tile_row][tile_col];
5719 tile_tok = allocated_tokens(*tile_info);
5721 cpi->tplist[tile_row][tile_col] = tplist + tplist_count;
5722 tplist = cpi->tplist[tile_row][tile_col];
5723 tplist_count = get_num_vert_units(*tile_info, MI_BLOCK_SIZE_LOG2);
5728 void vp9_encode_sb_row(VP9_COMP *cpi, ThreadData *td, int tile_row,
5729 int tile_col, int mi_row) {
5730 VP9_COMMON *const cm = &cpi->common;
5731 const int tile_cols = 1 << cm->log2_tile_cols;
5732 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5733 const TileInfo *const tile_info = &this_tile->tile_info;
5734 TOKENEXTRA *tok = NULL;
5736 int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
5738 tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile_info->mi_row_start) >>
5740 get_start_tok(cpi, tile_row, tile_col, mi_row, &tok);
5741 cpi->tplist[tile_row][tile_col][tile_sb_row].start = tok;
5743 if (cpi->sf.use_nonrd_pick_mode)
5744 encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5746 encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
5748 cpi->tplist[tile_row][tile_col][tile_sb_row].stop = tok;
5749 cpi->tplist[tile_row][tile_col][tile_sb_row].count =
5750 (unsigned int)(cpi->tplist[tile_row][tile_col][tile_sb_row].stop -
5751 cpi->tplist[tile_row][tile_col][tile_sb_row].start);
5752 assert(tok - cpi->tplist[tile_row][tile_col][tile_sb_row].start <=
5753 get_token_alloc(MI_BLOCK_SIZE >> 1, tile_mb_cols));
5758 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td, int tile_row,
5760 VP9_COMMON *const cm = &cpi->common;
5761 const int tile_cols = 1 << cm->log2_tile_cols;
5762 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5763 const TileInfo *const tile_info = &this_tile->tile_info;
5764 const int mi_row_start = tile_info->mi_row_start;
5765 const int mi_row_end = tile_info->mi_row_end;
5768 for (mi_row = mi_row_start; mi_row < mi_row_end; mi_row += MI_BLOCK_SIZE)
5769 vp9_encode_sb_row(cpi, td, tile_row, tile_col, mi_row);
5772 static void encode_tiles(VP9_COMP *cpi) {
5773 VP9_COMMON *const cm = &cpi->common;
5774 const int tile_cols = 1 << cm->log2_tile_cols;
5775 const int tile_rows = 1 << cm->log2_tile_rows;
5776 int tile_col, tile_row;
5778 vp9_init_tile_data(cpi);
5780 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5781 for (tile_col = 0; tile_col < tile_cols; ++tile_col)
5782 vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
5785 #if CONFIG_FP_MB_STATS
5786 static int input_fpmb_stats(FIRSTPASS_MB_STATS *firstpass_mb_stats,
5787 VP9_COMMON *cm, uint8_t **this_frame_mb_stats) {
5788 uint8_t *mb_stats_in = firstpass_mb_stats->mb_stats_start +
5789 cm->current_video_frame * cm->MBs * sizeof(uint8_t);
5791 if (mb_stats_in > firstpass_mb_stats->mb_stats_end) return EOF;
5793 *this_frame_mb_stats = mb_stats_in;
5799 static int compare_kmeans_data(const void *a, const void *b) {
5800 if (((const KMEANS_DATA *)a)->value > ((const KMEANS_DATA *)b)->value) {
5802 } else if (((const KMEANS_DATA *)a)->value <
5803 ((const KMEANS_DATA *)b)->value) {
5810 static void compute_boundary_ls(const double *ctr_ls, int k,
5811 double *boundary_ls) {
5812 // boundary_ls[j] is the upper bound of data centered at ctr_ls[j]
5814 for (j = 0; j < k - 1; ++j) {
5815 boundary_ls[j] = (ctr_ls[j] + ctr_ls[j + 1]) / 2.;
5817 boundary_ls[k - 1] = DBL_MAX;
5820 int vp9_get_group_idx(double value, double *boundary_ls, int k) {
5822 while (value >= boundary_ls[group_idx]) {
5824 if (group_idx == k - 1) {
5831 void vp9_kmeans(double *ctr_ls, double *boundary_ls, int *count_ls, int k,
5832 KMEANS_DATA *arr, int size) {
5836 double sum[MAX_KMEANS_GROUPS];
5837 int count[MAX_KMEANS_GROUPS];
5839 vpx_clear_system_state();
5841 assert(k >= 2 && k <= MAX_KMEANS_GROUPS);
5843 qsort(arr, size, sizeof(*arr), compare_kmeans_data);
5845 // initialize the center points
5846 for (j = 0; j < k; ++j) {
5847 ctr_ls[j] = arr[(size * (2 * j + 1)) / (2 * k)].value;
5850 for (itr = 0; itr < 10; ++itr) {
5851 compute_boundary_ls(ctr_ls, k, boundary_ls);
5852 for (i = 0; i < MAX_KMEANS_GROUPS; ++i) {
5857 // Both the data and centers are sorted in ascending order.
5858 // As each data point is processed in order, its corresponding group index
5859 // can only increase. So we only need to reset the group index to zero here.
5861 for (i = 0; i < size; ++i) {
5862 while (arr[i].value >= boundary_ls[group_idx]) {
5863 // place samples into clusters
5865 if (group_idx == k - 1) {
5869 sum[group_idx] += arr[i].value;
5873 for (group_idx = 0; group_idx < k; ++group_idx) {
5874 if (count[group_idx] > 0)
5875 ctr_ls[group_idx] = sum[group_idx] / count[group_idx];
5878 count[group_idx] = 0;
5882 // compute group_idx, boundary_ls and count_ls
5883 for (j = 0; j < k; ++j) {
5886 compute_boundary_ls(ctr_ls, k, boundary_ls);
5888 for (i = 0; i < size; ++i) {
5889 while (arr[i].value >= boundary_ls[group_idx]) {
5891 if (group_idx == k - 1) {
5895 arr[i].group_idx = group_idx;
5896 ++count_ls[group_idx];
5900 static void encode_frame_internal(VP9_COMP *cpi) {
5901 SPEED_FEATURES *const sf = &cpi->sf;
5902 ThreadData *const td = &cpi->td;
5903 MACROBLOCK *const x = &td->mb;
5904 VP9_COMMON *const cm = &cpi->common;
5905 MACROBLOCKD *const xd = &x->e_mbd;
5906 const int gf_group_index = cpi->twopass.gf_group.index;
5908 xd->mi = cm->mi_grid_visible;
5910 vp9_zero(*td->counts);
5911 vp9_zero(cpi->td.rd_counts);
5913 xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
5914 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
5916 #if CONFIG_VP9_HIGHBITDEPTH
5917 if (cm->use_highbitdepth)
5918 x->fwd_txfm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
5920 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5921 x->highbd_inv_txfm_add =
5922 xd->lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
5924 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5925 #endif // CONFIG_VP9_HIGHBITDEPTH
5926 x->inv_txfm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
5927 #if CONFIG_CONSISTENT_RECODE
5928 x->optimize = sf->optimize_coefficients == 1 && cpi->oxcf.pass != 1;
5930 if (xd->lossless) x->optimize = 0;
5931 x->sharpness = cpi->oxcf.sharpness;
5932 x->adjust_rdmult_by_segment = (cpi->oxcf.aq_mode == VARIANCE_AQ);
5934 cm->tx_mode = select_tx_mode(cpi, xd);
5936 vp9_frame_init_quantizer(cpi);
5938 vp9_initialize_rd_consts(cpi);
5939 vp9_initialize_me_consts(cpi, x, cm->base_qindex);
5940 init_encode_frame_mb_context(cpi);
5941 cm->use_prev_frame_mvs =
5942 !cm->error_resilient_mode && cm->width == cm->last_width &&
5943 cm->height == cm->last_height && !cm->intra_only && cm->last_show_frame;
5944 // Special case: set prev_mi to NULL when the previous mode info
5945 // context cannot be used.
5947 cm->use_prev_frame_mvs ? cm->prev_mip + cm->mi_stride + 1 : NULL;
5949 x->quant_fp = cpi->sf.use_quant_fp;
5950 vp9_zero(x->skip_txfm);
5951 if (sf->use_nonrd_pick_mode) {
5952 // Initialize internal buffer pointers for rtc coding, where non-RD
5953 // mode decision is used and hence no buffer pointer swap needed.
5955 struct macroblock_plane *const p = x->plane;
5956 struct macroblockd_plane *const pd = xd->plane;
5957 PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
5959 for (i = 0; i < MAX_MB_PLANE; ++i) {
5960 p[i].coeff = ctx->coeff_pbuf[i][0];
5961 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
5962 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
5963 p[i].eobs = ctx->eobs_pbuf[i][0];
5965 vp9_zero(x->zcoeff_blk);
5967 if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0 &&
5968 !(cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) &&
5970 cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
5972 if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
5973 source_var_based_partition_search_method(cpi);
5974 } else if (gf_group_index && gf_group_index < MAX_ARF_GOP_SIZE &&
5975 cpi->sf.enable_tpl_model) {
5976 TplDepFrame *tpl_frame = &cpi->tpl_stats[cpi->twopass.gf_group.index];
5977 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
5979 int tpl_stride = tpl_frame->stride;
5980 int64_t intra_cost_base = 0;
5981 int64_t mc_dep_cost_base = 0;
5984 for (row = 0; row < cm->mi_rows && tpl_frame->is_valid; ++row) {
5985 for (col = 0; col < cm->mi_cols; ++col) {
5986 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
5987 intra_cost_base += this_stats->intra_cost;
5988 mc_dep_cost_base += this_stats->mc_dep_cost;
5992 vpx_clear_system_state();
5994 if (tpl_frame->is_valid)
5995 cpi->rd.r0 = (double)intra_cost_base / mc_dep_cost_base;
5998 // Frame segmentation
5999 if (cpi->sf.enable_wiener_variance) build_kmeans_segmentation(cpi);
6002 struct vpx_usec_timer emr_timer;
6003 vpx_usec_timer_start(&emr_timer);
6005 #if CONFIG_FP_MB_STATS
6006 if (cpi->use_fp_mb_stats) {
6007 input_fpmb_stats(&cpi->twopass.firstpass_mb_stats, cm,
6008 &cpi->twopass.this_frame_mb_stats);
6013 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
6014 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
6015 // If allowed, encoding tiles in parallel with one thread handling one
6016 // tile when row based multi-threading is disabled.
6017 if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
6018 vp9_encode_tiles_mt(cpi);
6022 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
6023 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
6024 vp9_encode_tiles_row_mt(cpi);
6027 vpx_usec_timer_mark(&emr_timer);
6028 cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
6031 sf->skip_encode_frame =
6032 sf->skip_encode_sb ? get_skip_encode_frame(cm, td) : 0;
6035 // Keep record of the total distortion this time around for future use
6036 cpi->last_frame_distortion = cpi->frame_distortion;
6040 static INTERP_FILTER get_interp_filter(
6041 const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
6042 if (!is_alt_ref && threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
6043 threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
6044 threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
6045 return EIGHTTAP_SMOOTH;
6046 } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
6047 threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
6048 return EIGHTTAP_SHARP;
6049 } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
6056 static int compute_frame_aq_offset(struct VP9_COMP *cpi) {
6057 VP9_COMMON *const cm = &cpi->common;
6058 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
6059 struct segmentation *const seg = &cm->seg;
6067 for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
6068 MODE_INFO **mi_8x8 = mi_8x8_ptr;
6069 for (mi_col = 0; mi_col < cm->mi_cols; mi_col++, mi_8x8++) {
6070 segment_id = mi_8x8[0]->segment_id;
6071 qdelta_index = get_segdata(seg, segment_id, SEG_LVL_ALT_Q);
6072 sum_delta += qdelta_index;
6075 mi_8x8_ptr += cm->mi_stride;
6078 return sum_delta / (cm->mi_rows * cm->mi_cols);
6081 #if CONFIG_CONSISTENT_RECODE
6082 static void restore_encode_params(VP9_COMP *cpi) {
6083 VP9_COMMON *const cm = &cpi->common;
6084 const int tile_cols = 1 << cm->log2_tile_cols;
6085 const int tile_rows = 1 << cm->log2_tile_rows;
6086 int tile_col, tile_row;
6088 RD_OPT *rd_opt = &cpi->rd;
6089 for (i = 0; i < MAX_REF_FRAMES; i++) {
6090 for (j = 0; j < REFERENCE_MODES; j++)
6091 rd_opt->prediction_type_threshes[i][j] =
6092 rd_opt->prediction_type_threshes_prev[i][j];
6094 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
6095 rd_opt->filter_threshes[i][j] = rd_opt->filter_threshes_prev[i][j];
6098 if (cpi->tile_data != NULL) {
6099 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
6100 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
6101 TileDataEnc *tile_data =
6102 &cpi->tile_data[tile_row * tile_cols + tile_col];
6103 for (i = 0; i < BLOCK_SIZES; ++i) {
6104 for (j = 0; j < MAX_MODES; ++j) {
6105 tile_data->thresh_freq_fact[i][j] =
6106 tile_data->thresh_freq_fact_prev[i][j];
6112 cm->interp_filter = cpi->sf.default_interp_filter;
6116 void vp9_encode_frame(VP9_COMP *cpi) {
6117 VP9_COMMON *const cm = &cpi->common;
6119 #if CONFIG_CONSISTENT_RECODE
6120 restore_encode_params(cpi);
6123 // In the longer term the encoder should be generalized to match the
6124 // decoder such that we allow compound where one of the 3 buffers has a
6125 // different sign bias and that buffer is then the fixed ref. However, this
6126 // requires further work in the rd loop. For now the only supported encoder
6127 // side behavior is where the ALT ref buffer has opposite sign bias to
6129 if (!frame_is_intra_only(cm)) {
6130 if (vp9_compound_reference_allowed(cm)) {
6131 cpi->allow_comp_inter_inter = 1;
6132 vp9_setup_compound_reference_mode(cm);
6134 cpi->allow_comp_inter_inter = 0;
6138 if (cpi->sf.frame_parameter_update) {
6140 RD_OPT *const rd_opt = &cpi->rd;
6141 FRAME_COUNTS *counts = cpi->td.counts;
6142 RD_COUNTS *const rdc = &cpi->td.rd_counts;
6144 // This code does a single RD pass over the whole frame assuming
6145 // either compound, single or hybrid prediction as per whatever has
6146 // worked best for that type of frame in the past.
6147 // It also predicts whether another coding mode would have worked
6148 // better than this coding mode. If that is the case, it remembers
6149 // that for subsequent frames.
6150 // It also does the same analysis for transform size selection.
6151 const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
6152 int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
6153 int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
6154 const int is_alt_ref = frame_type == ALTREF_FRAME;
6156 /* prediction (compound, single or hybrid) mode selection */
6157 if (is_alt_ref || !cpi->allow_comp_inter_inter)
6158 cm->reference_mode = SINGLE_REFERENCE;
6159 else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
6160 mode_thrs[COMPOUND_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT] &&
6161 check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
6162 cm->reference_mode = COMPOUND_REFERENCE;
6163 else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
6164 cm->reference_mode = SINGLE_REFERENCE;
6166 cm->reference_mode = REFERENCE_MODE_SELECT;
6168 if (cm->interp_filter == SWITCHABLE)
6169 cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
6171 encode_frame_internal(cpi);
6173 for (i = 0; i < REFERENCE_MODES; ++i)
6174 mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
6176 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
6177 filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
6179 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6180 int single_count_zero = 0;
6181 int comp_count_zero = 0;
6183 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6184 single_count_zero += counts->comp_inter[i][0];
6185 comp_count_zero += counts->comp_inter[i][1];
6188 if (comp_count_zero == 0) {
6189 cm->reference_mode = SINGLE_REFERENCE;
6190 vp9_zero(counts->comp_inter);
6191 } else if (single_count_zero == 0) {
6192 cm->reference_mode = COMPOUND_REFERENCE;
6193 vp9_zero(counts->comp_inter);
6197 if (cm->tx_mode == TX_MODE_SELECT) {
6199 int count8x8_lp = 0, count8x8_8x8p = 0;
6200 int count16x16_16x16p = 0, count16x16_lp = 0;
6203 for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
6204 count4x4 += counts->tx.p32x32[i][TX_4X4];
6205 count4x4 += counts->tx.p16x16[i][TX_4X4];
6206 count4x4 += counts->tx.p8x8[i][TX_4X4];
6208 count8x8_lp += counts->tx.p32x32[i][TX_8X8];
6209 count8x8_lp += counts->tx.p16x16[i][TX_8X8];
6210 count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
6212 count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
6213 count16x16_lp += counts->tx.p32x32[i][TX_16X16];
6214 count32x32 += counts->tx.p32x32[i][TX_32X32];
6216 if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
6218 cm->tx_mode = ALLOW_8X8;
6219 reset_skip_tx_size(cm, TX_8X8);
6220 } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
6221 count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
6222 cm->tx_mode = ONLY_4X4;
6223 reset_skip_tx_size(cm, TX_4X4);
6224 } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
6225 cm->tx_mode = ALLOW_32X32;
6226 } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
6227 cm->tx_mode = ALLOW_16X16;
6228 reset_skip_tx_size(cm, TX_16X16);
6232 FRAME_COUNTS *counts = cpi->td.counts;
6233 cm->reference_mode = SINGLE_REFERENCE;
6234 if (cpi->allow_comp_inter_inter && cpi->sf.use_compound_nonrd_pickmode &&
6235 cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
6236 cm->frame_type != KEY_FRAME)
6237 cm->reference_mode = REFERENCE_MODE_SELECT;
6239 encode_frame_internal(cpi);
6241 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6242 int single_count_zero = 0;
6243 int comp_count_zero = 0;
6245 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6246 single_count_zero += counts->comp_inter[i][0];
6247 comp_count_zero += counts->comp_inter[i][1];
6249 if (comp_count_zero == 0) {
6250 cm->reference_mode = SINGLE_REFERENCE;
6251 vp9_zero(counts->comp_inter);
6252 } else if (single_count_zero == 0) {
6253 cm->reference_mode = COMPOUND_REFERENCE;
6254 vp9_zero(counts->comp_inter);
6259 // If segmented AQ is enabled compute the average AQ weighting.
6260 if (cm->seg.enabled && (cpi->oxcf.aq_mode != NO_AQ) &&
6261 (cm->seg.update_map || cm->seg.update_data)) {
6262 cm->seg.aq_av_offset = compute_frame_aq_offset(cpi);
6266 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
6267 const PREDICTION_MODE y_mode = mi->mode;
6268 const PREDICTION_MODE uv_mode = mi->uv_mode;
6269 const BLOCK_SIZE bsize = mi->sb_type;
6271 if (bsize < BLOCK_8X8) {
6273 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
6274 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
6275 for (idy = 0; idy < 2; idy += num_4x4_h)
6276 for (idx = 0; idx < 2; idx += num_4x4_w)
6277 ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
6279 ++counts->y_mode[size_group_lookup[bsize]][y_mode];
6282 ++counts->uv_mode[y_mode][uv_mode];
6285 static void update_zeromv_cnt(VP9_COMP *const cpi, const MODE_INFO *const mi,
6286 int mi_row, int mi_col, BLOCK_SIZE bsize) {
6287 const VP9_COMMON *const cm = &cpi->common;
6288 MV mv = mi->mv[0].as_mv;
6289 const int bw = num_8x8_blocks_wide_lookup[bsize];
6290 const int bh = num_8x8_blocks_high_lookup[bsize];
6291 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
6292 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
6293 const int block_index = mi_row * cm->mi_cols + mi_col;
6295 for (y = 0; y < ymis; y++)
6296 for (x = 0; x < xmis; x++) {
6297 int map_offset = block_index + y * cm->mi_cols + x;
6298 if (mi->ref_frame[0] == LAST_FRAME && is_inter_block(mi) &&
6299 mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
6300 if (abs(mv.row) < 8 && abs(mv.col) < 8) {
6301 if (cpi->consec_zero_mv[map_offset] < 255)
6302 cpi->consec_zero_mv[map_offset]++;
6304 cpi->consec_zero_mv[map_offset] = 0;
6310 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
6311 int output_enabled, int mi_row, int mi_col,
6312 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
6313 VP9_COMMON *const cm = &cpi->common;
6314 MACROBLOCK *const x = &td->mb;
6315 MACROBLOCKD *const xd = &x->e_mbd;
6316 MODE_INFO *mi = xd->mi[0];
6317 const int seg_skip =
6318 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP);
6319 x->skip_recode = !x->select_tx_size && mi->sb_type >= BLOCK_8X8 &&
6320 cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
6321 cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
6322 cpi->sf.allow_skip_recode;
6324 if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
6325 memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
6327 x->skip_optimize = ctx->is_coded;
6329 x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
6330 x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
6331 x->q_index < QIDX_SKIP_THRESH);
6333 if (x->skip_encode) return;
6335 if (!is_inter_block(mi)) {
6337 #if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6338 if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
6339 (xd->above_mi == NULL || xd->left_mi == NULL) &&
6340 need_top_left[mi->uv_mode])
6342 #endif // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6344 for (plane = 0; plane < MAX_MB_PLANE; ++plane)
6345 vp9_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane, 1);
6346 if (output_enabled) sum_intra_stats(td->counts, mi);
6347 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6348 VPXMAX(bsize, BLOCK_8X8));
6351 const int is_compound = has_second_ref(mi);
6352 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
6353 for (ref = 0; ref < 1 + is_compound; ++ref) {
6354 YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, mi->ref_frame[ref]);
6355 assert(cfg != NULL);
6356 vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
6357 &xd->block_refs[ref]->sf);
6359 if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
6360 vp9_build_inter_predictors_sby(xd, mi_row, mi_col,
6361 VPXMAX(bsize, BLOCK_8X8));
6363 vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col,
6364 VPXMAX(bsize, BLOCK_8X8));
6366 vp9_encode_sb(x, VPXMAX(bsize, BLOCK_8X8));
6367 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6368 VPXMAX(bsize, BLOCK_8X8));
6375 if (output_enabled) {
6376 if (cm->tx_mode == TX_MODE_SELECT && mi->sb_type >= BLOCK_8X8 &&
6377 !(is_inter_block(mi) && mi->skip)) {
6378 ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
6379 &td->counts->tx)[mi->tx_size];
6381 // The new intra coding scheme requires no change of transform size
6382 if (is_inter_block(mi)) {
6383 mi->tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
6384 max_txsize_lookup[bsize]);
6386 mi->tx_size = (bsize >= BLOCK_8X8) ? mi->tx_size : TX_4X4;
6390 ++td->counts->tx.tx_totals[mi->tx_size];
6391 ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])];
6392 if (cm->seg.enabled && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
6393 vp9_cyclic_refresh_update_sb_postencode(cpi, mi, mi_row, mi_col, bsize);
6394 if (cpi->oxcf.pass == 0 && cpi->svc.temporal_layer_id == 0 &&
6397 !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
6398 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)))
6399 update_zeromv_cnt(cpi, mi, mi_row, mi_col, bsize);