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 return cpi->mi_ssim_rdmult_scaling_factors[index];
276 static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
277 MACROBLOCK *const x, int mi_row, int mi_col,
279 VP9_COMMON *const cm = &cpi->common;
280 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
281 MACROBLOCKD *const xd = &x->e_mbd;
282 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
283 const int mi_height = num_8x8_blocks_high_lookup[bsize];
284 MvLimits *const mv_limits = &x->mv_limits;
286 set_skip_context(xd, mi_row, mi_col);
288 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
290 // Set up destination pointers.
291 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
293 // Set up limit values for MV components.
294 // Mv beyond the range do not produce new/different prediction block.
295 mv_limits->row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
296 mv_limits->col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
297 mv_limits->row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
298 mv_limits->col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
300 // Set up distance of MB to edge of frame in 1/8th pel units.
301 assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
302 set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width, cm->mi_rows,
305 // Set up source buffers.
306 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
309 x->rddiv = cpi->rd.RDDIV;
310 x->rdmult = cpi->rd.RDMULT;
311 if (oxcf->tuning == VP8_TUNE_SSIM) {
312 const double ssim_factor =
313 get_ssim_rdmult_scaling_factor(cpi, mi_row, mi_col);
314 x->rdmult = (int)(ssim_factor * x->rdmult);
317 // required by vp9_append_sub8x8_mvs_for_idx() and vp9_find_best_ref_mvs()
321 static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
322 int mi_row, int mi_col,
324 const int block_width =
325 VPXMIN(num_8x8_blocks_wide_lookup[bsize], cm->mi_cols - mi_col);
326 const int block_height =
327 VPXMIN(num_8x8_blocks_high_lookup[bsize], cm->mi_rows - mi_row);
328 const int mi_stride = xd->mi_stride;
329 MODE_INFO *const src_mi = xd->mi[0];
332 for (j = 0; j < block_height; ++j)
333 for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
336 static void set_block_size(VP9_COMP *const cpi, MACROBLOCK *const x,
337 MACROBLOCKD *const xd, int mi_row, int mi_col,
339 if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
340 set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
341 xd->mi[0]->sb_type = bsize;
346 // This struct is used for computing variance in choose_partitioning(), where
347 // the max number of samples within a superblock is 16x16 (with 4x4 avg). Even
348 // in high bitdepth, uint32_t is enough for sum_square_error (2^12 * 2^12 * 16
350 uint32_t sum_square_error;
360 } partition_variance;
363 partition_variance part_variances;
368 partition_variance part_variances;
373 partition_variance part_variances;
378 partition_variance part_variances;
383 partition_variance part_variances;
388 partition_variance *part_variances;
398 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
400 node->part_variances = NULL;
403 v64x64 *vt = (v64x64 *)data;
404 node->part_variances = &vt->part_variances;
405 for (i = 0; i < 4; i++)
406 node->split[i] = &vt->split[i].part_variances.none;
410 v32x32 *vt = (v32x32 *)data;
411 node->part_variances = &vt->part_variances;
412 for (i = 0; i < 4; i++)
413 node->split[i] = &vt->split[i].part_variances.none;
417 v16x16 *vt = (v16x16 *)data;
418 node->part_variances = &vt->part_variances;
419 for (i = 0; i < 4; i++)
420 node->split[i] = &vt->split[i].part_variances.none;
424 v8x8 *vt = (v8x8 *)data;
425 node->part_variances = &vt->part_variances;
426 for (i = 0; i < 4; i++)
427 node->split[i] = &vt->split[i].part_variances.none;
431 v4x4 *vt = (v4x4 *)data;
432 assert(bsize == BLOCK_4X4);
433 node->part_variances = &vt->part_variances;
434 for (i = 0; i < 4; i++) node->split[i] = &vt->split[i];
440 // Set variance values given sum square error, sum error, count.
441 static void fill_variance(uint32_t s2, int32_t s, int c, var *v) {
442 v->sum_square_error = s2;
447 static void get_variance(var *v) {
449 (int)(256 * (v->sum_square_error -
450 (uint32_t)(((int64_t)v->sum_error * v->sum_error) >>
455 static void sum_2_variances(const var *a, const var *b, var *r) {
456 assert(a->log2_count == b->log2_count);
457 fill_variance(a->sum_square_error + b->sum_square_error,
458 a->sum_error + b->sum_error, a->log2_count + 1, r);
461 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
463 memset(&node, 0, sizeof(node));
464 tree_to_node(data, bsize, &node);
465 sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
466 sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
467 sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
468 sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
469 sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
470 &node.part_variances->none);
473 static int set_vt_partitioning(VP9_COMP *cpi, MACROBLOCK *const x,
474 MACROBLOCKD *const xd, void *data,
475 BLOCK_SIZE bsize, int mi_row, int mi_col,
476 int64_t threshold, BLOCK_SIZE bsize_min,
478 VP9_COMMON *const cm = &cpi->common;
480 const int block_width = num_8x8_blocks_wide_lookup[bsize];
481 const int block_height = num_8x8_blocks_high_lookup[bsize];
483 assert(block_height == block_width);
484 tree_to_node(data, bsize, &vt);
486 if (force_split == 1) return 0;
488 // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
489 // variance is below threshold, otherwise split will be selected.
490 // No check for vert/horiz split as too few samples for variance.
491 if (bsize == bsize_min) {
492 // Variance already computed to set the force_split.
493 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
494 if (mi_col + block_width / 2 < cm->mi_cols &&
495 mi_row + block_height / 2 < cm->mi_rows &&
496 vt.part_variances->none.variance < threshold) {
497 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
501 } else if (bsize > bsize_min) {
502 // Variance already computed to set the force_split.
503 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
504 // For key frame: take split for bsize above 32X32 or very high variance.
505 if (frame_is_intra_only(cm) &&
506 (bsize > BLOCK_32X32 ||
507 vt.part_variances->none.variance > (threshold << 4))) {
510 // If variance is low, take the bsize (no split).
511 if (mi_col + block_width / 2 < cm->mi_cols &&
512 mi_row + block_height / 2 < cm->mi_rows &&
513 vt.part_variances->none.variance < threshold) {
514 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
518 // Check vertical split.
519 if (mi_row + block_height / 2 < cm->mi_rows) {
520 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
521 get_variance(&vt.part_variances->vert[0]);
522 get_variance(&vt.part_variances->vert[1]);
523 if (vt.part_variances->vert[0].variance < threshold &&
524 vt.part_variances->vert[1].variance < threshold &&
525 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
526 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
527 set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
531 // Check horizontal split.
532 if (mi_col + block_width / 2 < cm->mi_cols) {
533 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
534 get_variance(&vt.part_variances->horz[0]);
535 get_variance(&vt.part_variances->horz[1]);
536 if (vt.part_variances->horz[0].variance < threshold &&
537 vt.part_variances->horz[1].variance < threshold &&
538 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
539 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
540 set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
550 static int64_t scale_part_thresh_sumdiff(int64_t threshold_base, int speed,
551 int width, int height,
554 if (width <= 640 && height <= 480)
555 return (5 * threshold_base) >> 2;
556 else if ((content_state == kLowSadLowSumdiff) ||
557 (content_state == kHighSadLowSumdiff) ||
558 (content_state == kLowVarHighSumdiff))
559 return (5 * threshold_base) >> 2;
560 } else if (speed == 7) {
561 if ((content_state == kLowSadLowSumdiff) ||
562 (content_state == kHighSadLowSumdiff) ||
563 (content_state == kLowVarHighSumdiff)) {
564 return (5 * threshold_base) >> 2;
567 return threshold_base;
570 // Set the variance split thresholds for following the block sizes:
571 // 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
572 // 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
573 // currently only used on key frame.
574 static void set_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q,
576 VP9_COMMON *const cm = &cpi->common;
577 const int is_key_frame = frame_is_intra_only(cm);
578 const int threshold_multiplier =
579 is_key_frame ? 20 : cpi->sf.variance_part_thresh_mult;
580 int64_t threshold_base =
581 (int64_t)(threshold_multiplier * cpi->y_dequant[q][1]);
584 thresholds[0] = threshold_base;
585 thresholds[1] = threshold_base >> 2;
586 thresholds[2] = threshold_base >> 2;
587 thresholds[3] = threshold_base << 2;
589 // Increase base variance threshold based on estimated noise level.
590 if (cpi->noise_estimate.enabled && cm->width >= 640 && cm->height >= 480) {
591 NOISE_LEVEL noise_level =
592 vp9_noise_estimate_extract_level(&cpi->noise_estimate);
593 if (noise_level == kHigh)
594 threshold_base = 3 * threshold_base;
595 else if (noise_level == kMedium)
596 threshold_base = threshold_base << 1;
597 else if (noise_level < kLow)
598 threshold_base = (7 * threshold_base) >> 3;
600 #if CONFIG_VP9_TEMPORAL_DENOISING
601 if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
602 cpi->oxcf.speed > 5 && cpi->denoiser.denoising_level >= kDenLow)
604 vp9_scale_part_thresh(threshold_base, cpi->denoiser.denoising_level,
605 content_state, cpi->svc.temporal_layer_id);
608 scale_part_thresh_sumdiff(threshold_base, cpi->oxcf.speed, cm->width,
609 cm->height, content_state);
611 // Increase base variance threshold based on content_state/sum_diff level.
612 threshold_base = scale_part_thresh_sumdiff(
613 threshold_base, cpi->oxcf.speed, cm->width, cm->height, content_state);
615 thresholds[0] = threshold_base;
616 thresholds[2] = threshold_base << cpi->oxcf.speed;
617 if (cm->width >= 1280 && cm->height >= 720 && cpi->oxcf.speed < 7)
618 thresholds[2] = thresholds[2] << 1;
619 if (cm->width <= 352 && cm->height <= 288) {
620 thresholds[0] = threshold_base >> 3;
621 thresholds[1] = threshold_base >> 1;
622 thresholds[2] = threshold_base << 3;
623 } else if (cm->width < 1280 && cm->height < 720) {
624 thresholds[1] = (5 * threshold_base) >> 2;
625 } else if (cm->width < 1920 && cm->height < 1080) {
626 thresholds[1] = threshold_base << 1;
628 thresholds[1] = (5 * threshold_base) >> 1;
630 if (cpi->sf.disable_16x16part_nonkey) thresholds[2] = INT64_MAX;
634 void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q,
636 VP9_COMMON *const cm = &cpi->common;
637 SPEED_FEATURES *const sf = &cpi->sf;
638 const int is_key_frame = frame_is_intra_only(cm);
639 if (sf->partition_search_type != VAR_BASED_PARTITION &&
640 sf->partition_search_type != REFERENCE_PARTITION) {
643 set_vbp_thresholds(cpi, cpi->vbp_thresholds, q, content_state);
644 // The thresholds below are not changed locally.
646 cpi->vbp_threshold_sad = 0;
647 cpi->vbp_threshold_copy = 0;
648 cpi->vbp_bsize_min = BLOCK_8X8;
650 if (cm->width <= 352 && cm->height <= 288)
651 cpi->vbp_threshold_sad = 10;
653 cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000
654 ? (cpi->y_dequant[q][1] << 1)
656 cpi->vbp_bsize_min = BLOCK_16X16;
657 if (cm->width <= 352 && cm->height <= 288)
658 cpi->vbp_threshold_copy = 4000;
659 else if (cm->width <= 640 && cm->height <= 360)
660 cpi->vbp_threshold_copy = 8000;
662 cpi->vbp_threshold_copy = (cpi->y_dequant[q][1] << 3) > 8000
663 ? (cpi->y_dequant[q][1] << 3)
665 if (cpi->rc.high_source_sad ||
666 (cpi->use_svc && cpi->svc.high_source_sad_superframe)) {
667 cpi->vbp_threshold_sad = 0;
668 cpi->vbp_threshold_copy = 0;
671 cpi->vbp_threshold_minmax = 15 + (q >> 3);
675 // Compute the minmax over the 8x8 subblocks.
676 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
677 int dp, int x16_idx, int y16_idx,
678 #if CONFIG_VP9_HIGHBITDEPTH
681 int pixels_wide, int pixels_high) {
684 int minmax_min = 255;
685 // Loop over the 4 8x8 subblocks.
686 for (k = 0; k < 4; k++) {
687 int x8_idx = x16_idx + ((k & 1) << 3);
688 int y8_idx = y16_idx + ((k >> 1) << 3);
691 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
692 #if CONFIG_VP9_HIGHBITDEPTH
693 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
694 vpx_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
695 d + y8_idx * dp + x8_idx, dp, &min, &max);
697 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx,
701 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx, dp,
704 if ((max - min) > minmax_max) minmax_max = (max - min);
705 if ((max - min) < minmax_min) minmax_min = (max - min);
708 return (minmax_max - minmax_min);
711 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
712 int dp, int x8_idx, int y8_idx, v8x8 *vst,
713 #if CONFIG_VP9_HIGHBITDEPTH
716 int pixels_wide, int pixels_high,
719 for (k = 0; k < 4; k++) {
720 int x4_idx = x8_idx + ((k & 1) << 2);
721 int y4_idx = y8_idx + ((k >> 1) << 2);
722 unsigned int sse = 0;
724 if (x4_idx < pixels_wide && y4_idx < pixels_high) {
727 #if CONFIG_VP9_HIGHBITDEPTH
728 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
729 s_avg = vpx_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
731 d_avg = vpx_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
733 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
734 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
737 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
738 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
743 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
747 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
748 int dp, int x16_idx, int y16_idx, v16x16 *vst,
749 #if CONFIG_VP9_HIGHBITDEPTH
752 int pixels_wide, int pixels_high,
755 for (k = 0; k < 4; k++) {
756 int x8_idx = x16_idx + ((k & 1) << 3);
757 int y8_idx = y16_idx + ((k >> 1) << 3);
758 unsigned int sse = 0;
760 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
763 #if CONFIG_VP9_HIGHBITDEPTH
764 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
765 s_avg = vpx_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
767 d_avg = vpx_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
769 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
770 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
773 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
774 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
779 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
783 // Check if most of the superblock is skin content, and if so, force split to
784 // 32x32, and set x->sb_is_skin for use in mode selection.
785 static int skin_sb_split(VP9_COMP *cpi, MACROBLOCK *x, const int low_res,
786 int mi_row, int mi_col, int *force_split) {
787 VP9_COMMON *const cm = &cpi->common;
788 #if CONFIG_VP9_HIGHBITDEPTH
789 if (cm->use_highbitdepth) return 0;
791 // Avoid checking superblocks on/near boundary and avoid low resolutions.
792 // Note superblock may still pick 64X64 if y_sad is very small
793 // (i.e., y_sad < cpi->vbp_threshold_sad) below. For now leave this as is.
794 if (!low_res && (mi_col >= 8 && mi_col + 8 < cm->mi_cols && mi_row >= 8 &&
795 mi_row + 8 < cm->mi_rows)) {
796 int num_16x16_skin = 0;
797 int num_16x16_nonskin = 0;
798 uint8_t *ysignal = x->plane[0].src.buf;
799 uint8_t *usignal = x->plane[1].src.buf;
800 uint8_t *vsignal = x->plane[2].src.buf;
801 int sp = x->plane[0].src.stride;
802 int spuv = x->plane[1].src.stride;
803 const int block_index = mi_row * cm->mi_cols + mi_col;
804 const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
805 const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
806 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
807 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
808 // Loop through the 16x16 sub-blocks.
810 for (i = 0; i < ymis; i += 2) {
811 for (j = 0; j < xmis; j += 2) {
812 int bl_index = block_index + i * cm->mi_cols + j;
813 int is_skin = cpi->skin_map[bl_index];
814 num_16x16_skin += is_skin;
815 num_16x16_nonskin += (1 - is_skin);
816 if (num_16x16_nonskin > 3) {
817 // Exit loop if at least 4 of the 16x16 blocks are not skin.
825 ysignal += (sp << 4) - 64;
826 usignal += (spuv << 3) - 32;
827 vsignal += (spuv << 3) - 32;
829 if (num_16x16_skin > 12) {
837 static void set_low_temp_var_flag(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
838 v64x64 *vt, int64_t thresholds[],
839 MV_REFERENCE_FRAME ref_frame_partition,
840 int mi_col, int mi_row) {
842 VP9_COMMON *const cm = &cpi->common;
843 const int mv_thr = cm->width > 640 ? 8 : 4;
844 // Check temporal variance for bsize >= 16x16, if LAST_FRAME was selected and
845 // int_pro mv is small. If the temporal variance is small set the flag
846 // variance_low for the block. The variance threshold can be adjusted, the
847 // higher the more aggressive.
848 if (ref_frame_partition == LAST_FRAME &&
849 (cpi->sf.short_circuit_low_temp_var == 1 ||
850 (xd->mi[0]->mv[0].as_mv.col < mv_thr &&
851 xd->mi[0]->mv[0].as_mv.col > -mv_thr &&
852 xd->mi[0]->mv[0].as_mv.row < mv_thr &&
853 xd->mi[0]->mv[0].as_mv.row > -mv_thr))) {
854 if (xd->mi[0]->sb_type == BLOCK_64X64) {
855 if ((vt->part_variances).none.variance < (thresholds[0] >> 1))
856 x->variance_low[0] = 1;
857 } else if (xd->mi[0]->sb_type == BLOCK_64X32) {
858 for (i = 0; i < 2; i++) {
859 if (vt->part_variances.horz[i].variance < (thresholds[0] >> 2))
860 x->variance_low[i + 1] = 1;
862 } else if (xd->mi[0]->sb_type == BLOCK_32X64) {
863 for (i = 0; i < 2; i++) {
864 if (vt->part_variances.vert[i].variance < (thresholds[0] >> 2))
865 x->variance_low[i + 3] = 1;
868 for (i = 0; i < 4; i++) {
869 const int idx[4][2] = { { 0, 0 }, { 0, 4 }, { 4, 0 }, { 4, 4 } };
871 cm->mi_stride * (mi_row + idx[i][0]) + mi_col + idx[i][1];
872 MODE_INFO **this_mi = cm->mi_grid_visible + idx_str;
874 if (cm->mi_cols <= mi_col + idx[i][1] ||
875 cm->mi_rows <= mi_row + idx[i][0])
878 if ((*this_mi)->sb_type == BLOCK_32X32) {
879 int64_t threshold_32x32 = (cpi->sf.short_circuit_low_temp_var == 1 ||
880 cpi->sf.short_circuit_low_temp_var == 3)
881 ? ((5 * thresholds[1]) >> 3)
882 : (thresholds[1] >> 1);
883 if (vt->split[i].part_variances.none.variance < threshold_32x32)
884 x->variance_low[i + 5] = 1;
885 } else if (cpi->sf.short_circuit_low_temp_var >= 2) {
886 // For 32x16 and 16x32 blocks, the flag is set on each 16x16 block
888 if ((*this_mi)->sb_type == BLOCK_16X16 ||
889 (*this_mi)->sb_type == BLOCK_32X16 ||
890 (*this_mi)->sb_type == BLOCK_16X32) {
891 for (j = 0; j < 4; j++) {
892 if (vt->split[i].split[j].part_variances.none.variance <
893 (thresholds[2] >> 8))
894 x->variance_low[(i << 2) + j + 9] = 1;
903 static void copy_partitioning_helper(VP9_COMP *cpi, MACROBLOCK *x,
904 MACROBLOCKD *xd, BLOCK_SIZE bsize,
905 int mi_row, int mi_col) {
906 VP9_COMMON *const cm = &cpi->common;
907 BLOCK_SIZE *prev_part = cpi->prev_partition;
908 int start_pos = mi_row * cm->mi_stride + mi_col;
910 const int bsl = b_width_log2_lookup[bsize];
911 const int bs = (1 << bsl) >> 2;
913 PARTITION_TYPE partition;
915 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
917 partition = partition_lookup[bsl][prev_part[start_pos]];
918 subsize = get_subsize(bsize, partition);
920 if (subsize < BLOCK_8X8) {
921 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
925 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
928 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
929 set_block_size(cpi, x, xd, mi_row + bs, mi_col, subsize);
932 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
933 set_block_size(cpi, x, xd, mi_row, mi_col + bs, subsize);
936 assert(partition == PARTITION_SPLIT);
937 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col);
938 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col);
939 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col + bs);
940 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col + bs);
946 static int copy_partitioning(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
947 int mi_row, int mi_col, int segment_id,
949 int svc_copy_allowed = 1;
950 int frames_since_key_thresh = 1;
952 // For SVC, don't allow copy if base spatial layer is key frame, or if
953 // frame is not a temporal enhancement layer frame.
954 int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
955 cpi->svc.number_temporal_layers);
956 const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
957 if (lc->is_key_frame || !cpi->svc.non_reference_frame) svc_copy_allowed = 0;
958 frames_since_key_thresh = cpi->svc.number_spatial_layers << 1;
960 if (cpi->rc.frames_since_key > frames_since_key_thresh && svc_copy_allowed &&
961 !cpi->resize_pending && segment_id == CR_SEGMENT_ID_BASE &&
962 cpi->prev_segment_id[sb_offset] == CR_SEGMENT_ID_BASE &&
963 cpi->copied_frame_cnt[sb_offset] < cpi->max_copied_frame) {
964 if (cpi->prev_partition != NULL) {
965 copy_partitioning_helper(cpi, x, xd, BLOCK_64X64, mi_row, mi_col);
966 cpi->copied_frame_cnt[sb_offset] += 1;
967 memcpy(x->variance_low, &(cpi->prev_variance_low[sb_offset * 25]),
968 sizeof(x->variance_low));
976 static int scale_partitioning_svc(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
977 BLOCK_SIZE bsize, int mi_row, int mi_col,
978 int mi_row_high, int mi_col_high) {
979 VP9_COMMON *const cm = &cpi->common;
980 SVC *const svc = &cpi->svc;
981 BLOCK_SIZE *prev_part = svc->prev_partition_svc;
982 // Variables with _high are for higher resolution.
984 int subsize_high = 0;
985 const int bsl_high = b_width_log2_lookup[bsize];
986 const int bs_high = (1 << bsl_high) >> 2;
987 const int has_rows = (mi_row_high + bs_high) < cm->mi_rows;
988 const int has_cols = (mi_col_high + bs_high) < cm->mi_cols;
990 const int row_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 1, 0,
993 const int col_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 2, 2,
997 BLOCK_SIZE bsize_low;
998 PARTITION_TYPE partition_high;
1000 if (mi_row_high >= cm->mi_rows || mi_col_high >= cm->mi_cols) return 0;
1001 if (mi_row >= svc->mi_rows[svc->spatial_layer_id - 1] ||
1002 mi_col >= svc->mi_cols[svc->spatial_layer_id - 1])
1005 // Find corresponding (mi_col/mi_row) block down-scaled by 2x2.
1006 start_pos = mi_row * (svc->mi_stride[svc->spatial_layer_id - 1]) + mi_col;
1007 bsize_low = prev_part[start_pos];
1008 // The block size is too big for boundaries. Do variance based partitioning.
1009 if ((!has_rows || !has_cols) && bsize_low > BLOCK_16X16) return 1;
1011 // For reference frames: return 1 (do variance-based partitioning) if the
1012 // superblock is not low source sad and lower-resoln bsize is below 32x32.
1013 if (!cpi->svc.non_reference_frame && !x->skip_low_source_sad &&
1014 bsize_low < BLOCK_32X32)
1017 // Scale up block size by 2x2. Force 64x64 for size larger than 32x32.
1018 if (bsize_low < BLOCK_32X32) {
1019 bsize_high = bsize_low + 3;
1020 } else if (bsize_low >= BLOCK_32X32) {
1021 bsize_high = BLOCK_64X64;
1023 // Scale up blocks on boundary.
1024 if (!has_cols && has_rows) {
1025 bsize_high = bsize_low + row_boundary_block_scale_factor[bsize_low];
1026 } else if (has_cols && !has_rows) {
1027 bsize_high = bsize_low + col_boundary_block_scale_factor[bsize_low];
1028 } else if (!has_cols && !has_rows) {
1029 bsize_high = bsize_low;
1032 partition_high = partition_lookup[bsl_high][bsize_high];
1033 subsize_high = get_subsize(bsize, partition_high);
1035 if (subsize_high < BLOCK_8X8) {
1036 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1038 const int bsl = b_width_log2_lookup[bsize];
1039 const int bs = (1 << bsl) >> 2;
1040 switch (partition_high) {
1041 case PARTITION_NONE:
1042 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1044 case PARTITION_HORZ:
1045 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1046 if (subsize_high < BLOCK_64X64)
1047 set_block_size(cpi, x, xd, mi_row_high + bs_high, mi_col_high,
1050 case PARTITION_VERT:
1051 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1052 if (subsize_high < BLOCK_64X64)
1053 set_block_size(cpi, x, xd, mi_row_high, mi_col_high + bs_high,
1057 assert(partition_high == PARTITION_SPLIT);
1058 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row, mi_col,
1059 mi_row_high, mi_col_high))
1061 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1062 mi_col, mi_row_high + bs_high, mi_col_high))
1064 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row,
1065 mi_col + (bs >> 1), mi_row_high,
1066 mi_col_high + bs_high))
1068 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1069 mi_col + (bs >> 1), mi_row_high + bs_high,
1070 mi_col_high + bs_high))
1079 static void update_partition_svc(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
1081 VP9_COMMON *const cm = &cpi->common;
1082 BLOCK_SIZE *prev_part = cpi->svc.prev_partition_svc;
1083 int start_pos = mi_row * cm->mi_stride + mi_col;
1084 const int bsl = b_width_log2_lookup[bsize];
1085 const int bs = (1 << bsl) >> 2;
1087 PARTITION_TYPE partition;
1088 const MODE_INFO *mi = NULL;
1091 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1093 mi = cm->mi_grid_visible[start_pos];
1094 partition = partition_lookup[bsl][mi->sb_type];
1095 subsize = get_subsize(bsize, partition);
1096 if (subsize < BLOCK_8X8) {
1097 prev_part[start_pos] = bsize;
1099 switch (partition) {
1100 case PARTITION_NONE:
1101 prev_part[start_pos] = bsize;
1102 if (bsize == BLOCK_64X64) {
1103 for (xx = 0; xx < 8; xx += 4)
1104 for (yy = 0; yy < 8; yy += 4) {
1105 if ((mi_row + xx < cm->mi_rows) && (mi_col + yy < cm->mi_cols))
1106 prev_part[start_pos + xx * cm->mi_stride + yy] = bsize;
1110 case PARTITION_HORZ:
1111 prev_part[start_pos] = subsize;
1112 if (mi_row + bs < cm->mi_rows)
1113 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1115 case PARTITION_VERT:
1116 prev_part[start_pos] = subsize;
1117 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1120 assert(partition == PARTITION_SPLIT);
1121 update_partition_svc(cpi, subsize, mi_row, mi_col);
1122 update_partition_svc(cpi, subsize, mi_row + bs, mi_col);
1123 update_partition_svc(cpi, subsize, mi_row, mi_col + bs);
1124 update_partition_svc(cpi, subsize, mi_row + bs, mi_col + bs);
1130 static void update_prev_partition_helper(VP9_COMP *cpi, BLOCK_SIZE bsize,
1131 int mi_row, int mi_col) {
1132 VP9_COMMON *const cm = &cpi->common;
1133 BLOCK_SIZE *prev_part = cpi->prev_partition;
1134 int start_pos = mi_row * cm->mi_stride + mi_col;
1135 const int bsl = b_width_log2_lookup[bsize];
1136 const int bs = (1 << bsl) >> 2;
1138 PARTITION_TYPE partition;
1139 const MODE_INFO *mi = NULL;
1141 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1143 mi = cm->mi_grid_visible[start_pos];
1144 partition = partition_lookup[bsl][mi->sb_type];
1145 subsize = get_subsize(bsize, partition);
1146 if (subsize < BLOCK_8X8) {
1147 prev_part[start_pos] = bsize;
1149 switch (partition) {
1150 case PARTITION_NONE: prev_part[start_pos] = bsize; break;
1151 case PARTITION_HORZ:
1152 prev_part[start_pos] = subsize;
1153 if (mi_row + bs < cm->mi_rows)
1154 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1156 case PARTITION_VERT:
1157 prev_part[start_pos] = subsize;
1158 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1161 assert(partition == PARTITION_SPLIT);
1162 update_prev_partition_helper(cpi, subsize, mi_row, mi_col);
1163 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col);
1164 update_prev_partition_helper(cpi, subsize, mi_row, mi_col + bs);
1165 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col + bs);
1171 static void update_prev_partition(VP9_COMP *cpi, MACROBLOCK *x, int segment_id,
1172 int mi_row, int mi_col, int sb_offset) {
1173 update_prev_partition_helper(cpi, BLOCK_64X64, mi_row, mi_col);
1174 cpi->prev_segment_id[sb_offset] = segment_id;
1175 memcpy(&(cpi->prev_variance_low[sb_offset * 25]), x->variance_low,
1176 sizeof(x->variance_low));
1177 // Reset the counter for copy partitioning
1178 cpi->copied_frame_cnt[sb_offset] = 0;
1181 static void chroma_check(VP9_COMP *cpi, MACROBLOCK *x, int bsize,
1182 unsigned int y_sad, int is_key_frame) {
1184 MACROBLOCKD *xd = &x->e_mbd;
1186 if (is_key_frame) return;
1188 // For speed >= 8, avoid the chroma check if y_sad is above threshold.
1189 if (cpi->oxcf.speed >= 8) {
1190 if (y_sad > cpi->vbp_thresholds[1] &&
1191 (!cpi->noise_estimate.enabled ||
1192 vp9_noise_estimate_extract_level(&cpi->noise_estimate) < kMedium))
1196 for (i = 1; i <= 2; ++i) {
1197 unsigned int uv_sad = UINT_MAX;
1198 struct macroblock_plane *p = &x->plane[i];
1199 struct macroblockd_plane *pd = &xd->plane[i];
1200 const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
1202 if (bs != BLOCK_INVALID)
1203 uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride, pd->dst.buf,
1206 // TODO(marpan): Investigate if we should lower this threshold if
1207 // superblock is detected as skin.
1208 x->color_sensitivity[i - 1] = uv_sad > (y_sad >> 2);
1212 static uint64_t avg_source_sad(VP9_COMP *cpi, MACROBLOCK *x, int shift,
1214 unsigned int tmp_sse;
1216 unsigned int tmp_variance;
1217 const BLOCK_SIZE bsize = BLOCK_64X64;
1218 uint8_t *src_y = cpi->Source->y_buffer;
1219 int src_ystride = cpi->Source->y_stride;
1220 uint8_t *last_src_y = cpi->Last_Source->y_buffer;
1221 int last_src_ystride = cpi->Last_Source->y_stride;
1222 uint64_t avg_source_sad_threshold = 10000;
1223 uint64_t avg_source_sad_threshold2 = 12000;
1224 #if CONFIG_VP9_HIGHBITDEPTH
1225 if (cpi->common.use_highbitdepth) return 0;
1228 last_src_y += shift;
1230 cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y, last_src_ystride);
1231 tmp_variance = vpx_variance64x64(src_y, src_ystride, last_src_y,
1232 last_src_ystride, &tmp_sse);
1233 // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1234 if (tmp_sad < avg_source_sad_threshold)
1235 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kLowSadLowSumdiff
1236 : kLowSadHighSumdiff;
1238 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kHighSadLowSumdiff
1239 : kHighSadHighSumdiff;
1241 // Detect large lighting change.
1242 if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
1243 cpi->oxcf.rc_mode == VPX_CBR && tmp_variance < (tmp_sse >> 3) &&
1244 (tmp_sse - tmp_variance) > 10000)
1245 x->content_state_sb = kLowVarHighSumdiff;
1246 else if (tmp_sad > (avg_source_sad_threshold << 1))
1247 x->content_state_sb = kVeryHighSad;
1249 if (cpi->content_state_sb_fd != NULL) {
1250 if (tmp_sad < avg_source_sad_threshold2) {
1251 // Cap the increment to 255.
1252 if (cpi->content_state_sb_fd[sb_offset] < 255)
1253 cpi->content_state_sb_fd[sb_offset]++;
1255 cpi->content_state_sb_fd[sb_offset] = 0;
1258 if (tmp_sad == 0) x->zero_temp_sad_source = 1;
1262 // This function chooses partitioning based on the variance between source and
1263 // reconstructed last, where variance is computed for down-sampled inputs.
1264 static int choose_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1265 MACROBLOCK *x, int mi_row, int mi_col) {
1266 VP9_COMMON *const cm = &cpi->common;
1267 MACROBLOCKD *xd = &x->e_mbd;
1271 int force_split[21];
1273 int max_var_32x32 = 0;
1274 int min_var_32x32 = INT_MAX;
1277 int maxvar_16x16[4];
1278 int minvar_16x16[4];
1279 int64_t threshold_4x4avg;
1280 NOISE_LEVEL noise_level = kLow;
1281 int content_state = 0;
1286 int compute_minmax_variance = 1;
1287 unsigned int y_sad = UINT_MAX;
1288 BLOCK_SIZE bsize = BLOCK_64X64;
1289 // Ref frame used in partitioning.
1290 MV_REFERENCE_FRAME ref_frame_partition = LAST_FRAME;
1291 int pixels_wide = 64, pixels_high = 64;
1292 int64_t thresholds[4] = { cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
1293 cpi->vbp_thresholds[2], cpi->vbp_thresholds[3] };
1294 int force_64_split = cpi->rc.high_source_sad ||
1295 (cpi->use_svc && cpi->svc.high_source_sad_superframe) ||
1296 (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1297 cpi->compute_source_sad_onepass &&
1298 cpi->sf.use_source_sad && !x->zero_temp_sad_source);
1300 // For the variance computation under SVC mode, we treat the frame as key if
1301 // the reference (base layer frame) is key frame (i.e., is_key_frame == 1).
1303 (frame_is_intra_only(cm) ||
1304 (is_one_pass_cbr_svc(cpi) &&
1305 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame));
1306 // Always use 4x4 partition for key frame.
1307 const int use_4x4_partition = frame_is_intra_only(cm);
1308 const int low_res = (cm->width <= 352 && cm->height <= 288);
1309 int variance4x4downsample[16];
1311 int sb_offset = (cm->mi_stride >> 3) * (mi_row >> 3) + (mi_col >> 3);
1313 // For SVC: check if LAST frame is NULL or if the resolution of LAST is
1314 // different than the current frame resolution, and if so, treat this frame
1315 // as a key frame, for the purpose of the superblock partitioning.
1316 // LAST == NULL can happen in some cases where enhancement spatial layers are
1317 // enabled dyanmically in the stream and the only reference is the spatial
1318 // reference (GOLDEN).
1320 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, LAST_FRAME);
1321 if (ref == NULL || ref->y_crop_height != cm->height ||
1322 ref->y_crop_width != cm->width)
1326 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
1327 set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
1328 segment_id = xd->mi[0]->segment_id;
1330 if (cpi->oxcf.speed >= 8 || (cpi->use_svc && cpi->svc.non_reference_frame))
1331 compute_minmax_variance = 0;
1333 memset(x->variance_low, 0, sizeof(x->variance_low));
1335 if (cpi->sf.use_source_sad && !is_key_frame) {
1336 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1337 content_state = x->content_state_sb;
1338 x->skip_low_source_sad = (content_state == kLowSadLowSumdiff ||
1339 content_state == kLowSadHighSumdiff)
1342 x->lowvar_highsumdiff = (content_state == kLowVarHighSumdiff) ? 1 : 0;
1343 if (cpi->content_state_sb_fd != NULL)
1344 x->last_sb_high_content = cpi->content_state_sb_fd[sb_offset2];
1346 // For SVC on top spatial layer: use/scale the partition from
1347 // the lower spatial resolution if svc_use_lowres_part is enabled.
1348 if (cpi->sf.svc_use_lowres_part &&
1349 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1350 cpi->svc.prev_partition_svc != NULL && content_state != kVeryHighSad) {
1351 if (!scale_partitioning_svc(cpi, x, xd, BLOCK_64X64, mi_row >> 1,
1352 mi_col >> 1, mi_row, mi_col)) {
1353 if (cpi->sf.copy_partition_flag) {
1354 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1359 // If source_sad is low copy the partition without computing the y_sad.
1360 if (x->skip_low_source_sad && cpi->sf.copy_partition_flag &&
1362 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1363 x->sb_use_mv_part = 1;
1364 if (cpi->sf.svc_use_lowres_part &&
1365 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1366 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1371 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
1372 cyclic_refresh_segment_id_boosted(segment_id)) {
1373 int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
1374 set_vbp_thresholds(cpi, thresholds, q, content_state);
1376 set_vbp_thresholds(cpi, thresholds, cm->base_qindex, content_state);
1378 // Decrease 32x32 split threshold for screen on base layer, for scene
1379 // change/high motion frames.
1380 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1381 cpi->svc.spatial_layer_id == 0 && force_64_split)
1382 thresholds[1] = 3 * thresholds[1] >> 2;
1384 // For non keyframes, disable 4x4 average for low resolution when speed = 8
1385 threshold_4x4avg = (cpi->oxcf.speed < 8) ? thresholds[1] << 1 : INT64_MAX;
1387 if (xd->mb_to_right_edge < 0) pixels_wide += (xd->mb_to_right_edge >> 3);
1388 if (xd->mb_to_bottom_edge < 0) pixels_high += (xd->mb_to_bottom_edge >> 3);
1390 s = x->plane[0].src.buf;
1391 sp = x->plane[0].src.stride;
1393 // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
1394 // 5-20 for the 16x16 blocks.
1395 force_split[0] = force_64_split;
1397 if (!is_key_frame) {
1398 // In the case of spatial/temporal scalable coding, the assumption here is
1399 // that the temporal reference frame will always be of type LAST_FRAME.
1400 // TODO(marpan): If that assumption is broken, we need to revisit this code.
1401 MODE_INFO *mi = xd->mi[0];
1402 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1404 const YV12_BUFFER_CONFIG *yv12_g = NULL;
1405 unsigned int y_sad_g, y_sad_thr, y_sad_last;
1406 bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
1407 (mi_row + 4 < cm->mi_rows);
1409 assert(yv12 != NULL);
1411 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
1412 cpi->svc.use_gf_temporal_ref_current_layer) {
1413 // For now, GOLDEN will not be used for non-zero spatial layers, since
1414 // it may not be a temporal reference.
1415 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1418 // Only compute y_sad_g (sad for golden reference) for speed < 8.
1419 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
1420 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
1421 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1422 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1423 y_sad_g = cpi->fn_ptr[bsize].sdf(
1424 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1425 xd->plane[0].pre[0].stride);
1430 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
1431 cpi->rc.is_src_frame_alt_ref) {
1432 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
1433 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1434 &cm->frame_refs[ALTREF_FRAME - 1].sf);
1435 mi->ref_frame[0] = ALTREF_FRAME;
1438 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1439 &cm->frame_refs[LAST_FRAME - 1].sf);
1440 mi->ref_frame[0] = LAST_FRAME;
1442 mi->ref_frame[1] = NONE;
1443 mi->sb_type = BLOCK_64X64;
1444 mi->mv[0].as_int = 0;
1445 mi->interp_filter = BILINEAR;
1447 if (cpi->oxcf.speed >= 8 && !low_res &&
1448 x->content_state_sb != kVeryHighSad) {
1449 y_sad = cpi->fn_ptr[bsize].sdf(
1450 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1451 xd->plane[0].pre[0].stride);
1453 const MV dummy_mv = { 0, 0 };
1454 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
1456 x->sb_use_mv_part = 1;
1457 x->sb_mvcol_part = mi->mv[0].as_mv.col;
1458 x->sb_mvrow_part = mi->mv[0].as_mv.row;
1459 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1460 cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
1461 cpi->svc.high_num_blocks_with_motion && !x->zero_temp_sad_source &&
1462 cm->width > 640 && cm->height > 480) {
1463 // Disable split below 16x16 block size when scroll motion (horz or
1464 // vert) is detected.
1465 // TODO(marpan/jianj): Improve this condition: issue is that search
1466 // range is hard-coded/limited in vp9_int_pro_motion_estimation() so
1467 // scroll motion may not be detected here.
1468 if (((abs(x->sb_mvrow_part) >= 48 && abs(x->sb_mvcol_part) <= 8) ||
1469 (abs(x->sb_mvcol_part) >= 48 && abs(x->sb_mvrow_part) <= 8)) &&
1471 compute_minmax_variance = 0;
1472 thresholds[2] = INT64_MAX;
1478 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
1479 // are close if short_circuit_low_temp_var is on.
1480 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
1481 if (y_sad_g < y_sad_thr) {
1482 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1483 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1484 mi->ref_frame[0] = GOLDEN_FRAME;
1485 mi->mv[0].as_int = 0;
1487 ref_frame_partition = GOLDEN_FRAME;
1489 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
1490 ref_frame_partition = LAST_FRAME;
1493 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
1494 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
1496 if (cpi->use_skin_detection)
1498 skin_sb_split(cpi, x, low_res, mi_row, mi_col, force_split);
1500 d = xd->plane[0].dst.buf;
1501 dp = xd->plane[0].dst.stride;
1503 // If the y_sad is very small, take 64x64 as partition and exit.
1504 // Don't check on boosted segment for now, as 64x64 is suppressed there.
1505 if (segment_id == CR_SEGMENT_ID_BASE && y_sad < cpi->vbp_threshold_sad) {
1506 const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
1507 const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
1508 if (mi_col + block_width / 2 < cm->mi_cols &&
1509 mi_row + block_height / 2 < cm->mi_rows) {
1510 set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
1511 x->variance_low[0] = 1;
1512 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1513 if (cpi->sf.svc_use_lowres_part &&
1514 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1515 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1516 if (cpi->sf.copy_partition_flag) {
1517 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1523 // If the y_sad is small enough, copy the partition of the superblock in the
1524 // last frame to current frame only if the last frame is not a keyframe.
1525 // Stop the copy every cpi->max_copied_frame to refresh the partition.
1526 // TODO(jianj) : tune the threshold.
1527 if (cpi->sf.copy_partition_flag && y_sad_last < cpi->vbp_threshold_copy &&
1528 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1529 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1530 if (cpi->sf.svc_use_lowres_part &&
1531 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1532 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1538 #if CONFIG_VP9_HIGHBITDEPTH
1539 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1541 case 10: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10); break;
1542 case 12: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12); break;
1544 default: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8); break;
1547 #endif // CONFIG_VP9_HIGHBITDEPTH
1550 if (low_res && threshold_4x4avg < INT64_MAX)
1551 CHECK_MEM_ERROR(cm, vt2, vpx_calloc(16, sizeof(*vt2)));
1552 // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
1554 for (i = 0; i < 4; i++) {
1555 const int x32_idx = ((i & 1) << 5);
1556 const int y32_idx = ((i >> 1) << 5);
1557 const int i2 = i << 2;
1558 force_split[i + 1] = 0;
1560 maxvar_16x16[i] = 0;
1561 minvar_16x16[i] = INT_MAX;
1562 for (j = 0; j < 4; j++) {
1563 const int x16_idx = x32_idx + ((j & 1) << 4);
1564 const int y16_idx = y32_idx + ((j >> 1) << 4);
1565 const int split_index = 5 + i2 + j;
1566 v16x16 *vst = &vt.split[i].split[j];
1567 force_split[split_index] = 0;
1568 variance4x4downsample[i2 + j] = 0;
1569 if (!is_key_frame) {
1570 fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
1571 #if CONFIG_VP9_HIGHBITDEPTH
1574 pixels_wide, pixels_high, is_key_frame);
1575 fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1576 get_variance(&vt.split[i].split[j].part_variances.none);
1577 avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance;
1578 if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i])
1579 minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1580 if (vt.split[i].split[j].part_variances.none.variance > maxvar_16x16[i])
1581 maxvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1582 if (vt.split[i].split[j].part_variances.none.variance > thresholds[2]) {
1583 // 16X16 variance is above threshold for split, so force split to 8x8
1584 // for this 16x16 block (this also forces splits for upper levels).
1585 force_split[split_index] = 1;
1586 force_split[i + 1] = 1;
1588 } else if (compute_minmax_variance &&
1589 vt.split[i].split[j].part_variances.none.variance >
1591 !cyclic_refresh_segment_id_boosted(segment_id)) {
1592 // We have some nominal amount of 16x16 variance (based on average),
1593 // compute the minmax over the 8x8 sub-blocks, and if above threshold,
1594 // force split to 8x8 block for this 16x16 block.
1595 int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
1596 #if CONFIG_VP9_HIGHBITDEPTH
1599 pixels_wide, pixels_high);
1600 int thresh_minmax = (int)cpi->vbp_threshold_minmax;
1601 if (x->content_state_sb == kVeryHighSad)
1602 thresh_minmax = thresh_minmax << 1;
1603 if (minmax > thresh_minmax) {
1604 force_split[split_index] = 1;
1605 force_split[i + 1] = 1;
1611 (low_res && vt.split[i].split[j].part_variances.none.variance >
1612 threshold_4x4avg)) {
1613 force_split[split_index] = 0;
1614 // Go down to 4x4 down-sampling for variance.
1615 variance4x4downsample[i2 + j] = 1;
1616 for (k = 0; k < 4; k++) {
1617 int x8_idx = x16_idx + ((k & 1) << 3);
1618 int y8_idx = y16_idx + ((k >> 1) << 3);
1619 v8x8 *vst2 = is_key_frame ? &vst->split[k] : &vt2[i2 + j].split[k];
1620 fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
1621 #if CONFIG_VP9_HIGHBITDEPTH
1624 pixels_wide, pixels_high, is_key_frame);
1629 if (cpi->noise_estimate.enabled)
1630 noise_level = vp9_noise_estimate_extract_level(&cpi->noise_estimate);
1631 // Fill the rest of the variance tree by summing split partition values.
1633 for (i = 0; i < 4; i++) {
1634 const int i2 = i << 2;
1635 for (j = 0; j < 4; j++) {
1636 if (variance4x4downsample[i2 + j] == 1) {
1637 v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] : &vt.split[i].split[j];
1638 for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
1639 fill_variance_tree(vtemp, BLOCK_16X16);
1640 // If variance of this 16x16 block is above the threshold, force block
1641 // to split. This also forces a split on the upper levels.
1642 get_variance(&vtemp->part_variances.none);
1643 if (vtemp->part_variances.none.variance > thresholds[2]) {
1644 force_split[5 + i2 + j] = 1;
1645 force_split[i + 1] = 1;
1650 fill_variance_tree(&vt.split[i], BLOCK_32X32);
1651 // If variance of this 32x32 block is above the threshold, or if its above
1652 // (some threshold of) the average variance over the sub-16x16 blocks, then
1653 // force this block to split. This also forces a split on the upper
1655 if (!force_split[i + 1]) {
1656 get_variance(&vt.split[i].part_variances.none);
1657 var_32x32 = vt.split[i].part_variances.none.variance;
1658 max_var_32x32 = VPXMAX(var_32x32, max_var_32x32);
1659 min_var_32x32 = VPXMIN(var_32x32, min_var_32x32);
1660 if (vt.split[i].part_variances.none.variance > thresholds[1] ||
1662 vt.split[i].part_variances.none.variance > (thresholds[1] >> 1) &&
1663 vt.split[i].part_variances.none.variance > (avg_16x16[i] >> 1))) {
1664 force_split[i + 1] = 1;
1666 } else if (!is_key_frame && noise_level < kLow && cm->height <= 360 &&
1667 (maxvar_16x16[i] - minvar_16x16[i]) > (thresholds[1] >> 1) &&
1668 maxvar_16x16[i] > thresholds[1]) {
1669 force_split[i + 1] = 1;
1672 avg_32x32 += var_32x32;
1675 if (!force_split[0]) {
1676 fill_variance_tree(&vt, BLOCK_64X64);
1677 get_variance(&vt.part_variances.none);
1678 // If variance of this 64x64 block is above (some threshold of) the average
1679 // variance over the sub-32x32 blocks, then force this block to split.
1680 // Only checking this for noise level >= medium for now.
1681 if (!is_key_frame && noise_level >= kMedium &&
1682 vt.part_variances.none.variance > (9 * avg_32x32) >> 5)
1684 // Else if the maximum 32x32 variance minus the miniumum 32x32 variance in
1685 // a 64x64 block is greater than threshold and the maximum 32x32 variance is
1686 // above a miniumum threshold, then force the split of a 64x64 block
1687 // Only check this for low noise.
1688 else if (!is_key_frame && noise_level < kMedium &&
1689 (max_var_32x32 - min_var_32x32) > 3 * (thresholds[0] >> 3) &&
1690 max_var_32x32 > thresholds[0] >> 1)
1694 // Now go through the entire structure, splitting every block size until
1695 // we get to one that's got a variance lower than our threshold.
1696 if (mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
1697 !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
1698 thresholds[0], BLOCK_16X16, force_split[0])) {
1699 for (i = 0; i < 4; ++i) {
1700 const int x32_idx = ((i & 1) << 2);
1701 const int y32_idx = ((i >> 1) << 2);
1702 const int i2 = i << 2;
1703 if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
1704 (mi_row + y32_idx), (mi_col + x32_idx),
1705 thresholds[1], BLOCK_16X16,
1706 force_split[i + 1])) {
1707 for (j = 0; j < 4; ++j) {
1708 const int x16_idx = ((j & 1) << 1);
1709 const int y16_idx = ((j >> 1) << 1);
1710 // For inter frames: if variance4x4downsample[] == 1 for this 16x16
1711 // block, then the variance is based on 4x4 down-sampling, so use vt2
1712 // in set_vt_partioning(), otherwise use vt.
1713 v16x16 *vtemp = (!is_key_frame && variance4x4downsample[i2 + j] == 1)
1715 : &vt.split[i].split[j];
1716 if (!set_vt_partitioning(
1717 cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx,
1718 mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min,
1719 force_split[5 + i2 + j])) {
1720 for (k = 0; k < 4; ++k) {
1721 const int x8_idx = (k & 1);
1722 const int y8_idx = (k >> 1);
1723 if (use_4x4_partition) {
1724 if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
1726 mi_row + y32_idx + y16_idx + y8_idx,
1727 mi_col + x32_idx + x16_idx + x8_idx,
1728 thresholds[3], BLOCK_8X8, 0)) {
1730 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1731 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_4X4);
1735 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1736 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_8X8);
1745 if (!frame_is_intra_only(cm) && cpi->sf.copy_partition_flag) {
1746 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1749 if (!frame_is_intra_only(cm) && cpi->sf.svc_use_lowres_part &&
1750 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1751 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1753 if (cpi->sf.short_circuit_low_temp_var) {
1754 set_low_temp_var_flag(cpi, x, xd, &vt, thresholds, ref_frame_partition,
1758 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1759 if (vt2) vpx_free(vt2);
1763 static void update_state(VP9_COMP *cpi, ThreadData *td, PICK_MODE_CONTEXT *ctx,
1764 int mi_row, int mi_col, BLOCK_SIZE bsize,
1765 int output_enabled) {
1767 VP9_COMMON *const cm = &cpi->common;
1768 RD_COUNTS *const rdc = &td->rd_counts;
1769 MACROBLOCK *const x = &td->mb;
1770 MACROBLOCKD *const xd = &x->e_mbd;
1771 struct macroblock_plane *const p = x->plane;
1772 struct macroblockd_plane *const pd = xd->plane;
1773 MODE_INFO *mi = &ctx->mic;
1774 MODE_INFO *const xdmi = xd->mi[0];
1775 MODE_INFO *mi_addr = xd->mi[0];
1776 const struct segmentation *const seg = &cm->seg;
1777 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
1778 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
1779 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1780 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1781 MV_REF *const frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1784 const int mis = cm->mi_stride;
1785 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
1786 const int mi_height = num_8x8_blocks_high_lookup[bsize];
1789 assert(mi->sb_type == bsize);
1792 *x->mbmi_ext = ctx->mbmi_ext;
1794 // If segmentation in use
1796 // For in frame complexity AQ copy the segment id from the segment map.
1797 if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1798 const uint8_t *const map =
1799 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1800 mi_addr->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1802 // Else for cyclic refresh mode update the segment map, set the segment id
1803 // and then update the quantizer.
1804 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1805 vp9_cyclic_refresh_update_segment(cpi, xd->mi[0], mi_row, mi_col, bsize,
1806 ctx->rate, ctx->dist, x->skip, p);
1810 max_plane = is_inter_block(xdmi) ? MAX_MB_PLANE : 1;
1811 for (i = 0; i < max_plane; ++i) {
1812 p[i].coeff = ctx->coeff_pbuf[i][1];
1813 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1814 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1815 p[i].eobs = ctx->eobs_pbuf[i][1];
1818 for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1819 p[i].coeff = ctx->coeff_pbuf[i][2];
1820 p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1821 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1822 p[i].eobs = ctx->eobs_pbuf[i][2];
1825 // Restore the coding context of the MB to that that was in place
1826 // when the mode was picked for it
1827 for (y = 0; y < mi_height; y++)
1828 for (x_idx = 0; x_idx < mi_width; x_idx++)
1829 if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx &&
1830 (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1831 xd->mi[x_idx + y * mis] = mi_addr;
1834 if (cpi->oxcf.aq_mode != NO_AQ) vp9_init_plane_quantizers(cpi, x);
1836 if (is_inter_block(xdmi) && xdmi->sb_type < BLOCK_8X8) {
1837 xdmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1838 xdmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1841 x->skip = ctx->skip;
1842 memcpy(x->zcoeff_blk[xdmi->tx_size], ctx->zcoeff_blk,
1843 sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1845 if (!output_enabled) return;
1847 #if CONFIG_INTERNAL_STATS
1848 if (frame_is_intra_only(cm)) {
1849 static const int kf_mode_index[] = {
1850 THR_DC /*DC_PRED*/, THR_V_PRED /*V_PRED*/,
1851 THR_H_PRED /*H_PRED*/, THR_D45_PRED /*D45_PRED*/,
1852 THR_D135_PRED /*D135_PRED*/, THR_D117_PRED /*D117_PRED*/,
1853 THR_D153_PRED /*D153_PRED*/, THR_D207_PRED /*D207_PRED*/,
1854 THR_D63_PRED /*D63_PRED*/, THR_TM /*TM_PRED*/,
1856 ++cpi->mode_chosen_counts[kf_mode_index[xdmi->mode]];
1858 // Note how often each mode chosen as best
1859 ++cpi->mode_chosen_counts[ctx->best_mode_index];
1862 if (!frame_is_intra_only(cm)) {
1863 if (is_inter_block(xdmi)) {
1864 vp9_update_mv_count(td);
1866 if (cm->interp_filter == SWITCHABLE) {
1867 const int ctx = get_pred_context_switchable_interp(xd);
1868 ++td->counts->switchable_interp[ctx][xdmi->interp_filter];
1872 rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1873 rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1874 rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1876 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1877 rdc->filter_diff[i] += ctx->best_filter_diff[i];
1880 for (h = 0; h < y_mis; ++h) {
1881 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1882 for (w = 0; w < x_mis; ++w) {
1883 MV_REF *const mv = frame_mv + w;
1884 mv->ref_frame[0] = mi->ref_frame[0];
1885 mv->ref_frame[1] = mi->ref_frame[1];
1886 mv->mv[0].as_int = mi->mv[0].as_int;
1887 mv->mv[1].as_int = mi->mv[1].as_int;
1892 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1893 int mi_row, int mi_col) {
1894 uint8_t *const buffers[3] = { src->y_buffer, src->u_buffer, src->v_buffer };
1895 const int strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
1898 // Set current frame pointer.
1899 x->e_mbd.cur_buf = src;
1901 for (i = 0; i < MAX_MB_PLANE; i++)
1902 setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1903 NULL, x->e_mbd.plane[i].subsampling_x,
1904 x->e_mbd.plane[i].subsampling_y);
1907 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1908 RD_COST *rd_cost, BLOCK_SIZE bsize) {
1909 MACROBLOCKD *const xd = &x->e_mbd;
1910 MODE_INFO *const mi = xd->mi[0];
1911 INTERP_FILTER filter_ref;
1913 filter_ref = get_pred_context_switchable_interp(xd);
1914 if (filter_ref == SWITCHABLE_FILTERS) filter_ref = EIGHTTAP;
1916 mi->sb_type = bsize;
1919 VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[tx_mode]);
1921 mi->uv_mode = DC_PRED;
1922 mi->ref_frame[0] = LAST_FRAME;
1923 mi->ref_frame[1] = NONE;
1924 mi->mv[0].as_int = 0;
1925 mi->interp_filter = filter_ref;
1927 xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1930 vp9_rd_cost_init(rd_cost);
1933 static void set_segment_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
1934 int mi_row, int mi_col, BLOCK_SIZE bsize,
1936 VP9_COMMON *const cm = &cpi->common;
1937 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1938 const uint8_t *const map =
1939 cm->seg.update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1941 vp9_init_plane_quantizers(cpi, x);
1942 vpx_clear_system_state();
1944 if (aq_mode == NO_AQ || aq_mode == PSNR_AQ) {
1945 if (cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance)
1946 x->rdmult = x->cb_rdmult;
1947 } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1948 // If segment is boosted, use rdmult for that segment.
1949 if (cyclic_refresh_segment_id_boosted(
1950 get_segment_id(cm, map, bsize, mi_row, mi_col)))
1951 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1953 x->rdmult = vp9_compute_rd_mult(cpi, cm->base_qindex + cm->y_dc_delta_q);
1954 if (cpi->sf.enable_wiener_variance && cm->show_frame) {
1955 if (cm->seg.enabled)
1956 x->rdmult = vp9_compute_rd_mult(
1957 cpi, vp9_get_qindex(&cm->seg, x->e_mbd.mi[0]->segment_id,
1962 if (oxcf->tuning == VP8_TUNE_SSIM) {
1963 const double ssim_factor =
1964 get_ssim_rdmult_scaling_factor(cpi, mi_row, mi_col);
1965 x->rdmult = (int)(ssim_factor * x->rdmult);
1969 static void rd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
1970 MACROBLOCK *const x, int mi_row, int mi_col,
1971 RD_COST *rd_cost, BLOCK_SIZE bsize,
1972 PICK_MODE_CONTEXT *ctx, int64_t best_rd) {
1973 VP9_COMMON *const cm = &cpi->common;
1974 TileInfo *const tile_info = &tile_data->tile_info;
1975 MACROBLOCKD *const xd = &x->e_mbd;
1977 struct macroblock_plane *const p = x->plane;
1978 struct macroblockd_plane *const pd = xd->plane;
1979 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1982 vpx_clear_system_state();
1984 // Use the lower precision, but faster, 32x32 fdct for mode selection.
1985 x->use_lp32x32fdct = 1;
1987 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1989 mi->sb_type = bsize;
1991 for (i = 0; i < MAX_MB_PLANE; ++i) {
1992 p[i].coeff = ctx->coeff_pbuf[i][0];
1993 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1994 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1995 p[i].eobs = ctx->eobs_pbuf[i][0];
1999 ctx->pred_pixel_ready = 0;
2002 // Set to zero to make sure we do not use the previous encoded frame stats
2005 #if CONFIG_VP9_HIGHBITDEPTH
2006 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2007 x->source_variance = vp9_high_get_sby_perpixel_variance(
2008 cpi, &x->plane[0].src, bsize, xd->bd);
2010 x->source_variance =
2011 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2014 x->source_variance =
2015 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2016 #endif // CONFIG_VP9_HIGHBITDEPTH
2018 // Save rdmult before it might be changed, so it can be restored later.
2019 orig_rdmult = x->rdmult;
2021 if ((cpi->sf.tx_domain_thresh > 0.0) || (cpi->sf.quant_opt_thresh > 0.0)) {
2022 double logvar = vp9_log_block_var(cpi, x, bsize);
2023 // Check block complexity as part of descision on using pixel or transform
2024 // domain distortion in rd tests.
2025 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion &&
2026 (logvar >= cpi->sf.tx_domain_thresh);
2028 // Check block complexity as part of descision on using quantized
2029 // coefficient optimisation inside the rd loop.
2030 x->block_qcoeff_opt =
2031 cpi->sf.allow_quant_coeff_opt && (logvar <= cpi->sf.quant_opt_thresh);
2033 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion;
2034 x->block_qcoeff_opt = cpi->sf.allow_quant_coeff_opt;
2037 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
2038 set_segment_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode);
2040 // Find best coding mode & reconstruct the MB so it is available
2041 // as a predictor for MBs that follow in the SB
2042 if (frame_is_intra_only(cm)) {
2043 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
2045 if (bsize >= BLOCK_8X8) {
2046 if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
2047 vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
2050 vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2051 bsize, ctx, best_rd);
2053 vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2054 bsize, ctx, best_rd);
2058 // Examine the resulting rate and for AQ mode 2 make a segment choice.
2059 if ((rd_cost->rate != INT_MAX) && (aq_mode == COMPLEXITY_AQ) &&
2060 (bsize >= BLOCK_16X16) &&
2061 (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
2062 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
2063 vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
2066 // TODO(jingning) The rate-distortion optimization flow needs to be
2067 // refactored to provide proper exit/return handle.
2068 if (rd_cost->rate == INT_MAX)
2069 rd_cost->rdcost = INT64_MAX;
2071 rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2073 x->rdmult = orig_rdmult;
2075 ctx->rate = rd_cost->rate;
2076 ctx->dist = rd_cost->dist;
2079 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
2080 const MACROBLOCK *x = &td->mb;
2081 const MACROBLOCKD *const xd = &x->e_mbd;
2082 const MODE_INFO *const mi = xd->mi[0];
2083 const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2084 const BLOCK_SIZE bsize = mi->sb_type;
2086 if (!frame_is_intra_only(cm)) {
2087 FRAME_COUNTS *const counts = td->counts;
2088 const int inter_block = is_inter_block(mi);
2089 const int seg_ref_active =
2090 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_REF_FRAME);
2091 if (!seg_ref_active) {
2092 counts->intra_inter[get_intra_inter_context(xd)][inter_block]++;
2093 // If the segment reference feature is enabled we have only a single
2094 // reference frame allowed for the segment so exclude it from
2095 // the reference frame counts used to work out probabilities.
2097 const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
2098 if (cm->reference_mode == REFERENCE_MODE_SELECT)
2099 counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
2100 [has_second_ref(mi)]++;
2102 if (has_second_ref(mi)) {
2103 const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
2104 const int ctx = vp9_get_pred_context_comp_ref_p(cm, xd);
2105 const int bit = mi->ref_frame[!idx] == cm->comp_var_ref[1];
2106 counts->comp_ref[ctx][bit]++;
2108 counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
2109 [ref0 != LAST_FRAME]++;
2110 if (ref0 != LAST_FRAME)
2111 counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
2112 [ref0 != GOLDEN_FRAME]++;
2117 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP)) {
2118 const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
2119 if (bsize >= BLOCK_8X8) {
2120 const PREDICTION_MODE mode = mi->mode;
2121 ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
2123 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2124 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2126 for (idy = 0; idy < 2; idy += num_4x4_h) {
2127 for (idx = 0; idx < 2; idx += num_4x4_w) {
2128 const int j = idy * 2 + idx;
2129 const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
2130 ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
2138 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
2139 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2140 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2141 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2143 MACROBLOCKD *const xd = &x->e_mbd;
2145 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2146 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2147 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2148 int mi_height = num_8x8_blocks_high_lookup[bsize];
2149 for (p = 0; p < MAX_MB_PLANE; p++) {
2150 memcpy(xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
2151 a + num_4x4_blocks_wide * p,
2152 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2153 xd->plane[p].subsampling_x);
2154 memcpy(xd->left_context[p] +
2155 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2156 l + num_4x4_blocks_high * p,
2157 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2158 xd->plane[p].subsampling_y);
2160 memcpy(xd->above_seg_context + mi_col, sa,
2161 sizeof(*xd->above_seg_context) * mi_width);
2162 memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
2163 sizeof(xd->left_seg_context[0]) * mi_height);
2166 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
2167 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2168 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2169 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2171 const MACROBLOCKD *const xd = &x->e_mbd;
2173 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2174 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2175 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2176 int mi_height = num_8x8_blocks_high_lookup[bsize];
2178 // buffer the above/left context information of the block in search.
2179 for (p = 0; p < MAX_MB_PLANE; ++p) {
2180 memcpy(a + num_4x4_blocks_wide * p,
2181 xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
2182 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2183 xd->plane[p].subsampling_x);
2184 memcpy(l + num_4x4_blocks_high * p,
2185 xd->left_context[p] +
2186 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2187 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2188 xd->plane[p].subsampling_y);
2190 memcpy(sa, xd->above_seg_context + mi_col,
2191 sizeof(*xd->above_seg_context) * mi_width);
2192 memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
2193 sizeof(xd->left_seg_context[0]) * mi_height);
2196 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile, ThreadData *td,
2197 TOKENEXTRA **tp, int mi_row, int mi_col,
2198 int output_enabled, BLOCK_SIZE bsize,
2199 PICK_MODE_CONTEXT *ctx) {
2200 MACROBLOCK *const x = &td->mb;
2201 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2203 if ((cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance) &&
2204 cpi->oxcf.aq_mode == NO_AQ) {
2205 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2206 x->rdmult = x->cb_rdmult;
2207 if (oxcf->tuning == VP8_TUNE_SSIM) {
2208 const double ssim_factor =
2209 get_ssim_rdmult_scaling_factor(cpi, mi_row, mi_col);
2210 x->rdmult = (int)(ssim_factor * x->rdmult);
2214 update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
2215 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2217 if (output_enabled) {
2218 update_stats(&cpi->common, td);
2220 (*tp)->token = EOSB_TOKEN;
2225 static void encode_sb(VP9_COMP *cpi, ThreadData *td, const TileInfo *const tile,
2226 TOKENEXTRA **tp, int mi_row, int mi_col,
2227 int output_enabled, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2228 VP9_COMMON *const cm = &cpi->common;
2229 MACROBLOCK *const x = &td->mb;
2230 MACROBLOCKD *const xd = &x->e_mbd;
2232 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2234 PARTITION_TYPE partition;
2235 BLOCK_SIZE subsize = bsize;
2237 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2239 if (bsize >= BLOCK_8X8) {
2240 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2241 subsize = get_subsize(bsize, pc_tree->partitioning);
2244 subsize = BLOCK_4X4;
2247 partition = partition_lookup[bsl][subsize];
2248 if (output_enabled && bsize != BLOCK_4X4)
2249 td->counts->partition[ctx][partition]++;
2251 switch (partition) {
2252 case PARTITION_NONE:
2253 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2256 case PARTITION_VERT:
2257 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2258 &pc_tree->vertical[0]);
2259 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2260 encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
2261 subsize, &pc_tree->vertical[1]);
2264 case PARTITION_HORZ:
2265 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2266 &pc_tree->horizontal[0]);
2267 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2268 encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
2269 subsize, &pc_tree->horizontal[1]);
2273 assert(partition == PARTITION_SPLIT);
2274 if (bsize == BLOCK_8X8) {
2275 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2276 pc_tree->leaf_split[0]);
2278 encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2280 encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2281 subsize, pc_tree->split[1]);
2282 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2283 subsize, pc_tree->split[2]);
2284 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
2285 subsize, pc_tree->split[3]);
2290 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2291 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2294 // Check to see if the given partition size is allowed for a specified number
2295 // of 8x8 block rows and columns remaining in the image.
2296 // If not then return the largest allowed partition size
2297 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
2298 int cols_left, int *bh, int *bw) {
2299 if (rows_left <= 0 || cols_left <= 0) {
2300 return VPXMIN(bsize, BLOCK_8X8);
2302 for (; bsize > 0; bsize -= 3) {
2303 *bh = num_8x8_blocks_high_lookup[bsize];
2304 *bw = num_8x8_blocks_wide_lookup[bsize];
2305 if ((*bh <= rows_left) && (*bw <= cols_left)) {
2313 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis, int bh_in,
2314 int bw_in, int row8x8_remaining,
2315 int col8x8_remaining, BLOCK_SIZE bsize,
2316 MODE_INFO **mi_8x8) {
2319 for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
2321 for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
2322 const int index = r * mis + c;
2323 mi_8x8[index] = mi + index;
2324 mi_8x8[index]->sb_type = find_partition_size(
2325 bsize, row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
2330 // This function attempts to set all mode info entries in a given SB64
2331 // to the same block partition size.
2332 // However, at the bottom and right borders of the image the requested size
2333 // may not be allowed in which case this code attempts to choose the largest
2334 // allowable partition.
2335 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
2336 MODE_INFO **mi_8x8, int mi_row, int mi_col,
2338 VP9_COMMON *const cm = &cpi->common;
2339 const int mis = cm->mi_stride;
2340 const int row8x8_remaining = tile->mi_row_end - mi_row;
2341 const int col8x8_remaining = tile->mi_col_end - mi_col;
2342 int block_row, block_col;
2343 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2344 int bh = num_8x8_blocks_high_lookup[bsize];
2345 int bw = num_8x8_blocks_wide_lookup[bsize];
2347 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2349 // Apply the requested partition size to the SB64 if it is all "in image"
2350 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2351 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2352 for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
2353 for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
2354 int index = block_row * mis + block_col;
2355 mi_8x8[index] = mi_upper_left + index;
2356 mi_8x8[index]->sb_type = bsize;
2360 // Else this is a partial SB64.
2361 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2362 col8x8_remaining, bsize, mi_8x8);
2366 static const struct {
2369 } coord_lookup[16] = {
2392 static void set_source_var_based_partition(VP9_COMP *cpi,
2393 const TileInfo *const tile,
2394 MACROBLOCK *const x,
2395 MODE_INFO **mi_8x8, int mi_row,
2397 VP9_COMMON *const cm = &cpi->common;
2398 const int mis = cm->mi_stride;
2399 const int row8x8_remaining = tile->mi_row_end - mi_row;
2400 const int col8x8_remaining = tile->mi_col_end - mi_col;
2401 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2403 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
2405 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2408 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2409 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2413 const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
2414 int is_larger_better = 0;
2416 unsigned int thr = cpi->source_var_thresh;
2418 memset(d32, 0, 4 * sizeof(diff));
2420 for (i = 0; i < 4; i++) {
2423 for (j = 0; j < 4; j++) {
2424 int b_mi_row = coord_lookup[i * 4 + j].row;
2425 int b_mi_col = coord_lookup[i * 4 + j].col;
2426 int boffset = b_mi_row / 2 * cm->mb_cols + b_mi_col / 2;
2428 d16[j] = cpi->source_diff_var + offset + boffset;
2430 index = b_mi_row * mis + b_mi_col;
2431 mi_8x8[index] = mi_upper_left + index;
2432 mi_8x8[index]->sb_type = BLOCK_16X16;
2434 // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
2435 // size to further improve quality.
2438 is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
2439 (d16[2]->var < thr) && (d16[3]->var < thr);
2441 // Use 32x32 partition
2442 if (is_larger_better) {
2445 for (j = 0; j < 4; j++) {
2446 d32[i].sse += d16[j]->sse;
2447 d32[i].sum += d16[j]->sum;
2451 (unsigned int)(d32[i].sse -
2452 (unsigned int)(((int64_t)d32[i].sum * d32[i].sum) >>
2455 index = coord_lookup[i * 4].row * mis + coord_lookup[i * 4].col;
2456 mi_8x8[index] = mi_upper_left + index;
2457 mi_8x8[index]->sb_type = BLOCK_32X32;
2461 if (use32x32 == 4) {
2463 is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
2464 (d32[2].var < thr) && (d32[3].var < thr);
2466 // Use 64x64 partition
2467 if (is_larger_better) {
2468 mi_8x8[0] = mi_upper_left;
2469 mi_8x8[0]->sb_type = BLOCK_64X64;
2472 } else { // partial in-image SB64
2473 int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
2474 int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
2475 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2476 col8x8_remaining, BLOCK_16X16, mi_8x8);
2480 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
2481 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
2483 VP9_COMMON *const cm = &cpi->common;
2484 MACROBLOCK *const x = &td->mb;
2485 MACROBLOCKD *const xd = &x->e_mbd;
2486 MODE_INFO *const mi = xd->mi[0];
2487 struct macroblock_plane *const p = x->plane;
2488 const struct segmentation *const seg = &cm->seg;
2489 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
2490 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
2491 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
2492 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
2494 *(xd->mi[0]) = ctx->mic;
2495 *(x->mbmi_ext) = ctx->mbmi_ext;
2497 if (seg->enabled && (cpi->oxcf.aq_mode != NO_AQ || cpi->roi.enabled)) {
2498 // Setting segmentation map for cyclic_refresh.
2499 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
2500 vp9_cyclic_refresh_update_segment(cpi, mi, mi_row, mi_col, bsize,
2501 ctx->rate, ctx->dist, x->skip, p);
2503 const uint8_t *const map =
2504 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
2505 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
2507 vp9_init_plane_quantizers(cpi, x);
2510 if (is_inter_block(mi)) {
2511 vp9_update_mv_count(td);
2512 if (cm->interp_filter == SWITCHABLE) {
2513 const int pred_ctx = get_pred_context_switchable_interp(xd);
2514 ++td->counts->switchable_interp[pred_ctx][mi->interp_filter];
2517 if (mi->sb_type < BLOCK_8X8) {
2518 mi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
2519 mi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
2523 if (cm->use_prev_frame_mvs || !cm->error_resilient_mode ||
2524 (cpi->svc.use_base_mv && cpi->svc.number_spatial_layers > 1 &&
2525 cpi->svc.spatial_layer_id != cpi->svc.number_spatial_layers - 1)) {
2526 MV_REF *const frame_mvs =
2527 cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
2530 for (h = 0; h < y_mis; ++h) {
2531 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
2532 for (w = 0; w < x_mis; ++w) {
2533 MV_REF *const mv = frame_mv + w;
2534 mv->ref_frame[0] = mi->ref_frame[0];
2535 mv->ref_frame[1] = mi->ref_frame[1];
2536 mv->mv[0].as_int = mi->mv[0].as_int;
2537 mv->mv[1].as_int = mi->mv[1].as_int;
2542 x->skip = ctx->skip;
2543 x->skip_txfm[0] = (mi->segment_id || xd->lossless) ? 0 : ctx->skip_txfm[0];
2546 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
2547 const TileInfo *const tile, TOKENEXTRA **tp, int mi_row,
2548 int mi_col, int output_enabled, BLOCK_SIZE bsize,
2549 PICK_MODE_CONTEXT *ctx) {
2550 MACROBLOCK *const x = &td->mb;
2551 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2552 update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
2554 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2555 update_stats(&cpi->common, td);
2557 (*tp)->token = EOSB_TOKEN;
2561 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
2562 const TileInfo *const tile, TOKENEXTRA **tp,
2563 int mi_row, int mi_col, int output_enabled,
2564 BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2565 VP9_COMMON *const cm = &cpi->common;
2566 MACROBLOCK *const x = &td->mb;
2567 MACROBLOCKD *const xd = &x->e_mbd;
2569 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2571 PARTITION_TYPE partition;
2574 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2576 if (bsize >= BLOCK_8X8) {
2577 const int idx_str = xd->mi_stride * mi_row + mi_col;
2578 MODE_INFO **mi_8x8 = cm->mi_grid_visible + idx_str;
2579 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2580 subsize = mi_8x8[0]->sb_type;
2583 subsize = BLOCK_4X4;
2586 partition = partition_lookup[bsl][subsize];
2587 if (output_enabled && bsize != BLOCK_4X4)
2588 td->counts->partition[ctx][partition]++;
2590 switch (partition) {
2591 case PARTITION_NONE:
2592 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2595 case PARTITION_VERT:
2596 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2597 &pc_tree->vertical[0]);
2598 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2599 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2600 subsize, &pc_tree->vertical[1]);
2603 case PARTITION_HORZ:
2604 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2605 &pc_tree->horizontal[0]);
2606 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2607 encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2608 subsize, &pc_tree->horizontal[1]);
2612 assert(partition == PARTITION_SPLIT);
2613 subsize = get_subsize(bsize, PARTITION_SPLIT);
2614 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2616 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2617 subsize, pc_tree->split[1]);
2618 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2619 subsize, pc_tree->split[2]);
2620 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
2621 output_enabled, subsize, pc_tree->split[3]);
2625 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2626 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2629 static void rd_use_partition(VP9_COMP *cpi, ThreadData *td,
2630 TileDataEnc *tile_data, MODE_INFO **mi_8x8,
2631 TOKENEXTRA **tp, int mi_row, int mi_col,
2632 BLOCK_SIZE bsize, int *rate, int64_t *dist,
2633 int do_recon, PC_TREE *pc_tree) {
2634 VP9_COMMON *const cm = &cpi->common;
2635 TileInfo *const tile_info = &tile_data->tile_info;
2636 MACROBLOCK *const x = &td->mb;
2637 MACROBLOCKD *const xd = &x->e_mbd;
2638 const int mis = cm->mi_stride;
2639 const int bsl = b_width_log2_lookup[bsize];
2640 const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
2641 const int bss = (1 << bsl) / 4;
2643 PARTITION_TYPE partition = PARTITION_NONE;
2645 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2646 PARTITION_CONTEXT sl[8], sa[8];
2647 RD_COST last_part_rdc, none_rdc, chosen_rdc;
2648 BLOCK_SIZE sub_subsize = BLOCK_4X4;
2649 int splits_below = 0;
2650 BLOCK_SIZE bs_type = mi_8x8[0]->sb_type;
2651 int do_partition_search = 1;
2652 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2654 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2656 assert(num_4x4_blocks_wide_lookup[bsize] ==
2657 num_4x4_blocks_high_lookup[bsize]);
2659 vp9_rd_cost_reset(&last_part_rdc);
2660 vp9_rd_cost_reset(&none_rdc);
2661 vp9_rd_cost_reset(&chosen_rdc);
2663 partition = partition_lookup[bsl][bs_type];
2664 subsize = get_subsize(bsize, partition);
2666 pc_tree->partitioning = partition;
2667 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2669 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ) {
2670 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2671 x->mb_energy = vp9_block_energy(cpi, x, bsize);
2674 if (do_partition_search &&
2675 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2676 cpi->sf.adjust_partitioning_from_last_frame) {
2677 // Check if any of the sub blocks are further split.
2678 if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
2679 sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
2681 for (i = 0; i < 4; i++) {
2682 int jj = i >> 1, ii = i & 0x01;
2683 MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
2684 if (this_mi && this_mi->sb_type >= sub_subsize) {
2690 // If partition is not none try none unless each of the 4 splits are split
2692 if (partition != PARTITION_NONE && !splits_below &&
2693 mi_row + (mi_step >> 1) < cm->mi_rows &&
2694 mi_col + (mi_step >> 1) < cm->mi_cols) {
2695 pc_tree->partitioning = PARTITION_NONE;
2696 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize, ctx,
2699 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2701 if (none_rdc.rate < INT_MAX) {
2702 none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2704 RDCOST(x->rdmult, x->rddiv, none_rdc.rate, none_rdc.dist);
2707 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2708 mi_8x8[0]->sb_type = bs_type;
2709 pc_tree->partitioning = partition;
2713 switch (partition) {
2714 case PARTITION_NONE:
2715 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc, bsize,
2718 case PARTITION_HORZ:
2719 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
2720 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2721 subsize, &pc_tree->horizontal[0], INT64_MAX);
2722 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2723 mi_row + (mi_step >> 1) < cm->mi_rows) {
2725 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2726 vp9_rd_cost_init(&tmp_rdc);
2727 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2728 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2729 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
2730 rd_pick_sb_modes(cpi, tile_data, x, mi_row + (mi_step >> 1), mi_col,
2731 &tmp_rdc, subsize, &pc_tree->horizontal[1], INT64_MAX);
2732 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2733 vp9_rd_cost_reset(&last_part_rdc);
2736 last_part_rdc.rate += tmp_rdc.rate;
2737 last_part_rdc.dist += tmp_rdc.dist;
2738 last_part_rdc.rdcost += tmp_rdc.rdcost;
2741 case PARTITION_VERT:
2742 pc_tree->vertical[0].skip_ref_frame_mask = 0;
2743 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2744 subsize, &pc_tree->vertical[0], INT64_MAX);
2745 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2746 mi_col + (mi_step >> 1) < cm->mi_cols) {
2748 PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
2749 vp9_rd_cost_init(&tmp_rdc);
2750 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2751 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2752 pc_tree->vertical[bsize > BLOCK_8X8].skip_ref_frame_mask = 0;
2753 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + (mi_step >> 1),
2755 &pc_tree->vertical[bsize > BLOCK_8X8], INT64_MAX);
2756 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2757 vp9_rd_cost_reset(&last_part_rdc);
2760 last_part_rdc.rate += tmp_rdc.rate;
2761 last_part_rdc.dist += tmp_rdc.dist;
2762 last_part_rdc.rdcost += tmp_rdc.rdcost;
2766 assert(partition == PARTITION_SPLIT);
2767 if (bsize == BLOCK_8X8) {
2768 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2769 subsize, pc_tree->leaf_split[0], INT64_MAX);
2772 last_part_rdc.rate = 0;
2773 last_part_rdc.dist = 0;
2774 last_part_rdc.rdcost = 0;
2775 for (i = 0; i < 4; i++) {
2776 int x_idx = (i & 1) * (mi_step >> 1);
2777 int y_idx = (i >> 1) * (mi_step >> 1);
2778 int jj = i >> 1, ii = i & 0x01;
2780 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2783 vp9_rd_cost_init(&tmp_rdc);
2784 rd_use_partition(cpi, td, tile_data, mi_8x8 + jj * bss * mis + ii * bss,
2785 tp, mi_row + y_idx, mi_col + x_idx, subsize,
2786 &tmp_rdc.rate, &tmp_rdc.dist, i != 3,
2788 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2789 vp9_rd_cost_reset(&last_part_rdc);
2792 last_part_rdc.rate += tmp_rdc.rate;
2793 last_part_rdc.dist += tmp_rdc.dist;
2798 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2799 if (last_part_rdc.rate < INT_MAX) {
2800 last_part_rdc.rate += cpi->partition_cost[pl][partition];
2801 last_part_rdc.rdcost =
2802 RDCOST(x->rdmult, x->rddiv, last_part_rdc.rate, last_part_rdc.dist);
2805 if (do_partition_search && cpi->sf.adjust_partitioning_from_last_frame &&
2806 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2807 partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
2808 (mi_row + mi_step < cm->mi_rows ||
2809 mi_row + (mi_step >> 1) == cm->mi_rows) &&
2810 (mi_col + mi_step < cm->mi_cols ||
2811 mi_col + (mi_step >> 1) == cm->mi_cols)) {
2812 BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2813 chosen_rdc.rate = 0;
2814 chosen_rdc.dist = 0;
2815 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2816 pc_tree->partitioning = PARTITION_SPLIT;
2819 for (i = 0; i < 4; i++) {
2820 int x_idx = (i & 1) * (mi_step >> 1);
2821 int y_idx = (i >> 1) * (mi_step >> 1);
2823 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2824 PARTITION_CONTEXT sl[8], sa[8];
2826 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2829 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2830 pc_tree->split[i]->partitioning = PARTITION_NONE;
2831 rd_pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2832 &tmp_rdc, split_subsize, &pc_tree->split[i]->none,
2835 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2837 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2838 vp9_rd_cost_reset(&chosen_rdc);
2842 chosen_rdc.rate += tmp_rdc.rate;
2843 chosen_rdc.dist += tmp_rdc.dist;
2846 encode_sb(cpi, td, tile_info, tp, mi_row + y_idx, mi_col + x_idx, 0,
2847 split_subsize, pc_tree->split[i]);
2849 pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2851 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2853 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2854 if (chosen_rdc.rate < INT_MAX) {
2855 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2857 RDCOST(x->rdmult, x->rddiv, chosen_rdc.rate, chosen_rdc.dist);
2861 // If last_part is better set the partitioning to that.
2862 if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2863 mi_8x8[0]->sb_type = bsize;
2864 if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2865 chosen_rdc = last_part_rdc;
2867 // If none was better set the partitioning to that.
2868 if (none_rdc.rdcost < chosen_rdc.rdcost) {
2869 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2870 chosen_rdc = none_rdc;
2873 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2875 // We must have chosen a partitioning and encoding or we'll fail later on.
2876 // No other opportunities for success.
2877 if (bsize == BLOCK_64X64)
2878 assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2881 int output_enabled = (bsize == BLOCK_64X64);
2882 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2886 *rate = chosen_rdc.rate;
2887 *dist = chosen_rdc.dist;
2890 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2891 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2892 BLOCK_4X4, BLOCK_8X8, BLOCK_8X8, BLOCK_8X8, BLOCK_16X16,
2893 BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
2896 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2897 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2898 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2899 BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
2902 // Look at all the mode_info entries for blocks that are part of this
2903 // partition and find the min and max values for sb_type.
2904 // At the moment this is designed to work on a 64x64 SB but could be
2905 // adjusted to use a size parameter.
2907 // The min and max are assumed to have been initialized prior to calling this
2908 // function so repeat calls can accumulate a min and max of more than one sb64.
2909 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2910 BLOCK_SIZE *min_block_size,
2911 BLOCK_SIZE *max_block_size,
2912 int bs_hist[BLOCK_SIZES]) {
2913 int sb_width_in_blocks = MI_BLOCK_SIZE;
2914 int sb_height_in_blocks = MI_BLOCK_SIZE;
2918 // Check the sb_type for each block that belongs to this region.
2919 for (i = 0; i < sb_height_in_blocks; ++i) {
2920 for (j = 0; j < sb_width_in_blocks; ++j) {
2921 MODE_INFO *mi = mi_8x8[index + j];
2922 BLOCK_SIZE sb_type = mi ? mi->sb_type : 0;
2924 *min_block_size = VPXMIN(*min_block_size, sb_type);
2925 *max_block_size = VPXMAX(*max_block_size, sb_type);
2927 index += xd->mi_stride;
2931 // Next square block size less or equal than current block size.
2932 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2933 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_8X8, BLOCK_8X8,
2934 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2935 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64
2938 // Look at neighboring blocks and set a min and max partition size based on
2940 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2941 MACROBLOCKD *const xd, int mi_row,
2942 int mi_col, BLOCK_SIZE *min_block_size,
2943 BLOCK_SIZE *max_block_size) {
2944 VP9_COMMON *const cm = &cpi->common;
2945 MODE_INFO **mi = xd->mi;
2946 const int left_in_image = !!xd->left_mi;
2947 const int above_in_image = !!xd->above_mi;
2948 const int row8x8_remaining = tile->mi_row_end - mi_row;
2949 const int col8x8_remaining = tile->mi_col_end - mi_col;
2951 BLOCK_SIZE min_size = BLOCK_4X4;
2952 BLOCK_SIZE max_size = BLOCK_64X64;
2953 int bs_hist[BLOCK_SIZES] = { 0 };
2955 // Trap case where we do not have a prediction.
2956 if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2957 // Default "min to max" and "max to min"
2958 min_size = BLOCK_64X64;
2959 max_size = BLOCK_4X4;
2961 // NOTE: each call to get_sb_partition_size_range() uses the previous
2962 // passed in values for min and max as a starting point.
2963 // Find the min and max partition used in previous frame at this location
2964 if (cm->frame_type != KEY_FRAME) {
2965 MODE_INFO **prev_mi =
2966 &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2967 get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2969 // Find the min and max partition sizes used in the left SB64
2970 if (left_in_image) {
2971 MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2972 get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2975 // Find the min and max partition sizes used in the above SB64.
2976 if (above_in_image) {
2977 MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2978 get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2982 // Adjust observed min and max for "relaxed" auto partition case.
2983 if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2984 min_size = min_partition_size[min_size];
2985 max_size = max_partition_size[max_size];
2989 // Check border cases where max and min from neighbors may not be legal.
2990 max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
2992 // Test for blocks at the edge of the active image.
2993 // This may be the actual edge of the image or where there are formatting
2995 if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
2996 min_size = BLOCK_4X4;
2999 VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
3002 // When use_square_partition_only is true, make sure at least one square
3003 // partition is allowed by selecting the next smaller square size as
3005 if (cpi->sf.use_square_partition_only &&
3006 next_square_size[max_size] < min_size) {
3007 min_size = next_square_size[max_size];
3010 *min_block_size = min_size;
3011 *max_block_size = max_size;
3014 // TODO(jingning) refactor functions setting partition search range
3015 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd, int mi_row,
3016 int mi_col, BLOCK_SIZE bsize,
3017 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
3018 int mi_width = num_8x8_blocks_wide_lookup[bsize];
3019 int mi_height = num_8x8_blocks_high_lookup[bsize];
3023 const int idx_str = cm->mi_stride * mi_row + mi_col;
3024 MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
3025 BLOCK_SIZE bs, min_size, max_size;
3027 min_size = BLOCK_64X64;
3028 max_size = BLOCK_4X4;
3031 for (idy = 0; idy < mi_height; ++idy) {
3032 for (idx = 0; idx < mi_width; ++idx) {
3033 mi = prev_mi[idy * cm->mi_stride + idx];
3034 bs = mi ? mi->sb_type : bsize;
3035 min_size = VPXMIN(min_size, bs);
3036 max_size = VPXMAX(max_size, bs);
3042 for (idy = 0; idy < mi_height; ++idy) {
3043 mi = xd->mi[idy * cm->mi_stride - 1];
3044 bs = mi ? mi->sb_type : bsize;
3045 min_size = VPXMIN(min_size, bs);
3046 max_size = VPXMAX(max_size, bs);
3051 for (idx = 0; idx < mi_width; ++idx) {
3052 mi = xd->mi[idx - cm->mi_stride];
3053 bs = mi ? mi->sb_type : bsize;
3054 min_size = VPXMIN(min_size, bs);
3055 max_size = VPXMAX(max_size, bs);
3059 if (min_size == max_size) {
3060 min_size = min_partition_size[min_size];
3061 max_size = max_partition_size[max_size];
3068 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3069 memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
3072 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3073 memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
3076 #if CONFIG_FP_MB_STATS
3077 const int num_16x16_blocks_wide_lookup[BLOCK_SIZES] = { 1, 1, 1, 1, 1, 1, 1,
3079 const int num_16x16_blocks_high_lookup[BLOCK_SIZES] = { 1, 1, 1, 1, 1, 1, 1,
3081 const int qindex_skip_threshold_lookup[BLOCK_SIZES] = { 0, 10, 10, 30, 40,
3084 const int qindex_split_threshold_lookup[BLOCK_SIZES] = { 0, 3, 3, 7, 15,
3087 const int complexity_16x16_blocks_threshold[BLOCK_SIZES] = { 1, 1, 1, 1, 1,
3100 static INLINE MOTION_DIRECTION get_motion_direction_fp(uint8_t fp_byte) {
3101 if (fp_byte & FPMB_MOTION_ZERO_MASK) {
3103 } else if (fp_byte & FPMB_MOTION_LEFT_MASK) {
3105 } else if (fp_byte & FPMB_MOTION_RIGHT_MASK) {
3107 } else if (fp_byte & FPMB_MOTION_UP_MASK) {
3114 static INLINE int get_motion_inconsistency(MOTION_DIRECTION this_mv,
3115 MOTION_DIRECTION that_mv) {
3116 if (this_mv == that_mv) {
3119 return abs(this_mv - that_mv) == 2 ? 2 : 1;
3124 // Calculate prediction based on the given input features and neural net config.
3125 // Assume there are no more than NN_MAX_NODES_PER_LAYER nodes in each hidden
3127 static void nn_predict(const float *features, const NN_CONFIG *nn_config,
3129 int num_input_nodes = nn_config->num_inputs;
3131 float buf[2][NN_MAX_NODES_PER_LAYER];
3132 const float *input_nodes = features;
3134 // Propagate hidden layers.
3135 const int num_layers = nn_config->num_hidden_layers;
3137 assert(num_layers <= NN_MAX_HIDDEN_LAYERS);
3138 for (layer = 0; layer < num_layers; ++layer) {
3139 const float *weights = nn_config->weights[layer];
3140 const float *bias = nn_config->bias[layer];
3141 float *output_nodes = buf[buf_index];
3142 const int num_output_nodes = nn_config->num_hidden_nodes[layer];
3143 assert(num_output_nodes < NN_MAX_NODES_PER_LAYER);
3144 for (node = 0; node < num_output_nodes; ++node) {
3146 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3148 // ReLU as activation function.
3149 val = VPXMAX(val, 0.0f);
3150 output_nodes[node] = val;
3151 weights += num_input_nodes;
3153 num_input_nodes = num_output_nodes;
3154 input_nodes = output_nodes;
3155 buf_index = 1 - buf_index;
3158 // Final output layer.
3160 const float *weights = nn_config->weights[num_layers];
3161 for (node = 0; node < nn_config->num_outputs; ++node) {
3162 const float *bias = nn_config->bias[num_layers];
3164 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3165 output[node] = val + bias[node];
3166 weights += num_input_nodes;
3172 // Machine-learning based partition search early termination.
3173 // Return 1 to skip split and rect partitions.
3174 static int ml_pruning_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
3175 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
3178 abs(ctx->mic.mv[0].as_mv.col) + abs(ctx->mic.mv[0].as_mv.row);
3179 const int left_in_image = !!xd->left_mi;
3180 const int above_in_image = !!xd->above_mi;
3181 MODE_INFO **prev_mi =
3182 &cm->prev_mi_grid_visible[mi_col + cm->mi_stride * mi_row];
3183 int above_par = 0; // above_partitioning
3184 int left_par = 0; // left_partitioning
3185 int last_par = 0; // last_partitioning
3188 BLOCK_SIZE context_size;
3189 const NN_CONFIG *nn_config = NULL;
3190 const float *mean, *sd, *linear_weights;
3191 float nn_score, linear_score;
3192 float features[FEATURES];
3194 assert(b_width_log2_lookup[bsize] == b_height_log2_lookup[bsize]);
3195 vpx_clear_system_state();
3200 nn_config = &vp9_partition_nnconfig_64x64;
3204 nn_config = &vp9_partition_nnconfig_32x32;
3208 nn_config = &vp9_partition_nnconfig_16x16;
3210 default: assert(0 && "Unexpected block size."); return 0;
3213 if (above_in_image) {
3214 context_size = xd->above_mi->sb_type;
3215 if (context_size < bsize)
3217 else if (context_size == bsize)
3221 if (left_in_image) {
3222 context_size = xd->left_mi->sb_type;
3223 if (context_size < bsize)
3225 else if (context_size == bsize)
3230 context_size = prev_mi[0]->sb_type;
3231 if (context_size < bsize)
3233 else if (context_size == bsize)
3237 mean = &vp9_partition_feature_mean[offset];
3238 sd = &vp9_partition_feature_std[offset];
3239 features[0] = ((float)ctx->rate - mean[0]) / sd[0];
3240 features[1] = ((float)ctx->dist - mean[1]) / sd[1];
3241 features[2] = ((float)mag_mv / 2 - mean[2]) * sd[2];
3242 features[3] = ((float)(left_par + above_par) / 2 - mean[3]) * sd[3];
3243 features[4] = ((float)ctx->sum_y_eobs - mean[4]) / sd[4];
3244 features[5] = ((float)cm->base_qindex - mean[5]) * sd[5];
3245 features[6] = ((float)last_par - mean[6]) * sd[6];
3247 // Predict using linear model.
3248 linear_weights = &vp9_partition_linear_weights[offset];
3249 linear_score = linear_weights[FEATURES];
3250 for (i = 0; i < FEATURES; ++i)
3251 linear_score += linear_weights[i] * features[i];
3252 if (linear_score > 0.1f) return 0;
3254 // Predict using neural net model.
3255 nn_predict(features, nn_config, &nn_score);
3257 if (linear_score < -0.0f && nn_score < 0.1f) return 1;
3258 if (nn_score < -0.0f && linear_score < 0.1f) return 1;
3264 // ML-based partition search breakout.
3265 static int ml_predict_breakout(VP9_COMP *const cpi, BLOCK_SIZE bsize,
3266 const MACROBLOCK *const x,
3267 const RD_COST *const rd_cost) {
3268 DECLARE_ALIGNED(16, static const uint8_t, vp9_64_zeros[64]) = { 0 };
3269 const VP9_COMMON *const cm = &cpi->common;
3270 float features[FEATURES];
3271 const float *linear_weights = NULL; // Linear model weights.
3272 float linear_score = 0.0f;
3273 const int qindex = cm->base_qindex;
3274 const int q_ctx = qindex >= 200 ? 0 : (qindex >= 150 ? 1 : 2);
3275 const int is_720p_or_larger = VPXMIN(cm->width, cm->height) >= 720;
3276 const int resolution_ctx = is_720p_or_larger ? 1 : 0;
3280 linear_weights = vp9_partition_breakout_weights_64[resolution_ctx][q_ctx];
3283 linear_weights = vp9_partition_breakout_weights_32[resolution_ctx][q_ctx];
3286 linear_weights = vp9_partition_breakout_weights_16[resolution_ctx][q_ctx];
3289 linear_weights = vp9_partition_breakout_weights_8[resolution_ctx][q_ctx];
3291 default: assert(0 && "Unexpected block size."); return 0;
3293 if (!linear_weights) return 0;
3295 { // Generate feature values.
3296 #if CONFIG_VP9_HIGHBITDEPTH
3298 vp9_ac_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3300 const int ac_q = vp9_ac_quant(qindex, 0, cm->bit_depth);
3301 #endif // CONFIG_VP9_HIGHBITDEPTH
3302 const int num_pels_log2 = num_pels_log2_lookup[bsize];
3303 int feature_index = 0;
3304 unsigned int var, sse;
3305 float rate_f, dist_f;
3307 #if CONFIG_VP9_HIGHBITDEPTH
3308 if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3310 vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, x->e_mbd.bd);
3312 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3313 vp9_64_zeros, 0, &sse);
3316 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3317 vp9_64_zeros, 0, &sse);
3319 var = var >> num_pels_log2;
3321 vpx_clear_system_state();
3323 rate_f = (float)VPXMIN(rd_cost->rate, INT_MAX);
3324 dist_f = (float)(VPXMIN(rd_cost->dist, INT_MAX) >> num_pels_log2);
3326 ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
3329 features[feature_index++] = rate_f;
3330 features[feature_index++] = dist_f;
3331 features[feature_index++] = (float)var;
3332 features[feature_index++] = (float)ac_q;
3333 assert(feature_index == FEATURES);
3336 { // Calculate the output score.
3338 linear_score = linear_weights[FEATURES];
3339 for (i = 0; i < FEATURES; ++i)
3340 linear_score += linear_weights[i] * features[i];
3343 return linear_score >= cpi->sf.rd_ml_partition.search_breakout_thresh[q_ctx];
3349 static void ml_prune_rect_partition(VP9_COMP *const cpi, MACROBLOCK *const x,
3351 const PC_TREE *const pc_tree,
3352 int *allow_horz, int *allow_vert,
3354 const NN_CONFIG *nn_config = NULL;
3355 float score[LABELS] = {
3362 if (ref_rd <= 0 || ref_rd > 1000000000) return;
3365 case BLOCK_8X8: break;
3367 nn_config = &vp9_rect_part_nnconfig_16;
3368 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[1];
3371 nn_config = &vp9_rect_part_nnconfig_32;
3372 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[2];
3375 nn_config = &vp9_rect_part_nnconfig_64;
3376 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[3];
3378 default: assert(0 && "Unexpected block size."); return;
3380 if (!nn_config || thresh < 0) return;
3382 // Feature extraction and model score calculation.
3384 const VP9_COMMON *const cm = &cpi->common;
3385 #if CONFIG_VP9_HIGHBITDEPTH
3387 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3389 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3390 #endif // CONFIG_VP9_HIGHBITDEPTH
3391 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3392 int feature_index = 0;
3393 float features[FEATURES];
3395 features[feature_index++] = logf((float)dc_q + 1.0f);
3396 features[feature_index++] =
3397 (float)(pc_tree->partitioning == PARTITION_NONE);
3398 features[feature_index++] = logf((float)ref_rd / bs / bs + 1.0f);
3401 const float norm_factor = 1.0f / ((float)ref_rd + 1.0f);
3402 const int64_t none_rdcost = pc_tree->none.rdcost;
3403 float rd_ratio = 2.0f;
3404 if (none_rdcost > 0 && none_rdcost < 1000000000)
3405 rd_ratio = (float)none_rdcost * norm_factor;
3406 features[feature_index++] = VPXMIN(rd_ratio, 2.0f);
3408 for (i = 0; i < 4; ++i) {
3409 const int64_t this_rd = pc_tree->split[i]->none.rdcost;
3410 const int rd_valid = this_rd > 0 && this_rd < 1000000000;
3411 // Ratio between sub-block RD and whole block RD.
3412 features[feature_index++] =
3413 rd_valid ? (float)this_rd * norm_factor : 1.0f;
3417 assert(feature_index == FEATURES);
3418 nn_predict(features, nn_config, score);
3421 // Make decisions based on the model score.
3423 int max_score = -1000;
3424 int horz = 0, vert = 0;
3425 int int_score[LABELS];
3426 for (i = 0; i < LABELS; ++i) {
3427 int_score[i] = (int)(100 * score[i]);
3428 max_score = VPXMAX(int_score[i], max_score);
3430 thresh = max_score - thresh;
3431 for (i = 0; i < LABELS; ++i) {
3432 if (int_score[i] >= thresh) {
3433 if ((i >> 0) & 1) horz = 1;
3434 if ((i >> 1) & 1) vert = 1;
3437 *allow_horz = *allow_horz && horz;
3438 *allow_vert = *allow_vert && vert;
3444 // Perform fast and coarse motion search for the given block. This is a
3445 // pre-processing step for the ML based partition search speedup.
3446 static void simple_motion_search(const VP9_COMP *const cpi, MACROBLOCK *const x,
3447 BLOCK_SIZE bsize, int mi_row, int mi_col,
3448 MV ref_mv, MV_REFERENCE_FRAME ref,
3449 uint8_t *const pred_buf) {
3450 const VP9_COMMON *const cm = &cpi->common;
3451 MACROBLOCKD *const xd = &x->e_mbd;
3452 MODE_INFO *const mi = xd->mi[0];
3453 const YV12_BUFFER_CONFIG *const yv12 = get_ref_frame_buffer(cpi, ref);
3454 const int step_param = 1;
3455 const MvLimits tmp_mv_limits = x->mv_limits;
3456 const SEARCH_METHODS search_method = NSTEP;
3457 const int sadpb = x->sadperbit16;
3458 MV ref_mv_full = { ref_mv.row >> 3, ref_mv.col >> 3 };
3459 MV best_mv = { 0, 0 };
3462 assert(yv12 != NULL);
3464 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
3465 &cm->frame_refs[ref - 1].sf);
3466 mi->ref_frame[0] = ref;
3467 mi->ref_frame[1] = NONE;
3468 mi->sb_type = bsize;
3469 vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
3470 vp9_full_pixel_search(cpi, x, bsize, &ref_mv_full, step_param, search_method,
3471 sadpb, cond_cost_list(cpi, cost_list), &ref_mv,
3475 x->mv_limits = tmp_mv_limits;
3476 mi->mv[0].as_mv = best_mv;
3478 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3479 xd->plane[0].dst.buf = pred_buf;
3480 xd->plane[0].dst.stride = 64;
3481 vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
3484 // Use a neural net model to prune partition-none and partition-split search.
3485 // Features used: QP; spatial block size contexts; variance of prediction
3486 // residue after simple_motion_search.
3488 static void ml_predict_var_rd_paritioning(const VP9_COMP *const cpi,
3489 MACROBLOCK *const x,
3490 PC_TREE *const pc_tree,
3491 BLOCK_SIZE bsize, int mi_row,
3492 int mi_col, int *none, int *split) {
3493 const VP9_COMMON *const cm = &cpi->common;
3494 const NN_CONFIG *nn_config = NULL;
3495 #if CONFIG_VP9_HIGHBITDEPTH
3496 MACROBLOCKD *xd = &x->e_mbd;
3497 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64 * 2]);
3498 uint8_t *const pred_buf = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
3499 ? (CONVERT_TO_BYTEPTR(pred_buffer))
3502 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64]);
3503 uint8_t *const pred_buf = pred_buffer;
3504 #endif // CONFIG_VP9_HIGHBITDEPTH
3505 const int speed = cpi->oxcf.speed;
3506 float thresh = 0.0f;
3510 nn_config = &vp9_part_split_nnconfig_64;
3511 thresh = speed > 0 ? 2.8f : 3.0f;
3514 nn_config = &vp9_part_split_nnconfig_32;
3515 thresh = speed > 0 ? 3.5f : 3.0f;
3518 nn_config = &vp9_part_split_nnconfig_16;
3519 thresh = speed > 0 ? 3.8f : 4.0f;
3522 nn_config = &vp9_part_split_nnconfig_8;
3523 if (cm->width >= 720 && cm->height >= 720)
3524 thresh = speed > 0 ? 2.5f : 2.0f;
3526 thresh = speed > 0 ? 3.8f : 2.0f;
3528 default: assert(0 && "Unexpected block size."); return;
3531 if (!nn_config) return;
3533 // Do a simple single motion search to find a prediction for current block.
3534 // The variance of the residue will be used as input features.
3537 const MV_REFERENCE_FRAME ref =
3538 cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
3539 // If bsize is 64x64, use zero MV as reference; otherwise, use MV result
3540 // of previous(larger) block as reference.
3541 if (bsize == BLOCK_64X64)
3542 ref_mv.row = ref_mv.col = 0;
3544 ref_mv = pc_tree->mv;
3545 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
3546 simple_motion_search(cpi, x, bsize, mi_row, mi_col, ref_mv, ref, pred_buf);
3547 pc_tree->mv = x->e_mbd.mi[0]->mv[0].as_mv;
3550 vpx_clear_system_state();
3553 float features[FEATURES] = { 0.0f };
3554 #if CONFIG_VP9_HIGHBITDEPTH
3556 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (xd->bd - 8);
3558 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3559 #endif // CONFIG_VP9_HIGHBITDEPTH
3560 int feature_idx = 0;
3563 // Generate model input features.
3564 features[feature_idx++] = logf((float)dc_q + 1.0f);
3566 // Get the variance of the residue as input features.
3568 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3569 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3570 const uint8_t *pred = pred_buf;
3571 const uint8_t *src = x->plane[0].src.buf;
3572 const int src_stride = x->plane[0].src.stride;
3573 const int pred_stride = 64;
3575 // Variance of whole block.
3576 const unsigned int var =
3577 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
3578 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
3579 const MACROBLOCKD *const xd = &x->e_mbd;
3580 const int has_above = !!xd->above_mi;
3581 const int has_left = !!xd->left_mi;
3582 const BLOCK_SIZE above_bsize = has_above ? xd->above_mi->sb_type : bsize;
3583 const BLOCK_SIZE left_bsize = has_left ? xd->left_mi->sb_type : bsize;
3586 features[feature_idx++] = (float)has_above;
3587 features[feature_idx++] = (float)b_width_log2_lookup[above_bsize];
3588 features[feature_idx++] = (float)b_height_log2_lookup[above_bsize];
3589 features[feature_idx++] = (float)has_left;
3590 features[feature_idx++] = (float)b_width_log2_lookup[left_bsize];
3591 features[feature_idx++] = (float)b_height_log2_lookup[left_bsize];
3592 features[feature_idx++] = logf((float)var + 1.0f);
3593 for (i = 0; i < 4; ++i) {
3594 const int x_idx = (i & 1) * bs / 2;
3595 const int y_idx = (i >> 1) * bs / 2;
3596 const int src_offset = y_idx * src_stride + x_idx;
3597 const int pred_offset = y_idx * pred_stride + x_idx;
3598 // Variance of quarter block.
3599 const unsigned int sub_var =
3600 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
3601 pred + pred_offset, pred_stride, &sse);
3602 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
3603 features[feature_idx++] = var_ratio;
3606 assert(feature_idx == FEATURES);
3608 // Feed the features into the model to get the confidence score.
3609 nn_predict(features, nn_config, &score);
3611 // Higher score means that the model has higher confidence that the split
3612 // partition is better than the non-split partition. So if the score is
3613 // high enough, we skip the none-split partition search; if the score is
3614 // low enough, we skip the split partition search.
3615 if (score > thresh) *none = 0;
3616 if (score < -thresh) *split = 0;
3621 static double log_wiener_var(int64_t wiener_variance) {
3622 return log(1.0 + wiener_variance) / log(2.0);
3625 static void build_kmeans_segmentation(VP9_COMP *cpi) {
3626 VP9_COMMON *cm = &cpi->common;
3627 BLOCK_SIZE bsize = BLOCK_64X64;
3628 KMEANS_DATA *kmeans_data;
3630 vp9_disable_segmentation(&cm->seg);
3631 if (cm->show_frame) {
3633 cpi->kmeans_data_size = 0;
3634 cpi->kmeans_ctr_num = 8;
3636 for (mi_row = 0; mi_row < cm->mi_rows; mi_row += MI_BLOCK_SIZE) {
3637 for (mi_col = 0; mi_col < cm->mi_cols; mi_col += MI_BLOCK_SIZE) {
3638 int mb_row_start = mi_row >> 1;
3639 int mb_col_start = mi_col >> 1;
3640 int mb_row_end = VPXMIN(
3641 (mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3642 int mb_col_end = VPXMIN(
3643 (mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3645 int64_t wiener_variance = 0;
3647 for (row = mb_row_start; row < mb_row_end; ++row)
3648 for (col = mb_col_start; col < mb_col_end; ++col)
3649 wiener_variance += cpi->mb_wiener_variance[row * cm->mb_cols + col];
3652 (mb_row_end - mb_row_start) * (mb_col_end - mb_col_start);
3654 #if CONFIG_MULTITHREAD
3655 pthread_mutex_lock(&cpi->kmeans_mutex);
3656 #endif // CONFIG_MULTITHREAD
3658 kmeans_data = &cpi->kmeans_data_arr[cpi->kmeans_data_size++];
3659 kmeans_data->value = log_wiener_var(wiener_variance);
3660 kmeans_data->pos = mi_row * cpi->kmeans_data_stride + mi_col;
3661 #if CONFIG_MULTITHREAD
3662 pthread_mutex_unlock(&cpi->kmeans_mutex);
3663 #endif // CONFIG_MULTITHREAD
3667 vp9_kmeans(cpi->kmeans_ctr_ls, cpi->kmeans_boundary_ls,
3668 cpi->kmeans_count_ls, cpi->kmeans_ctr_num, cpi->kmeans_data_arr,
3669 cpi->kmeans_data_size);
3671 vp9_perceptual_aq_mode_setup(cpi, &cm->seg);
3675 static int wiener_var_segment(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3677 VP9_COMMON *cm = &cpi->common;
3678 int mb_row_start = mi_row >> 1;
3679 int mb_col_start = mi_col >> 1;
3681 VPXMIN((mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3683 VPXMIN((mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3685 int64_t wiener_variance = 0;
3687 int8_t seg_hist[MAX_SEGMENTS] = { 0 };
3688 int8_t max_count = 0, max_index = -1;
3690 vpx_clear_system_state();
3692 assert(cpi->norm_wiener_variance > 0);
3694 for (row = mb_row_start; row < mb_row_end; ++row) {
3695 for (col = mb_col_start; col < mb_col_end; ++col) {
3696 wiener_variance = cpi->mb_wiener_variance[row * cm->mb_cols + col];
3698 vp9_get_group_idx(log_wiener_var(wiener_variance),
3699 cpi->kmeans_boundary_ls, cpi->kmeans_ctr_num);
3700 ++seg_hist[segment_id];
3704 for (idx = 0; idx < cpi->kmeans_ctr_num; ++idx) {
3705 if (seg_hist[idx] > max_count) {
3706 max_count = seg_hist[idx];
3711 assert(max_index >= 0);
3712 segment_id = max_index;
3717 static int get_rdmult_delta(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3718 int mi_col, int orig_rdmult) {
3719 const int gf_group_index = cpi->twopass.gf_group.index;
3720 TplDepFrame *tpl_frame = &cpi->tpl_stats[gf_group_index];
3721 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
3722 int tpl_stride = tpl_frame->stride;
3723 int64_t intra_cost = 0;
3724 int64_t mc_dep_cost = 0;
3725 int mi_wide = num_8x8_blocks_wide_lookup[bsize];
3726 int mi_high = num_8x8_blocks_high_lookup[bsize];
3731 double r0, rk, beta;
3733 if (tpl_frame->is_valid == 0) return orig_rdmult;
3735 if (cpi->twopass.gf_group.layer_depth[gf_group_index] > 1) return orig_rdmult;
3737 if (gf_group_index >= MAX_ARF_GOP_SIZE) return orig_rdmult;
3739 for (row = mi_row; row < mi_row + mi_high; ++row) {
3740 for (col = mi_col; col < mi_col + mi_wide; ++col) {
3741 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
3743 if (row >= cpi->common.mi_rows || col >= cpi->common.mi_cols) continue;
3745 intra_cost += this_stats->intra_cost;
3746 mc_dep_cost += this_stats->mc_dep_cost;
3752 vpx_clear_system_state();
3755 rk = (double)intra_cost / mc_dep_cost;
3757 dr = vp9_get_adaptive_rdmult(cpi, beta);
3759 dr = VPXMIN(dr, orig_rdmult * 3 / 2);
3760 dr = VPXMAX(dr, orig_rdmult * 1 / 2);
3767 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
3768 // unlikely to be selected depending on previous rate-distortion optimization
3769 // results, for encoding speed-up.
3770 static void rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3771 TileDataEnc *tile_data, TOKENEXTRA **tp,
3772 int mi_row, int mi_col, BLOCK_SIZE bsize,
3773 RD_COST *rd_cost, int64_t best_rd,
3775 VP9_COMMON *const cm = &cpi->common;
3776 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3777 TileInfo *const tile_info = &tile_data->tile_info;
3778 MACROBLOCK *const x = &td->mb;
3779 MACROBLOCKD *const xd = &x->e_mbd;
3780 const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
3781 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
3782 PARTITION_CONTEXT sl[8], sa[8];
3783 TOKENEXTRA *tp_orig = *tp;
3784 PICK_MODE_CONTEXT *const ctx = &pc_tree->none;
3786 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3788 RD_COST this_rdc, sum_rdc, best_rdc;
3789 int do_split = bsize >= BLOCK_8X8;
3791 INTERP_FILTER pred_interp_filter;
3793 // Override skipping rectangular partition operations for edge blocks
3794 const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
3795 const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
3796 const int xss = x->e_mbd.plane[1].subsampling_x;
3797 const int yss = x->e_mbd.plane[1].subsampling_y;
3799 BLOCK_SIZE min_size = x->min_partition_size;
3800 BLOCK_SIZE max_size = x->max_partition_size;
3802 #if CONFIG_FP_MB_STATS
3803 unsigned int src_diff_var = UINT_MAX;
3804 int none_complexity = 0;
3807 int partition_none_allowed = !force_horz_split && !force_vert_split;
3808 int partition_horz_allowed =
3809 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
3810 int partition_vert_allowed =
3811 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
3813 int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_thr.dist;
3814 int rate_breakout_thr = cpi->sf.partition_search_breakout_thr.rate;
3817 // Ref frames picked in the [i_th] quarter subblock during square partition
3818 // RD search. It may be used to prune ref frame selection of rect partitions.
3819 uint8_t ref_frames_used[4] = { 0, 0, 0, 0 };
3821 int partition_mul = x->cb_rdmult;
3822 if (oxcf->tuning == VP8_TUNE_SSIM) {
3823 const double ssim_factor =
3824 get_ssim_rdmult_scaling_factor(cpi, mi_row, mi_col);
3825 partition_mul = (int)(ssim_factor * partition_mul);
3830 assert(num_8x8_blocks_wide_lookup[bsize] ==
3831 num_8x8_blocks_high_lookup[bsize]);
3833 dist_breakout_thr >>=
3834 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
3836 rate_breakout_thr *= num_pels_log2_lookup[bsize];
3838 vp9_rd_cost_init(&this_rdc);
3839 vp9_rd_cost_init(&sum_rdc);
3840 vp9_rd_cost_reset(&best_rdc);
3841 best_rdc.rdcost = best_rd;
3843 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3845 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ &&
3846 cpi->oxcf.aq_mode != LOOKAHEAD_AQ)
3847 x->mb_energy = vp9_block_energy(cpi, x, bsize);
3849 if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
3850 int cb_partition_search_ctrl =
3851 ((pc_tree->index == 0 || pc_tree->index == 3) +
3852 get_chessboard_index(cm->current_video_frame)) &
3855 if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
3856 set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
3859 // Get sub block energy range
3860 if (bsize >= BLOCK_16X16) {
3861 int min_energy, max_energy;
3862 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3864 must_split = (min_energy < -3) && (max_energy - min_energy > 2);
3867 // Determine partition types in search according to the speed features.
3868 // The threshold set here has to be of square block size.
3869 if (cpi->sf.auto_min_max_partition_size) {
3870 partition_none_allowed &= (bsize <= max_size);
3871 partition_horz_allowed &=
3872 ((bsize <= max_size && bsize > min_size) || force_horz_split);
3873 partition_vert_allowed &=
3874 ((bsize <= max_size && bsize > min_size) || force_vert_split);
3875 do_split &= bsize > min_size;
3878 if (cpi->sf.use_square_partition_only &&
3879 (bsize > cpi->sf.use_square_only_thresh_high ||
3880 bsize < cpi->sf.use_square_only_thresh_low)) {
3882 if (!vp9_active_h_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3883 partition_horz_allowed &= force_horz_split;
3884 if (!vp9_active_v_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3885 partition_vert_allowed &= force_vert_split;
3887 partition_horz_allowed &= force_horz_split;
3888 partition_vert_allowed &= force_vert_split;
3892 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3894 #if CONFIG_FP_MB_STATS
3895 if (cpi->use_fp_mb_stats) {
3896 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3897 src_diff_var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src, mi_row,
3902 #if CONFIG_FP_MB_STATS
3903 // Decide whether we shall split directly and skip searching NONE by using
3904 // the first pass block statistics
3905 if (cpi->use_fp_mb_stats && bsize >= BLOCK_32X32 && do_split &&
3906 partition_none_allowed && src_diff_var > 4 &&
3907 cm->base_qindex < qindex_split_threshold_lookup[bsize]) {
3908 int mb_row = mi_row >> 1;
3909 int mb_col = mi_col >> 1;
3911 VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
3913 VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
3916 // compute a complexity measure, basically measure inconsistency of motion
3917 // vectors obtained from the first pass in the current block
3918 for (r = mb_row; r < mb_row_end; r++) {
3919 for (c = mb_col; c < mb_col_end; c++) {
3920 const int mb_index = r * cm->mb_cols + c;
3922 MOTION_DIRECTION this_mv;
3923 MOTION_DIRECTION right_mv;
3924 MOTION_DIRECTION bottom_mv;
3927 get_motion_direction_fp(cpi->twopass.this_frame_mb_stats[mb_index]);
3930 if (c != mb_col_end - 1) {
3931 right_mv = get_motion_direction_fp(
3932 cpi->twopass.this_frame_mb_stats[mb_index + 1]);
3933 none_complexity += get_motion_inconsistency(this_mv, right_mv);
3937 if (r != mb_row_end - 1) {
3938 bottom_mv = get_motion_direction_fp(
3939 cpi->twopass.this_frame_mb_stats[mb_index + cm->mb_cols]);
3940 none_complexity += get_motion_inconsistency(this_mv, bottom_mv);
3943 // do not count its left and top neighbors to avoid double counting
3947 if (none_complexity > complexity_16x16_blocks_threshold[bsize]) {
3948 partition_none_allowed = 0;
3953 pc_tree->partitioning = PARTITION_NONE;
3955 if (cpi->sf.rd_ml_partition.var_pruning && !frame_is_intra_only(cm)) {
3956 const int do_rd_ml_partition_var_pruning =
3957 partition_none_allowed && do_split &&
3958 mi_row + num_8x8_blocks_high_lookup[bsize] <= cm->mi_rows &&
3959 mi_col + num_8x8_blocks_wide_lookup[bsize] <= cm->mi_cols;
3960 if (do_rd_ml_partition_var_pruning) {
3961 ml_predict_var_rd_paritioning(cpi, x, pc_tree, bsize, mi_row, mi_col,
3962 &partition_none_allowed, &do_split);
3964 vp9_zero(pc_tree->mv);
3966 if (bsize > BLOCK_8X8) { // Store MV result as reference for subblocks.
3967 for (i = 0; i < 4; ++i) pc_tree->split[i]->mv = pc_tree->mv;
3972 if (partition_none_allowed) {
3973 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize, ctx,
3975 ctx->rdcost = this_rdc.rdcost;
3976 if (this_rdc.rate != INT_MAX) {
3977 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
3978 const int ref1 = ctx->mic.ref_frame[0];
3979 const int ref2 = ctx->mic.ref_frame[1];
3980 for (i = 0; i < 4; ++i) {
3981 ref_frames_used[i] |= (1 << ref1);
3982 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3985 if (bsize >= BLOCK_8X8) {
3986 this_rdc.rdcost += RDCOST(partition_mul, x->rddiv,
3987 cpi->partition_cost[pl][PARTITION_NONE], 0);
3988 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3991 if (this_rdc.rdcost < best_rdc.rdcost) {
3992 MODE_INFO *mi = xd->mi[0];
3994 best_rdc = this_rdc;
3995 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
3997 if (cpi->sf.rd_ml_partition.search_early_termination) {
3998 // Currently, the machine-learning based partition search early
3999 // termination is only used while bsize is 16x16, 32x32 or 64x64,
4000 // VPXMIN(cm->width, cm->height) >= 480, and speed = 0.
4001 if (!x->e_mbd.lossless &&
4002 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP) &&
4003 ctx->mic.mode >= INTRA_MODES && bsize >= BLOCK_16X16) {
4004 if (ml_pruning_partition(cm, xd, ctx, mi_row, mi_col, bsize)) {
4011 if ((do_split || do_rect) && !x->e_mbd.lossless && ctx->skippable) {
4012 const int use_ml_based_breakout =
4013 cpi->sf.rd_ml_partition.search_breakout && cm->base_qindex >= 100;
4014 if (use_ml_based_breakout) {
4015 if (ml_predict_breakout(cpi, bsize, x, &this_rdc)) {
4020 if (!cpi->sf.rd_ml_partition.search_early_termination) {
4021 if ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4022 (best_rdc.dist < dist_breakout_thr &&
4023 best_rdc.rate < rate_breakout_thr)) {
4031 #if CONFIG_FP_MB_STATS
4032 // Check if every 16x16 first pass block statistics has zero
4033 // motion and the corresponding first pass residue is small enough.
4034 // If that is the case, check the difference variance between the
4035 // current frame and the last frame. If the variance is small enough,
4036 // stop further splitting in RD optimization
4037 if (cpi->use_fp_mb_stats && do_split != 0 &&
4038 cm->base_qindex > qindex_skip_threshold_lookup[bsize]) {
4039 int mb_row = mi_row >> 1;
4040 int mb_col = mi_col >> 1;
4042 VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
4044 VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
4048 for (r = mb_row; r < mb_row_end; r++) {
4049 for (c = mb_col; c < mb_col_end; c++) {
4050 const int mb_index = r * cm->mb_cols + c;
4051 if (!(cpi->twopass.this_frame_mb_stats[mb_index] &
4052 FPMB_MOTION_ZERO_MASK) ||
4053 !(cpi->twopass.this_frame_mb_stats[mb_index] &
4054 FPMB_ERROR_SMALL_MASK)) {
4065 if (src_diff_var == UINT_MAX) {
4066 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4067 src_diff_var = get_sby_perpixel_diff_variance(
4068 cpi, &x->plane[0].src, mi_row, mi_col, bsize);
4070 if (src_diff_var < 8) {
4079 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4081 vp9_zero(ctx->pred_mv);
4082 ctx->mic.interp_filter = EIGHTTAP;
4085 // store estimated motion vector
4086 store_pred_mv(x, ctx);
4088 // If the interp_filter is marked as SWITCHABLE_FILTERS, it was for an
4089 // intra block and used for context purposes.
4090 if (ctx->mic.interp_filter == SWITCHABLE_FILTERS) {
4091 pred_interp_filter = EIGHTTAP;
4093 pred_interp_filter = ctx->mic.interp_filter;
4097 // TODO(jingning): use the motion vectors given by the above search as
4098 // the starting point of motion search in the following partition type check.
4099 pc_tree->split[0]->none.rdcost = 0;
4100 pc_tree->split[1]->none.rdcost = 0;
4101 pc_tree->split[2]->none.rdcost = 0;
4102 pc_tree->split[3]->none.rdcost = 0;
4103 if (do_split || must_split) {
4104 subsize = get_subsize(bsize, PARTITION_SPLIT);
4105 load_pred_mv(x, ctx);
4106 if (bsize == BLOCK_8X8) {
4108 if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
4109 pc_tree->leaf_split[0]->pred_interp_filter = pred_interp_filter;
4110 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4111 pc_tree->leaf_split[0], best_rdc.rdcost);
4112 if (sum_rdc.rate == INT_MAX) {
4113 sum_rdc.rdcost = INT64_MAX;
4115 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4116 const int ref1 = pc_tree->leaf_split[0]->mic.ref_frame[0];
4117 const int ref2 = pc_tree->leaf_split[0]->mic.ref_frame[1];
4118 for (i = 0; i < 4; ++i) {
4119 ref_frames_used[i] |= (1 << ref1);
4120 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4125 for (i = 0; (i < 4) && ((sum_rdc.rdcost < best_rdc.rdcost) || must_split);
4127 const int x_idx = (i & 1) * mi_step;
4128 const int y_idx = (i >> 1) * mi_step;
4130 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4133 pc_tree->split[i]->index = i;
4134 if (cpi->sf.prune_ref_frame_for_rect_partitions)
4135 pc_tree->split[i]->none.rate = INT_MAX;
4136 rd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4137 mi_col + x_idx, subsize, &this_rdc,
4138 // A must split test here increases the number of sub
4139 // partitions but hurts metrics results quite a bit,
4140 // so this extra test is commented out pending
4141 // further tests on whether it adds much in terms of
4143 // (must_split) ? best_rdc.rdcost
4144 // : best_rdc.rdcost - sum_rdc.rdcost,
4145 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4147 if (this_rdc.rate == INT_MAX) {
4148 sum_rdc.rdcost = INT64_MAX;
4151 if (cpi->sf.prune_ref_frame_for_rect_partitions &&
4152 pc_tree->split[i]->none.rate != INT_MAX) {
4153 const int ref1 = pc_tree->split[i]->none.mic.ref_frame[0];
4154 const int ref2 = pc_tree->split[i]->none.mic.ref_frame[1];
4155 ref_frames_used[i] |= (1 << ref1);
4156 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4158 sum_rdc.rate += this_rdc.rate;
4159 sum_rdc.dist += this_rdc.dist;
4160 sum_rdc.rdcost += this_rdc.rdcost;
4165 if (((sum_rdc.rdcost < best_rdc.rdcost) || must_split) && i == 4) {
4166 sum_rdc.rdcost += RDCOST(partition_mul, x->rddiv,
4167 cpi->partition_cost[pl][PARTITION_SPLIT], 0);
4168 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4170 if ((sum_rdc.rdcost < best_rdc.rdcost) ||
4171 (must_split && (sum_rdc.dist < best_rdc.dist))) {
4173 pc_tree->partitioning = PARTITION_SPLIT;
4175 // Rate and distortion based partition search termination clause.
4176 if (!cpi->sf.rd_ml_partition.search_early_termination &&
4177 !x->e_mbd.lossless &&
4178 ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4179 (best_rdc.dist < dist_breakout_thr &&
4180 best_rdc.rate < rate_breakout_thr))) {
4185 // skip rectangular partition test when larger block size
4186 // gives better rd cost
4187 if (cpi->sf.less_rectangular_check &&
4188 (bsize > cpi->sf.use_square_only_thresh_high ||
4189 best_rdc.dist < dist_breakout_thr))
4190 do_rect &= !partition_none_allowed;
4192 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4195 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
4196 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
4197 pc_tree->vertical[0].skip_ref_frame_mask = 0;
4198 pc_tree->vertical[1].skip_ref_frame_mask = 0;
4199 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4200 uint8_t used_frames;
4201 used_frames = ref_frames_used[0] | ref_frames_used[1];
4202 if (used_frames) pc_tree->horizontal[0].skip_ref_frame_mask = ~used_frames;
4203 used_frames = ref_frames_used[2] | ref_frames_used[3];
4204 if (used_frames) pc_tree->horizontal[1].skip_ref_frame_mask = ~used_frames;
4205 used_frames = ref_frames_used[0] | ref_frames_used[2];
4206 if (used_frames) pc_tree->vertical[0].skip_ref_frame_mask = ~used_frames;
4207 used_frames = ref_frames_used[1] | ref_frames_used[3];
4208 if (used_frames) pc_tree->vertical[1].skip_ref_frame_mask = ~used_frames;
4212 const int do_ml_rect_partition_pruning =
4213 !frame_is_intra_only(cm) && !force_horz_split && !force_vert_split &&
4214 (partition_horz_allowed || partition_vert_allowed) && bsize > BLOCK_8X8;
4215 if (do_ml_rect_partition_pruning) {
4216 ml_prune_rect_partition(cpi, x, bsize, pc_tree, &partition_horz_allowed,
4217 &partition_vert_allowed, best_rdc.rdcost);
4222 if (partition_horz_allowed &&
4223 (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
4224 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_HORZ];
4225 const int64_t part_mode_rdcost =
4226 RDCOST(partition_mul, x->rddiv, part_mode_rate, 0);
4227 subsize = get_subsize(bsize, PARTITION_HORZ);
4228 load_pred_mv(x, ctx);
4229 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4230 partition_none_allowed)
4231 pc_tree->horizontal[0].pred_interp_filter = pred_interp_filter;
4232 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4233 &pc_tree->horizontal[0],
4234 best_rdc.rdcost - part_mode_rdcost);
4235 if (sum_rdc.rdcost < INT64_MAX) {
4236 sum_rdc.rdcost += part_mode_rdcost;
4237 sum_rdc.rate += part_mode_rate;
4240 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
4241 bsize > BLOCK_8X8) {
4242 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
4243 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
4244 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
4245 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4246 partition_none_allowed)
4247 pc_tree->horizontal[1].pred_interp_filter = pred_interp_filter;
4248 rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col, &this_rdc,
4249 subsize, &pc_tree->horizontal[1],
4250 best_rdc.rdcost - sum_rdc.rdcost);
4251 if (this_rdc.rate == INT_MAX) {
4252 sum_rdc.rdcost = INT64_MAX;
4254 sum_rdc.rate += this_rdc.rate;
4255 sum_rdc.dist += this_rdc.dist;
4256 sum_rdc.rdcost += this_rdc.rdcost;
4260 if (sum_rdc.rdcost < best_rdc.rdcost) {
4262 pc_tree->partitioning = PARTITION_HORZ;
4264 if (cpi->sf.less_rectangular_check &&
4265 bsize > cpi->sf.use_square_only_thresh_high)
4268 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4272 if (partition_vert_allowed &&
4273 (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
4274 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_VERT];
4275 const int64_t part_mode_rdcost =
4276 RDCOST(partition_mul, x->rddiv, part_mode_rate, 0);
4277 subsize = get_subsize(bsize, PARTITION_VERT);
4278 load_pred_mv(x, ctx);
4279 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4280 partition_none_allowed)
4281 pc_tree->vertical[0].pred_interp_filter = pred_interp_filter;
4282 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4283 &pc_tree->vertical[0], best_rdc.rdcost - part_mode_rdcost);
4284 if (sum_rdc.rdcost < INT64_MAX) {
4285 sum_rdc.rdcost += part_mode_rdcost;
4286 sum_rdc.rate += part_mode_rate;
4289 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
4290 bsize > BLOCK_8X8) {
4291 update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
4292 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
4293 &pc_tree->vertical[0]);
4294 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4295 partition_none_allowed)
4296 pc_tree->vertical[1].pred_interp_filter = pred_interp_filter;
4297 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step, &this_rdc,
4298 subsize, &pc_tree->vertical[1],
4299 best_rdc.rdcost - sum_rdc.rdcost);
4300 if (this_rdc.rate == INT_MAX) {
4301 sum_rdc.rdcost = INT64_MAX;
4303 sum_rdc.rate += this_rdc.rate;
4304 sum_rdc.dist += this_rdc.dist;
4305 sum_rdc.rdcost += this_rdc.rdcost;
4309 if (sum_rdc.rdcost < best_rdc.rdcost) {
4311 pc_tree->partitioning = PARTITION_VERT;
4313 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4316 // TODO(jbb): This code added so that we avoid static analysis
4317 // warning related to the fact that best_rd isn't used after this
4318 // point. This code should be refactored so that the duplicate
4319 // checks occur in some sub function and thus are used...
4321 *rd_cost = best_rdc;
4323 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX &&
4324 pc_tree->index != 3) {
4325 int output_enabled = (bsize == BLOCK_64X64);
4326 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4330 if (bsize == BLOCK_64X64) {
4331 assert(tp_orig < *tp);
4332 assert(best_rdc.rate < INT_MAX);
4333 assert(best_rdc.dist < INT64_MAX);
4335 assert(tp_orig == *tp);
4339 static void encode_rd_sb_row(VP9_COMP *cpi, ThreadData *td,
4340 TileDataEnc *tile_data, int mi_row,
4342 VP9_COMMON *const cm = &cpi->common;
4343 TileInfo *const tile_info = &tile_data->tile_info;
4344 MACROBLOCK *const x = &td->mb;
4345 MACROBLOCKD *const xd = &x->e_mbd;
4346 SPEED_FEATURES *const sf = &cpi->sf;
4347 const int mi_col_start = tile_info->mi_col_start;
4348 const int mi_col_end = tile_info->mi_col_end;
4350 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
4351 const int num_sb_cols =
4352 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
4355 // Initialize the left context for the new SB row
4356 memset(&xd->left_context, 0, sizeof(xd->left_context));
4357 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
4359 // Code each SB in the row
4360 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
4361 mi_col += MI_BLOCK_SIZE, sb_col_in_tile++) {
4362 const struct segmentation *const seg = &cm->seg;
4368 int orig_rdmult = cpi->rd.RDMULT;
4370 const int idx_str = cm->mi_stride * mi_row + mi_col;
4371 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
4373 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
4376 if (sf->adaptive_pred_interp_filter) {
4377 for (i = 0; i < 64; ++i) td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
4379 for (i = 0; i < 64; ++i) {
4380 td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
4381 td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
4382 td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
4383 td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
4387 for (i = 0; i < MAX_REF_FRAMES; ++i) {
4388 x->pred_mv[i].row = INT16_MAX;
4389 x->pred_mv[i].col = INT16_MAX;
4391 td->pc_root->index = 0;
4394 const uint8_t *const map =
4395 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
4396 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
4397 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
4400 x->source_variance = UINT_MAX;
4402 x->cb_rdmult = orig_rdmult;
4404 if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
4405 const BLOCK_SIZE bsize =
4406 seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
4407 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4408 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4409 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4410 &dummy_rate, &dummy_dist, 1, td->pc_root);
4411 } else if (cpi->partition_search_skippable_frame) {
4413 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4414 bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col);
4415 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4416 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4417 &dummy_rate, &dummy_dist, 1, td->pc_root);
4418 } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
4419 cm->frame_type != KEY_FRAME) {
4420 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
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);
4424 if (cpi->twopass.gf_group.index > 0 && cpi->sf.enable_tpl_model) {
4426 get_rdmult_delta(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4430 if (cpi->sf.enable_wiener_variance && cm->show_frame) {
4431 x->segment_id = wiener_var_segment(cpi, BLOCK_64X64, mi_row, mi_col);
4432 x->cb_rdmult = vp9_compute_rd_mult(
4433 cpi, vp9_get_qindex(&cm->seg, x->segment_id, cm->base_qindex));
4436 // If required set upper and lower partition size limits
4437 if (sf->auto_min_max_partition_size) {
4438 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4439 rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
4440 &x->min_partition_size, &x->max_partition_size);
4442 td->pc_root->none.rdcost = 0;
4443 rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
4444 &dummy_rdc, INT64_MAX, td->pc_root);
4446 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
4447 sb_col_in_tile, num_sb_cols);
4451 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
4452 MACROBLOCK *const x = &cpi->td.mb;
4453 VP9_COMMON *const cm = &cpi->common;
4454 MACROBLOCKD *const xd = &x->e_mbd;
4455 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
4457 // Copy data over into macro block data structures.
4458 vp9_setup_src_planes(x, cpi->Source, 0, 0);
4460 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
4462 // Note: this memset assumes above_context[0], [1] and [2]
4463 // are allocated as part of the same buffer.
4464 memset(xd->above_context[0], 0,
4465 sizeof(*xd->above_context[0]) * 2 * aligned_mi_cols * MAX_MB_PLANE);
4466 memset(xd->above_seg_context, 0,
4467 sizeof(*xd->above_seg_context) * aligned_mi_cols);
4470 static int check_dual_ref_flags(VP9_COMP *cpi) {
4471 const int ref_flags = cpi->ref_frame_flags;
4473 if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
4476 return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG) +
4477 !!(ref_flags & VP9_ALT_FLAG)) >= 2;
4481 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
4483 const int mis = cm->mi_stride;
4484 MODE_INFO **mi_ptr = cm->mi_grid_visible;
4486 for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
4487 for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
4488 if (mi_ptr[mi_col]->tx_size > max_tx_size)
4489 mi_ptr[mi_col]->tx_size = max_tx_size;
4494 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
4495 if (frame_is_intra_only(&cpi->common))
4497 else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
4498 return ALTREF_FRAME;
4499 else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
4500 return GOLDEN_FRAME;
4505 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
4506 if (xd->lossless) return ONLY_4X4;
4507 if (cpi->common.frame_type == KEY_FRAME && cpi->sf.use_nonrd_pick_mode)
4509 if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
4511 else if (cpi->sf.tx_size_search_method == USE_FULL_RD ||
4512 cpi->sf.tx_size_search_method == USE_TX_8X8)
4513 return TX_MODE_SELECT;
4515 return cpi->common.tx_mode;
4518 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
4519 RD_COST *rd_cost, BLOCK_SIZE bsize,
4520 PICK_MODE_CONTEXT *ctx) {
4521 if (!cpi->sf.nonrd_keyframe && bsize < BLOCK_16X16)
4522 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4524 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4527 static void hybrid_search_svc_baseiskey(VP9_COMP *cpi, MACROBLOCK *const x,
4528 RD_COST *rd_cost, BLOCK_SIZE bsize,
4529 PICK_MODE_CONTEXT *ctx,
4530 TileDataEnc *tile_data, int mi_row,
4532 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4533 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4535 if (cpi->svc.disable_inter_layer_pred == INTER_LAYER_PRED_OFF)
4536 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4537 else if (bsize >= BLOCK_8X8)
4538 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4541 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4545 static void hybrid_search_scene_change(VP9_COMP *cpi, MACROBLOCK *const x,
4546 RD_COST *rd_cost, BLOCK_SIZE bsize,
4547 PICK_MODE_CONTEXT *ctx,
4548 TileDataEnc *tile_data, int mi_row,
4550 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4551 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4553 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize, ctx);
4557 static void nonrd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
4558 MACROBLOCK *const x, int mi_row, int mi_col,
4559 RD_COST *rd_cost, BLOCK_SIZE bsize,
4560 PICK_MODE_CONTEXT *ctx) {
4561 VP9_COMMON *const cm = &cpi->common;
4562 TileInfo *const tile_info = &tile_data->tile_info;
4563 MACROBLOCKD *const xd = &x->e_mbd;
4565 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
4566 BLOCK_SIZE bs = VPXMAX(bsize, BLOCK_8X8); // processing unit block size
4567 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bs];
4568 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bs];
4571 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4573 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
4576 mi->sb_type = bsize;
4578 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4579 struct macroblockd_plane *pd = &xd->plane[plane];
4580 memcpy(a + num_4x4_blocks_wide * plane, pd->above_context,
4581 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4582 memcpy(l + num_4x4_blocks_high * plane, pd->left_context,
4583 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4586 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
4587 if (cyclic_refresh_segment_id_boosted(mi->segment_id))
4588 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
4590 if (frame_is_intra_only(cm))
4591 hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
4592 else if (cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
4593 hybrid_search_svc_baseiskey(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4595 else if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
4596 set_mode_info_seg_skip(x, cm->tx_mode, rd_cost, bsize);
4597 else if (bsize >= BLOCK_8X8) {
4598 if (cpi->rc.hybrid_intra_scene_change)
4599 hybrid_search_scene_change(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4602 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4605 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4608 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4610 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4611 struct macroblockd_plane *pd = &xd->plane[plane];
4612 memcpy(pd->above_context, a + num_4x4_blocks_wide * plane,
4613 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4614 memcpy(pd->left_context, l + num_4x4_blocks_high * plane,
4615 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4618 if (rd_cost->rate == INT_MAX) vp9_rd_cost_reset(rd_cost);
4620 ctx->rate = rd_cost->rate;
4621 ctx->dist = rd_cost->dist;
4624 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x, int mi_row,
4625 int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4626 MACROBLOCKD *xd = &x->e_mbd;
4627 int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4628 PARTITION_TYPE partition = pc_tree->partitioning;
4629 BLOCK_SIZE subsize = get_subsize(bsize, partition);
4631 assert(bsize >= BLOCK_8X8);
4633 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4635 switch (partition) {
4636 case PARTITION_NONE:
4637 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4638 *(xd->mi[0]) = pc_tree->none.mic;
4639 *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
4640 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4642 case PARTITION_VERT:
4643 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4644 *(xd->mi[0]) = pc_tree->vertical[0].mic;
4645 *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
4646 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4648 if (mi_col + hbs < cm->mi_cols) {
4649 set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
4650 *(xd->mi[0]) = pc_tree->vertical[1].mic;
4651 *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
4652 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
4655 case PARTITION_HORZ:
4656 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4657 *(xd->mi[0]) = pc_tree->horizontal[0].mic;
4658 *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
4659 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4660 if (mi_row + hbs < cm->mi_rows) {
4661 set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
4662 *(xd->mi[0]) = pc_tree->horizontal[1].mic;
4663 *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
4664 duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
4667 case PARTITION_SPLIT: {
4668 fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
4669 fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
4671 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
4673 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
4681 // Reset the prediction pixel ready flag recursively.
4682 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
4683 pc_tree->none.pred_pixel_ready = 0;
4684 pc_tree->horizontal[0].pred_pixel_ready = 0;
4685 pc_tree->horizontal[1].pred_pixel_ready = 0;
4686 pc_tree->vertical[0].pred_pixel_ready = 0;
4687 pc_tree->vertical[1].pred_pixel_ready = 0;
4689 if (bsize > BLOCK_8X8) {
4690 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4692 for (i = 0; i < 4; ++i) pred_pixel_ready_reset(pc_tree->split[i], subsize);
4698 static int ml_predict_var_paritioning(VP9_COMP *cpi, MACROBLOCK *x,
4699 BLOCK_SIZE bsize, int mi_row,
4701 VP9_COMMON *const cm = &cpi->common;
4702 const NN_CONFIG *nn_config = NULL;
4705 case BLOCK_64X64: nn_config = &vp9_var_part_nnconfig_64; break;
4706 case BLOCK_32X32: nn_config = &vp9_var_part_nnconfig_32; break;
4707 case BLOCK_16X16: nn_config = &vp9_var_part_nnconfig_16; break;
4708 case BLOCK_8X8: break;
4709 default: assert(0 && "Unexpected block size."); return -1;
4712 if (!nn_config) return -1;
4714 vpx_clear_system_state();
4717 const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
4718 float features[FEATURES] = { 0.0f };
4719 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
4720 int feature_idx = 0;
4721 float score[LABELS];
4723 features[feature_idx++] = logf((float)(dc_q * dc_q) / 256.0f + 1.0f);
4724 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
4726 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
4727 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4728 const int sb_offset_row = 8 * (mi_row & 7);
4729 const int sb_offset_col = 8 * (mi_col & 7);
4730 const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
4731 const uint8_t *src = x->plane[0].src.buf;
4732 const int src_stride = x->plane[0].src.stride;
4733 const int pred_stride = 64;
4736 // Variance of whole block.
4737 const unsigned int var =
4738 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
4739 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
4741 features[feature_idx++] = logf((float)var + 1.0f);
4742 for (i = 0; i < 4; ++i) {
4743 const int x_idx = (i & 1) * bs / 2;
4744 const int y_idx = (i >> 1) * bs / 2;
4745 const int src_offset = y_idx * src_stride + x_idx;
4746 const int pred_offset = y_idx * pred_stride + x_idx;
4747 // Variance of quarter block.
4748 const unsigned int sub_var =
4749 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
4750 pred + pred_offset, pred_stride, &sse);
4751 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
4752 features[feature_idx++] = var_ratio;
4756 assert(feature_idx == FEATURES);
4757 nn_predict(features, nn_config, score);
4758 if (score[0] > thresh) return PARTITION_SPLIT;
4759 if (score[0] < -thresh) return PARTITION_NONE;
4766 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
4767 TileDataEnc *tile_data, TOKENEXTRA **tp,
4768 int mi_row, int mi_col, BLOCK_SIZE bsize,
4769 RD_COST *rd_cost, int do_recon,
4770 int64_t best_rd, PC_TREE *pc_tree) {
4771 const SPEED_FEATURES *const sf = &cpi->sf;
4772 VP9_COMMON *const cm = &cpi->common;
4773 TileInfo *const tile_info = &tile_data->tile_info;
4774 MACROBLOCK *const x = &td->mb;
4775 MACROBLOCKD *const xd = &x->e_mbd;
4776 const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
4777 TOKENEXTRA *tp_orig = *tp;
4778 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
4780 BLOCK_SIZE subsize = bsize;
4781 RD_COST this_rdc, sum_rdc, best_rdc;
4782 int do_split = bsize >= BLOCK_8X8;
4784 // Override skipping rectangular partition operations for edge blocks
4785 const int force_horz_split = (mi_row + ms >= cm->mi_rows);
4786 const int force_vert_split = (mi_col + ms >= cm->mi_cols);
4787 const int xss = x->e_mbd.plane[1].subsampling_x;
4788 const int yss = x->e_mbd.plane[1].subsampling_y;
4790 int partition_none_allowed = !force_horz_split && !force_vert_split;
4791 int partition_horz_allowed =
4792 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
4793 int partition_vert_allowed =
4794 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
4795 const int use_ml_based_partitioning =
4796 sf->partition_search_type == ML_BASED_PARTITION;
4800 // Avoid checking for rectangular partitions for speed >= 6.
4801 if (cpi->oxcf.speed >= 6) do_rect = 0;
4803 assert(num_8x8_blocks_wide_lookup[bsize] ==
4804 num_8x8_blocks_high_lookup[bsize]);
4806 vp9_rd_cost_init(&sum_rdc);
4807 vp9_rd_cost_reset(&best_rdc);
4808 best_rdc.rdcost = best_rd;
4810 // Determine partition types in search according to the speed features.
4811 // The threshold set here has to be of square block size.
4812 if (sf->auto_min_max_partition_size) {
4813 partition_none_allowed &=
4814 (bsize <= x->max_partition_size && bsize >= x->min_partition_size);
4815 partition_horz_allowed &=
4816 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4818 partition_vert_allowed &=
4819 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4821 do_split &= bsize > x->min_partition_size;
4823 if (sf->use_square_partition_only) {
4824 partition_horz_allowed &= force_horz_split;
4825 partition_vert_allowed &= force_vert_split;
4828 if (use_ml_based_partitioning) {
4829 if (partition_none_allowed || do_split) do_rect = 0;
4830 if (partition_none_allowed && do_split) {
4831 const int ml_predicted_partition =
4832 ml_predict_var_paritioning(cpi, x, bsize, mi_row, mi_col);
4833 if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
4834 if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
4838 if (!partition_none_allowed && !do_split) do_rect = 1;
4840 ctx->pred_pixel_ready =
4841 !(partition_vert_allowed || partition_horz_allowed || do_split);
4844 if (partition_none_allowed) {
4845 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
4847 ctx->mic = *xd->mi[0];
4848 ctx->mbmi_ext = *x->mbmi_ext;
4849 ctx->skip_txfm[0] = x->skip_txfm[0];
4850 ctx->skip = x->skip;
4852 if (this_rdc.rate != INT_MAX) {
4853 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4854 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4856 RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
4857 if (this_rdc.rdcost < best_rdc.rdcost) {
4858 best_rdc = this_rdc;
4859 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4861 if (!use_ml_based_partitioning) {
4862 int64_t dist_breakout_thr = sf->partition_search_breakout_thr.dist;
4863 int64_t rate_breakout_thr = sf->partition_search_breakout_thr.rate;
4864 dist_breakout_thr >>=
4865 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4866 rate_breakout_thr *= num_pels_log2_lookup[bsize];
4867 if (!x->e_mbd.lossless && this_rdc.rate < rate_breakout_thr &&
4868 this_rdc.dist < dist_breakout_thr) {
4877 // store estimated motion vector
4878 store_pred_mv(x, ctx);
4882 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4883 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4884 sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4885 subsize = get_subsize(bsize, PARTITION_SPLIT);
4886 for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
4887 const int x_idx = (i & 1) * ms;
4888 const int y_idx = (i >> 1) * ms;
4890 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4892 load_pred_mv(x, ctx);
4893 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4894 mi_col + x_idx, subsize, &this_rdc, 0,
4895 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4897 if (this_rdc.rate == INT_MAX) {
4898 vp9_rd_cost_reset(&sum_rdc);
4900 sum_rdc.rate += this_rdc.rate;
4901 sum_rdc.dist += this_rdc.dist;
4902 sum_rdc.rdcost += this_rdc.rdcost;
4906 if (sum_rdc.rdcost < best_rdc.rdcost) {
4908 pc_tree->partitioning = PARTITION_SPLIT;
4910 // skip rectangular partition test when larger block size
4911 // gives better rd cost
4912 if (sf->less_rectangular_check) do_rect &= !partition_none_allowed;
4917 if (partition_horz_allowed && do_rect) {
4918 subsize = get_subsize(bsize, PARTITION_HORZ);
4919 load_pred_mv(x, ctx);
4920 pc_tree->horizontal[0].pred_pixel_ready = 1;
4921 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4922 &pc_tree->horizontal[0]);
4924 pc_tree->horizontal[0].mic = *xd->mi[0];
4925 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4926 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4927 pc_tree->horizontal[0].skip = x->skip;
4929 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
4930 load_pred_mv(x, ctx);
4931 pc_tree->horizontal[1].pred_pixel_ready = 1;
4932 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc,
4933 subsize, &pc_tree->horizontal[1]);
4935 pc_tree->horizontal[1].mic = *xd->mi[0];
4936 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
4937 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
4938 pc_tree->horizontal[1].skip = x->skip;
4940 if (this_rdc.rate == INT_MAX) {
4941 vp9_rd_cost_reset(&sum_rdc);
4943 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4944 this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
4945 sum_rdc.rate += this_rdc.rate;
4946 sum_rdc.dist += this_rdc.dist;
4948 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4952 if (sum_rdc.rdcost < best_rdc.rdcost) {
4954 pc_tree->partitioning = PARTITION_HORZ;
4956 pred_pixel_ready_reset(pc_tree, bsize);
4961 if (partition_vert_allowed && do_rect) {
4962 subsize = get_subsize(bsize, PARTITION_VERT);
4963 load_pred_mv(x, ctx);
4964 pc_tree->vertical[0].pred_pixel_ready = 1;
4965 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4966 &pc_tree->vertical[0]);
4967 pc_tree->vertical[0].mic = *xd->mi[0];
4968 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4969 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4970 pc_tree->vertical[0].skip = x->skip;
4972 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
4973 load_pred_mv(x, ctx);
4974 pc_tree->vertical[1].pred_pixel_ready = 1;
4975 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc,
4976 subsize, &pc_tree->vertical[1]);
4977 pc_tree->vertical[1].mic = *xd->mi[0];
4978 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4979 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4980 pc_tree->vertical[1].skip = x->skip;
4982 if (this_rdc.rate == INT_MAX) {
4983 vp9_rd_cost_reset(&sum_rdc);
4985 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4986 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
4987 sum_rdc.rate += this_rdc.rate;
4988 sum_rdc.dist += this_rdc.dist;
4990 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4994 if (sum_rdc.rdcost < best_rdc.rdcost) {
4996 pc_tree->partitioning = PARTITION_VERT;
4998 pred_pixel_ready_reset(pc_tree, bsize);
5002 *rd_cost = best_rdc;
5004 if (best_rdc.rate == INT_MAX) {
5005 vp9_rd_cost_reset(rd_cost);
5009 // update mode info array
5010 fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
5012 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
5013 int output_enabled = (bsize == BLOCK_64X64);
5014 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
5018 if (bsize == BLOCK_64X64 && do_recon) {
5019 assert(tp_orig < *tp);
5020 assert(best_rdc.rate < INT_MAX);
5021 assert(best_rdc.dist < INT64_MAX);
5023 assert(tp_orig == *tp);
5027 static void nonrd_select_partition(VP9_COMP *cpi, ThreadData *td,
5028 TileDataEnc *tile_data, MODE_INFO **mi,
5029 TOKENEXTRA **tp, int mi_row, int mi_col,
5030 BLOCK_SIZE bsize, int output_enabled,
5031 RD_COST *rd_cost, PC_TREE *pc_tree) {
5032 VP9_COMMON *const cm = &cpi->common;
5033 TileInfo *const tile_info = &tile_data->tile_info;
5034 MACROBLOCK *const x = &td->mb;
5035 MACROBLOCKD *const xd = &x->e_mbd;
5036 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5037 const int mis = cm->mi_stride;
5038 PARTITION_TYPE partition;
5041 BLOCK_SIZE subsize_ref =
5042 (cpi->sf.adapt_partition_source_sad) ? BLOCK_8X8 : BLOCK_16X16;
5044 vp9_rd_cost_reset(&this_rdc);
5045 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5047 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5048 partition = partition_lookup[bsl][subsize];
5050 if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
5051 x->max_partition_size = BLOCK_32X32;
5052 x->min_partition_size = BLOCK_16X16;
5053 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5054 0, INT64_MAX, pc_tree);
5055 } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
5056 subsize >= subsize_ref) {
5057 x->max_partition_size = BLOCK_32X32;
5058 x->min_partition_size = BLOCK_8X8;
5059 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5060 0, INT64_MAX, pc_tree);
5061 } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
5062 x->max_partition_size = BLOCK_16X16;
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);
5067 switch (partition) {
5068 case PARTITION_NONE:
5069 pc_tree->none.pred_pixel_ready = 1;
5070 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5072 pc_tree->none.mic = *xd->mi[0];
5073 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5074 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5075 pc_tree->none.skip = x->skip;
5077 case PARTITION_VERT:
5078 pc_tree->vertical[0].pred_pixel_ready = 1;
5079 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5080 &pc_tree->vertical[0]);
5081 pc_tree->vertical[0].mic = *xd->mi[0];
5082 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5083 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5084 pc_tree->vertical[0].skip = x->skip;
5085 if (mi_col + hbs < cm->mi_cols) {
5086 pc_tree->vertical[1].pred_pixel_ready = 1;
5087 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
5088 &this_rdc, subsize, &pc_tree->vertical[1]);
5089 pc_tree->vertical[1].mic = *xd->mi[0];
5090 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5091 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5092 pc_tree->vertical[1].skip = x->skip;
5093 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5094 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5095 rd_cost->rate += this_rdc.rate;
5096 rd_cost->dist += this_rdc.dist;
5100 case PARTITION_HORZ:
5101 pc_tree->horizontal[0].pred_pixel_ready = 1;
5102 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5103 &pc_tree->horizontal[0]);
5104 pc_tree->horizontal[0].mic = *xd->mi[0];
5105 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5106 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5107 pc_tree->horizontal[0].skip = x->skip;
5108 if (mi_row + hbs < cm->mi_rows) {
5109 pc_tree->horizontal[1].pred_pixel_ready = 1;
5110 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
5111 &this_rdc, subsize, &pc_tree->horizontal[1]);
5112 pc_tree->horizontal[1].mic = *xd->mi[0];
5113 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5114 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5115 pc_tree->horizontal[1].skip = x->skip;
5116 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5117 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5118 rd_cost->rate += this_rdc.rate;
5119 rd_cost->dist += this_rdc.dist;
5124 assert(partition == PARTITION_SPLIT);
5125 subsize = get_subsize(bsize, PARTITION_SPLIT);
5126 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5127 subsize, output_enabled, rd_cost,
5129 nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5130 mi_col + hbs, subsize, output_enabled, &this_rdc,
5132 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5133 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5134 rd_cost->rate += this_rdc.rate;
5135 rd_cost->dist += this_rdc.dist;
5137 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5138 mi_row + hbs, mi_col, subsize, output_enabled,
5139 &this_rdc, pc_tree->split[2]);
5140 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5141 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5142 rd_cost->rate += this_rdc.rate;
5143 rd_cost->dist += this_rdc.dist;
5145 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5146 mi_row + hbs, mi_col + hbs, subsize,
5147 output_enabled, &this_rdc, pc_tree->split[3]);
5148 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5149 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5150 rd_cost->rate += this_rdc.rate;
5151 rd_cost->dist += this_rdc.dist;
5157 if (bsize == BLOCK_64X64 && output_enabled)
5158 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
5161 static void nonrd_use_partition(VP9_COMP *cpi, ThreadData *td,
5162 TileDataEnc *tile_data, MODE_INFO **mi,
5163 TOKENEXTRA **tp, int mi_row, int mi_col,
5164 BLOCK_SIZE bsize, int output_enabled,
5165 RD_COST *dummy_cost, PC_TREE *pc_tree) {
5166 VP9_COMMON *const cm = &cpi->common;
5167 TileInfo *tile_info = &tile_data->tile_info;
5168 MACROBLOCK *const x = &td->mb;
5169 MACROBLOCKD *const xd = &x->e_mbd;
5170 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5171 const int mis = cm->mi_stride;
5172 PARTITION_TYPE partition;
5175 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5177 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5178 partition = partition_lookup[bsl][subsize];
5180 if (output_enabled && bsize != BLOCK_4X4) {
5181 int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
5182 td->counts->partition[ctx][partition]++;
5185 switch (partition) {
5186 case PARTITION_NONE:
5187 pc_tree->none.pred_pixel_ready = 1;
5188 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5189 subsize, &pc_tree->none);
5190 pc_tree->none.mic = *xd->mi[0];
5191 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5192 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5193 pc_tree->none.skip = x->skip;
5194 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5195 subsize, &pc_tree->none);
5197 case PARTITION_VERT:
5198 pc_tree->vertical[0].pred_pixel_ready = 1;
5199 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5200 subsize, &pc_tree->vertical[0]);
5201 pc_tree->vertical[0].mic = *xd->mi[0];
5202 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5203 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5204 pc_tree->vertical[0].skip = x->skip;
5205 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5206 subsize, &pc_tree->vertical[0]);
5207 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
5208 pc_tree->vertical[1].pred_pixel_ready = 1;
5209 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost,
5210 subsize, &pc_tree->vertical[1]);
5211 pc_tree->vertical[1].mic = *xd->mi[0];
5212 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5213 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5214 pc_tree->vertical[1].skip = x->skip;
5215 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
5216 output_enabled, subsize, &pc_tree->vertical[1]);
5219 case PARTITION_HORZ:
5220 pc_tree->horizontal[0].pred_pixel_ready = 1;
5221 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5222 subsize, &pc_tree->horizontal[0]);
5223 pc_tree->horizontal[0].mic = *xd->mi[0];
5224 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5225 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5226 pc_tree->horizontal[0].skip = x->skip;
5227 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5228 subsize, &pc_tree->horizontal[0]);
5230 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
5231 pc_tree->horizontal[1].pred_pixel_ready = 1;
5232 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost,
5233 subsize, &pc_tree->horizontal[1]);
5234 pc_tree->horizontal[1].mic = *xd->mi[0];
5235 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5236 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5237 pc_tree->horizontal[1].skip = x->skip;
5238 encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
5239 output_enabled, subsize, &pc_tree->horizontal[1]);
5243 assert(partition == PARTITION_SPLIT);
5244 subsize = get_subsize(bsize, PARTITION_SPLIT);
5245 if (bsize == BLOCK_8X8) {
5246 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5247 subsize, pc_tree->leaf_split[0]);
5248 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5249 subsize, pc_tree->leaf_split[0]);
5251 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, subsize,
5252 output_enabled, dummy_cost, pc_tree->split[0]);
5253 nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5254 mi_col + hbs, subsize, output_enabled, dummy_cost,
5256 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5257 mi_row + hbs, mi_col, subsize, output_enabled,
5258 dummy_cost, pc_tree->split[2]);
5259 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5260 mi_row + hbs, mi_col + hbs, subsize, output_enabled,
5261 dummy_cost, pc_tree->split[3]);
5266 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
5267 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
5270 // Get a prediction(stored in x->est_pred) for the whole 64x64 superblock.
5271 static void get_estimated_pred(VP9_COMP *cpi, const TileInfo *const tile,
5272 MACROBLOCK *x, int mi_row, int mi_col) {
5273 VP9_COMMON *const cm = &cpi->common;
5274 const int is_key_frame = frame_is_intra_only(cm);
5275 MACROBLOCKD *xd = &x->e_mbd;
5277 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
5279 if (!is_key_frame) {
5280 MODE_INFO *mi = xd->mi[0];
5281 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
5282 const YV12_BUFFER_CONFIG *yv12_g = NULL;
5283 const BLOCK_SIZE bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
5284 (mi_row + 4 < cm->mi_rows);
5285 unsigned int y_sad_g, y_sad_thr;
5286 unsigned int y_sad = UINT_MAX;
5288 assert(yv12 != NULL);
5290 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
5291 cpi->svc.use_gf_temporal_ref_current_layer) {
5292 // For now, GOLDEN will not be used for non-zero spatial layers, since
5293 // it may not be a temporal reference.
5294 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
5297 // Only compute y_sad_g (sad for golden reference) for speed < 8.
5298 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
5299 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
5300 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5301 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5302 y_sad_g = cpi->fn_ptr[bsize].sdf(
5303 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
5304 xd->plane[0].pre[0].stride);
5309 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
5310 cpi->rc.is_src_frame_alt_ref) {
5311 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
5312 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5313 &cm->frame_refs[ALTREF_FRAME - 1].sf);
5314 mi->ref_frame[0] = ALTREF_FRAME;
5317 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5318 &cm->frame_refs[LAST_FRAME - 1].sf);
5319 mi->ref_frame[0] = LAST_FRAME;
5321 mi->ref_frame[1] = NONE;
5322 mi->sb_type = BLOCK_64X64;
5323 mi->mv[0].as_int = 0;
5324 mi->interp_filter = BILINEAR;
5327 const MV dummy_mv = { 0, 0 };
5328 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
5330 x->sb_use_mv_part = 1;
5331 x->sb_mvcol_part = mi->mv[0].as_mv.col;
5332 x->sb_mvrow_part = mi->mv[0].as_mv.row;
5335 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
5336 // are close if short_circuit_low_temp_var is on.
5337 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
5338 if (y_sad_g < y_sad_thr) {
5339 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5340 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5341 mi->ref_frame[0] = GOLDEN_FRAME;
5342 mi->mv[0].as_int = 0;
5344 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
5347 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
5348 xd->plane[0].dst.buf = x->est_pred;
5349 xd->plane[0].dst.stride = 64;
5350 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
5352 #if CONFIG_VP9_HIGHBITDEPTH
5354 case 8: memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); break;
5356 memset(x->est_pred, 128 * 4, 64 * 64 * sizeof(x->est_pred[0]));
5359 memset(x->est_pred, 128 * 16, 64 * 64 * sizeof(x->est_pred[0]));
5363 memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0]));
5364 #endif // CONFIG_VP9_HIGHBITDEPTH
5368 static void encode_nonrd_sb_row(VP9_COMP *cpi, ThreadData *td,
5369 TileDataEnc *tile_data, int mi_row,
5371 SPEED_FEATURES *const sf = &cpi->sf;
5372 VP9_COMMON *const cm = &cpi->common;
5373 TileInfo *const tile_info = &tile_data->tile_info;
5374 MACROBLOCK *const x = &td->mb;
5375 MACROBLOCKD *const xd = &x->e_mbd;
5376 const int mi_col_start = tile_info->mi_col_start;
5377 const int mi_col_end = tile_info->mi_col_end;
5379 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
5380 const int num_sb_cols =
5381 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
5384 // Initialize the left context for the new SB row
5385 memset(&xd->left_context, 0, sizeof(xd->left_context));
5386 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
5388 // Code each SB in the row
5389 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
5390 mi_col += MI_BLOCK_SIZE, ++sb_col_in_tile) {
5391 const struct segmentation *const seg = &cm->seg;
5393 const int idx_str = cm->mi_stride * mi_row + mi_col;
5394 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
5395 PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
5396 BLOCK_SIZE bsize = BLOCK_64X64;
5400 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
5403 if (cpi->use_skin_detection) {
5404 vp9_compute_skin_sb(cpi, BLOCK_16X16, mi_row, mi_col);
5407 x->source_variance = UINT_MAX;
5408 for (i = 0; i < MAX_REF_FRAMES; ++i) {
5409 x->pred_mv[i].row = INT16_MAX;
5410 x->pred_mv[i].col = INT16_MAX;
5412 vp9_rd_cost_init(&dummy_rdc);
5413 x->color_sensitivity[0] = 0;
5414 x->color_sensitivity[1] = 0;
5416 x->skip_low_source_sad = 0;
5417 x->lowvar_highsumdiff = 0;
5418 x->content_state_sb = 0;
5419 x->zero_temp_sad_source = 0;
5420 x->sb_use_mv_part = 0;
5421 x->sb_mvcol_part = 0;
5422 x->sb_mvrow_part = 0;
5423 x->sb_pickmode_part = 0;
5424 x->arf_frame_usage = 0;
5425 x->lastgolden_frame_usage = 0;
5428 const uint8_t *const map =
5429 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
5430 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
5431 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
5433 partition_search_type = FIXED_PARTITION;
5437 if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
5438 int shift = cpi->Source->y_stride * (mi_row << 3) + (mi_col << 3);
5439 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5440 int64_t source_sad = avg_source_sad(cpi, x, shift, sb_offset2);
5441 if (sf->adapt_partition_source_sad &&
5442 (cpi->oxcf.rc_mode == VPX_VBR && !cpi->rc.is_src_frame_alt_ref &&
5443 source_sad > sf->adapt_partition_thresh &&
5444 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)))
5445 partition_search_type = REFERENCE_PARTITION;
5448 // Set the partition type of the 64X64 block
5449 switch (partition_search_type) {
5450 case VAR_BASED_PARTITION:
5451 // TODO(jingning, marpan): The mode decision and encoding process
5452 // support both intra and inter sub8x8 block coding for RTC mode.
5453 // Tune the thresholds accordingly to use sub8x8 block coding for
5454 // coding performance improvement.
5455 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5456 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5457 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5459 case ML_BASED_PARTITION:
5460 get_estimated_pred(cpi, tile_info, x, mi_row, mi_col);
5461 x->max_partition_size = BLOCK_64X64;
5462 x->min_partition_size = BLOCK_8X8;
5463 x->sb_pickmode_part = 1;
5464 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5465 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5468 case SOURCE_VAR_BASED_PARTITION:
5469 set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
5470 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5471 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5473 case FIXED_PARTITION:
5474 if (!seg_skip) bsize = sf->always_this_block_size;
5475 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
5476 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5477 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5480 assert(partition_search_type == REFERENCE_PARTITION);
5481 x->sb_pickmode_part = 1;
5482 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
5483 // Use nonrd_pick_partition on scene-cut for VBR mode.
5484 // nonrd_pick_partition does not support 4x4 partition, so avoid it
5485 // on key frame for now.
5486 if ((cpi->oxcf.rc_mode == VPX_VBR && cpi->rc.high_source_sad &&
5487 cpi->oxcf.speed < 6 && !frame_is_intra_only(cm) &&
5488 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
5489 // Use lower max_partition_size for low resoultions.
5490 if (cm->width <= 352 && cm->height <= 288)
5491 x->max_partition_size = BLOCK_32X32;
5493 x->max_partition_size = BLOCK_64X64;
5494 x->min_partition_size = BLOCK_8X8;
5495 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5496 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5499 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5500 // TODO(marpan): Seems like nonrd_select_partition does not support
5501 // 4x4 partition. Since 4x4 is used on key frame, use this switch
5503 if (frame_is_intra_only(cm))
5504 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5505 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5507 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5508 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5514 // Update ref_frame usage for inter frame if this group is ARF group.
5515 if (!cpi->rc.is_src_frame_alt_ref && !cpi->refresh_golden_frame &&
5516 !cpi->refresh_alt_ref_frame && cpi->rc.alt_ref_gf_group &&
5517 cpi->sf.use_altref_onepass) {
5518 int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5519 if (cpi->count_arf_frame_usage != NULL)
5520 cpi->count_arf_frame_usage[sboffset] = x->arf_frame_usage;
5521 if (cpi->count_lastgolden_frame_usage != NULL)
5522 cpi->count_lastgolden_frame_usage[sboffset] = x->lastgolden_frame_usage;
5525 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
5526 sb_col_in_tile, num_sb_cols);
5529 // end RTC play code
5531 static INLINE uint32_t variance(const diff *const d) {
5532 return d->sse - (uint32_t)(((int64_t)d->sum * d->sum) >> 8);
5535 #if CONFIG_VP9_HIGHBITDEPTH
5536 static INLINE uint32_t variance_highbd(diff *const d) {
5537 const int64_t var = (int64_t)d->sse - (((int64_t)d->sum * d->sum) >> 8);
5538 return (var >= 0) ? (uint32_t)var : 0;
5540 #endif // CONFIG_VP9_HIGHBITDEPTH
5542 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
5543 const SPEED_FEATURES *const sf = &cpi->sf;
5544 const VP9_COMMON *const cm = &cpi->common;
5546 const uint8_t *src = cpi->Source->y_buffer;
5547 const uint8_t *last_src = cpi->Last_Source->y_buffer;
5548 const int src_stride = cpi->Source->y_stride;
5549 const int last_stride = cpi->Last_Source->y_stride;
5551 // Pick cutoff threshold
5552 const int cutoff = (VPXMIN(cm->width, cm->height) >= 720)
5553 ? (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100)
5554 : (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
5555 DECLARE_ALIGNED(16, int, hist[VAR_HIST_BINS]);
5556 diff *var16 = cpi->source_diff_var;
5561 memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
5563 for (i = 0; i < cm->mb_rows; i++) {
5564 for (j = 0; j < cm->mb_cols; j++) {
5565 #if CONFIG_VP9_HIGHBITDEPTH
5566 if (cm->use_highbitdepth) {
5567 switch (cm->bit_depth) {
5569 vpx_highbd_8_get16x16var(src, src_stride, last_src, last_stride,
5570 &var16->sse, &var16->sum);
5571 var16->var = variance(var16);
5574 vpx_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
5575 &var16->sse, &var16->sum);
5576 var16->var = variance_highbd(var16);
5579 assert(cm->bit_depth == VPX_BITS_12);
5580 vpx_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
5581 &var16->sse, &var16->sum);
5582 var16->var = variance_highbd(var16);
5586 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5588 var16->var = variance(var16);
5591 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5593 var16->var = variance(var16);
5594 #endif // CONFIG_VP9_HIGHBITDEPTH
5596 if (var16->var >= VAR_HIST_MAX_BG_VAR)
5597 hist[VAR_HIST_BINS - 1]++;
5599 hist[var16->var / VAR_HIST_FACTOR]++;
5606 src = src - cm->mb_cols * 16 + 16 * src_stride;
5607 last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
5610 cpi->source_var_thresh = 0;
5612 if (hist[VAR_HIST_BINS - 1] < cutoff) {
5613 for (i = 0; i < VAR_HIST_BINS - 1; i++) {
5617 cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
5623 return sf->search_type_check_frequency;
5626 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
5627 VP9_COMMON *const cm = &cpi->common;
5628 SPEED_FEATURES *const sf = &cpi->sf;
5630 if (cm->frame_type == KEY_FRAME) {
5631 // For key frame, use SEARCH_PARTITION.
5632 sf->partition_search_type = SEARCH_PARTITION;
5633 } else if (cm->intra_only) {
5634 sf->partition_search_type = FIXED_PARTITION;
5636 if (cm->last_width != cm->width || cm->last_height != cm->height) {
5637 if (cpi->source_diff_var) vpx_free(cpi->source_diff_var);
5639 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
5640 vpx_calloc(cm->MBs, sizeof(diff)));
5643 if (!cpi->frames_till_next_var_check)
5644 cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
5646 if (cpi->frames_till_next_var_check > 0) {
5647 sf->partition_search_type = FIXED_PARTITION;
5648 cpi->frames_till_next_var_check--;
5653 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
5654 unsigned int intra_count = 0, inter_count = 0;
5657 for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
5658 intra_count += td->counts->intra_inter[j][0];
5659 inter_count += td->counts->intra_inter[j][1];
5662 return (intra_count << 2) < inter_count && cm->frame_type != KEY_FRAME &&
5666 void vp9_init_tile_data(VP9_COMP *cpi) {
5667 VP9_COMMON *const cm = &cpi->common;
5668 const int tile_cols = 1 << cm->log2_tile_cols;
5669 const int tile_rows = 1 << cm->log2_tile_rows;
5670 int tile_col, tile_row;
5671 TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
5672 TOKENLIST *tplist = cpi->tplist[0][0];
5674 int tplist_count = 0;
5676 if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
5677 if (cpi->tile_data != NULL) vpx_free(cpi->tile_data);
5680 vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
5681 cpi->allocated_tiles = tile_cols * tile_rows;
5683 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5684 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5685 TileDataEnc *tile_data =
5686 &cpi->tile_data[tile_row * tile_cols + tile_col];
5688 for (i = 0; i < BLOCK_SIZES; ++i) {
5689 for (j = 0; j < MAX_MODES; ++j) {
5690 tile_data->thresh_freq_fact[i][j] = RD_THRESH_INIT_FACT;
5691 #if CONFIG_CONSISTENT_RECODE
5692 tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5694 tile_data->mode_map[i][j] = j;
5697 #if CONFIG_MULTITHREAD
5698 tile_data->row_base_thresh_freq_fact = NULL;
5703 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
5704 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5705 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5706 TileInfo *tile_info = &this_tile->tile_info;
5707 if (cpi->sf.adaptive_rd_thresh_row_mt &&
5708 this_tile->row_base_thresh_freq_fact == NULL)
5709 vp9_row_mt_alloc_rd_thresh(cpi, this_tile);
5710 vp9_tile_init(tile_info, cm, tile_row, tile_col);
5712 cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
5713 pre_tok = cpi->tile_tok[tile_row][tile_col];
5714 tile_tok = allocated_tokens(*tile_info);
5716 cpi->tplist[tile_row][tile_col] = tplist + tplist_count;
5717 tplist = cpi->tplist[tile_row][tile_col];
5718 tplist_count = get_num_vert_units(*tile_info, MI_BLOCK_SIZE_LOG2);
5723 void vp9_encode_sb_row(VP9_COMP *cpi, ThreadData *td, int tile_row,
5724 int tile_col, int mi_row) {
5725 VP9_COMMON *const cm = &cpi->common;
5726 const int tile_cols = 1 << cm->log2_tile_cols;
5727 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5728 const TileInfo *const tile_info = &this_tile->tile_info;
5729 TOKENEXTRA *tok = NULL;
5731 int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
5733 tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile_info->mi_row_start) >>
5735 get_start_tok(cpi, tile_row, tile_col, mi_row, &tok);
5736 cpi->tplist[tile_row][tile_col][tile_sb_row].start = tok;
5738 if (cpi->sf.use_nonrd_pick_mode)
5739 encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5741 encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
5743 cpi->tplist[tile_row][tile_col][tile_sb_row].stop = tok;
5744 cpi->tplist[tile_row][tile_col][tile_sb_row].count =
5745 (unsigned int)(cpi->tplist[tile_row][tile_col][tile_sb_row].stop -
5746 cpi->tplist[tile_row][tile_col][tile_sb_row].start);
5747 assert(tok - cpi->tplist[tile_row][tile_col][tile_sb_row].start <=
5748 get_token_alloc(MI_BLOCK_SIZE >> 1, tile_mb_cols));
5753 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td, int tile_row,
5755 VP9_COMMON *const cm = &cpi->common;
5756 const int tile_cols = 1 << cm->log2_tile_cols;
5757 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5758 const TileInfo *const tile_info = &this_tile->tile_info;
5759 const int mi_row_start = tile_info->mi_row_start;
5760 const int mi_row_end = tile_info->mi_row_end;
5763 for (mi_row = mi_row_start; mi_row < mi_row_end; mi_row += MI_BLOCK_SIZE)
5764 vp9_encode_sb_row(cpi, td, tile_row, tile_col, mi_row);
5767 static void encode_tiles(VP9_COMP *cpi) {
5768 VP9_COMMON *const cm = &cpi->common;
5769 const int tile_cols = 1 << cm->log2_tile_cols;
5770 const int tile_rows = 1 << cm->log2_tile_rows;
5771 int tile_col, tile_row;
5773 vp9_init_tile_data(cpi);
5775 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5776 for (tile_col = 0; tile_col < tile_cols; ++tile_col)
5777 vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
5780 #if CONFIG_FP_MB_STATS
5781 static int input_fpmb_stats(FIRSTPASS_MB_STATS *firstpass_mb_stats,
5782 VP9_COMMON *cm, uint8_t **this_frame_mb_stats) {
5783 uint8_t *mb_stats_in = firstpass_mb_stats->mb_stats_start +
5784 cm->current_video_frame * cm->MBs * sizeof(uint8_t);
5786 if (mb_stats_in > firstpass_mb_stats->mb_stats_end) return EOF;
5788 *this_frame_mb_stats = mb_stats_in;
5794 static int compare_kmeans_data(const void *a, const void *b) {
5795 if (((const KMEANS_DATA *)a)->value > ((const KMEANS_DATA *)b)->value) {
5797 } else if (((const KMEANS_DATA *)a)->value <
5798 ((const KMEANS_DATA *)b)->value) {
5805 static void compute_boundary_ls(const double *ctr_ls, int k,
5806 double *boundary_ls) {
5807 // boundary_ls[j] is the upper bound of data centered at ctr_ls[j]
5809 for (j = 0; j < k - 1; ++j) {
5810 boundary_ls[j] = (ctr_ls[j] + ctr_ls[j + 1]) / 2.;
5812 boundary_ls[k - 1] = DBL_MAX;
5815 int vp9_get_group_idx(double value, double *boundary_ls, int k) {
5817 while (value >= boundary_ls[group_idx]) {
5819 if (group_idx == k - 1) {
5826 void vp9_kmeans(double *ctr_ls, double *boundary_ls, int *count_ls, int k,
5827 KMEANS_DATA *arr, int size) {
5831 double sum[MAX_KMEANS_GROUPS];
5832 int count[MAX_KMEANS_GROUPS];
5834 vpx_clear_system_state();
5836 assert(k >= 2 && k <= MAX_KMEANS_GROUPS);
5838 qsort(arr, size, sizeof(*arr), compare_kmeans_data);
5840 // initialize the center points
5841 for (j = 0; j < k; ++j) {
5842 ctr_ls[j] = arr[(size * (2 * j + 1)) / (2 * k)].value;
5845 for (itr = 0; itr < 10; ++itr) {
5846 compute_boundary_ls(ctr_ls, k, boundary_ls);
5847 for (i = 0; i < MAX_KMEANS_GROUPS; ++i) {
5852 // Both the data and centers are sorted in ascending order.
5853 // As each data point is processed in order, its corresponding group index
5854 // can only increase. So we only need to reset the group index to zero here.
5856 for (i = 0; i < size; ++i) {
5857 while (arr[i].value >= boundary_ls[group_idx]) {
5858 // place samples into clusters
5860 if (group_idx == k - 1) {
5864 sum[group_idx] += arr[i].value;
5868 for (group_idx = 0; group_idx < k; ++group_idx) {
5869 if (count[group_idx] > 0)
5870 ctr_ls[group_idx] = sum[group_idx] / count[group_idx];
5873 count[group_idx] = 0;
5877 // compute group_idx, boundary_ls and count_ls
5878 for (j = 0; j < k; ++j) {
5881 compute_boundary_ls(ctr_ls, k, boundary_ls);
5883 for (i = 0; i < size; ++i) {
5884 while (arr[i].value >= boundary_ls[group_idx]) {
5886 if (group_idx == k - 1) {
5890 arr[i].group_idx = group_idx;
5891 ++count_ls[group_idx];
5895 static void encode_frame_internal(VP9_COMP *cpi) {
5896 SPEED_FEATURES *const sf = &cpi->sf;
5897 ThreadData *const td = &cpi->td;
5898 MACROBLOCK *const x = &td->mb;
5899 VP9_COMMON *const cm = &cpi->common;
5900 MACROBLOCKD *const xd = &x->e_mbd;
5901 const int gf_group_index = cpi->twopass.gf_group.index;
5903 xd->mi = cm->mi_grid_visible;
5905 vp9_zero(*td->counts);
5906 vp9_zero(cpi->td.rd_counts);
5908 xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
5909 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
5911 #if CONFIG_VP9_HIGHBITDEPTH
5912 if (cm->use_highbitdepth)
5913 x->fwd_txfm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
5915 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5916 x->highbd_inv_txfm_add =
5917 xd->lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
5919 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5920 #endif // CONFIG_VP9_HIGHBITDEPTH
5921 x->inv_txfm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
5922 #if CONFIG_CONSISTENT_RECODE
5923 x->optimize = sf->optimize_coefficients == 1 && cpi->oxcf.pass != 1;
5925 if (xd->lossless) x->optimize = 0;
5926 x->sharpness = cpi->oxcf.sharpness;
5927 x->adjust_rdmult_by_segment = (cpi->oxcf.aq_mode == VARIANCE_AQ);
5929 cm->tx_mode = select_tx_mode(cpi, xd);
5931 vp9_frame_init_quantizer(cpi);
5933 vp9_initialize_rd_consts(cpi);
5934 vp9_initialize_me_consts(cpi, x, cm->base_qindex);
5935 init_encode_frame_mb_context(cpi);
5936 cm->use_prev_frame_mvs =
5937 !cm->error_resilient_mode && cm->width == cm->last_width &&
5938 cm->height == cm->last_height && !cm->intra_only && cm->last_show_frame;
5939 // Special case: set prev_mi to NULL when the previous mode info
5940 // context cannot be used.
5942 cm->use_prev_frame_mvs ? cm->prev_mip + cm->mi_stride + 1 : NULL;
5944 x->quant_fp = cpi->sf.use_quant_fp;
5945 vp9_zero(x->skip_txfm);
5946 if (sf->use_nonrd_pick_mode) {
5947 // Initialize internal buffer pointers for rtc coding, where non-RD
5948 // mode decision is used and hence no buffer pointer swap needed.
5950 struct macroblock_plane *const p = x->plane;
5951 struct macroblockd_plane *const pd = xd->plane;
5952 PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
5954 for (i = 0; i < MAX_MB_PLANE; ++i) {
5955 p[i].coeff = ctx->coeff_pbuf[i][0];
5956 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
5957 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
5958 p[i].eobs = ctx->eobs_pbuf[i][0];
5960 vp9_zero(x->zcoeff_blk);
5962 if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0 &&
5963 !(cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) &&
5965 cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
5967 if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
5968 source_var_based_partition_search_method(cpi);
5969 } else if (gf_group_index && gf_group_index < MAX_ARF_GOP_SIZE &&
5970 cpi->sf.enable_tpl_model) {
5971 TplDepFrame *tpl_frame = &cpi->tpl_stats[cpi->twopass.gf_group.index];
5972 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
5974 int tpl_stride = tpl_frame->stride;
5975 int64_t intra_cost_base = 0;
5976 int64_t mc_dep_cost_base = 0;
5979 for (row = 0; row < cm->mi_rows && tpl_frame->is_valid; ++row) {
5980 for (col = 0; col < cm->mi_cols; ++col) {
5981 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
5982 intra_cost_base += this_stats->intra_cost;
5983 mc_dep_cost_base += this_stats->mc_dep_cost;
5987 vpx_clear_system_state();
5989 if (tpl_frame->is_valid)
5990 cpi->rd.r0 = (double)intra_cost_base / mc_dep_cost_base;
5993 // Frame segmentation
5994 if (cpi->sf.enable_wiener_variance) build_kmeans_segmentation(cpi);
5997 struct vpx_usec_timer emr_timer;
5998 vpx_usec_timer_start(&emr_timer);
6000 #if CONFIG_FP_MB_STATS
6001 if (cpi->use_fp_mb_stats) {
6002 input_fpmb_stats(&cpi->twopass.firstpass_mb_stats, cm,
6003 &cpi->twopass.this_frame_mb_stats);
6008 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
6009 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
6010 // If allowed, encoding tiles in parallel with one thread handling one
6011 // tile when row based multi-threading is disabled.
6012 if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
6013 vp9_encode_tiles_mt(cpi);
6017 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
6018 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
6019 vp9_encode_tiles_row_mt(cpi);
6022 vpx_usec_timer_mark(&emr_timer);
6023 cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
6026 sf->skip_encode_frame =
6027 sf->skip_encode_sb ? get_skip_encode_frame(cm, td) : 0;
6030 // Keep record of the total distortion this time around for future use
6031 cpi->last_frame_distortion = cpi->frame_distortion;
6035 static INTERP_FILTER get_interp_filter(
6036 const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
6037 if (!is_alt_ref && threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
6038 threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
6039 threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
6040 return EIGHTTAP_SMOOTH;
6041 } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
6042 threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
6043 return EIGHTTAP_SHARP;
6044 } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
6051 static int compute_frame_aq_offset(struct VP9_COMP *cpi) {
6052 VP9_COMMON *const cm = &cpi->common;
6053 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
6054 struct segmentation *const seg = &cm->seg;
6062 for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
6063 MODE_INFO **mi_8x8 = mi_8x8_ptr;
6064 for (mi_col = 0; mi_col < cm->mi_cols; mi_col++, mi_8x8++) {
6065 segment_id = mi_8x8[0]->segment_id;
6066 qdelta_index = get_segdata(seg, segment_id, SEG_LVL_ALT_Q);
6067 sum_delta += qdelta_index;
6070 mi_8x8_ptr += cm->mi_stride;
6073 return sum_delta / (cm->mi_rows * cm->mi_cols);
6076 #if CONFIG_CONSISTENT_RECODE
6077 static void restore_encode_params(VP9_COMP *cpi) {
6078 VP9_COMMON *const cm = &cpi->common;
6079 const int tile_cols = 1 << cm->log2_tile_cols;
6080 const int tile_rows = 1 << cm->log2_tile_rows;
6081 int tile_col, tile_row;
6083 RD_OPT *rd_opt = &cpi->rd;
6084 for (i = 0; i < MAX_REF_FRAMES; i++) {
6085 for (j = 0; j < REFERENCE_MODES; j++)
6086 rd_opt->prediction_type_threshes[i][j] =
6087 rd_opt->prediction_type_threshes_prev[i][j];
6089 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
6090 rd_opt->filter_threshes[i][j] = rd_opt->filter_threshes_prev[i][j];
6093 if (cpi->tile_data != NULL) {
6094 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
6095 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
6096 TileDataEnc *tile_data =
6097 &cpi->tile_data[tile_row * tile_cols + tile_col];
6098 for (i = 0; i < BLOCK_SIZES; ++i) {
6099 for (j = 0; j < MAX_MODES; ++j) {
6100 tile_data->thresh_freq_fact[i][j] =
6101 tile_data->thresh_freq_fact_prev[i][j];
6107 cm->interp_filter = cpi->sf.default_interp_filter;
6111 void vp9_encode_frame(VP9_COMP *cpi) {
6112 VP9_COMMON *const cm = &cpi->common;
6114 #if CONFIG_CONSISTENT_RECODE
6115 restore_encode_params(cpi);
6118 // In the longer term the encoder should be generalized to match the
6119 // decoder such that we allow compound where one of the 3 buffers has a
6120 // different sign bias and that buffer is then the fixed ref. However, this
6121 // requires further work in the rd loop. For now the only supported encoder
6122 // side behavior is where the ALT ref buffer has opposite sign bias to
6124 if (!frame_is_intra_only(cm)) {
6125 if (vp9_compound_reference_allowed(cm)) {
6126 cpi->allow_comp_inter_inter = 1;
6127 vp9_setup_compound_reference_mode(cm);
6129 cpi->allow_comp_inter_inter = 0;
6133 if (cpi->sf.frame_parameter_update) {
6135 RD_OPT *const rd_opt = &cpi->rd;
6136 FRAME_COUNTS *counts = cpi->td.counts;
6137 RD_COUNTS *const rdc = &cpi->td.rd_counts;
6139 // This code does a single RD pass over the whole frame assuming
6140 // either compound, single or hybrid prediction as per whatever has
6141 // worked best for that type of frame in the past.
6142 // It also predicts whether another coding mode would have worked
6143 // better than this coding mode. If that is the case, it remembers
6144 // that for subsequent frames.
6145 // It also does the same analysis for transform size selection.
6146 const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
6147 int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
6148 int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
6149 const int is_alt_ref = frame_type == ALTREF_FRAME;
6151 /* prediction (compound, single or hybrid) mode selection */
6152 if (is_alt_ref || !cpi->allow_comp_inter_inter)
6153 cm->reference_mode = SINGLE_REFERENCE;
6154 else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
6155 mode_thrs[COMPOUND_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT] &&
6156 check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
6157 cm->reference_mode = COMPOUND_REFERENCE;
6158 else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
6159 cm->reference_mode = SINGLE_REFERENCE;
6161 cm->reference_mode = REFERENCE_MODE_SELECT;
6163 if (cm->interp_filter == SWITCHABLE)
6164 cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
6166 encode_frame_internal(cpi);
6168 for (i = 0; i < REFERENCE_MODES; ++i)
6169 mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
6171 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
6172 filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
6174 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6175 int single_count_zero = 0;
6176 int comp_count_zero = 0;
6178 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6179 single_count_zero += counts->comp_inter[i][0];
6180 comp_count_zero += counts->comp_inter[i][1];
6183 if (comp_count_zero == 0) {
6184 cm->reference_mode = SINGLE_REFERENCE;
6185 vp9_zero(counts->comp_inter);
6186 } else if (single_count_zero == 0) {
6187 cm->reference_mode = COMPOUND_REFERENCE;
6188 vp9_zero(counts->comp_inter);
6192 if (cm->tx_mode == TX_MODE_SELECT) {
6194 int count8x8_lp = 0, count8x8_8x8p = 0;
6195 int count16x16_16x16p = 0, count16x16_lp = 0;
6198 for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
6199 count4x4 += counts->tx.p32x32[i][TX_4X4];
6200 count4x4 += counts->tx.p16x16[i][TX_4X4];
6201 count4x4 += counts->tx.p8x8[i][TX_4X4];
6203 count8x8_lp += counts->tx.p32x32[i][TX_8X8];
6204 count8x8_lp += counts->tx.p16x16[i][TX_8X8];
6205 count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
6207 count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
6208 count16x16_lp += counts->tx.p32x32[i][TX_16X16];
6209 count32x32 += counts->tx.p32x32[i][TX_32X32];
6211 if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
6213 cm->tx_mode = ALLOW_8X8;
6214 reset_skip_tx_size(cm, TX_8X8);
6215 } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
6216 count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
6217 cm->tx_mode = ONLY_4X4;
6218 reset_skip_tx_size(cm, TX_4X4);
6219 } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
6220 cm->tx_mode = ALLOW_32X32;
6221 } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
6222 cm->tx_mode = ALLOW_16X16;
6223 reset_skip_tx_size(cm, TX_16X16);
6227 FRAME_COUNTS *counts = cpi->td.counts;
6228 cm->reference_mode = SINGLE_REFERENCE;
6229 if (cpi->allow_comp_inter_inter && cpi->sf.use_compound_nonrd_pickmode &&
6230 cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
6231 cm->frame_type != KEY_FRAME)
6232 cm->reference_mode = REFERENCE_MODE_SELECT;
6234 encode_frame_internal(cpi);
6236 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6237 int single_count_zero = 0;
6238 int comp_count_zero = 0;
6240 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6241 single_count_zero += counts->comp_inter[i][0];
6242 comp_count_zero += counts->comp_inter[i][1];
6244 if (comp_count_zero == 0) {
6245 cm->reference_mode = SINGLE_REFERENCE;
6246 vp9_zero(counts->comp_inter);
6247 } else if (single_count_zero == 0) {
6248 cm->reference_mode = COMPOUND_REFERENCE;
6249 vp9_zero(counts->comp_inter);
6254 // If segmented AQ is enabled compute the average AQ weighting.
6255 if (cm->seg.enabled && (cpi->oxcf.aq_mode != NO_AQ) &&
6256 (cm->seg.update_map || cm->seg.update_data)) {
6257 cm->seg.aq_av_offset = compute_frame_aq_offset(cpi);
6261 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
6262 const PREDICTION_MODE y_mode = mi->mode;
6263 const PREDICTION_MODE uv_mode = mi->uv_mode;
6264 const BLOCK_SIZE bsize = mi->sb_type;
6266 if (bsize < BLOCK_8X8) {
6268 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
6269 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
6270 for (idy = 0; idy < 2; idy += num_4x4_h)
6271 for (idx = 0; idx < 2; idx += num_4x4_w)
6272 ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
6274 ++counts->y_mode[size_group_lookup[bsize]][y_mode];
6277 ++counts->uv_mode[y_mode][uv_mode];
6280 static void update_zeromv_cnt(VP9_COMP *const cpi, const MODE_INFO *const mi,
6281 int mi_row, int mi_col, BLOCK_SIZE bsize) {
6282 const VP9_COMMON *const cm = &cpi->common;
6283 MV mv = mi->mv[0].as_mv;
6284 const int bw = num_8x8_blocks_wide_lookup[bsize];
6285 const int bh = num_8x8_blocks_high_lookup[bsize];
6286 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
6287 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
6288 const int block_index = mi_row * cm->mi_cols + mi_col;
6290 for (y = 0; y < ymis; y++)
6291 for (x = 0; x < xmis; x++) {
6292 int map_offset = block_index + y * cm->mi_cols + x;
6293 if (mi->ref_frame[0] == LAST_FRAME && is_inter_block(mi) &&
6294 mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
6295 if (abs(mv.row) < 8 && abs(mv.col) < 8) {
6296 if (cpi->consec_zero_mv[map_offset] < 255)
6297 cpi->consec_zero_mv[map_offset]++;
6299 cpi->consec_zero_mv[map_offset] = 0;
6305 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
6306 int output_enabled, int mi_row, int mi_col,
6307 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
6308 VP9_COMMON *const cm = &cpi->common;
6309 MACROBLOCK *const x = &td->mb;
6310 MACROBLOCKD *const xd = &x->e_mbd;
6311 MODE_INFO *mi = xd->mi[0];
6312 const int seg_skip =
6313 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP);
6314 x->skip_recode = !x->select_tx_size && mi->sb_type >= BLOCK_8X8 &&
6315 cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
6316 cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
6317 cpi->sf.allow_skip_recode;
6319 if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
6320 memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
6322 x->skip_optimize = ctx->is_coded;
6324 x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
6325 x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
6326 x->q_index < QIDX_SKIP_THRESH);
6328 if (x->skip_encode) return;
6330 if (!is_inter_block(mi)) {
6332 #if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6333 if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
6334 (xd->above_mi == NULL || xd->left_mi == NULL) &&
6335 need_top_left[mi->uv_mode])
6337 #endif // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6339 for (plane = 0; plane < MAX_MB_PLANE; ++plane)
6340 vp9_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane, 1);
6341 if (output_enabled) sum_intra_stats(td->counts, mi);
6342 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6343 VPXMAX(bsize, BLOCK_8X8));
6346 const int is_compound = has_second_ref(mi);
6347 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
6348 for (ref = 0; ref < 1 + is_compound; ++ref) {
6349 YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, mi->ref_frame[ref]);
6350 assert(cfg != NULL);
6351 vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
6352 &xd->block_refs[ref]->sf);
6354 if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
6355 vp9_build_inter_predictors_sby(xd, mi_row, mi_col,
6356 VPXMAX(bsize, BLOCK_8X8));
6358 vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col,
6359 VPXMAX(bsize, BLOCK_8X8));
6361 vp9_encode_sb(x, VPXMAX(bsize, BLOCK_8X8));
6362 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6363 VPXMAX(bsize, BLOCK_8X8));
6370 if (output_enabled) {
6371 if (cm->tx_mode == TX_MODE_SELECT && mi->sb_type >= BLOCK_8X8 &&
6372 !(is_inter_block(mi) && mi->skip)) {
6373 ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
6374 &td->counts->tx)[mi->tx_size];
6376 // The new intra coding scheme requires no change of transform size
6377 if (is_inter_block(mi)) {
6378 mi->tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
6379 max_txsize_lookup[bsize]);
6381 mi->tx_size = (bsize >= BLOCK_8X8) ? mi->tx_size : TX_4X4;
6385 ++td->counts->tx.tx_totals[mi->tx_size];
6386 ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])];
6387 if (cm->seg.enabled && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
6388 vp9_cyclic_refresh_update_sb_postencode(cpi, mi, mi_row, mi_col, bsize);
6389 if (cpi->oxcf.pass == 0 && cpi->svc.temporal_layer_id == 0 &&
6392 !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
6393 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)))
6394 update_zeromv_cnt(cpi, mi, mi_row, mi_col, bsize);