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;
259 x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
262 static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
263 MACROBLOCK *const x, int mi_row, int mi_col,
265 VP9_COMMON *const cm = &cpi->common;
266 MACROBLOCKD *const xd = &x->e_mbd;
267 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
268 const int mi_height = num_8x8_blocks_high_lookup[bsize];
269 MvLimits *const mv_limits = &x->mv_limits;
271 set_skip_context(xd, mi_row, mi_col);
273 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
275 // Set up destination pointers.
276 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
278 // Set up limit values for MV components.
279 // Mv beyond the range do not produce new/different prediction block.
280 mv_limits->row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
281 mv_limits->col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
282 mv_limits->row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
283 mv_limits->col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
285 // Set up distance of MB to edge of frame in 1/8th pel units.
286 assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
287 set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width, cm->mi_rows,
290 // Set up source buffers.
291 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
294 x->rddiv = cpi->rd.RDDIV;
295 x->rdmult = cpi->rd.RDMULT;
297 // required by vp9_append_sub8x8_mvs_for_idx() and vp9_find_best_ref_mvs()
301 static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
302 int mi_row, int mi_col,
304 const int block_width =
305 VPXMIN(num_8x8_blocks_wide_lookup[bsize], cm->mi_cols - mi_col);
306 const int block_height =
307 VPXMIN(num_8x8_blocks_high_lookup[bsize], cm->mi_rows - mi_row);
308 const int mi_stride = xd->mi_stride;
309 MODE_INFO *const src_mi = xd->mi[0];
312 for (j = 0; j < block_height; ++j)
313 for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
316 static void set_block_size(VP9_COMP *const cpi, MACROBLOCK *const x,
317 MACROBLOCKD *const xd, int mi_row, int mi_col,
319 if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
320 set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
321 xd->mi[0]->sb_type = bsize;
326 // This struct is used for computing variance in choose_partitioning(), where
327 // the max number of samples within a superblock is 16x16 (with 4x4 avg). Even
328 // in high bitdepth, uint32_t is enough for sum_square_error (2^12 * 2^12 * 16
330 uint32_t sum_square_error;
340 } partition_variance;
343 partition_variance part_variances;
348 partition_variance part_variances;
353 partition_variance part_variances;
358 partition_variance part_variances;
363 partition_variance part_variances;
368 partition_variance *part_variances;
378 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
380 node->part_variances = NULL;
383 v64x64 *vt = (v64x64 *)data;
384 node->part_variances = &vt->part_variances;
385 for (i = 0; i < 4; i++)
386 node->split[i] = &vt->split[i].part_variances.none;
390 v32x32 *vt = (v32x32 *)data;
391 node->part_variances = &vt->part_variances;
392 for (i = 0; i < 4; i++)
393 node->split[i] = &vt->split[i].part_variances.none;
397 v16x16 *vt = (v16x16 *)data;
398 node->part_variances = &vt->part_variances;
399 for (i = 0; i < 4; i++)
400 node->split[i] = &vt->split[i].part_variances.none;
404 v8x8 *vt = (v8x8 *)data;
405 node->part_variances = &vt->part_variances;
406 for (i = 0; i < 4; i++)
407 node->split[i] = &vt->split[i].part_variances.none;
411 v4x4 *vt = (v4x4 *)data;
412 assert(bsize == BLOCK_4X4);
413 node->part_variances = &vt->part_variances;
414 for (i = 0; i < 4; i++) node->split[i] = &vt->split[i];
420 // Set variance values given sum square error, sum error, count.
421 static void fill_variance(uint32_t s2, int32_t s, int c, var *v) {
422 v->sum_square_error = s2;
427 static void get_variance(var *v) {
429 (int)(256 * (v->sum_square_error -
430 (uint32_t)(((int64_t)v->sum_error * v->sum_error) >>
435 static void sum_2_variances(const var *a, const var *b, var *r) {
436 assert(a->log2_count == b->log2_count);
437 fill_variance(a->sum_square_error + b->sum_square_error,
438 a->sum_error + b->sum_error, a->log2_count + 1, r);
441 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
443 memset(&node, 0, sizeof(node));
444 tree_to_node(data, bsize, &node);
445 sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
446 sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
447 sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
448 sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
449 sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
450 &node.part_variances->none);
453 static int set_vt_partitioning(VP9_COMP *cpi, MACROBLOCK *const x,
454 MACROBLOCKD *const xd, void *data,
455 BLOCK_SIZE bsize, int mi_row, int mi_col,
456 int64_t threshold, BLOCK_SIZE bsize_min,
458 VP9_COMMON *const cm = &cpi->common;
460 const int block_width = num_8x8_blocks_wide_lookup[bsize];
461 const int block_height = num_8x8_blocks_high_lookup[bsize];
463 assert(block_height == block_width);
464 tree_to_node(data, bsize, &vt);
466 if (force_split == 1) return 0;
468 // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
469 // variance is below threshold, otherwise split will be selected.
470 // No check for vert/horiz split as too few samples for variance.
471 if (bsize == bsize_min) {
472 // Variance already computed to set the force_split.
473 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
474 if (mi_col + block_width / 2 < cm->mi_cols &&
475 mi_row + block_height / 2 < cm->mi_rows &&
476 vt.part_variances->none.variance < threshold) {
477 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
481 } else if (bsize > bsize_min) {
482 // Variance already computed to set the force_split.
483 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
484 // For key frame: take split for bsize above 32X32 or very high variance.
485 if (frame_is_intra_only(cm) &&
486 (bsize > BLOCK_32X32 ||
487 vt.part_variances->none.variance > (threshold << 4))) {
490 // If variance is low, take the bsize (no split).
491 if (mi_col + block_width / 2 < cm->mi_cols &&
492 mi_row + block_height / 2 < cm->mi_rows &&
493 vt.part_variances->none.variance < threshold) {
494 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
498 // Check vertical split.
499 if (mi_row + block_height / 2 < cm->mi_rows) {
500 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
501 get_variance(&vt.part_variances->vert[0]);
502 get_variance(&vt.part_variances->vert[1]);
503 if (vt.part_variances->vert[0].variance < threshold &&
504 vt.part_variances->vert[1].variance < threshold &&
505 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
506 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
507 set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
511 // Check horizontal split.
512 if (mi_col + block_width / 2 < cm->mi_cols) {
513 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
514 get_variance(&vt.part_variances->horz[0]);
515 get_variance(&vt.part_variances->horz[1]);
516 if (vt.part_variances->horz[0].variance < threshold &&
517 vt.part_variances->horz[1].variance < threshold &&
518 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
519 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
520 set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
530 static int64_t scale_part_thresh_sumdiff(int64_t threshold_base, int speed,
531 int width, int height,
534 if (width <= 640 && height <= 480)
535 return (5 * threshold_base) >> 2;
536 else if ((content_state == kLowSadLowSumdiff) ||
537 (content_state == kHighSadLowSumdiff) ||
538 (content_state == kLowVarHighSumdiff))
539 return (5 * threshold_base) >> 2;
540 } else if (speed == 7) {
541 if ((content_state == kLowSadLowSumdiff) ||
542 (content_state == kHighSadLowSumdiff) ||
543 (content_state == kLowVarHighSumdiff)) {
544 return (5 * threshold_base) >> 2;
547 return threshold_base;
550 // Set the variance split thresholds for following the block sizes:
551 // 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
552 // 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
553 // currently only used on key frame.
554 static void set_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q,
556 VP9_COMMON *const cm = &cpi->common;
557 const int is_key_frame = frame_is_intra_only(cm);
558 const int threshold_multiplier = is_key_frame ? 20 : 1;
559 int64_t threshold_base =
560 (int64_t)(threshold_multiplier * cpi->y_dequant[q][1]);
563 thresholds[0] = threshold_base;
564 thresholds[1] = threshold_base >> 2;
565 thresholds[2] = threshold_base >> 2;
566 thresholds[3] = threshold_base << 2;
568 // Increase base variance threshold based on estimated noise level.
569 if (cpi->noise_estimate.enabled && cm->width >= 640 && cm->height >= 480) {
570 NOISE_LEVEL noise_level =
571 vp9_noise_estimate_extract_level(&cpi->noise_estimate);
572 if (noise_level == kHigh)
573 threshold_base = 3 * threshold_base;
574 else if (noise_level == kMedium)
575 threshold_base = threshold_base << 1;
576 else if (noise_level < kLow)
577 threshold_base = (7 * threshold_base) >> 3;
579 #if CONFIG_VP9_TEMPORAL_DENOISING
580 if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
581 cpi->oxcf.speed > 5 && cpi->denoiser.denoising_level >= kDenLow)
583 vp9_scale_part_thresh(threshold_base, cpi->denoiser.denoising_level,
584 content_state, cpi->svc.temporal_layer_id);
587 scale_part_thresh_sumdiff(threshold_base, cpi->oxcf.speed, cm->width,
588 cm->height, content_state);
590 // Increase base variance threshold based on content_state/sum_diff level.
591 threshold_base = scale_part_thresh_sumdiff(
592 threshold_base, cpi->oxcf.speed, cm->width, cm->height, content_state);
594 thresholds[0] = threshold_base;
595 thresholds[2] = threshold_base << cpi->oxcf.speed;
596 if (cm->width >= 1280 && cm->height >= 720 && cpi->oxcf.speed < 7)
597 thresholds[2] = thresholds[2] << 1;
598 if (cm->width <= 352 && cm->height <= 288) {
599 thresholds[0] = threshold_base >> 3;
600 thresholds[1] = threshold_base >> 1;
601 thresholds[2] = threshold_base << 3;
602 } else if (cm->width < 1280 && cm->height < 720) {
603 thresholds[1] = (5 * threshold_base) >> 2;
604 } else if (cm->width < 1920 && cm->height < 1080) {
605 thresholds[1] = threshold_base << 1;
607 thresholds[1] = (5 * threshold_base) >> 1;
609 if (cpi->sf.disable_16x16part_nonkey) thresholds[2] = INT64_MAX;
613 void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q,
615 VP9_COMMON *const cm = &cpi->common;
616 SPEED_FEATURES *const sf = &cpi->sf;
617 const int is_key_frame = frame_is_intra_only(cm);
618 if (sf->partition_search_type != VAR_BASED_PARTITION &&
619 sf->partition_search_type != REFERENCE_PARTITION) {
622 set_vbp_thresholds(cpi, cpi->vbp_thresholds, q, content_state);
623 // The thresholds below are not changed locally.
625 cpi->vbp_threshold_sad = 0;
626 cpi->vbp_threshold_copy = 0;
627 cpi->vbp_bsize_min = BLOCK_8X8;
629 if (cm->width <= 352 && cm->height <= 288)
630 cpi->vbp_threshold_sad = 10;
632 cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000
633 ? (cpi->y_dequant[q][1] << 1)
635 cpi->vbp_bsize_min = BLOCK_16X16;
636 if (cm->width <= 352 && cm->height <= 288)
637 cpi->vbp_threshold_copy = 4000;
638 else if (cm->width <= 640 && cm->height <= 360)
639 cpi->vbp_threshold_copy = 8000;
641 cpi->vbp_threshold_copy = (cpi->y_dequant[q][1] << 3) > 8000
642 ? (cpi->y_dequant[q][1] << 3)
644 if (cpi->rc.high_source_sad ||
645 (cpi->use_svc && cpi->svc.high_source_sad_superframe)) {
646 cpi->vbp_threshold_sad = 0;
647 cpi->vbp_threshold_copy = 0;
650 cpi->vbp_threshold_minmax = 15 + (q >> 3);
654 // Compute the minmax over the 8x8 subblocks.
655 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
656 int dp, int x16_idx, int y16_idx,
657 #if CONFIG_VP9_HIGHBITDEPTH
660 int pixels_wide, int pixels_high) {
663 int minmax_min = 255;
664 // Loop over the 4 8x8 subblocks.
665 for (k = 0; k < 4; k++) {
666 int x8_idx = x16_idx + ((k & 1) << 3);
667 int y8_idx = y16_idx + ((k >> 1) << 3);
670 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
671 #if CONFIG_VP9_HIGHBITDEPTH
672 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
673 vpx_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
674 d + y8_idx * dp + x8_idx, dp, &min, &max);
676 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx,
680 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx, dp,
683 if ((max - min) > minmax_max) minmax_max = (max - min);
684 if ((max - min) < minmax_min) minmax_min = (max - min);
687 return (minmax_max - minmax_min);
690 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
691 int dp, int x8_idx, int y8_idx, v8x8 *vst,
692 #if CONFIG_VP9_HIGHBITDEPTH
695 int pixels_wide, int pixels_high,
698 for (k = 0; k < 4; k++) {
699 int x4_idx = x8_idx + ((k & 1) << 2);
700 int y4_idx = y8_idx + ((k >> 1) << 2);
701 unsigned int sse = 0;
703 if (x4_idx < pixels_wide && y4_idx < pixels_high) {
706 #if CONFIG_VP9_HIGHBITDEPTH
707 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
708 s_avg = vpx_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
710 d_avg = vpx_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
712 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
713 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
716 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
717 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
722 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
726 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
727 int dp, int x16_idx, int y16_idx, v16x16 *vst,
728 #if CONFIG_VP9_HIGHBITDEPTH
731 int pixels_wide, int pixels_high,
734 for (k = 0; k < 4; k++) {
735 int x8_idx = x16_idx + ((k & 1) << 3);
736 int y8_idx = y16_idx + ((k >> 1) << 3);
737 unsigned int sse = 0;
739 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
742 #if CONFIG_VP9_HIGHBITDEPTH
743 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
744 s_avg = vpx_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
746 d_avg = vpx_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
748 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
749 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
752 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
753 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
758 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
762 // Check if most of the superblock is skin content, and if so, force split to
763 // 32x32, and set x->sb_is_skin for use in mode selection.
764 static int skin_sb_split(VP9_COMP *cpi, MACROBLOCK *x, const int low_res,
765 int mi_row, int mi_col, int *force_split) {
766 VP9_COMMON *const cm = &cpi->common;
767 #if CONFIG_VP9_HIGHBITDEPTH
768 if (cm->use_highbitdepth) return 0;
770 // Avoid checking superblocks on/near boundary and avoid low resolutions.
771 // Note superblock may still pick 64X64 if y_sad is very small
772 // (i.e., y_sad < cpi->vbp_threshold_sad) below. For now leave this as is.
773 if (!low_res && (mi_col >= 8 && mi_col + 8 < cm->mi_cols && mi_row >= 8 &&
774 mi_row + 8 < cm->mi_rows)) {
775 int num_16x16_skin = 0;
776 int num_16x16_nonskin = 0;
777 uint8_t *ysignal = x->plane[0].src.buf;
778 uint8_t *usignal = x->plane[1].src.buf;
779 uint8_t *vsignal = x->plane[2].src.buf;
780 int sp = x->plane[0].src.stride;
781 int spuv = x->plane[1].src.stride;
782 const int block_index = mi_row * cm->mi_cols + mi_col;
783 const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
784 const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
785 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
786 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
787 // Loop through the 16x16 sub-blocks.
789 for (i = 0; i < ymis; i += 2) {
790 for (j = 0; j < xmis; j += 2) {
791 int bl_index = block_index + i * cm->mi_cols + j;
792 int is_skin = cpi->skin_map[bl_index];
793 num_16x16_skin += is_skin;
794 num_16x16_nonskin += (1 - is_skin);
795 if (num_16x16_nonskin > 3) {
796 // Exit loop if at least 4 of the 16x16 blocks are not skin.
804 ysignal += (sp << 4) - 64;
805 usignal += (spuv << 3) - 32;
806 vsignal += (spuv << 3) - 32;
808 if (num_16x16_skin > 12) {
816 static void set_low_temp_var_flag(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
817 v64x64 *vt, int64_t thresholds[],
818 MV_REFERENCE_FRAME ref_frame_partition,
819 int mi_col, int mi_row) {
821 VP9_COMMON *const cm = &cpi->common;
822 const int mv_thr = cm->width > 640 ? 8 : 4;
823 // Check temporal variance for bsize >= 16x16, if LAST_FRAME was selected and
824 // int_pro mv is small. If the temporal variance is small set the flag
825 // variance_low for the block. The variance threshold can be adjusted, the
826 // higher the more aggressive.
827 if (ref_frame_partition == LAST_FRAME &&
828 (cpi->sf.short_circuit_low_temp_var == 1 ||
829 (xd->mi[0]->mv[0].as_mv.col < mv_thr &&
830 xd->mi[0]->mv[0].as_mv.col > -mv_thr &&
831 xd->mi[0]->mv[0].as_mv.row < mv_thr &&
832 xd->mi[0]->mv[0].as_mv.row > -mv_thr))) {
833 if (xd->mi[0]->sb_type == BLOCK_64X64) {
834 if ((vt->part_variances).none.variance < (thresholds[0] >> 1))
835 x->variance_low[0] = 1;
836 } else if (xd->mi[0]->sb_type == BLOCK_64X32) {
837 for (i = 0; i < 2; i++) {
838 if (vt->part_variances.horz[i].variance < (thresholds[0] >> 2))
839 x->variance_low[i + 1] = 1;
841 } else if (xd->mi[0]->sb_type == BLOCK_32X64) {
842 for (i = 0; i < 2; i++) {
843 if (vt->part_variances.vert[i].variance < (thresholds[0] >> 2))
844 x->variance_low[i + 3] = 1;
847 for (i = 0; i < 4; i++) {
848 const int idx[4][2] = { { 0, 0 }, { 0, 4 }, { 4, 0 }, { 4, 4 } };
850 cm->mi_stride * (mi_row + idx[i][0]) + mi_col + idx[i][1];
851 MODE_INFO **this_mi = cm->mi_grid_visible + idx_str;
853 if (cm->mi_cols <= mi_col + idx[i][1] ||
854 cm->mi_rows <= mi_row + idx[i][0])
857 if ((*this_mi)->sb_type == BLOCK_32X32) {
858 int64_t threshold_32x32 = (cpi->sf.short_circuit_low_temp_var == 1 ||
859 cpi->sf.short_circuit_low_temp_var == 3)
860 ? ((5 * thresholds[1]) >> 3)
861 : (thresholds[1] >> 1);
862 if (vt->split[i].part_variances.none.variance < threshold_32x32)
863 x->variance_low[i + 5] = 1;
864 } else if (cpi->sf.short_circuit_low_temp_var >= 2) {
865 // For 32x16 and 16x32 blocks, the flag is set on each 16x16 block
867 if ((*this_mi)->sb_type == BLOCK_16X16 ||
868 (*this_mi)->sb_type == BLOCK_32X16 ||
869 (*this_mi)->sb_type == BLOCK_16X32) {
870 for (j = 0; j < 4; j++) {
871 if (vt->split[i].split[j].part_variances.none.variance <
872 (thresholds[2] >> 8))
873 x->variance_low[(i << 2) + j + 9] = 1;
882 static void copy_partitioning_helper(VP9_COMP *cpi, MACROBLOCK *x,
883 MACROBLOCKD *xd, BLOCK_SIZE bsize,
884 int mi_row, int mi_col) {
885 VP9_COMMON *const cm = &cpi->common;
886 BLOCK_SIZE *prev_part = cpi->prev_partition;
887 int start_pos = mi_row * cm->mi_stride + mi_col;
889 const int bsl = b_width_log2_lookup[bsize];
890 const int bs = (1 << bsl) >> 2;
892 PARTITION_TYPE partition;
894 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
896 partition = partition_lookup[bsl][prev_part[start_pos]];
897 subsize = get_subsize(bsize, partition);
899 if (subsize < BLOCK_8X8) {
900 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
904 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
907 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
908 set_block_size(cpi, x, xd, mi_row + bs, mi_col, subsize);
911 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
912 set_block_size(cpi, x, xd, mi_row, mi_col + bs, subsize);
915 assert(partition == PARTITION_SPLIT);
916 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col);
917 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col);
918 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col + bs);
919 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col + bs);
925 static int copy_partitioning(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
926 int mi_row, int mi_col, int segment_id,
928 int svc_copy_allowed = 1;
929 int frames_since_key_thresh = 1;
931 // For SVC, don't allow copy if base spatial layer is key frame, or if
932 // frame is not a temporal enhancement layer frame.
933 int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
934 cpi->svc.number_temporal_layers);
935 const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
936 if (lc->is_key_frame || !cpi->svc.non_reference_frame) svc_copy_allowed = 0;
937 frames_since_key_thresh = cpi->svc.number_spatial_layers << 1;
939 if (cpi->rc.frames_since_key > frames_since_key_thresh && svc_copy_allowed &&
940 !cpi->resize_pending && segment_id == CR_SEGMENT_ID_BASE &&
941 cpi->prev_segment_id[sb_offset] == CR_SEGMENT_ID_BASE &&
942 cpi->copied_frame_cnt[sb_offset] < cpi->max_copied_frame) {
943 if (cpi->prev_partition != NULL) {
944 copy_partitioning_helper(cpi, x, xd, BLOCK_64X64, mi_row, mi_col);
945 cpi->copied_frame_cnt[sb_offset] += 1;
946 memcpy(x->variance_low, &(cpi->prev_variance_low[sb_offset * 25]),
947 sizeof(x->variance_low));
955 static int scale_partitioning_svc(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
956 BLOCK_SIZE bsize, int mi_row, int mi_col,
957 int mi_row_high, int mi_col_high) {
958 VP9_COMMON *const cm = &cpi->common;
959 SVC *const svc = &cpi->svc;
960 BLOCK_SIZE *prev_part = svc->prev_partition_svc;
961 // Variables with _high are for higher resolution.
963 int subsize_high = 0;
964 const int bsl_high = b_width_log2_lookup[bsize];
965 const int bs_high = (1 << bsl_high) >> 2;
966 const int has_rows = (mi_row_high + bs_high) < cm->mi_rows;
967 const int has_cols = (mi_col_high + bs_high) < cm->mi_cols;
969 const int row_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 1, 0,
972 const int col_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 2, 2,
976 BLOCK_SIZE bsize_low;
977 PARTITION_TYPE partition_high;
979 if (mi_row_high >= cm->mi_rows || mi_col_high >= cm->mi_cols) return 0;
980 if (mi_row >= svc->mi_rows[svc->spatial_layer_id - 1] ||
981 mi_col >= svc->mi_cols[svc->spatial_layer_id - 1])
984 // Find corresponding (mi_col/mi_row) block down-scaled by 2x2.
985 start_pos = mi_row * (svc->mi_stride[svc->spatial_layer_id - 1]) + mi_col;
986 bsize_low = prev_part[start_pos];
987 // The block size is too big for boundaries. Do variance based partitioning.
988 if ((!has_rows || !has_cols) && bsize_low > BLOCK_16X16) return 1;
990 // For reference frames: return 1 (do variance-based partitioning) if the
991 // superblock is not low source sad and lower-resoln bsize is below 32x32.
992 if (!cpi->svc.non_reference_frame && !x->skip_low_source_sad &&
993 bsize_low < BLOCK_32X32)
996 // Scale up block size by 2x2. Force 64x64 for size larger than 32x32.
997 if (bsize_low < BLOCK_32X32) {
998 bsize_high = bsize_low + 3;
999 } else if (bsize_low >= BLOCK_32X32) {
1000 bsize_high = BLOCK_64X64;
1002 // Scale up blocks on boundary.
1003 if (!has_cols && has_rows) {
1004 bsize_high = bsize_low + row_boundary_block_scale_factor[bsize_low];
1005 } else if (has_cols && !has_rows) {
1006 bsize_high = bsize_low + col_boundary_block_scale_factor[bsize_low];
1007 } else if (!has_cols && !has_rows) {
1008 bsize_high = bsize_low;
1011 partition_high = partition_lookup[bsl_high][bsize_high];
1012 subsize_high = get_subsize(bsize, partition_high);
1014 if (subsize_high < BLOCK_8X8) {
1015 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1017 const int bsl = b_width_log2_lookup[bsize];
1018 const int bs = (1 << bsl) >> 2;
1019 switch (partition_high) {
1020 case PARTITION_NONE:
1021 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1023 case PARTITION_HORZ:
1024 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1025 if (subsize_high < BLOCK_64X64)
1026 set_block_size(cpi, x, xd, mi_row_high + bs_high, mi_col_high,
1029 case PARTITION_VERT:
1030 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1031 if (subsize_high < BLOCK_64X64)
1032 set_block_size(cpi, x, xd, mi_row_high, mi_col_high + bs_high,
1036 assert(partition_high == PARTITION_SPLIT);
1037 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row, mi_col,
1038 mi_row_high, mi_col_high))
1040 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1041 mi_col, mi_row_high + bs_high, mi_col_high))
1043 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row,
1044 mi_col + (bs >> 1), mi_row_high,
1045 mi_col_high + bs_high))
1047 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1048 mi_col + (bs >> 1), mi_row_high + bs_high,
1049 mi_col_high + bs_high))
1058 static void update_partition_svc(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
1060 VP9_COMMON *const cm = &cpi->common;
1061 BLOCK_SIZE *prev_part = cpi->svc.prev_partition_svc;
1062 int start_pos = mi_row * cm->mi_stride + mi_col;
1063 const int bsl = b_width_log2_lookup[bsize];
1064 const int bs = (1 << bsl) >> 2;
1066 PARTITION_TYPE partition;
1067 const MODE_INFO *mi = NULL;
1070 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1072 mi = cm->mi_grid_visible[start_pos];
1073 partition = partition_lookup[bsl][mi->sb_type];
1074 subsize = get_subsize(bsize, partition);
1075 if (subsize < BLOCK_8X8) {
1076 prev_part[start_pos] = bsize;
1078 switch (partition) {
1079 case PARTITION_NONE:
1080 prev_part[start_pos] = bsize;
1081 if (bsize == BLOCK_64X64) {
1082 for (xx = 0; xx < 8; xx += 4)
1083 for (yy = 0; yy < 8; yy += 4) {
1084 if ((mi_row + xx < cm->mi_rows) && (mi_col + yy < cm->mi_cols))
1085 prev_part[start_pos + xx * cm->mi_stride + yy] = bsize;
1089 case PARTITION_HORZ:
1090 prev_part[start_pos] = subsize;
1091 if (mi_row + bs < cm->mi_rows)
1092 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1094 case PARTITION_VERT:
1095 prev_part[start_pos] = subsize;
1096 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1099 assert(partition == PARTITION_SPLIT);
1100 update_partition_svc(cpi, subsize, mi_row, mi_col);
1101 update_partition_svc(cpi, subsize, mi_row + bs, mi_col);
1102 update_partition_svc(cpi, subsize, mi_row, mi_col + bs);
1103 update_partition_svc(cpi, subsize, mi_row + bs, mi_col + bs);
1109 static void update_prev_partition_helper(VP9_COMP *cpi, BLOCK_SIZE bsize,
1110 int mi_row, int mi_col) {
1111 VP9_COMMON *const cm = &cpi->common;
1112 BLOCK_SIZE *prev_part = cpi->prev_partition;
1113 int start_pos = mi_row * cm->mi_stride + mi_col;
1114 const int bsl = b_width_log2_lookup[bsize];
1115 const int bs = (1 << bsl) >> 2;
1117 PARTITION_TYPE partition;
1118 const MODE_INFO *mi = NULL;
1120 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1122 mi = cm->mi_grid_visible[start_pos];
1123 partition = partition_lookup[bsl][mi->sb_type];
1124 subsize = get_subsize(bsize, partition);
1125 if (subsize < BLOCK_8X8) {
1126 prev_part[start_pos] = bsize;
1128 switch (partition) {
1129 case PARTITION_NONE: prev_part[start_pos] = bsize; break;
1130 case PARTITION_HORZ:
1131 prev_part[start_pos] = subsize;
1132 if (mi_row + bs < cm->mi_rows)
1133 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1135 case PARTITION_VERT:
1136 prev_part[start_pos] = subsize;
1137 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1140 assert(partition == PARTITION_SPLIT);
1141 update_prev_partition_helper(cpi, subsize, mi_row, mi_col);
1142 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col);
1143 update_prev_partition_helper(cpi, subsize, mi_row, mi_col + bs);
1144 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col + bs);
1150 static void update_prev_partition(VP9_COMP *cpi, MACROBLOCK *x, int segment_id,
1151 int mi_row, int mi_col, int sb_offset) {
1152 update_prev_partition_helper(cpi, BLOCK_64X64, mi_row, mi_col);
1153 cpi->prev_segment_id[sb_offset] = segment_id;
1154 memcpy(&(cpi->prev_variance_low[sb_offset * 25]), x->variance_low,
1155 sizeof(x->variance_low));
1156 // Reset the counter for copy partitioning
1157 cpi->copied_frame_cnt[sb_offset] = 0;
1160 static void chroma_check(VP9_COMP *cpi, MACROBLOCK *x, int bsize,
1161 unsigned int y_sad, int is_key_frame) {
1163 MACROBLOCKD *xd = &x->e_mbd;
1165 if (is_key_frame) return;
1167 // For speed >= 8, avoid the chroma check if y_sad is above threshold.
1168 if (cpi->oxcf.speed >= 8) {
1169 if (y_sad > cpi->vbp_thresholds[1] &&
1170 (!cpi->noise_estimate.enabled ||
1171 vp9_noise_estimate_extract_level(&cpi->noise_estimate) < kMedium))
1175 for (i = 1; i <= 2; ++i) {
1176 unsigned int uv_sad = UINT_MAX;
1177 struct macroblock_plane *p = &x->plane[i];
1178 struct macroblockd_plane *pd = &xd->plane[i];
1179 const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
1181 if (bs != BLOCK_INVALID)
1182 uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride, pd->dst.buf,
1185 // TODO(marpan): Investigate if we should lower this threshold if
1186 // superblock is detected as skin.
1187 x->color_sensitivity[i - 1] = uv_sad > (y_sad >> 2);
1191 static uint64_t avg_source_sad(VP9_COMP *cpi, MACROBLOCK *x, int shift,
1193 unsigned int tmp_sse;
1195 unsigned int tmp_variance;
1196 const BLOCK_SIZE bsize = BLOCK_64X64;
1197 uint8_t *src_y = cpi->Source->y_buffer;
1198 int src_ystride = cpi->Source->y_stride;
1199 uint8_t *last_src_y = cpi->Last_Source->y_buffer;
1200 int last_src_ystride = cpi->Last_Source->y_stride;
1201 uint64_t avg_source_sad_threshold = 10000;
1202 uint64_t avg_source_sad_threshold2 = 12000;
1203 #if CONFIG_VP9_HIGHBITDEPTH
1204 if (cpi->common.use_highbitdepth) return 0;
1207 last_src_y += shift;
1209 cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y, last_src_ystride);
1210 tmp_variance = vpx_variance64x64(src_y, src_ystride, last_src_y,
1211 last_src_ystride, &tmp_sse);
1212 // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1213 if (tmp_sad < avg_source_sad_threshold)
1214 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kLowSadLowSumdiff
1215 : kLowSadHighSumdiff;
1217 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kHighSadLowSumdiff
1218 : kHighSadHighSumdiff;
1220 // Detect large lighting change.
1221 if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
1222 cpi->oxcf.rc_mode == VPX_CBR && tmp_variance < (tmp_sse >> 3) &&
1223 (tmp_sse - tmp_variance) > 10000)
1224 x->content_state_sb = kLowVarHighSumdiff;
1225 else if (tmp_sad > (avg_source_sad_threshold << 1))
1226 x->content_state_sb = kVeryHighSad;
1228 if (cpi->content_state_sb_fd != NULL) {
1229 if (tmp_sad < avg_source_sad_threshold2) {
1230 // Cap the increment to 255.
1231 if (cpi->content_state_sb_fd[sb_offset] < 255)
1232 cpi->content_state_sb_fd[sb_offset]++;
1234 cpi->content_state_sb_fd[sb_offset] = 0;
1237 if (tmp_sad == 0) x->zero_temp_sad_source = 1;
1241 // This function chooses partitioning based on the variance between source and
1242 // reconstructed last, where variance is computed for down-sampled inputs.
1243 static int choose_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1244 MACROBLOCK *x, int mi_row, int mi_col) {
1245 VP9_COMMON *const cm = &cpi->common;
1246 MACROBLOCKD *xd = &x->e_mbd;
1250 int force_split[21];
1252 int max_var_32x32 = 0;
1253 int min_var_32x32 = INT_MAX;
1256 int maxvar_16x16[4];
1257 int minvar_16x16[4];
1258 int64_t threshold_4x4avg;
1259 NOISE_LEVEL noise_level = kLow;
1260 int content_state = 0;
1265 int compute_minmax_variance = 1;
1266 unsigned int y_sad = UINT_MAX;
1267 BLOCK_SIZE bsize = BLOCK_64X64;
1268 // Ref frame used in partitioning.
1269 MV_REFERENCE_FRAME ref_frame_partition = LAST_FRAME;
1270 int pixels_wide = 64, pixels_high = 64;
1271 int64_t thresholds[4] = { cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
1272 cpi->vbp_thresholds[2], cpi->vbp_thresholds[3] };
1273 int force_64_split = cpi->rc.high_source_sad ||
1274 (cpi->use_svc && cpi->svc.high_source_sad_superframe) ||
1275 (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1276 cpi->compute_source_sad_onepass &&
1277 cpi->sf.use_source_sad && !x->zero_temp_sad_source);
1279 // For the variance computation under SVC mode, we treat the frame as key if
1280 // the reference (base layer frame) is key frame (i.e., is_key_frame == 1).
1282 (frame_is_intra_only(cm) ||
1283 (is_one_pass_cbr_svc(cpi) &&
1284 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame));
1285 // Always use 4x4 partition for key frame.
1286 const int use_4x4_partition = frame_is_intra_only(cm);
1287 const int low_res = (cm->width <= 352 && cm->height <= 288);
1288 int variance4x4downsample[16];
1290 int sb_offset = (cm->mi_stride >> 3) * (mi_row >> 3) + (mi_col >> 3);
1292 // For SVC: check if LAST frame is NULL or if the resolution of LAST is
1293 // different than the current frame resolution, and if so, treat this frame
1294 // as a key frame, for the purpose of the superblock partitioning.
1295 // LAST == NULL can happen in some cases where enhancement spatial layers are
1296 // enabled dyanmically in the stream and the only reference is the spatial
1297 // reference (GOLDEN).
1299 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, LAST_FRAME);
1300 if (ref == NULL || ref->y_crop_height != cm->height ||
1301 ref->y_crop_width != cm->width)
1305 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
1306 set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
1307 segment_id = xd->mi[0]->segment_id;
1309 if (cpi->oxcf.speed >= 8 || (cpi->use_svc && cpi->svc.non_reference_frame))
1310 compute_minmax_variance = 0;
1312 memset(x->variance_low, 0, sizeof(x->variance_low));
1314 if (cpi->sf.use_source_sad && !is_key_frame) {
1315 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1316 content_state = x->content_state_sb;
1317 x->skip_low_source_sad = (content_state == kLowSadLowSumdiff ||
1318 content_state == kLowSadHighSumdiff)
1321 x->lowvar_highsumdiff = (content_state == kLowVarHighSumdiff) ? 1 : 0;
1322 if (cpi->content_state_sb_fd != NULL)
1323 x->last_sb_high_content = cpi->content_state_sb_fd[sb_offset2];
1325 // For SVC on top spatial layer: use/scale the partition from
1326 // the lower spatial resolution if svc_use_lowres_part is enabled.
1327 if (cpi->sf.svc_use_lowres_part &&
1328 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1329 cpi->svc.prev_partition_svc != NULL && content_state != kVeryHighSad) {
1330 if (!scale_partitioning_svc(cpi, x, xd, BLOCK_64X64, mi_row >> 1,
1331 mi_col >> 1, mi_row, mi_col)) {
1332 if (cpi->sf.copy_partition_flag) {
1333 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1338 // If source_sad is low copy the partition without computing the y_sad.
1339 if (x->skip_low_source_sad && cpi->sf.copy_partition_flag &&
1341 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1342 x->sb_use_mv_part = 1;
1343 if (cpi->sf.svc_use_lowres_part &&
1344 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1345 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1350 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
1351 cyclic_refresh_segment_id_boosted(segment_id)) {
1352 int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
1353 set_vbp_thresholds(cpi, thresholds, q, content_state);
1355 set_vbp_thresholds(cpi, thresholds, cm->base_qindex, content_state);
1357 // Decrease 32x32 split threshold for screen on base layer, for scene
1358 // change/high motion frames.
1359 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1360 cpi->svc.spatial_layer_id == 0 && force_64_split)
1361 thresholds[1] = 3 * thresholds[1] >> 2;
1363 // For non keyframes, disable 4x4 average for low resolution when speed = 8
1364 threshold_4x4avg = (cpi->oxcf.speed < 8) ? thresholds[1] << 1 : INT64_MAX;
1366 if (xd->mb_to_right_edge < 0) pixels_wide += (xd->mb_to_right_edge >> 3);
1367 if (xd->mb_to_bottom_edge < 0) pixels_high += (xd->mb_to_bottom_edge >> 3);
1369 s = x->plane[0].src.buf;
1370 sp = x->plane[0].src.stride;
1372 // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
1373 // 5-20 for the 16x16 blocks.
1374 force_split[0] = force_64_split;
1376 if (!is_key_frame) {
1377 // In the case of spatial/temporal scalable coding, the assumption here is
1378 // that the temporal reference frame will always be of type LAST_FRAME.
1379 // TODO(marpan): If that assumption is broken, we need to revisit this code.
1380 MODE_INFO *mi = xd->mi[0];
1381 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1383 const YV12_BUFFER_CONFIG *yv12_g = NULL;
1384 unsigned int y_sad_g, y_sad_thr, y_sad_last;
1385 bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
1386 (mi_row + 4 < cm->mi_rows);
1388 assert(yv12 != NULL);
1390 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
1391 cpi->svc.use_gf_temporal_ref_current_layer) {
1392 // For now, GOLDEN will not be used for non-zero spatial layers, since
1393 // it may not be a temporal reference.
1394 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1397 // Only compute y_sad_g (sad for golden reference) for speed < 8.
1398 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
1399 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
1400 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1401 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1402 y_sad_g = cpi->fn_ptr[bsize].sdf(
1403 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1404 xd->plane[0].pre[0].stride);
1409 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
1410 cpi->rc.is_src_frame_alt_ref) {
1411 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
1412 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1413 &cm->frame_refs[ALTREF_FRAME - 1].sf);
1414 mi->ref_frame[0] = ALTREF_FRAME;
1417 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1418 &cm->frame_refs[LAST_FRAME - 1].sf);
1419 mi->ref_frame[0] = LAST_FRAME;
1421 mi->ref_frame[1] = NONE;
1422 mi->sb_type = BLOCK_64X64;
1423 mi->mv[0].as_int = 0;
1424 mi->interp_filter = BILINEAR;
1426 if (cpi->oxcf.speed >= 8 && !low_res &&
1427 x->content_state_sb != kVeryHighSad) {
1428 y_sad = cpi->fn_ptr[bsize].sdf(
1429 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1430 xd->plane[0].pre[0].stride);
1432 const MV dummy_mv = { 0, 0 };
1433 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
1435 x->sb_use_mv_part = 1;
1436 x->sb_mvcol_part = mi->mv[0].as_mv.col;
1437 x->sb_mvrow_part = mi->mv[0].as_mv.row;
1438 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1439 cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
1440 cpi->svc.high_num_blocks_with_motion && !x->zero_temp_sad_source &&
1441 cm->width > 640 && cm->height > 480) {
1442 // Disable split below 16x16 block size when scroll motion (horz or
1443 // vert) is detected.
1444 // TODO(marpan/jianj): Improve this condition: issue is that search
1445 // range is hard-coded/limited in vp9_int_pro_motion_estimation() so
1446 // scroll motion may not be detected here.
1447 if (((abs(x->sb_mvrow_part) >= 48 && abs(x->sb_mvcol_part) <= 8) ||
1448 (abs(x->sb_mvcol_part) >= 48 && abs(x->sb_mvrow_part) <= 8)) &&
1450 compute_minmax_variance = 0;
1451 thresholds[2] = INT64_MAX;
1457 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
1458 // are close if short_circuit_low_temp_var is on.
1459 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
1460 if (y_sad_g < y_sad_thr) {
1461 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1462 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1463 mi->ref_frame[0] = GOLDEN_FRAME;
1464 mi->mv[0].as_int = 0;
1466 ref_frame_partition = GOLDEN_FRAME;
1468 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
1469 ref_frame_partition = LAST_FRAME;
1472 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
1473 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
1475 if (cpi->use_skin_detection)
1477 skin_sb_split(cpi, x, low_res, mi_row, mi_col, force_split);
1479 d = xd->plane[0].dst.buf;
1480 dp = xd->plane[0].dst.stride;
1482 // If the y_sad is very small, take 64x64 as partition and exit.
1483 // Don't check on boosted segment for now, as 64x64 is suppressed there.
1484 if (segment_id == CR_SEGMENT_ID_BASE && y_sad < cpi->vbp_threshold_sad) {
1485 const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
1486 const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
1487 if (mi_col + block_width / 2 < cm->mi_cols &&
1488 mi_row + block_height / 2 < cm->mi_rows) {
1489 set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
1490 x->variance_low[0] = 1;
1491 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1492 if (cpi->sf.svc_use_lowres_part &&
1493 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1494 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1495 if (cpi->sf.copy_partition_flag) {
1496 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1502 // If the y_sad is small enough, copy the partition of the superblock in the
1503 // last frame to current frame only if the last frame is not a keyframe.
1504 // Stop the copy every cpi->max_copied_frame to refresh the partition.
1505 // TODO(jianj) : tune the threshold.
1506 if (cpi->sf.copy_partition_flag && y_sad_last < cpi->vbp_threshold_copy &&
1507 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1508 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1509 if (cpi->sf.svc_use_lowres_part &&
1510 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1511 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1517 #if CONFIG_VP9_HIGHBITDEPTH
1518 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1520 case 10: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10); break;
1521 case 12: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12); break;
1523 default: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8); break;
1526 #endif // CONFIG_VP9_HIGHBITDEPTH
1529 if (low_res && threshold_4x4avg < INT64_MAX)
1530 CHECK_MEM_ERROR(cm, vt2, vpx_calloc(16, sizeof(*vt2)));
1531 // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
1533 for (i = 0; i < 4; i++) {
1534 const int x32_idx = ((i & 1) << 5);
1535 const int y32_idx = ((i >> 1) << 5);
1536 const int i2 = i << 2;
1537 force_split[i + 1] = 0;
1539 maxvar_16x16[i] = 0;
1540 minvar_16x16[i] = INT_MAX;
1541 for (j = 0; j < 4; j++) {
1542 const int x16_idx = x32_idx + ((j & 1) << 4);
1543 const int y16_idx = y32_idx + ((j >> 1) << 4);
1544 const int split_index = 5 + i2 + j;
1545 v16x16 *vst = &vt.split[i].split[j];
1546 force_split[split_index] = 0;
1547 variance4x4downsample[i2 + j] = 0;
1548 if (!is_key_frame) {
1549 fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
1550 #if CONFIG_VP9_HIGHBITDEPTH
1553 pixels_wide, pixels_high, is_key_frame);
1554 fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1555 get_variance(&vt.split[i].split[j].part_variances.none);
1556 avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance;
1557 if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i])
1558 minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1559 if (vt.split[i].split[j].part_variances.none.variance > maxvar_16x16[i])
1560 maxvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1561 if (vt.split[i].split[j].part_variances.none.variance > thresholds[2]) {
1562 // 16X16 variance is above threshold for split, so force split to 8x8
1563 // for this 16x16 block (this also forces splits for upper levels).
1564 force_split[split_index] = 1;
1565 force_split[i + 1] = 1;
1567 } else if (compute_minmax_variance &&
1568 vt.split[i].split[j].part_variances.none.variance >
1570 !cyclic_refresh_segment_id_boosted(segment_id)) {
1571 // We have some nominal amount of 16x16 variance (based on average),
1572 // compute the minmax over the 8x8 sub-blocks, and if above threshold,
1573 // force split to 8x8 block for this 16x16 block.
1574 int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
1575 #if CONFIG_VP9_HIGHBITDEPTH
1578 pixels_wide, pixels_high);
1579 int thresh_minmax = (int)cpi->vbp_threshold_minmax;
1580 if (x->content_state_sb == kVeryHighSad)
1581 thresh_minmax = thresh_minmax << 1;
1582 if (minmax > thresh_minmax) {
1583 force_split[split_index] = 1;
1584 force_split[i + 1] = 1;
1590 (low_res && vt.split[i].split[j].part_variances.none.variance >
1591 threshold_4x4avg)) {
1592 force_split[split_index] = 0;
1593 // Go down to 4x4 down-sampling for variance.
1594 variance4x4downsample[i2 + j] = 1;
1595 for (k = 0; k < 4; k++) {
1596 int x8_idx = x16_idx + ((k & 1) << 3);
1597 int y8_idx = y16_idx + ((k >> 1) << 3);
1598 v8x8 *vst2 = is_key_frame ? &vst->split[k] : &vt2[i2 + j].split[k];
1599 fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
1600 #if CONFIG_VP9_HIGHBITDEPTH
1603 pixels_wide, pixels_high, is_key_frame);
1608 if (cpi->noise_estimate.enabled)
1609 noise_level = vp9_noise_estimate_extract_level(&cpi->noise_estimate);
1610 // Fill the rest of the variance tree by summing split partition values.
1612 for (i = 0; i < 4; i++) {
1613 const int i2 = i << 2;
1614 for (j = 0; j < 4; j++) {
1615 if (variance4x4downsample[i2 + j] == 1) {
1616 v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] : &vt.split[i].split[j];
1617 for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
1618 fill_variance_tree(vtemp, BLOCK_16X16);
1619 // If variance of this 16x16 block is above the threshold, force block
1620 // to split. This also forces a split on the upper levels.
1621 get_variance(&vtemp->part_variances.none);
1622 if (vtemp->part_variances.none.variance > thresholds[2]) {
1623 force_split[5 + i2 + j] = 1;
1624 force_split[i + 1] = 1;
1629 fill_variance_tree(&vt.split[i], BLOCK_32X32);
1630 // If variance of this 32x32 block is above the threshold, or if its above
1631 // (some threshold of) the average variance over the sub-16x16 blocks, then
1632 // force this block to split. This also forces a split on the upper
1634 if (!force_split[i + 1]) {
1635 get_variance(&vt.split[i].part_variances.none);
1636 var_32x32 = vt.split[i].part_variances.none.variance;
1637 max_var_32x32 = VPXMAX(var_32x32, max_var_32x32);
1638 min_var_32x32 = VPXMIN(var_32x32, min_var_32x32);
1639 if (vt.split[i].part_variances.none.variance > thresholds[1] ||
1641 vt.split[i].part_variances.none.variance > (thresholds[1] >> 1) &&
1642 vt.split[i].part_variances.none.variance > (avg_16x16[i] >> 1))) {
1643 force_split[i + 1] = 1;
1645 } else if (!is_key_frame && noise_level < kLow && cm->height <= 360 &&
1646 (maxvar_16x16[i] - minvar_16x16[i]) > (thresholds[1] >> 1) &&
1647 maxvar_16x16[i] > thresholds[1]) {
1648 force_split[i + 1] = 1;
1651 avg_32x32 += var_32x32;
1654 if (!force_split[0]) {
1655 fill_variance_tree(&vt, BLOCK_64X64);
1656 get_variance(&vt.part_variances.none);
1657 // If variance of this 64x64 block is above (some threshold of) the average
1658 // variance over the sub-32x32 blocks, then force this block to split.
1659 // Only checking this for noise level >= medium for now.
1660 if (!is_key_frame && noise_level >= kMedium &&
1661 vt.part_variances.none.variance > (9 * avg_32x32) >> 5)
1663 // Else if the maximum 32x32 variance minus the miniumum 32x32 variance in
1664 // a 64x64 block is greater than threshold and the maximum 32x32 variance is
1665 // above a miniumum threshold, then force the split of a 64x64 block
1666 // Only check this for low noise.
1667 else if (!is_key_frame && noise_level < kMedium &&
1668 (max_var_32x32 - min_var_32x32) > 3 * (thresholds[0] >> 3) &&
1669 max_var_32x32 > thresholds[0] >> 1)
1673 // Now go through the entire structure, splitting every block size until
1674 // we get to one that's got a variance lower than our threshold.
1675 if (mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
1676 !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
1677 thresholds[0], BLOCK_16X16, force_split[0])) {
1678 for (i = 0; i < 4; ++i) {
1679 const int x32_idx = ((i & 1) << 2);
1680 const int y32_idx = ((i >> 1) << 2);
1681 const int i2 = i << 2;
1682 if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
1683 (mi_row + y32_idx), (mi_col + x32_idx),
1684 thresholds[1], BLOCK_16X16,
1685 force_split[i + 1])) {
1686 for (j = 0; j < 4; ++j) {
1687 const int x16_idx = ((j & 1) << 1);
1688 const int y16_idx = ((j >> 1) << 1);
1689 // For inter frames: if variance4x4downsample[] == 1 for this 16x16
1690 // block, then the variance is based on 4x4 down-sampling, so use vt2
1691 // in set_vt_partioning(), otherwise use vt.
1692 v16x16 *vtemp = (!is_key_frame && variance4x4downsample[i2 + j] == 1)
1694 : &vt.split[i].split[j];
1695 if (!set_vt_partitioning(
1696 cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx,
1697 mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min,
1698 force_split[5 + i2 + j])) {
1699 for (k = 0; k < 4; ++k) {
1700 const int x8_idx = (k & 1);
1701 const int y8_idx = (k >> 1);
1702 if (use_4x4_partition) {
1703 if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
1705 mi_row + y32_idx + y16_idx + y8_idx,
1706 mi_col + x32_idx + x16_idx + x8_idx,
1707 thresholds[3], BLOCK_8X8, 0)) {
1709 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1710 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_4X4);
1714 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1715 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_8X8);
1724 if (!frame_is_intra_only(cm) && cpi->sf.copy_partition_flag) {
1725 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1728 if (!frame_is_intra_only(cm) && cpi->sf.svc_use_lowres_part &&
1729 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1730 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1732 if (cpi->sf.short_circuit_low_temp_var) {
1733 set_low_temp_var_flag(cpi, x, xd, &vt, thresholds, ref_frame_partition,
1737 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1738 if (vt2) vpx_free(vt2);
1742 static void update_state(VP9_COMP *cpi, ThreadData *td, PICK_MODE_CONTEXT *ctx,
1743 int mi_row, int mi_col, BLOCK_SIZE bsize,
1744 int output_enabled) {
1746 VP9_COMMON *const cm = &cpi->common;
1747 RD_COUNTS *const rdc = &td->rd_counts;
1748 MACROBLOCK *const x = &td->mb;
1749 MACROBLOCKD *const xd = &x->e_mbd;
1750 struct macroblock_plane *const p = x->plane;
1751 struct macroblockd_plane *const pd = xd->plane;
1752 MODE_INFO *mi = &ctx->mic;
1753 MODE_INFO *const xdmi = xd->mi[0];
1754 MODE_INFO *mi_addr = xd->mi[0];
1755 const struct segmentation *const seg = &cm->seg;
1756 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
1757 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
1758 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1759 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1760 MV_REF *const frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1763 const int mis = cm->mi_stride;
1764 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
1765 const int mi_height = num_8x8_blocks_high_lookup[bsize];
1768 assert(mi->sb_type == bsize);
1771 *x->mbmi_ext = ctx->mbmi_ext;
1773 // If segmentation in use
1775 // For in frame complexity AQ copy the segment id from the segment map.
1776 if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1777 const uint8_t *const map =
1778 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1779 mi_addr->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1781 // Else for cyclic refresh mode update the segment map, set the segment id
1782 // and then update the quantizer.
1783 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1784 vp9_cyclic_refresh_update_segment(cpi, xd->mi[0], mi_row, mi_col, bsize,
1785 ctx->rate, ctx->dist, x->skip, p);
1789 max_plane = is_inter_block(xdmi) ? MAX_MB_PLANE : 1;
1790 for (i = 0; i < max_plane; ++i) {
1791 p[i].coeff = ctx->coeff_pbuf[i][1];
1792 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1793 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1794 p[i].eobs = ctx->eobs_pbuf[i][1];
1797 for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1798 p[i].coeff = ctx->coeff_pbuf[i][2];
1799 p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1800 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1801 p[i].eobs = ctx->eobs_pbuf[i][2];
1804 // Restore the coding context of the MB to that that was in place
1805 // when the mode was picked for it
1806 for (y = 0; y < mi_height; y++)
1807 for (x_idx = 0; x_idx < mi_width; x_idx++)
1808 if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx &&
1809 (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1810 xd->mi[x_idx + y * mis] = mi_addr;
1813 if (cpi->oxcf.aq_mode != NO_AQ) vp9_init_plane_quantizers(cpi, x);
1815 if (is_inter_block(xdmi) && xdmi->sb_type < BLOCK_8X8) {
1816 xdmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1817 xdmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1820 x->skip = ctx->skip;
1821 memcpy(x->zcoeff_blk[xdmi->tx_size], ctx->zcoeff_blk,
1822 sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1824 if (!output_enabled) return;
1826 #if CONFIG_INTERNAL_STATS
1827 if (frame_is_intra_only(cm)) {
1828 static const int kf_mode_index[] = {
1829 THR_DC /*DC_PRED*/, THR_V_PRED /*V_PRED*/,
1830 THR_H_PRED /*H_PRED*/, THR_D45_PRED /*D45_PRED*/,
1831 THR_D135_PRED /*D135_PRED*/, THR_D117_PRED /*D117_PRED*/,
1832 THR_D153_PRED /*D153_PRED*/, THR_D207_PRED /*D207_PRED*/,
1833 THR_D63_PRED /*D63_PRED*/, THR_TM /*TM_PRED*/,
1835 ++cpi->mode_chosen_counts[kf_mode_index[xdmi->mode]];
1837 // Note how often each mode chosen as best
1838 ++cpi->mode_chosen_counts[ctx->best_mode_index];
1841 if (!frame_is_intra_only(cm)) {
1842 if (is_inter_block(xdmi)) {
1843 vp9_update_mv_count(td);
1845 if (cm->interp_filter == SWITCHABLE) {
1846 const int ctx = get_pred_context_switchable_interp(xd);
1847 ++td->counts->switchable_interp[ctx][xdmi->interp_filter];
1851 rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1852 rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1853 rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1855 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1856 rdc->filter_diff[i] += ctx->best_filter_diff[i];
1859 for (h = 0; h < y_mis; ++h) {
1860 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1861 for (w = 0; w < x_mis; ++w) {
1862 MV_REF *const mv = frame_mv + w;
1863 mv->ref_frame[0] = mi->ref_frame[0];
1864 mv->ref_frame[1] = mi->ref_frame[1];
1865 mv->mv[0].as_int = mi->mv[0].as_int;
1866 mv->mv[1].as_int = mi->mv[1].as_int;
1871 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1872 int mi_row, int mi_col) {
1873 uint8_t *const buffers[3] = { src->y_buffer, src->u_buffer, src->v_buffer };
1874 const int strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
1877 // Set current frame pointer.
1878 x->e_mbd.cur_buf = src;
1880 for (i = 0; i < MAX_MB_PLANE; i++)
1881 setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1882 NULL, x->e_mbd.plane[i].subsampling_x,
1883 x->e_mbd.plane[i].subsampling_y);
1886 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1887 RD_COST *rd_cost, BLOCK_SIZE bsize) {
1888 MACROBLOCKD *const xd = &x->e_mbd;
1889 MODE_INFO *const mi = xd->mi[0];
1890 INTERP_FILTER filter_ref;
1892 filter_ref = get_pred_context_switchable_interp(xd);
1893 if (filter_ref == SWITCHABLE_FILTERS) filter_ref = EIGHTTAP;
1895 mi->sb_type = bsize;
1898 VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[tx_mode]);
1900 mi->uv_mode = DC_PRED;
1901 mi->ref_frame[0] = LAST_FRAME;
1902 mi->ref_frame[1] = NONE;
1903 mi->mv[0].as_int = 0;
1904 mi->interp_filter = filter_ref;
1906 xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1909 vp9_rd_cost_init(rd_cost);
1912 static void set_segment_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
1913 int mi_row, int mi_col, BLOCK_SIZE bsize,
1915 VP9_COMMON *const cm = &cpi->common;
1916 const uint8_t *const map =
1917 cm->seg.update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1919 vp9_init_plane_quantizers(cpi, x);
1920 vpx_clear_system_state();
1922 if (aq_mode == NO_AQ || aq_mode == PSNR_AQ) {
1923 if (cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance)
1924 x->rdmult = x->cb_rdmult;
1928 if (aq_mode == CYCLIC_REFRESH_AQ) {
1929 // If segment is boosted, use rdmult for that segment.
1930 if (cyclic_refresh_segment_id_boosted(
1931 get_segment_id(cm, map, bsize, mi_row, mi_col)))
1932 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1936 x->rdmult = vp9_compute_rd_mult(cpi, cm->base_qindex + cm->y_dc_delta_q);
1938 if (cpi->sf.enable_wiener_variance && cm->show_frame) {
1939 if (cm->seg.enabled)
1940 x->rdmult = vp9_compute_rd_mult(
1941 cpi, vp9_get_qindex(&cm->seg, x->e_mbd.mi[0]->segment_id,
1946 static void rd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
1947 MACROBLOCK *const x, int mi_row, int mi_col,
1948 RD_COST *rd_cost, BLOCK_SIZE bsize,
1949 PICK_MODE_CONTEXT *ctx, int64_t best_rd) {
1950 VP9_COMMON *const cm = &cpi->common;
1951 TileInfo *const tile_info = &tile_data->tile_info;
1952 MACROBLOCKD *const xd = &x->e_mbd;
1954 struct macroblock_plane *const p = x->plane;
1955 struct macroblockd_plane *const pd = xd->plane;
1956 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1959 vpx_clear_system_state();
1961 // Use the lower precision, but faster, 32x32 fdct for mode selection.
1962 x->use_lp32x32fdct = 1;
1964 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1966 mi->sb_type = bsize;
1968 for (i = 0; i < MAX_MB_PLANE; ++i) {
1969 p[i].coeff = ctx->coeff_pbuf[i][0];
1970 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1971 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1972 p[i].eobs = ctx->eobs_pbuf[i][0];
1976 ctx->pred_pixel_ready = 0;
1979 // Set to zero to make sure we do not use the previous encoded frame stats
1982 #if CONFIG_VP9_HIGHBITDEPTH
1983 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1984 x->source_variance = vp9_high_get_sby_perpixel_variance(
1985 cpi, &x->plane[0].src, bsize, xd->bd);
1987 x->source_variance =
1988 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1991 x->source_variance =
1992 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1993 #endif // CONFIG_VP9_HIGHBITDEPTH
1995 // Save rdmult before it might be changed, so it can be restored later.
1996 orig_rdmult = x->rdmult;
1998 if ((cpi->sf.tx_domain_thresh > 0.0) || (cpi->sf.quant_opt_thresh > 0.0)) {
1999 double logvar = vp9_log_block_var(cpi, x, bsize);
2000 // Check block complexity as part of descision on using pixel or transform
2001 // domain distortion in rd tests.
2002 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion &&
2003 (logvar >= cpi->sf.tx_domain_thresh);
2005 // Check block complexity as part of descision on using quantized
2006 // coefficient optimisation inside the rd loop.
2007 x->block_qcoeff_opt =
2008 cpi->sf.allow_quant_coeff_opt && (logvar <= cpi->sf.quant_opt_thresh);
2010 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion;
2011 x->block_qcoeff_opt = cpi->sf.allow_quant_coeff_opt;
2014 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
2015 set_segment_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode);
2017 // Find best coding mode & reconstruct the MB so it is available
2018 // as a predictor for MBs that follow in the SB
2019 if (frame_is_intra_only(cm)) {
2020 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
2022 if (bsize >= BLOCK_8X8) {
2023 if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
2024 vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
2027 vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2028 bsize, ctx, best_rd);
2030 vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2031 bsize, ctx, best_rd);
2035 // Examine the resulting rate and for AQ mode 2 make a segment choice.
2036 if ((rd_cost->rate != INT_MAX) && (aq_mode == COMPLEXITY_AQ) &&
2037 (bsize >= BLOCK_16X16) &&
2038 (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
2039 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
2040 vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
2043 // TODO(jingning) The rate-distortion optimization flow needs to be
2044 // refactored to provide proper exit/return handle.
2045 if (rd_cost->rate == INT_MAX)
2046 rd_cost->rdcost = INT64_MAX;
2048 rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2050 x->rdmult = orig_rdmult;
2052 ctx->rate = rd_cost->rate;
2053 ctx->dist = rd_cost->dist;
2056 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
2057 const MACROBLOCK *x = &td->mb;
2058 const MACROBLOCKD *const xd = &x->e_mbd;
2059 const MODE_INFO *const mi = xd->mi[0];
2060 const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2061 const BLOCK_SIZE bsize = mi->sb_type;
2063 if (!frame_is_intra_only(cm)) {
2064 FRAME_COUNTS *const counts = td->counts;
2065 const int inter_block = is_inter_block(mi);
2066 const int seg_ref_active =
2067 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_REF_FRAME);
2068 if (!seg_ref_active) {
2069 counts->intra_inter[get_intra_inter_context(xd)][inter_block]++;
2070 // If the segment reference feature is enabled we have only a single
2071 // reference frame allowed for the segment so exclude it from
2072 // the reference frame counts used to work out probabilities.
2074 const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
2075 if (cm->reference_mode == REFERENCE_MODE_SELECT)
2076 counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
2077 [has_second_ref(mi)]++;
2079 if (has_second_ref(mi)) {
2080 const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
2081 const int ctx = vp9_get_pred_context_comp_ref_p(cm, xd);
2082 const int bit = mi->ref_frame[!idx] == cm->comp_var_ref[1];
2083 counts->comp_ref[ctx][bit]++;
2085 counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
2086 [ref0 != LAST_FRAME]++;
2087 if (ref0 != LAST_FRAME)
2088 counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
2089 [ref0 != GOLDEN_FRAME]++;
2094 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP)) {
2095 const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
2096 if (bsize >= BLOCK_8X8) {
2097 const PREDICTION_MODE mode = mi->mode;
2098 ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
2100 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2101 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2103 for (idy = 0; idy < 2; idy += num_4x4_h) {
2104 for (idx = 0; idx < 2; idx += num_4x4_w) {
2105 const int j = idy * 2 + idx;
2106 const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
2107 ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
2115 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
2116 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2117 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2118 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2120 MACROBLOCKD *const xd = &x->e_mbd;
2122 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2123 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2124 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2125 int mi_height = num_8x8_blocks_high_lookup[bsize];
2126 for (p = 0; p < MAX_MB_PLANE; p++) {
2127 memcpy(xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
2128 a + num_4x4_blocks_wide * p,
2129 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2130 xd->plane[p].subsampling_x);
2131 memcpy(xd->left_context[p] +
2132 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2133 l + num_4x4_blocks_high * p,
2134 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2135 xd->plane[p].subsampling_y);
2137 memcpy(xd->above_seg_context + mi_col, sa,
2138 sizeof(*xd->above_seg_context) * mi_width);
2139 memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
2140 sizeof(xd->left_seg_context[0]) * mi_height);
2143 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
2144 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2145 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2146 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2148 const MACROBLOCKD *const xd = &x->e_mbd;
2150 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2151 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2152 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2153 int mi_height = num_8x8_blocks_high_lookup[bsize];
2155 // buffer the above/left context information of the block in search.
2156 for (p = 0; p < MAX_MB_PLANE; ++p) {
2157 memcpy(a + num_4x4_blocks_wide * p,
2158 xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
2159 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2160 xd->plane[p].subsampling_x);
2161 memcpy(l + num_4x4_blocks_high * p,
2162 xd->left_context[p] +
2163 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2164 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2165 xd->plane[p].subsampling_y);
2167 memcpy(sa, xd->above_seg_context + mi_col,
2168 sizeof(*xd->above_seg_context) * mi_width);
2169 memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
2170 sizeof(xd->left_seg_context[0]) * mi_height);
2173 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile, ThreadData *td,
2174 TOKENEXTRA **tp, int mi_row, int mi_col,
2175 int output_enabled, BLOCK_SIZE bsize,
2176 PICK_MODE_CONTEXT *ctx) {
2177 MACROBLOCK *const x = &td->mb;
2178 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2180 if ((cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance) &&
2181 cpi->oxcf.aq_mode == NO_AQ)
2182 x->rdmult = x->cb_rdmult;
2184 update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
2185 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2187 if (output_enabled) {
2188 update_stats(&cpi->common, td);
2190 (*tp)->token = EOSB_TOKEN;
2195 static void encode_sb(VP9_COMP *cpi, ThreadData *td, const TileInfo *const tile,
2196 TOKENEXTRA **tp, int mi_row, int mi_col,
2197 int output_enabled, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2198 VP9_COMMON *const cm = &cpi->common;
2199 MACROBLOCK *const x = &td->mb;
2200 MACROBLOCKD *const xd = &x->e_mbd;
2202 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2204 PARTITION_TYPE partition;
2205 BLOCK_SIZE subsize = bsize;
2207 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2209 if (bsize >= BLOCK_8X8) {
2210 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2211 subsize = get_subsize(bsize, pc_tree->partitioning);
2214 subsize = BLOCK_4X4;
2217 partition = partition_lookup[bsl][subsize];
2218 if (output_enabled && bsize != BLOCK_4X4)
2219 td->counts->partition[ctx][partition]++;
2221 switch (partition) {
2222 case PARTITION_NONE:
2223 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2226 case PARTITION_VERT:
2227 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2228 &pc_tree->vertical[0]);
2229 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2230 encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
2231 subsize, &pc_tree->vertical[1]);
2234 case PARTITION_HORZ:
2235 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2236 &pc_tree->horizontal[0]);
2237 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2238 encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
2239 subsize, &pc_tree->horizontal[1]);
2243 assert(partition == PARTITION_SPLIT);
2244 if (bsize == BLOCK_8X8) {
2245 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2246 pc_tree->leaf_split[0]);
2248 encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2250 encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2251 subsize, pc_tree->split[1]);
2252 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2253 subsize, pc_tree->split[2]);
2254 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
2255 subsize, pc_tree->split[3]);
2260 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2261 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2264 // Check to see if the given partition size is allowed for a specified number
2265 // of 8x8 block rows and columns remaining in the image.
2266 // If not then return the largest allowed partition size
2267 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
2268 int cols_left, int *bh, int *bw) {
2269 if (rows_left <= 0 || cols_left <= 0) {
2270 return VPXMIN(bsize, BLOCK_8X8);
2272 for (; bsize > 0; bsize -= 3) {
2273 *bh = num_8x8_blocks_high_lookup[bsize];
2274 *bw = num_8x8_blocks_wide_lookup[bsize];
2275 if ((*bh <= rows_left) && (*bw <= cols_left)) {
2283 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis, int bh_in,
2284 int bw_in, int row8x8_remaining,
2285 int col8x8_remaining, BLOCK_SIZE bsize,
2286 MODE_INFO **mi_8x8) {
2289 for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
2291 for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
2292 const int index = r * mis + c;
2293 mi_8x8[index] = mi + index;
2294 mi_8x8[index]->sb_type = find_partition_size(
2295 bsize, row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
2300 // This function attempts to set all mode info entries in a given SB64
2301 // to the same block partition size.
2302 // However, at the bottom and right borders of the image the requested size
2303 // may not be allowed in which case this code attempts to choose the largest
2304 // allowable partition.
2305 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
2306 MODE_INFO **mi_8x8, int mi_row, int mi_col,
2308 VP9_COMMON *const cm = &cpi->common;
2309 const int mis = cm->mi_stride;
2310 const int row8x8_remaining = tile->mi_row_end - mi_row;
2311 const int col8x8_remaining = tile->mi_col_end - mi_col;
2312 int block_row, block_col;
2313 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2314 int bh = num_8x8_blocks_high_lookup[bsize];
2315 int bw = num_8x8_blocks_wide_lookup[bsize];
2317 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2319 // Apply the requested partition size to the SB64 if it is all "in image"
2320 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2321 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2322 for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
2323 for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
2324 int index = block_row * mis + block_col;
2325 mi_8x8[index] = mi_upper_left + index;
2326 mi_8x8[index]->sb_type = bsize;
2330 // Else this is a partial SB64.
2331 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2332 col8x8_remaining, bsize, mi_8x8);
2336 static const struct {
2339 } coord_lookup[16] = {
2362 static void set_source_var_based_partition(VP9_COMP *cpi,
2363 const TileInfo *const tile,
2364 MACROBLOCK *const x,
2365 MODE_INFO **mi_8x8, int mi_row,
2367 VP9_COMMON *const cm = &cpi->common;
2368 const int mis = cm->mi_stride;
2369 const int row8x8_remaining = tile->mi_row_end - mi_row;
2370 const int col8x8_remaining = tile->mi_col_end - mi_col;
2371 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2373 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
2375 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2378 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2379 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2383 const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
2384 int is_larger_better = 0;
2386 unsigned int thr = cpi->source_var_thresh;
2388 memset(d32, 0, 4 * sizeof(diff));
2390 for (i = 0; i < 4; i++) {
2393 for (j = 0; j < 4; j++) {
2394 int b_mi_row = coord_lookup[i * 4 + j].row;
2395 int b_mi_col = coord_lookup[i * 4 + j].col;
2396 int boffset = b_mi_row / 2 * cm->mb_cols + b_mi_col / 2;
2398 d16[j] = cpi->source_diff_var + offset + boffset;
2400 index = b_mi_row * mis + b_mi_col;
2401 mi_8x8[index] = mi_upper_left + index;
2402 mi_8x8[index]->sb_type = BLOCK_16X16;
2404 // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
2405 // size to further improve quality.
2408 is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
2409 (d16[2]->var < thr) && (d16[3]->var < thr);
2411 // Use 32x32 partition
2412 if (is_larger_better) {
2415 for (j = 0; j < 4; j++) {
2416 d32[i].sse += d16[j]->sse;
2417 d32[i].sum += d16[j]->sum;
2421 (unsigned int)(d32[i].sse -
2422 (unsigned int)(((int64_t)d32[i].sum * d32[i].sum) >>
2425 index = coord_lookup[i * 4].row * mis + coord_lookup[i * 4].col;
2426 mi_8x8[index] = mi_upper_left + index;
2427 mi_8x8[index]->sb_type = BLOCK_32X32;
2431 if (use32x32 == 4) {
2433 is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
2434 (d32[2].var < thr) && (d32[3].var < thr);
2436 // Use 64x64 partition
2437 if (is_larger_better) {
2438 mi_8x8[0] = mi_upper_left;
2439 mi_8x8[0]->sb_type = BLOCK_64X64;
2442 } else { // partial in-image SB64
2443 int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
2444 int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
2445 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2446 col8x8_remaining, BLOCK_16X16, mi_8x8);
2450 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
2451 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
2453 VP9_COMMON *const cm = &cpi->common;
2454 MACROBLOCK *const x = &td->mb;
2455 MACROBLOCKD *const xd = &x->e_mbd;
2456 MODE_INFO *const mi = xd->mi[0];
2457 struct macroblock_plane *const p = x->plane;
2458 const struct segmentation *const seg = &cm->seg;
2459 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
2460 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
2461 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
2462 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
2464 *(xd->mi[0]) = ctx->mic;
2465 *(x->mbmi_ext) = ctx->mbmi_ext;
2467 if (seg->enabled && (cpi->oxcf.aq_mode != NO_AQ || cpi->roi.enabled)) {
2468 // Setting segmentation map for cyclic_refresh.
2469 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
2470 vp9_cyclic_refresh_update_segment(cpi, mi, mi_row, mi_col, bsize,
2471 ctx->rate, ctx->dist, x->skip, p);
2473 const uint8_t *const map =
2474 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
2475 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
2477 vp9_init_plane_quantizers(cpi, x);
2480 if (is_inter_block(mi)) {
2481 vp9_update_mv_count(td);
2482 if (cm->interp_filter == SWITCHABLE) {
2483 const int pred_ctx = get_pred_context_switchable_interp(xd);
2484 ++td->counts->switchable_interp[pred_ctx][mi->interp_filter];
2487 if (mi->sb_type < BLOCK_8X8) {
2488 mi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
2489 mi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
2493 if (cm->use_prev_frame_mvs || !cm->error_resilient_mode ||
2494 (cpi->svc.use_base_mv && cpi->svc.number_spatial_layers > 1 &&
2495 cpi->svc.spatial_layer_id != cpi->svc.number_spatial_layers - 1)) {
2496 MV_REF *const frame_mvs =
2497 cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
2500 for (h = 0; h < y_mis; ++h) {
2501 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
2502 for (w = 0; w < x_mis; ++w) {
2503 MV_REF *const mv = frame_mv + w;
2504 mv->ref_frame[0] = mi->ref_frame[0];
2505 mv->ref_frame[1] = mi->ref_frame[1];
2506 mv->mv[0].as_int = mi->mv[0].as_int;
2507 mv->mv[1].as_int = mi->mv[1].as_int;
2512 x->skip = ctx->skip;
2513 x->skip_txfm[0] = (mi->segment_id || xd->lossless) ? 0 : ctx->skip_txfm[0];
2516 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
2517 const TileInfo *const tile, TOKENEXTRA **tp, int mi_row,
2518 int mi_col, int output_enabled, BLOCK_SIZE bsize,
2519 PICK_MODE_CONTEXT *ctx) {
2520 MACROBLOCK *const x = &td->mb;
2521 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2522 update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
2524 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2525 update_stats(&cpi->common, td);
2527 (*tp)->token = EOSB_TOKEN;
2531 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
2532 const TileInfo *const tile, TOKENEXTRA **tp,
2533 int mi_row, int mi_col, int output_enabled,
2534 BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2535 VP9_COMMON *const cm = &cpi->common;
2536 MACROBLOCK *const x = &td->mb;
2537 MACROBLOCKD *const xd = &x->e_mbd;
2539 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2541 PARTITION_TYPE partition;
2544 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2546 if (bsize >= BLOCK_8X8) {
2547 const int idx_str = xd->mi_stride * mi_row + mi_col;
2548 MODE_INFO **mi_8x8 = cm->mi_grid_visible + idx_str;
2549 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2550 subsize = mi_8x8[0]->sb_type;
2553 subsize = BLOCK_4X4;
2556 partition = partition_lookup[bsl][subsize];
2557 if (output_enabled && bsize != BLOCK_4X4)
2558 td->counts->partition[ctx][partition]++;
2560 switch (partition) {
2561 case PARTITION_NONE:
2562 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2565 case PARTITION_VERT:
2566 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2567 &pc_tree->vertical[0]);
2568 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2569 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2570 subsize, &pc_tree->vertical[1]);
2573 case PARTITION_HORZ:
2574 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2575 &pc_tree->horizontal[0]);
2576 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2577 encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2578 subsize, &pc_tree->horizontal[1]);
2582 assert(partition == PARTITION_SPLIT);
2583 subsize = get_subsize(bsize, PARTITION_SPLIT);
2584 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2586 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2587 subsize, pc_tree->split[1]);
2588 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2589 subsize, pc_tree->split[2]);
2590 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
2591 output_enabled, subsize, pc_tree->split[3]);
2595 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2596 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2599 static void rd_use_partition(VP9_COMP *cpi, ThreadData *td,
2600 TileDataEnc *tile_data, MODE_INFO **mi_8x8,
2601 TOKENEXTRA **tp, int mi_row, int mi_col,
2602 BLOCK_SIZE bsize, int *rate, int64_t *dist,
2603 int do_recon, PC_TREE *pc_tree) {
2604 VP9_COMMON *const cm = &cpi->common;
2605 TileInfo *const tile_info = &tile_data->tile_info;
2606 MACROBLOCK *const x = &td->mb;
2607 MACROBLOCKD *const xd = &x->e_mbd;
2608 const int mis = cm->mi_stride;
2609 const int bsl = b_width_log2_lookup[bsize];
2610 const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
2611 const int bss = (1 << bsl) / 4;
2613 PARTITION_TYPE partition = PARTITION_NONE;
2615 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2616 PARTITION_CONTEXT sl[8], sa[8];
2617 RD_COST last_part_rdc, none_rdc, chosen_rdc;
2618 BLOCK_SIZE sub_subsize = BLOCK_4X4;
2619 int splits_below = 0;
2620 BLOCK_SIZE bs_type = mi_8x8[0]->sb_type;
2621 int do_partition_search = 1;
2622 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2624 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2626 assert(num_4x4_blocks_wide_lookup[bsize] ==
2627 num_4x4_blocks_high_lookup[bsize]);
2629 vp9_rd_cost_reset(&last_part_rdc);
2630 vp9_rd_cost_reset(&none_rdc);
2631 vp9_rd_cost_reset(&chosen_rdc);
2633 partition = partition_lookup[bsl][bs_type];
2634 subsize = get_subsize(bsize, partition);
2636 pc_tree->partitioning = partition;
2637 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2639 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ) {
2640 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2641 x->mb_energy = vp9_block_energy(cpi, x, bsize);
2644 if (do_partition_search &&
2645 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2646 cpi->sf.adjust_partitioning_from_last_frame) {
2647 // Check if any of the sub blocks are further split.
2648 if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
2649 sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
2651 for (i = 0; i < 4; i++) {
2652 int jj = i >> 1, ii = i & 0x01;
2653 MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
2654 if (this_mi && this_mi->sb_type >= sub_subsize) {
2660 // If partition is not none try none unless each of the 4 splits are split
2662 if (partition != PARTITION_NONE && !splits_below &&
2663 mi_row + (mi_step >> 1) < cm->mi_rows &&
2664 mi_col + (mi_step >> 1) < cm->mi_cols) {
2665 pc_tree->partitioning = PARTITION_NONE;
2666 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize, ctx,
2669 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2671 if (none_rdc.rate < INT_MAX) {
2672 none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2674 RDCOST(x->rdmult, x->rddiv, none_rdc.rate, none_rdc.dist);
2677 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2678 mi_8x8[0]->sb_type = bs_type;
2679 pc_tree->partitioning = partition;
2683 switch (partition) {
2684 case PARTITION_NONE:
2685 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc, bsize,
2688 case PARTITION_HORZ:
2689 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
2690 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2691 subsize, &pc_tree->horizontal[0], INT64_MAX);
2692 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2693 mi_row + (mi_step >> 1) < cm->mi_rows) {
2695 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2696 vp9_rd_cost_init(&tmp_rdc);
2697 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2698 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2699 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
2700 rd_pick_sb_modes(cpi, tile_data, x, mi_row + (mi_step >> 1), mi_col,
2701 &tmp_rdc, subsize, &pc_tree->horizontal[1], INT64_MAX);
2702 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2703 vp9_rd_cost_reset(&last_part_rdc);
2706 last_part_rdc.rate += tmp_rdc.rate;
2707 last_part_rdc.dist += tmp_rdc.dist;
2708 last_part_rdc.rdcost += tmp_rdc.rdcost;
2711 case PARTITION_VERT:
2712 pc_tree->vertical[0].skip_ref_frame_mask = 0;
2713 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2714 subsize, &pc_tree->vertical[0], INT64_MAX);
2715 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2716 mi_col + (mi_step >> 1) < cm->mi_cols) {
2718 PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
2719 vp9_rd_cost_init(&tmp_rdc);
2720 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2721 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2722 pc_tree->vertical[bsize > BLOCK_8X8].skip_ref_frame_mask = 0;
2723 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + (mi_step >> 1),
2725 &pc_tree->vertical[bsize > BLOCK_8X8], INT64_MAX);
2726 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2727 vp9_rd_cost_reset(&last_part_rdc);
2730 last_part_rdc.rate += tmp_rdc.rate;
2731 last_part_rdc.dist += tmp_rdc.dist;
2732 last_part_rdc.rdcost += tmp_rdc.rdcost;
2736 assert(partition == PARTITION_SPLIT);
2737 if (bsize == BLOCK_8X8) {
2738 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2739 subsize, pc_tree->leaf_split[0], INT64_MAX);
2742 last_part_rdc.rate = 0;
2743 last_part_rdc.dist = 0;
2744 last_part_rdc.rdcost = 0;
2745 for (i = 0; i < 4; i++) {
2746 int x_idx = (i & 1) * (mi_step >> 1);
2747 int y_idx = (i >> 1) * (mi_step >> 1);
2748 int jj = i >> 1, ii = i & 0x01;
2750 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2753 vp9_rd_cost_init(&tmp_rdc);
2754 rd_use_partition(cpi, td, tile_data, mi_8x8 + jj * bss * mis + ii * bss,
2755 tp, mi_row + y_idx, mi_col + x_idx, subsize,
2756 &tmp_rdc.rate, &tmp_rdc.dist, i != 3,
2758 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2759 vp9_rd_cost_reset(&last_part_rdc);
2762 last_part_rdc.rate += tmp_rdc.rate;
2763 last_part_rdc.dist += tmp_rdc.dist;
2768 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2769 if (last_part_rdc.rate < INT_MAX) {
2770 last_part_rdc.rate += cpi->partition_cost[pl][partition];
2771 last_part_rdc.rdcost =
2772 RDCOST(x->rdmult, x->rddiv, last_part_rdc.rate, last_part_rdc.dist);
2775 if (do_partition_search && cpi->sf.adjust_partitioning_from_last_frame &&
2776 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2777 partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
2778 (mi_row + mi_step < cm->mi_rows ||
2779 mi_row + (mi_step >> 1) == cm->mi_rows) &&
2780 (mi_col + mi_step < cm->mi_cols ||
2781 mi_col + (mi_step >> 1) == cm->mi_cols)) {
2782 BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2783 chosen_rdc.rate = 0;
2784 chosen_rdc.dist = 0;
2785 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2786 pc_tree->partitioning = PARTITION_SPLIT;
2789 for (i = 0; i < 4; i++) {
2790 int x_idx = (i & 1) * (mi_step >> 1);
2791 int y_idx = (i >> 1) * (mi_step >> 1);
2793 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2794 PARTITION_CONTEXT sl[8], sa[8];
2796 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2799 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2800 pc_tree->split[i]->partitioning = PARTITION_NONE;
2801 rd_pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2802 &tmp_rdc, split_subsize, &pc_tree->split[i]->none,
2805 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2807 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2808 vp9_rd_cost_reset(&chosen_rdc);
2812 chosen_rdc.rate += tmp_rdc.rate;
2813 chosen_rdc.dist += tmp_rdc.dist;
2816 encode_sb(cpi, td, tile_info, tp, mi_row + y_idx, mi_col + x_idx, 0,
2817 split_subsize, pc_tree->split[i]);
2819 pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2821 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2823 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2824 if (chosen_rdc.rate < INT_MAX) {
2825 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2827 RDCOST(x->rdmult, x->rddiv, chosen_rdc.rate, chosen_rdc.dist);
2831 // If last_part is better set the partitioning to that.
2832 if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2833 mi_8x8[0]->sb_type = bsize;
2834 if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2835 chosen_rdc = last_part_rdc;
2837 // If none was better set the partitioning to that.
2838 if (none_rdc.rdcost < chosen_rdc.rdcost) {
2839 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2840 chosen_rdc = none_rdc;
2843 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2845 // We must have chosen a partitioning and encoding or we'll fail later on.
2846 // No other opportunities for success.
2847 if (bsize == BLOCK_64X64)
2848 assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2851 int output_enabled = (bsize == BLOCK_64X64);
2852 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2856 *rate = chosen_rdc.rate;
2857 *dist = chosen_rdc.dist;
2860 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2861 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2862 BLOCK_4X4, BLOCK_8X8, BLOCK_8X8, BLOCK_8X8, BLOCK_16X16,
2863 BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
2866 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2867 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2868 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2869 BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
2872 // Look at all the mode_info entries for blocks that are part of this
2873 // partition and find the min and max values for sb_type.
2874 // At the moment this is designed to work on a 64x64 SB but could be
2875 // adjusted to use a size parameter.
2877 // The min and max are assumed to have been initialized prior to calling this
2878 // function so repeat calls can accumulate a min and max of more than one sb64.
2879 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2880 BLOCK_SIZE *min_block_size,
2881 BLOCK_SIZE *max_block_size,
2882 int bs_hist[BLOCK_SIZES]) {
2883 int sb_width_in_blocks = MI_BLOCK_SIZE;
2884 int sb_height_in_blocks = MI_BLOCK_SIZE;
2888 // Check the sb_type for each block that belongs to this region.
2889 for (i = 0; i < sb_height_in_blocks; ++i) {
2890 for (j = 0; j < sb_width_in_blocks; ++j) {
2891 MODE_INFO *mi = mi_8x8[index + j];
2892 BLOCK_SIZE sb_type = mi ? mi->sb_type : 0;
2894 *min_block_size = VPXMIN(*min_block_size, sb_type);
2895 *max_block_size = VPXMAX(*max_block_size, sb_type);
2897 index += xd->mi_stride;
2901 // Next square block size less or equal than current block size.
2902 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2903 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_8X8, BLOCK_8X8,
2904 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2905 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64
2908 // Look at neighboring blocks and set a min and max partition size based on
2910 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2911 MACROBLOCKD *const xd, int mi_row,
2912 int mi_col, BLOCK_SIZE *min_block_size,
2913 BLOCK_SIZE *max_block_size) {
2914 VP9_COMMON *const cm = &cpi->common;
2915 MODE_INFO **mi = xd->mi;
2916 const int left_in_image = !!xd->left_mi;
2917 const int above_in_image = !!xd->above_mi;
2918 const int row8x8_remaining = tile->mi_row_end - mi_row;
2919 const int col8x8_remaining = tile->mi_col_end - mi_col;
2921 BLOCK_SIZE min_size = BLOCK_4X4;
2922 BLOCK_SIZE max_size = BLOCK_64X64;
2923 int bs_hist[BLOCK_SIZES] = { 0 };
2925 // Trap case where we do not have a prediction.
2926 if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2927 // Default "min to max" and "max to min"
2928 min_size = BLOCK_64X64;
2929 max_size = BLOCK_4X4;
2931 // NOTE: each call to get_sb_partition_size_range() uses the previous
2932 // passed in values for min and max as a starting point.
2933 // Find the min and max partition used in previous frame at this location
2934 if (cm->frame_type != KEY_FRAME) {
2935 MODE_INFO **prev_mi =
2936 &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2937 get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2939 // Find the min and max partition sizes used in the left SB64
2940 if (left_in_image) {
2941 MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2942 get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2945 // Find the min and max partition sizes used in the above SB64.
2946 if (above_in_image) {
2947 MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2948 get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2952 // Adjust observed min and max for "relaxed" auto partition case.
2953 if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2954 min_size = min_partition_size[min_size];
2955 max_size = max_partition_size[max_size];
2959 // Check border cases where max and min from neighbors may not be legal.
2960 max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
2962 // Test for blocks at the edge of the active image.
2963 // This may be the actual edge of the image or where there are formatting
2965 if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
2966 min_size = BLOCK_4X4;
2969 VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
2972 // When use_square_partition_only is true, make sure at least one square
2973 // partition is allowed by selecting the next smaller square size as
2975 if (cpi->sf.use_square_partition_only &&
2976 next_square_size[max_size] < min_size) {
2977 min_size = next_square_size[max_size];
2980 *min_block_size = min_size;
2981 *max_block_size = max_size;
2984 // TODO(jingning) refactor functions setting partition search range
2985 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd, int mi_row,
2986 int mi_col, BLOCK_SIZE bsize,
2987 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
2988 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2989 int mi_height = num_8x8_blocks_high_lookup[bsize];
2993 const int idx_str = cm->mi_stride * mi_row + mi_col;
2994 MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
2995 BLOCK_SIZE bs, min_size, max_size;
2997 min_size = BLOCK_64X64;
2998 max_size = BLOCK_4X4;
3001 for (idy = 0; idy < mi_height; ++idy) {
3002 for (idx = 0; idx < mi_width; ++idx) {
3003 mi = prev_mi[idy * cm->mi_stride + idx];
3004 bs = mi ? mi->sb_type : bsize;
3005 min_size = VPXMIN(min_size, bs);
3006 max_size = VPXMAX(max_size, bs);
3012 for (idy = 0; idy < mi_height; ++idy) {
3013 mi = xd->mi[idy * cm->mi_stride - 1];
3014 bs = mi ? mi->sb_type : bsize;
3015 min_size = VPXMIN(min_size, bs);
3016 max_size = VPXMAX(max_size, bs);
3021 for (idx = 0; idx < mi_width; ++idx) {
3022 mi = xd->mi[idx - cm->mi_stride];
3023 bs = mi ? mi->sb_type : bsize;
3024 min_size = VPXMIN(min_size, bs);
3025 max_size = VPXMAX(max_size, bs);
3029 if (min_size == max_size) {
3030 min_size = min_partition_size[min_size];
3031 max_size = max_partition_size[max_size];
3038 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3039 memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
3042 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3043 memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
3046 #if CONFIG_FP_MB_STATS
3047 const int num_16x16_blocks_wide_lookup[BLOCK_SIZES] = { 1, 1, 1, 1, 1, 1, 1,
3049 const int num_16x16_blocks_high_lookup[BLOCK_SIZES] = { 1, 1, 1, 1, 1, 1, 1,
3051 const int qindex_skip_threshold_lookup[BLOCK_SIZES] = { 0, 10, 10, 30, 40,
3054 const int qindex_split_threshold_lookup[BLOCK_SIZES] = { 0, 3, 3, 7, 15,
3057 const int complexity_16x16_blocks_threshold[BLOCK_SIZES] = { 1, 1, 1, 1, 1,
3070 static INLINE MOTION_DIRECTION get_motion_direction_fp(uint8_t fp_byte) {
3071 if (fp_byte & FPMB_MOTION_ZERO_MASK) {
3073 } else if (fp_byte & FPMB_MOTION_LEFT_MASK) {
3075 } else if (fp_byte & FPMB_MOTION_RIGHT_MASK) {
3077 } else if (fp_byte & FPMB_MOTION_UP_MASK) {
3084 static INLINE int get_motion_inconsistency(MOTION_DIRECTION this_mv,
3085 MOTION_DIRECTION that_mv) {
3086 if (this_mv == that_mv) {
3089 return abs(this_mv - that_mv) == 2 ? 2 : 1;
3094 // Calculate prediction based on the given input features and neural net config.
3095 // Assume there are no more than NN_MAX_NODES_PER_LAYER nodes in each hidden
3097 static void nn_predict(const float *features, const NN_CONFIG *nn_config,
3099 int num_input_nodes = nn_config->num_inputs;
3101 float buf[2][NN_MAX_NODES_PER_LAYER];
3102 const float *input_nodes = features;
3104 // Propagate hidden layers.
3105 const int num_layers = nn_config->num_hidden_layers;
3107 assert(num_layers <= NN_MAX_HIDDEN_LAYERS);
3108 for (layer = 0; layer < num_layers; ++layer) {
3109 const float *weights = nn_config->weights[layer];
3110 const float *bias = nn_config->bias[layer];
3111 float *output_nodes = buf[buf_index];
3112 const int num_output_nodes = nn_config->num_hidden_nodes[layer];
3113 assert(num_output_nodes < NN_MAX_NODES_PER_LAYER);
3114 for (node = 0; node < num_output_nodes; ++node) {
3116 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3118 // ReLU as activation function.
3119 val = VPXMAX(val, 0.0f);
3120 output_nodes[node] = val;
3121 weights += num_input_nodes;
3123 num_input_nodes = num_output_nodes;
3124 input_nodes = output_nodes;
3125 buf_index = 1 - buf_index;
3128 // Final output layer.
3130 const float *weights = nn_config->weights[num_layers];
3131 for (node = 0; node < nn_config->num_outputs; ++node) {
3132 const float *bias = nn_config->bias[num_layers];
3134 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3135 output[node] = val + bias[node];
3136 weights += num_input_nodes;
3142 // Machine-learning based partition search early termination.
3143 // Return 1 to skip split and rect partitions.
3144 static int ml_pruning_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
3145 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
3148 abs(ctx->mic.mv[0].as_mv.col) + abs(ctx->mic.mv[0].as_mv.row);
3149 const int left_in_image = !!xd->left_mi;
3150 const int above_in_image = !!xd->above_mi;
3151 MODE_INFO **prev_mi =
3152 &cm->prev_mi_grid_visible[mi_col + cm->mi_stride * mi_row];
3153 int above_par = 0; // above_partitioning
3154 int left_par = 0; // left_partitioning
3155 int last_par = 0; // last_partitioning
3158 BLOCK_SIZE context_size;
3159 const NN_CONFIG *nn_config = NULL;
3160 const float *mean, *sd, *linear_weights;
3161 float nn_score, linear_score;
3162 float features[FEATURES];
3164 assert(b_width_log2_lookup[bsize] == b_height_log2_lookup[bsize]);
3165 vpx_clear_system_state();
3170 nn_config = &vp9_partition_nnconfig_64x64;
3174 nn_config = &vp9_partition_nnconfig_32x32;
3178 nn_config = &vp9_partition_nnconfig_16x16;
3180 default: assert(0 && "Unexpected block size."); return 0;
3183 if (above_in_image) {
3184 context_size = xd->above_mi->sb_type;
3185 if (context_size < bsize)
3187 else if (context_size == bsize)
3191 if (left_in_image) {
3192 context_size = xd->left_mi->sb_type;
3193 if (context_size < bsize)
3195 else if (context_size == bsize)
3200 context_size = prev_mi[0]->sb_type;
3201 if (context_size < bsize)
3203 else if (context_size == bsize)
3207 mean = &vp9_partition_feature_mean[offset];
3208 sd = &vp9_partition_feature_std[offset];
3209 features[0] = ((float)ctx->rate - mean[0]) / sd[0];
3210 features[1] = ((float)ctx->dist - mean[1]) / sd[1];
3211 features[2] = ((float)mag_mv / 2 - mean[2]) * sd[2];
3212 features[3] = ((float)(left_par + above_par) / 2 - mean[3]) * sd[3];
3213 features[4] = ((float)ctx->sum_y_eobs - mean[4]) / sd[4];
3214 features[5] = ((float)cm->base_qindex - mean[5]) * sd[5];
3215 features[6] = ((float)last_par - mean[6]) * sd[6];
3217 // Predict using linear model.
3218 linear_weights = &vp9_partition_linear_weights[offset];
3219 linear_score = linear_weights[FEATURES];
3220 for (i = 0; i < FEATURES; ++i)
3221 linear_score += linear_weights[i] * features[i];
3222 if (linear_score > 0.1f) return 0;
3224 // Predict using neural net model.
3225 nn_predict(features, nn_config, &nn_score);
3227 if (linear_score < -0.0f && nn_score < 0.1f) return 1;
3228 if (nn_score < -0.0f && linear_score < 0.1f) return 1;
3234 // ML-based partition search breakout.
3235 static int ml_predict_breakout(VP9_COMP *const cpi, BLOCK_SIZE bsize,
3236 const MACROBLOCK *const x,
3237 const RD_COST *const rd_cost) {
3238 DECLARE_ALIGNED(16, static const uint8_t, vp9_64_zeros[64]) = { 0 };
3239 const VP9_COMMON *const cm = &cpi->common;
3240 float features[FEATURES];
3241 const float *linear_weights = NULL; // Linear model weights.
3242 float linear_score = 0.0f;
3243 const int qindex = cm->base_qindex;
3244 const int q_ctx = qindex >= 200 ? 0 : (qindex >= 150 ? 1 : 2);
3245 const int is_720p_or_larger = VPXMIN(cm->width, cm->height) >= 720;
3246 const int resolution_ctx = is_720p_or_larger ? 1 : 0;
3250 linear_weights = vp9_partition_breakout_weights_64[resolution_ctx][q_ctx];
3253 linear_weights = vp9_partition_breakout_weights_32[resolution_ctx][q_ctx];
3256 linear_weights = vp9_partition_breakout_weights_16[resolution_ctx][q_ctx];
3259 linear_weights = vp9_partition_breakout_weights_8[resolution_ctx][q_ctx];
3261 default: assert(0 && "Unexpected block size."); return 0;
3263 if (!linear_weights) return 0;
3265 { // Generate feature values.
3266 #if CONFIG_VP9_HIGHBITDEPTH
3268 vp9_ac_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3270 const int ac_q = vp9_ac_quant(qindex, 0, cm->bit_depth);
3271 #endif // CONFIG_VP9_HIGHBITDEPTH
3272 const int num_pels_log2 = num_pels_log2_lookup[bsize];
3273 int feature_index = 0;
3274 unsigned int var, sse;
3275 float rate_f, dist_f;
3277 #if CONFIG_VP9_HIGHBITDEPTH
3278 if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3280 vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, x->e_mbd.bd);
3282 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3283 vp9_64_zeros, 0, &sse);
3286 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3287 vp9_64_zeros, 0, &sse);
3289 var = var >> num_pels_log2;
3291 vpx_clear_system_state();
3293 rate_f = (float)VPXMIN(rd_cost->rate, INT_MAX);
3294 dist_f = (float)(VPXMIN(rd_cost->dist, INT_MAX) >> num_pels_log2);
3296 ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
3299 features[feature_index++] = rate_f;
3300 features[feature_index++] = dist_f;
3301 features[feature_index++] = (float)var;
3302 features[feature_index++] = (float)ac_q;
3303 assert(feature_index == FEATURES);
3306 { // Calculate the output score.
3308 linear_score = linear_weights[FEATURES];
3309 for (i = 0; i < FEATURES; ++i)
3310 linear_score += linear_weights[i] * features[i];
3313 return linear_score >= cpi->sf.rd_ml_partition.search_breakout_thresh[q_ctx];
3319 static void ml_prune_rect_partition(VP9_COMP *const cpi, MACROBLOCK *const x,
3321 const PC_TREE *const pc_tree,
3322 int *allow_horz, int *allow_vert,
3324 const NN_CONFIG *nn_config = NULL;
3325 float score[LABELS] = {
3332 if (ref_rd <= 0 || ref_rd > 1000000000) return;
3335 case BLOCK_8X8: break;
3337 nn_config = &vp9_rect_part_nnconfig_16;
3338 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[1];
3341 nn_config = &vp9_rect_part_nnconfig_32;
3342 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[2];
3345 nn_config = &vp9_rect_part_nnconfig_64;
3346 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[3];
3348 default: assert(0 && "Unexpected block size."); return;
3350 if (!nn_config || thresh < 0) return;
3352 // Feature extraction and model score calculation.
3354 const VP9_COMMON *const cm = &cpi->common;
3355 #if CONFIG_VP9_HIGHBITDEPTH
3357 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3359 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3360 #endif // CONFIG_VP9_HIGHBITDEPTH
3361 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3362 int feature_index = 0;
3363 float features[FEATURES];
3365 features[feature_index++] = logf((float)dc_q + 1.0f);
3366 features[feature_index++] =
3367 (float)(pc_tree->partitioning == PARTITION_NONE);
3368 features[feature_index++] = logf((float)ref_rd / bs / bs + 1.0f);
3371 const float norm_factor = 1.0f / ((float)ref_rd + 1.0f);
3372 const int64_t none_rdcost = pc_tree->none.rdcost;
3373 float rd_ratio = 2.0f;
3374 if (none_rdcost > 0 && none_rdcost < 1000000000)
3375 rd_ratio = (float)none_rdcost * norm_factor;
3376 features[feature_index++] = VPXMIN(rd_ratio, 2.0f);
3378 for (i = 0; i < 4; ++i) {
3379 const int64_t this_rd = pc_tree->split[i]->none.rdcost;
3380 const int rd_valid = this_rd > 0 && this_rd < 1000000000;
3381 // Ratio between sub-block RD and whole block RD.
3382 features[feature_index++] =
3383 rd_valid ? (float)this_rd * norm_factor : 1.0f;
3387 assert(feature_index == FEATURES);
3388 nn_predict(features, nn_config, score);
3391 // Make decisions based on the model score.
3393 int max_score = -1000;
3394 int horz = 0, vert = 0;
3395 int int_score[LABELS];
3396 for (i = 0; i < LABELS; ++i) {
3397 int_score[i] = (int)(100 * score[i]);
3398 max_score = VPXMAX(int_score[i], max_score);
3400 thresh = max_score - thresh;
3401 for (i = 0; i < LABELS; ++i) {
3402 if (int_score[i] >= thresh) {
3403 if ((i >> 0) & 1) horz = 1;
3404 if ((i >> 1) & 1) vert = 1;
3407 *allow_horz = *allow_horz && horz;
3408 *allow_vert = *allow_vert && vert;
3414 // Perform fast and coarse motion search for the given block. This is a
3415 // pre-processing step for the ML based partition search speedup.
3416 static void simple_motion_search(const VP9_COMP *const cpi, MACROBLOCK *const x,
3417 BLOCK_SIZE bsize, int mi_row, int mi_col,
3418 MV ref_mv, MV_REFERENCE_FRAME ref,
3419 uint8_t *const pred_buf) {
3420 const VP9_COMMON *const cm = &cpi->common;
3421 MACROBLOCKD *const xd = &x->e_mbd;
3422 MODE_INFO *const mi = xd->mi[0];
3423 const YV12_BUFFER_CONFIG *const yv12 = get_ref_frame_buffer(cpi, ref);
3424 const int step_param = 1;
3425 const MvLimits tmp_mv_limits = x->mv_limits;
3426 const SEARCH_METHODS search_method = NSTEP;
3427 const int sadpb = x->sadperbit16;
3428 MV ref_mv_full = { ref_mv.row >> 3, ref_mv.col >> 3 };
3429 MV best_mv = { 0, 0 };
3432 assert(yv12 != NULL);
3434 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
3435 &cm->frame_refs[ref - 1].sf);
3436 mi->ref_frame[0] = ref;
3437 mi->ref_frame[1] = NONE;
3438 mi->sb_type = bsize;
3439 vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
3440 vp9_full_pixel_search(cpi, x, bsize, &ref_mv_full, step_param, search_method,
3441 sadpb, cond_cost_list(cpi, cost_list), &ref_mv,
3445 x->mv_limits = tmp_mv_limits;
3446 mi->mv[0].as_mv = best_mv;
3448 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3449 xd->plane[0].dst.buf = pred_buf;
3450 xd->plane[0].dst.stride = 64;
3451 vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
3454 // Use a neural net model to prune partition-none and partition-split search.
3455 // Features used: QP; spatial block size contexts; variance of prediction
3456 // residue after simple_motion_search.
3458 static void ml_predict_var_rd_paritioning(const VP9_COMP *const cpi,
3459 MACROBLOCK *const x,
3460 PC_TREE *const pc_tree,
3461 BLOCK_SIZE bsize, int mi_row,
3462 int mi_col, int *none, int *split) {
3463 const VP9_COMMON *const cm = &cpi->common;
3464 const NN_CONFIG *nn_config = NULL;
3465 #if CONFIG_VP9_HIGHBITDEPTH
3466 MACROBLOCKD *xd = &x->e_mbd;
3467 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64 * 2]);
3468 uint8_t *const pred_buf = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
3469 ? (CONVERT_TO_BYTEPTR(pred_buffer))
3472 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64]);
3473 uint8_t *const pred_buf = pred_buffer;
3474 #endif // CONFIG_VP9_HIGHBITDEPTH
3475 const int speed = cpi->oxcf.speed;
3476 float thresh = 0.0f;
3480 nn_config = &vp9_part_split_nnconfig_64;
3481 thresh = speed > 0 ? 2.8f : 3.0f;
3484 nn_config = &vp9_part_split_nnconfig_32;
3485 thresh = speed > 0 ? 3.5f : 3.0f;
3488 nn_config = &vp9_part_split_nnconfig_16;
3489 thresh = speed > 0 ? 3.8f : 4.0f;
3492 nn_config = &vp9_part_split_nnconfig_8;
3493 if (cm->width >= 720 && cm->height >= 720)
3494 thresh = speed > 0 ? 2.5f : 2.0f;
3496 thresh = speed > 0 ? 3.8f : 2.0f;
3498 default: assert(0 && "Unexpected block size."); return;
3501 if (!nn_config) return;
3503 // Do a simple single motion search to find a prediction for current block.
3504 // The variance of the residue will be used as input features.
3507 const MV_REFERENCE_FRAME ref =
3508 cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
3509 // If bsize is 64x64, use zero MV as reference; otherwise, use MV result
3510 // of previous(larger) block as reference.
3511 if (bsize == BLOCK_64X64)
3512 ref_mv.row = ref_mv.col = 0;
3514 ref_mv = pc_tree->mv;
3515 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
3516 simple_motion_search(cpi, x, bsize, mi_row, mi_col, ref_mv, ref, pred_buf);
3517 pc_tree->mv = x->e_mbd.mi[0]->mv[0].as_mv;
3520 vpx_clear_system_state();
3523 float features[FEATURES] = { 0.0f };
3524 #if CONFIG_VP9_HIGHBITDEPTH
3526 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (xd->bd - 8);
3528 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3529 #endif // CONFIG_VP9_HIGHBITDEPTH
3530 int feature_idx = 0;
3533 // Generate model input features.
3534 features[feature_idx++] = logf((float)dc_q + 1.0f);
3536 // Get the variance of the residue as input features.
3538 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3539 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3540 const uint8_t *pred = pred_buf;
3541 const uint8_t *src = x->plane[0].src.buf;
3542 const int src_stride = x->plane[0].src.stride;
3543 const int pred_stride = 64;
3545 // Variance of whole block.
3546 const unsigned int var =
3547 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
3548 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
3549 const MACROBLOCKD *const xd = &x->e_mbd;
3550 const int has_above = !!xd->above_mi;
3551 const int has_left = !!xd->left_mi;
3552 const BLOCK_SIZE above_bsize = has_above ? xd->above_mi->sb_type : bsize;
3553 const BLOCK_SIZE left_bsize = has_left ? xd->left_mi->sb_type : bsize;
3556 features[feature_idx++] = (float)has_above;
3557 features[feature_idx++] = (float)b_width_log2_lookup[above_bsize];
3558 features[feature_idx++] = (float)b_height_log2_lookup[above_bsize];
3559 features[feature_idx++] = (float)has_left;
3560 features[feature_idx++] = (float)b_width_log2_lookup[left_bsize];
3561 features[feature_idx++] = (float)b_height_log2_lookup[left_bsize];
3562 features[feature_idx++] = logf((float)var + 1.0f);
3563 for (i = 0; i < 4; ++i) {
3564 const int x_idx = (i & 1) * bs / 2;
3565 const int y_idx = (i >> 1) * bs / 2;
3566 const int src_offset = y_idx * src_stride + x_idx;
3567 const int pred_offset = y_idx * pred_stride + x_idx;
3568 // Variance of quarter block.
3569 const unsigned int sub_var =
3570 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
3571 pred + pred_offset, pred_stride, &sse);
3572 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
3573 features[feature_idx++] = var_ratio;
3576 assert(feature_idx == FEATURES);
3578 // Feed the features into the model to get the confidence score.
3579 nn_predict(features, nn_config, &score);
3581 // Higher score means that the model has higher confidence that the split
3582 // partition is better than the non-split partition. So if the score is
3583 // high enough, we skip the none-split partition search; if the score is
3584 // low enough, we skip the split partition search.
3585 if (score > thresh) *none = 0;
3586 if (score < -thresh) *split = 0;
3591 static double log_wiener_var(int64_t wiener_variance) {
3592 return log(1.0 + wiener_variance) / log(2.0);
3595 static void build_kmeans_segmentation(VP9_COMP *cpi) {
3596 VP9_COMMON *cm = &cpi->common;
3597 BLOCK_SIZE bsize = BLOCK_64X64;
3598 KMEANS_DATA *kmeans_data;
3600 vp9_disable_segmentation(&cm->seg);
3601 if (cm->show_frame) {
3603 cpi->kmeans_data_size = 0;
3604 cpi->kmeans_ctr_num = 8;
3606 for (mi_row = 0; mi_row < cm->mi_rows; mi_row += MI_BLOCK_SIZE) {
3607 for (mi_col = 0; mi_col < cm->mi_cols; mi_col += MI_BLOCK_SIZE) {
3608 int mb_row_start = mi_row >> 1;
3609 int mb_col_start = mi_col >> 1;
3610 int mb_row_end = VPXMIN(
3611 (mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3612 int mb_col_end = VPXMIN(
3613 (mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3615 int64_t wiener_variance = 0;
3617 for (row = mb_row_start; row < mb_row_end; ++row)
3618 for (col = mb_col_start; col < mb_col_end; ++col)
3619 wiener_variance += cpi->mb_wiener_variance[row * cm->mb_cols + col];
3622 (mb_row_end - mb_row_start) * (mb_col_end - mb_col_start);
3624 #if CONFIG_MULTITHREAD
3625 pthread_mutex_lock(&cpi->kmeans_mutex);
3626 #endif // CONFIG_MULTITHREAD
3628 kmeans_data = &cpi->kmeans_data_arr[cpi->kmeans_data_size++];
3629 kmeans_data->value = log_wiener_var(wiener_variance);
3630 kmeans_data->pos = mi_row * cpi->kmeans_data_stride + mi_col;
3631 #if CONFIG_MULTITHREAD
3632 pthread_mutex_unlock(&cpi->kmeans_mutex);
3633 #endif // CONFIG_MULTITHREAD
3637 vp9_kmeans(cpi->kmeans_ctr_ls, cpi->kmeans_boundary_ls,
3638 cpi->kmeans_count_ls, cpi->kmeans_ctr_num, cpi->kmeans_data_arr,
3639 cpi->kmeans_data_size);
3641 vp9_perceptual_aq_mode_setup(cpi, &cm->seg);
3645 static int wiener_var_segment(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3647 VP9_COMMON *cm = &cpi->common;
3648 int mb_row_start = mi_row >> 1;
3649 int mb_col_start = mi_col >> 1;
3651 VPXMIN((mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3653 VPXMIN((mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3655 int64_t wiener_variance = 0;
3657 int8_t seg_hist[MAX_SEGMENTS] = { 0 };
3658 int8_t max_count = 0, max_index = -1;
3660 vpx_clear_system_state();
3662 assert(cpi->norm_wiener_variance > 0);
3664 for (row = mb_row_start; row < mb_row_end; ++row) {
3665 for (col = mb_col_start; col < mb_col_end; ++col) {
3666 wiener_variance = cpi->mb_wiener_variance[row * cm->mb_cols + col];
3668 vp9_get_group_idx(log_wiener_var(wiener_variance),
3669 cpi->kmeans_boundary_ls, cpi->kmeans_ctr_num);
3670 ++seg_hist[segment_id];
3674 for (idx = 0; idx < cpi->kmeans_ctr_num; ++idx) {
3675 if (seg_hist[idx] > max_count) {
3676 max_count = seg_hist[idx];
3681 assert(max_index >= 0);
3682 segment_id = max_index;
3687 static int get_rdmult_delta(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3688 int mi_col, int orig_rdmult) {
3689 const int gf_group_index = cpi->twopass.gf_group.index;
3690 TplDepFrame *tpl_frame = &cpi->tpl_stats[gf_group_index];
3691 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
3692 int tpl_stride = tpl_frame->stride;
3693 int64_t intra_cost = 0;
3694 int64_t mc_dep_cost = 0;
3695 int mi_wide = num_8x8_blocks_wide_lookup[bsize];
3696 int mi_high = num_8x8_blocks_high_lookup[bsize];
3701 double r0, rk, beta;
3703 if (tpl_frame->is_valid == 0) return orig_rdmult;
3705 if (cpi->twopass.gf_group.layer_depth[gf_group_index] > 1) return orig_rdmult;
3707 if (gf_group_index >= MAX_ARF_GOP_SIZE) return orig_rdmult;
3709 for (row = mi_row; row < mi_row + mi_high; ++row) {
3710 for (col = mi_col; col < mi_col + mi_wide; ++col) {
3711 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
3713 if (row >= cpi->common.mi_rows || col >= cpi->common.mi_cols) continue;
3715 intra_cost += this_stats->intra_cost;
3716 mc_dep_cost += this_stats->mc_dep_cost;
3722 vpx_clear_system_state();
3725 rk = (double)intra_cost / mc_dep_cost;
3727 dr = vp9_get_adaptive_rdmult(cpi, beta);
3729 dr = VPXMIN(dr, orig_rdmult * 3 / 2);
3730 dr = VPXMAX(dr, orig_rdmult * 1 / 2);
3737 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
3738 // unlikely to be selected depending on previous rate-distortion optimization
3739 // results, for encoding speed-up.
3740 static void rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3741 TileDataEnc *tile_data, TOKENEXTRA **tp,
3742 int mi_row, int mi_col, BLOCK_SIZE bsize,
3743 RD_COST *rd_cost, int64_t best_rd,
3745 VP9_COMMON *const cm = &cpi->common;
3746 TileInfo *const tile_info = &tile_data->tile_info;
3747 MACROBLOCK *const x = &td->mb;
3748 MACROBLOCKD *const xd = &x->e_mbd;
3749 const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
3750 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
3751 PARTITION_CONTEXT sl[8], sa[8];
3752 TOKENEXTRA *tp_orig = *tp;
3753 PICK_MODE_CONTEXT *const ctx = &pc_tree->none;
3755 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3757 RD_COST this_rdc, sum_rdc, best_rdc;
3758 int do_split = bsize >= BLOCK_8X8;
3760 INTERP_FILTER pred_interp_filter;
3762 // Override skipping rectangular partition operations for edge blocks
3763 const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
3764 const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
3765 const int xss = x->e_mbd.plane[1].subsampling_x;
3766 const int yss = x->e_mbd.plane[1].subsampling_y;
3768 BLOCK_SIZE min_size = x->min_partition_size;
3769 BLOCK_SIZE max_size = x->max_partition_size;
3771 #if CONFIG_FP_MB_STATS
3772 unsigned int src_diff_var = UINT_MAX;
3773 int none_complexity = 0;
3776 int partition_none_allowed = !force_horz_split && !force_vert_split;
3777 int partition_horz_allowed =
3778 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
3779 int partition_vert_allowed =
3780 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
3782 int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_thr.dist;
3783 int rate_breakout_thr = cpi->sf.partition_search_breakout_thr.rate;
3785 int partition_mul = x->cb_rdmult;
3786 // Ref frames picked in the [i_th] quarter subblock during square partition
3787 // RD search. It may be used to prune ref frame selection of rect partitions.
3788 uint8_t ref_frames_used[4] = { 0, 0, 0, 0 };
3792 assert(num_8x8_blocks_wide_lookup[bsize] ==
3793 num_8x8_blocks_high_lookup[bsize]);
3795 dist_breakout_thr >>=
3796 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
3798 rate_breakout_thr *= num_pels_log2_lookup[bsize];
3800 vp9_rd_cost_init(&this_rdc);
3801 vp9_rd_cost_init(&sum_rdc);
3802 vp9_rd_cost_reset(&best_rdc);
3803 best_rdc.rdcost = best_rd;
3805 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3807 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ &&
3808 cpi->oxcf.aq_mode != LOOKAHEAD_AQ)
3809 x->mb_energy = vp9_block_energy(cpi, x, bsize);
3811 if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
3812 int cb_partition_search_ctrl =
3813 ((pc_tree->index == 0 || pc_tree->index == 3) +
3814 get_chessboard_index(cm->current_video_frame)) &
3817 if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
3818 set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
3821 // Get sub block energy range
3822 if (bsize >= BLOCK_16X16) {
3823 int min_energy, max_energy;
3824 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3826 must_split = (min_energy < -3) && (max_energy - min_energy > 2);
3829 // Determine partition types in search according to the speed features.
3830 // The threshold set here has to be of square block size.
3831 if (cpi->sf.auto_min_max_partition_size) {
3832 partition_none_allowed &= (bsize <= max_size);
3833 partition_horz_allowed &=
3834 ((bsize <= max_size && bsize > min_size) || force_horz_split);
3835 partition_vert_allowed &=
3836 ((bsize <= max_size && bsize > min_size) || force_vert_split);
3837 do_split &= bsize > min_size;
3840 if (cpi->sf.use_square_partition_only &&
3841 (bsize > cpi->sf.use_square_only_thresh_high ||
3842 bsize < cpi->sf.use_square_only_thresh_low)) {
3844 if (!vp9_active_h_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3845 partition_horz_allowed &= force_horz_split;
3846 if (!vp9_active_v_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3847 partition_vert_allowed &= force_vert_split;
3849 partition_horz_allowed &= force_horz_split;
3850 partition_vert_allowed &= force_vert_split;
3854 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3856 #if CONFIG_FP_MB_STATS
3857 if (cpi->use_fp_mb_stats) {
3858 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3859 src_diff_var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src, mi_row,
3864 #if CONFIG_FP_MB_STATS
3865 // Decide whether we shall split directly and skip searching NONE by using
3866 // the first pass block statistics
3867 if (cpi->use_fp_mb_stats && bsize >= BLOCK_32X32 && do_split &&
3868 partition_none_allowed && src_diff_var > 4 &&
3869 cm->base_qindex < qindex_split_threshold_lookup[bsize]) {
3870 int mb_row = mi_row >> 1;
3871 int mb_col = mi_col >> 1;
3873 VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
3875 VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
3878 // compute a complexity measure, basically measure inconsistency of motion
3879 // vectors obtained from the first pass in the current block
3880 for (r = mb_row; r < mb_row_end; r++) {
3881 for (c = mb_col; c < mb_col_end; c++) {
3882 const int mb_index = r * cm->mb_cols + c;
3884 MOTION_DIRECTION this_mv;
3885 MOTION_DIRECTION right_mv;
3886 MOTION_DIRECTION bottom_mv;
3889 get_motion_direction_fp(cpi->twopass.this_frame_mb_stats[mb_index]);
3892 if (c != mb_col_end - 1) {
3893 right_mv = get_motion_direction_fp(
3894 cpi->twopass.this_frame_mb_stats[mb_index + 1]);
3895 none_complexity += get_motion_inconsistency(this_mv, right_mv);
3899 if (r != mb_row_end - 1) {
3900 bottom_mv = get_motion_direction_fp(
3901 cpi->twopass.this_frame_mb_stats[mb_index + cm->mb_cols]);
3902 none_complexity += get_motion_inconsistency(this_mv, bottom_mv);
3905 // do not count its left and top neighbors to avoid double counting
3909 if (none_complexity > complexity_16x16_blocks_threshold[bsize]) {
3910 partition_none_allowed = 0;
3915 pc_tree->partitioning = PARTITION_NONE;
3917 if (cpi->sf.rd_ml_partition.var_pruning && !frame_is_intra_only(cm)) {
3918 const int do_rd_ml_partition_var_pruning =
3919 partition_none_allowed && do_split &&
3920 mi_row + num_8x8_blocks_high_lookup[bsize] <= cm->mi_rows &&
3921 mi_col + num_8x8_blocks_wide_lookup[bsize] <= cm->mi_cols;
3922 if (do_rd_ml_partition_var_pruning) {
3923 ml_predict_var_rd_paritioning(cpi, x, pc_tree, bsize, mi_row, mi_col,
3924 &partition_none_allowed, &do_split);
3926 vp9_zero(pc_tree->mv);
3928 if (bsize > BLOCK_8X8) { // Store MV result as reference for subblocks.
3929 for (i = 0; i < 4; ++i) pc_tree->split[i]->mv = pc_tree->mv;
3934 if (partition_none_allowed) {
3935 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize, ctx,
3937 ctx->rdcost = this_rdc.rdcost;
3938 if (this_rdc.rate != INT_MAX) {
3939 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
3940 const int ref1 = ctx->mic.ref_frame[0];
3941 const int ref2 = ctx->mic.ref_frame[1];
3942 for (i = 0; i < 4; ++i) {
3943 ref_frames_used[i] |= (1 << ref1);
3944 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3947 if (bsize >= BLOCK_8X8) {
3948 this_rdc.rdcost += RDCOST(partition_mul, x->rddiv,
3949 cpi->partition_cost[pl][PARTITION_NONE], 0);
3950 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3953 if (this_rdc.rdcost < best_rdc.rdcost) {
3954 MODE_INFO *mi = xd->mi[0];
3956 best_rdc = this_rdc;
3957 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
3959 if (cpi->sf.rd_ml_partition.search_early_termination) {
3960 // Currently, the machine-learning based partition search early
3961 // termination is only used while bsize is 16x16, 32x32 or 64x64,
3962 // VPXMIN(cm->width, cm->height) >= 480, and speed = 0.
3963 if (!x->e_mbd.lossless &&
3964 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP) &&
3965 ctx->mic.mode >= INTRA_MODES && bsize >= BLOCK_16X16) {
3966 if (ml_pruning_partition(cm, xd, ctx, mi_row, mi_col, bsize)) {
3973 if ((do_split || do_rect) && !x->e_mbd.lossless && ctx->skippable) {
3974 const int use_ml_based_breakout =
3975 cpi->sf.rd_ml_partition.search_breakout && cm->base_qindex >= 100;
3976 if (use_ml_based_breakout) {
3977 if (ml_predict_breakout(cpi, bsize, x, &this_rdc)) {
3982 if (!cpi->sf.rd_ml_partition.search_early_termination) {
3983 if ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
3984 (best_rdc.dist < dist_breakout_thr &&
3985 best_rdc.rate < rate_breakout_thr)) {
3993 #if CONFIG_FP_MB_STATS
3994 // Check if every 16x16 first pass block statistics has zero
3995 // motion and the corresponding first pass residue is small enough.
3996 // If that is the case, check the difference variance between the
3997 // current frame and the last frame. If the variance is small enough,
3998 // stop further splitting in RD optimization
3999 if (cpi->use_fp_mb_stats && do_split != 0 &&
4000 cm->base_qindex > qindex_skip_threshold_lookup[bsize]) {
4001 int mb_row = mi_row >> 1;
4002 int mb_col = mi_col >> 1;
4004 VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
4006 VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
4010 for (r = mb_row; r < mb_row_end; r++) {
4011 for (c = mb_col; c < mb_col_end; c++) {
4012 const int mb_index = r * cm->mb_cols + c;
4013 if (!(cpi->twopass.this_frame_mb_stats[mb_index] &
4014 FPMB_MOTION_ZERO_MASK) ||
4015 !(cpi->twopass.this_frame_mb_stats[mb_index] &
4016 FPMB_ERROR_SMALL_MASK)) {
4027 if (src_diff_var == UINT_MAX) {
4028 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4029 src_diff_var = get_sby_perpixel_diff_variance(
4030 cpi, &x->plane[0].src, mi_row, mi_col, bsize);
4032 if (src_diff_var < 8) {
4041 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4043 vp9_zero(ctx->pred_mv);
4044 ctx->mic.interp_filter = EIGHTTAP;
4047 // store estimated motion vector
4048 store_pred_mv(x, ctx);
4050 // If the interp_filter is marked as SWITCHABLE_FILTERS, it was for an
4051 // intra block and used for context purposes.
4052 if (ctx->mic.interp_filter == SWITCHABLE_FILTERS) {
4053 pred_interp_filter = EIGHTTAP;
4055 pred_interp_filter = ctx->mic.interp_filter;
4059 // TODO(jingning): use the motion vectors given by the above search as
4060 // the starting point of motion search in the following partition type check.
4061 pc_tree->split[0]->none.rdcost = 0;
4062 pc_tree->split[1]->none.rdcost = 0;
4063 pc_tree->split[2]->none.rdcost = 0;
4064 pc_tree->split[3]->none.rdcost = 0;
4065 if (do_split || must_split) {
4066 subsize = get_subsize(bsize, PARTITION_SPLIT);
4067 load_pred_mv(x, ctx);
4068 if (bsize == BLOCK_8X8) {
4070 if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
4071 pc_tree->leaf_split[0]->pred_interp_filter = pred_interp_filter;
4072 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4073 pc_tree->leaf_split[0], best_rdc.rdcost);
4074 if (sum_rdc.rate == INT_MAX) {
4075 sum_rdc.rdcost = INT64_MAX;
4077 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4078 const int ref1 = pc_tree->leaf_split[0]->mic.ref_frame[0];
4079 const int ref2 = pc_tree->leaf_split[0]->mic.ref_frame[1];
4080 for (i = 0; i < 4; ++i) {
4081 ref_frames_used[i] |= (1 << ref1);
4082 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4087 for (i = 0; (i < 4) && ((sum_rdc.rdcost < best_rdc.rdcost) || must_split);
4089 const int x_idx = (i & 1) * mi_step;
4090 const int y_idx = (i >> 1) * mi_step;
4092 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4095 pc_tree->split[i]->index = i;
4096 if (cpi->sf.prune_ref_frame_for_rect_partitions)
4097 pc_tree->split[i]->none.rate = INT_MAX;
4098 rd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4099 mi_col + x_idx, subsize, &this_rdc,
4100 // A must split test here increases the number of sub
4101 // partitions but hurts metrics results quite a bit,
4102 // so this extra test is commented out pending
4103 // further tests on whether it adds much in terms of
4105 // (must_split) ? best_rdc.rdcost
4106 // : best_rdc.rdcost - sum_rdc.rdcost,
4107 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4109 if (this_rdc.rate == INT_MAX) {
4110 sum_rdc.rdcost = INT64_MAX;
4113 if (cpi->sf.prune_ref_frame_for_rect_partitions &&
4114 pc_tree->split[i]->none.rate != INT_MAX) {
4115 const int ref1 = pc_tree->split[i]->none.mic.ref_frame[0];
4116 const int ref2 = pc_tree->split[i]->none.mic.ref_frame[1];
4117 ref_frames_used[i] |= (1 << ref1);
4118 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4120 sum_rdc.rate += this_rdc.rate;
4121 sum_rdc.dist += this_rdc.dist;
4122 sum_rdc.rdcost += this_rdc.rdcost;
4127 if (((sum_rdc.rdcost < best_rdc.rdcost) || must_split) && i == 4) {
4128 sum_rdc.rdcost += RDCOST(partition_mul, x->rddiv,
4129 cpi->partition_cost[pl][PARTITION_SPLIT], 0);
4130 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4132 if ((sum_rdc.rdcost < best_rdc.rdcost) ||
4133 (must_split && (sum_rdc.dist < best_rdc.dist))) {
4135 pc_tree->partitioning = PARTITION_SPLIT;
4137 // Rate and distortion based partition search termination clause.
4138 if (!cpi->sf.rd_ml_partition.search_early_termination &&
4139 !x->e_mbd.lossless &&
4140 ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4141 (best_rdc.dist < dist_breakout_thr &&
4142 best_rdc.rate < rate_breakout_thr))) {
4147 // skip rectangular partition test when larger block size
4148 // gives better rd cost
4149 if (cpi->sf.less_rectangular_check &&
4150 (bsize > cpi->sf.use_square_only_thresh_high ||
4151 best_rdc.dist < dist_breakout_thr))
4152 do_rect &= !partition_none_allowed;
4154 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4157 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
4158 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
4159 pc_tree->vertical[0].skip_ref_frame_mask = 0;
4160 pc_tree->vertical[1].skip_ref_frame_mask = 0;
4161 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4162 uint8_t used_frames;
4163 used_frames = ref_frames_used[0] | ref_frames_used[1];
4164 if (used_frames) pc_tree->horizontal[0].skip_ref_frame_mask = ~used_frames;
4165 used_frames = ref_frames_used[2] | ref_frames_used[3];
4166 if (used_frames) pc_tree->horizontal[1].skip_ref_frame_mask = ~used_frames;
4167 used_frames = ref_frames_used[0] | ref_frames_used[2];
4168 if (used_frames) pc_tree->vertical[0].skip_ref_frame_mask = ~used_frames;
4169 used_frames = ref_frames_used[1] | ref_frames_used[3];
4170 if (used_frames) pc_tree->vertical[1].skip_ref_frame_mask = ~used_frames;
4174 const int do_ml_rect_partition_pruning =
4175 !frame_is_intra_only(cm) && !force_horz_split && !force_vert_split &&
4176 (partition_horz_allowed || partition_vert_allowed) && bsize > BLOCK_8X8;
4177 if (do_ml_rect_partition_pruning) {
4178 ml_prune_rect_partition(cpi, x, bsize, pc_tree, &partition_horz_allowed,
4179 &partition_vert_allowed, best_rdc.rdcost);
4184 if (partition_horz_allowed &&
4185 (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
4186 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_HORZ];
4187 const int64_t part_mode_rdcost =
4188 RDCOST(partition_mul, x->rddiv, part_mode_rate, 0);
4189 subsize = get_subsize(bsize, PARTITION_HORZ);
4190 load_pred_mv(x, ctx);
4191 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4192 partition_none_allowed)
4193 pc_tree->horizontal[0].pred_interp_filter = pred_interp_filter;
4194 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4195 &pc_tree->horizontal[0],
4196 best_rdc.rdcost - part_mode_rdcost);
4197 if (sum_rdc.rdcost < INT64_MAX) {
4198 sum_rdc.rdcost += part_mode_rdcost;
4199 sum_rdc.rate += part_mode_rate;
4202 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
4203 bsize > BLOCK_8X8) {
4204 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
4205 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
4206 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
4207 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4208 partition_none_allowed)
4209 pc_tree->horizontal[1].pred_interp_filter = pred_interp_filter;
4210 rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col, &this_rdc,
4211 subsize, &pc_tree->horizontal[1],
4212 best_rdc.rdcost - sum_rdc.rdcost);
4213 if (this_rdc.rate == INT_MAX) {
4214 sum_rdc.rdcost = INT64_MAX;
4216 sum_rdc.rate += this_rdc.rate;
4217 sum_rdc.dist += this_rdc.dist;
4218 sum_rdc.rdcost += this_rdc.rdcost;
4222 if (sum_rdc.rdcost < best_rdc.rdcost) {
4224 pc_tree->partitioning = PARTITION_HORZ;
4226 if (cpi->sf.less_rectangular_check &&
4227 bsize > cpi->sf.use_square_only_thresh_high)
4230 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4234 if (partition_vert_allowed &&
4235 (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
4236 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_VERT];
4237 const int64_t part_mode_rdcost =
4238 RDCOST(partition_mul, x->rddiv, part_mode_rate, 0);
4239 subsize = get_subsize(bsize, PARTITION_VERT);
4240 load_pred_mv(x, ctx);
4241 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4242 partition_none_allowed)
4243 pc_tree->vertical[0].pred_interp_filter = pred_interp_filter;
4244 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4245 &pc_tree->vertical[0], best_rdc.rdcost - part_mode_rdcost);
4246 if (sum_rdc.rdcost < INT64_MAX) {
4247 sum_rdc.rdcost += part_mode_rdcost;
4248 sum_rdc.rate += part_mode_rate;
4251 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
4252 bsize > BLOCK_8X8) {
4253 update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
4254 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
4255 &pc_tree->vertical[0]);
4256 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4257 partition_none_allowed)
4258 pc_tree->vertical[1].pred_interp_filter = pred_interp_filter;
4259 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step, &this_rdc,
4260 subsize, &pc_tree->vertical[1],
4261 best_rdc.rdcost - sum_rdc.rdcost);
4262 if (this_rdc.rate == INT_MAX) {
4263 sum_rdc.rdcost = INT64_MAX;
4265 sum_rdc.rate += this_rdc.rate;
4266 sum_rdc.dist += this_rdc.dist;
4267 sum_rdc.rdcost += this_rdc.rdcost;
4271 if (sum_rdc.rdcost < best_rdc.rdcost) {
4273 pc_tree->partitioning = PARTITION_VERT;
4275 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4278 // TODO(jbb): This code added so that we avoid static analysis
4279 // warning related to the fact that best_rd isn't used after this
4280 // point. This code should be refactored so that the duplicate
4281 // checks occur in some sub function and thus are used...
4283 *rd_cost = best_rdc;
4285 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX &&
4286 pc_tree->index != 3) {
4287 int output_enabled = (bsize == BLOCK_64X64);
4288 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4292 if (bsize == BLOCK_64X64) {
4293 assert(tp_orig < *tp);
4294 assert(best_rdc.rate < INT_MAX);
4295 assert(best_rdc.dist < INT64_MAX);
4297 assert(tp_orig == *tp);
4301 static void encode_rd_sb_row(VP9_COMP *cpi, ThreadData *td,
4302 TileDataEnc *tile_data, int mi_row,
4304 VP9_COMMON *const cm = &cpi->common;
4305 TileInfo *const tile_info = &tile_data->tile_info;
4306 MACROBLOCK *const x = &td->mb;
4307 MACROBLOCKD *const xd = &x->e_mbd;
4308 SPEED_FEATURES *const sf = &cpi->sf;
4309 const int mi_col_start = tile_info->mi_col_start;
4310 const int mi_col_end = tile_info->mi_col_end;
4312 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
4313 const int num_sb_cols =
4314 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
4317 // Initialize the left context for the new SB row
4318 memset(&xd->left_context, 0, sizeof(xd->left_context));
4319 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
4321 // Code each SB in the row
4322 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
4323 mi_col += MI_BLOCK_SIZE, sb_col_in_tile++) {
4324 const struct segmentation *const seg = &cm->seg;
4330 int orig_rdmult = cpi->rd.RDMULT;
4332 const int idx_str = cm->mi_stride * mi_row + mi_col;
4333 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
4335 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
4338 if (sf->adaptive_pred_interp_filter) {
4339 for (i = 0; i < 64; ++i) td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
4341 for (i = 0; i < 64; ++i) {
4342 td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
4343 td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
4344 td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
4345 td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
4349 for (i = 0; i < MAX_REF_FRAMES; ++i) {
4350 x->pred_mv[i].row = INT16_MAX;
4351 x->pred_mv[i].col = INT16_MAX;
4353 td->pc_root->index = 0;
4356 const uint8_t *const map =
4357 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
4358 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
4359 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
4362 x->source_variance = UINT_MAX;
4364 x->cb_rdmult = orig_rdmult;
4366 if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
4367 const BLOCK_SIZE bsize =
4368 seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
4369 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4370 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4371 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4372 &dummy_rate, &dummy_dist, 1, td->pc_root);
4373 } else if (cpi->partition_search_skippable_frame) {
4375 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4376 bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col);
4377 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4378 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4379 &dummy_rate, &dummy_dist, 1, td->pc_root);
4380 } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
4381 cm->frame_type != KEY_FRAME) {
4382 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
4383 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4384 &dummy_rate, &dummy_dist, 1, td->pc_root);
4386 if (cpi->twopass.gf_group.index > 0 && cpi->sf.enable_tpl_model) {
4388 get_rdmult_delta(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4392 if (cpi->sf.enable_wiener_variance && cm->show_frame) {
4393 x->segment_id = wiener_var_segment(cpi, BLOCK_64X64, mi_row, mi_col);
4394 x->cb_rdmult = vp9_compute_rd_mult(
4395 cpi, vp9_get_qindex(&cm->seg, x->segment_id, cm->base_qindex));
4398 // If required set upper and lower partition size limits
4399 if (sf->auto_min_max_partition_size) {
4400 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4401 rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
4402 &x->min_partition_size, &x->max_partition_size);
4404 td->pc_root->none.rdcost = 0;
4405 rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
4406 &dummy_rdc, INT64_MAX, td->pc_root);
4408 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
4409 sb_col_in_tile, num_sb_cols);
4413 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
4414 MACROBLOCK *const x = &cpi->td.mb;
4415 VP9_COMMON *const cm = &cpi->common;
4416 MACROBLOCKD *const xd = &x->e_mbd;
4417 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
4419 // Copy data over into macro block data structures.
4420 vp9_setup_src_planes(x, cpi->Source, 0, 0);
4422 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
4424 // Note: this memset assumes above_context[0], [1] and [2]
4425 // are allocated as part of the same buffer.
4426 memset(xd->above_context[0], 0,
4427 sizeof(*xd->above_context[0]) * 2 * aligned_mi_cols * MAX_MB_PLANE);
4428 memset(xd->above_seg_context, 0,
4429 sizeof(*xd->above_seg_context) * aligned_mi_cols);
4432 static int check_dual_ref_flags(VP9_COMP *cpi) {
4433 const int ref_flags = cpi->ref_frame_flags;
4435 if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
4438 return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG) +
4439 !!(ref_flags & VP9_ALT_FLAG)) >= 2;
4443 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
4445 const int mis = cm->mi_stride;
4446 MODE_INFO **mi_ptr = cm->mi_grid_visible;
4448 for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
4449 for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
4450 if (mi_ptr[mi_col]->tx_size > max_tx_size)
4451 mi_ptr[mi_col]->tx_size = max_tx_size;
4456 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
4457 if (frame_is_intra_only(&cpi->common))
4459 else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
4460 return ALTREF_FRAME;
4461 else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
4462 return GOLDEN_FRAME;
4467 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
4468 if (xd->lossless) return ONLY_4X4;
4469 if (cpi->common.frame_type == KEY_FRAME && cpi->sf.use_nonrd_pick_mode)
4471 if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
4473 else if (cpi->sf.tx_size_search_method == USE_FULL_RD ||
4474 cpi->sf.tx_size_search_method == USE_TX_8X8)
4475 return TX_MODE_SELECT;
4477 return cpi->common.tx_mode;
4480 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
4481 RD_COST *rd_cost, BLOCK_SIZE bsize,
4482 PICK_MODE_CONTEXT *ctx) {
4483 if (!cpi->sf.nonrd_keyframe && bsize < BLOCK_16X16)
4484 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4486 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4489 static void hybrid_search_svc_baseiskey(VP9_COMP *cpi, MACROBLOCK *const x,
4490 RD_COST *rd_cost, BLOCK_SIZE bsize,
4491 PICK_MODE_CONTEXT *ctx,
4492 TileDataEnc *tile_data, int mi_row,
4494 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4495 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4497 if (cpi->svc.disable_inter_layer_pred == INTER_LAYER_PRED_OFF)
4498 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4499 else if (bsize >= BLOCK_8X8)
4500 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4503 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4507 static void hybrid_search_scene_change(VP9_COMP *cpi, MACROBLOCK *const x,
4508 RD_COST *rd_cost, BLOCK_SIZE bsize,
4509 PICK_MODE_CONTEXT *ctx,
4510 TileDataEnc *tile_data, int mi_row,
4512 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4513 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4515 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize, ctx);
4519 static void nonrd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
4520 MACROBLOCK *const x, int mi_row, int mi_col,
4521 RD_COST *rd_cost, BLOCK_SIZE bsize,
4522 PICK_MODE_CONTEXT *ctx) {
4523 VP9_COMMON *const cm = &cpi->common;
4524 TileInfo *const tile_info = &tile_data->tile_info;
4525 MACROBLOCKD *const xd = &x->e_mbd;
4527 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
4528 BLOCK_SIZE bs = VPXMAX(bsize, BLOCK_8X8); // processing unit block size
4529 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bs];
4530 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bs];
4533 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4535 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
4538 mi->sb_type = bsize;
4540 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4541 struct macroblockd_plane *pd = &xd->plane[plane];
4542 memcpy(a + num_4x4_blocks_wide * plane, pd->above_context,
4543 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4544 memcpy(l + num_4x4_blocks_high * plane, pd->left_context,
4545 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4548 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
4549 if (cyclic_refresh_segment_id_boosted(mi->segment_id))
4550 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
4552 if (frame_is_intra_only(cm))
4553 hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
4554 else if (cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
4555 hybrid_search_svc_baseiskey(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4557 else if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
4558 set_mode_info_seg_skip(x, cm->tx_mode, rd_cost, bsize);
4559 else if (bsize >= BLOCK_8X8) {
4560 if (cpi->rc.hybrid_intra_scene_change)
4561 hybrid_search_scene_change(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4564 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4567 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4570 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4572 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4573 struct macroblockd_plane *pd = &xd->plane[plane];
4574 memcpy(pd->above_context, a + num_4x4_blocks_wide * plane,
4575 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4576 memcpy(pd->left_context, l + num_4x4_blocks_high * plane,
4577 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4580 if (rd_cost->rate == INT_MAX) vp9_rd_cost_reset(rd_cost);
4582 ctx->rate = rd_cost->rate;
4583 ctx->dist = rd_cost->dist;
4586 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x, int mi_row,
4587 int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4588 MACROBLOCKD *xd = &x->e_mbd;
4589 int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4590 PARTITION_TYPE partition = pc_tree->partitioning;
4591 BLOCK_SIZE subsize = get_subsize(bsize, partition);
4593 assert(bsize >= BLOCK_8X8);
4595 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4597 switch (partition) {
4598 case PARTITION_NONE:
4599 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4600 *(xd->mi[0]) = pc_tree->none.mic;
4601 *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
4602 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4604 case PARTITION_VERT:
4605 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4606 *(xd->mi[0]) = pc_tree->vertical[0].mic;
4607 *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
4608 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4610 if (mi_col + hbs < cm->mi_cols) {
4611 set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
4612 *(xd->mi[0]) = pc_tree->vertical[1].mic;
4613 *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
4614 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
4617 case PARTITION_HORZ:
4618 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4619 *(xd->mi[0]) = pc_tree->horizontal[0].mic;
4620 *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
4621 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4622 if (mi_row + hbs < cm->mi_rows) {
4623 set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
4624 *(xd->mi[0]) = pc_tree->horizontal[1].mic;
4625 *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
4626 duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
4629 case PARTITION_SPLIT: {
4630 fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
4631 fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
4633 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
4635 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
4643 // Reset the prediction pixel ready flag recursively.
4644 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
4645 pc_tree->none.pred_pixel_ready = 0;
4646 pc_tree->horizontal[0].pred_pixel_ready = 0;
4647 pc_tree->horizontal[1].pred_pixel_ready = 0;
4648 pc_tree->vertical[0].pred_pixel_ready = 0;
4649 pc_tree->vertical[1].pred_pixel_ready = 0;
4651 if (bsize > BLOCK_8X8) {
4652 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4654 for (i = 0; i < 4; ++i) pred_pixel_ready_reset(pc_tree->split[i], subsize);
4660 static int ml_predict_var_paritioning(VP9_COMP *cpi, MACROBLOCK *x,
4661 BLOCK_SIZE bsize, int mi_row,
4663 VP9_COMMON *const cm = &cpi->common;
4664 const NN_CONFIG *nn_config = NULL;
4667 case BLOCK_64X64: nn_config = &vp9_var_part_nnconfig_64; break;
4668 case BLOCK_32X32: nn_config = &vp9_var_part_nnconfig_32; break;
4669 case BLOCK_16X16: nn_config = &vp9_var_part_nnconfig_16; break;
4670 case BLOCK_8X8: break;
4671 default: assert(0 && "Unexpected block size."); return -1;
4674 if (!nn_config) return -1;
4676 vpx_clear_system_state();
4679 const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
4680 float features[FEATURES] = { 0.0f };
4681 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
4682 int feature_idx = 0;
4683 float score[LABELS];
4685 features[feature_idx++] = logf((float)(dc_q * dc_q) / 256.0f + 1.0f);
4686 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
4688 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
4689 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4690 const int sb_offset_row = 8 * (mi_row & 7);
4691 const int sb_offset_col = 8 * (mi_col & 7);
4692 const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
4693 const uint8_t *src = x->plane[0].src.buf;
4694 const int src_stride = x->plane[0].src.stride;
4695 const int pred_stride = 64;
4698 // Variance of whole block.
4699 const unsigned int var =
4700 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
4701 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
4703 features[feature_idx++] = logf((float)var + 1.0f);
4704 for (i = 0; i < 4; ++i) {
4705 const int x_idx = (i & 1) * bs / 2;
4706 const int y_idx = (i >> 1) * bs / 2;
4707 const int src_offset = y_idx * src_stride + x_idx;
4708 const int pred_offset = y_idx * pred_stride + x_idx;
4709 // Variance of quarter block.
4710 const unsigned int sub_var =
4711 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
4712 pred + pred_offset, pred_stride, &sse);
4713 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
4714 features[feature_idx++] = var_ratio;
4718 assert(feature_idx == FEATURES);
4719 nn_predict(features, nn_config, score);
4720 if (score[0] > thresh) return PARTITION_SPLIT;
4721 if (score[0] < -thresh) return PARTITION_NONE;
4728 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
4729 TileDataEnc *tile_data, TOKENEXTRA **tp,
4730 int mi_row, int mi_col, BLOCK_SIZE bsize,
4731 RD_COST *rd_cost, int do_recon,
4732 int64_t best_rd, PC_TREE *pc_tree) {
4733 const SPEED_FEATURES *const sf = &cpi->sf;
4734 VP9_COMMON *const cm = &cpi->common;
4735 TileInfo *const tile_info = &tile_data->tile_info;
4736 MACROBLOCK *const x = &td->mb;
4737 MACROBLOCKD *const xd = &x->e_mbd;
4738 const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
4739 TOKENEXTRA *tp_orig = *tp;
4740 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
4742 BLOCK_SIZE subsize = bsize;
4743 RD_COST this_rdc, sum_rdc, best_rdc;
4744 int do_split = bsize >= BLOCK_8X8;
4746 // Override skipping rectangular partition operations for edge blocks
4747 const int force_horz_split = (mi_row + ms >= cm->mi_rows);
4748 const int force_vert_split = (mi_col + ms >= cm->mi_cols);
4749 const int xss = x->e_mbd.plane[1].subsampling_x;
4750 const int yss = x->e_mbd.plane[1].subsampling_y;
4752 int partition_none_allowed = !force_horz_split && !force_vert_split;
4753 int partition_horz_allowed =
4754 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
4755 int partition_vert_allowed =
4756 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
4757 const int use_ml_based_partitioning =
4758 sf->partition_search_type == ML_BASED_PARTITION;
4762 // Avoid checking for rectangular partitions for speed >= 6.
4763 if (cpi->oxcf.speed >= 6) do_rect = 0;
4765 assert(num_8x8_blocks_wide_lookup[bsize] ==
4766 num_8x8_blocks_high_lookup[bsize]);
4768 vp9_rd_cost_init(&sum_rdc);
4769 vp9_rd_cost_reset(&best_rdc);
4770 best_rdc.rdcost = best_rd;
4772 // Determine partition types in search according to the speed features.
4773 // The threshold set here has to be of square block size.
4774 if (sf->auto_min_max_partition_size) {
4775 partition_none_allowed &=
4776 (bsize <= x->max_partition_size && bsize >= x->min_partition_size);
4777 partition_horz_allowed &=
4778 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4780 partition_vert_allowed &=
4781 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4783 do_split &= bsize > x->min_partition_size;
4785 if (sf->use_square_partition_only) {
4786 partition_horz_allowed &= force_horz_split;
4787 partition_vert_allowed &= force_vert_split;
4790 if (use_ml_based_partitioning) {
4791 if (partition_none_allowed || do_split) do_rect = 0;
4792 if (partition_none_allowed && do_split) {
4793 const int ml_predicted_partition =
4794 ml_predict_var_paritioning(cpi, x, bsize, mi_row, mi_col);
4795 if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
4796 if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
4800 if (!partition_none_allowed && !do_split) do_rect = 1;
4802 ctx->pred_pixel_ready =
4803 !(partition_vert_allowed || partition_horz_allowed || do_split);
4806 if (partition_none_allowed) {
4807 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
4809 ctx->mic = *xd->mi[0];
4810 ctx->mbmi_ext = *x->mbmi_ext;
4811 ctx->skip_txfm[0] = x->skip_txfm[0];
4812 ctx->skip = x->skip;
4814 if (this_rdc.rate != INT_MAX) {
4815 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4816 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4818 RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
4819 if (this_rdc.rdcost < best_rdc.rdcost) {
4820 best_rdc = this_rdc;
4821 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4823 if (!use_ml_based_partitioning) {
4824 int64_t dist_breakout_thr = sf->partition_search_breakout_thr.dist;
4825 int64_t rate_breakout_thr = sf->partition_search_breakout_thr.rate;
4826 dist_breakout_thr >>=
4827 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4828 rate_breakout_thr *= num_pels_log2_lookup[bsize];
4829 if (!x->e_mbd.lossless && this_rdc.rate < rate_breakout_thr &&
4830 this_rdc.dist < dist_breakout_thr) {
4839 // store estimated motion vector
4840 store_pred_mv(x, ctx);
4844 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4845 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4846 sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4847 subsize = get_subsize(bsize, PARTITION_SPLIT);
4848 for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
4849 const int x_idx = (i & 1) * ms;
4850 const int y_idx = (i >> 1) * ms;
4852 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4854 load_pred_mv(x, ctx);
4855 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4856 mi_col + x_idx, subsize, &this_rdc, 0,
4857 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4859 if (this_rdc.rate == INT_MAX) {
4860 vp9_rd_cost_reset(&sum_rdc);
4862 sum_rdc.rate += this_rdc.rate;
4863 sum_rdc.dist += this_rdc.dist;
4864 sum_rdc.rdcost += this_rdc.rdcost;
4868 if (sum_rdc.rdcost < best_rdc.rdcost) {
4870 pc_tree->partitioning = PARTITION_SPLIT;
4872 // skip rectangular partition test when larger block size
4873 // gives better rd cost
4874 if (sf->less_rectangular_check) do_rect &= !partition_none_allowed;
4879 if (partition_horz_allowed && do_rect) {
4880 subsize = get_subsize(bsize, PARTITION_HORZ);
4881 load_pred_mv(x, ctx);
4882 pc_tree->horizontal[0].pred_pixel_ready = 1;
4883 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4884 &pc_tree->horizontal[0]);
4886 pc_tree->horizontal[0].mic = *xd->mi[0];
4887 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4888 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4889 pc_tree->horizontal[0].skip = x->skip;
4891 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
4892 load_pred_mv(x, ctx);
4893 pc_tree->horizontal[1].pred_pixel_ready = 1;
4894 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc,
4895 subsize, &pc_tree->horizontal[1]);
4897 pc_tree->horizontal[1].mic = *xd->mi[0];
4898 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
4899 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
4900 pc_tree->horizontal[1].skip = x->skip;
4902 if (this_rdc.rate == INT_MAX) {
4903 vp9_rd_cost_reset(&sum_rdc);
4905 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4906 this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
4907 sum_rdc.rate += this_rdc.rate;
4908 sum_rdc.dist += this_rdc.dist;
4910 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4914 if (sum_rdc.rdcost < best_rdc.rdcost) {
4916 pc_tree->partitioning = PARTITION_HORZ;
4918 pred_pixel_ready_reset(pc_tree, bsize);
4923 if (partition_vert_allowed && do_rect) {
4924 subsize = get_subsize(bsize, PARTITION_VERT);
4925 load_pred_mv(x, ctx);
4926 pc_tree->vertical[0].pred_pixel_ready = 1;
4927 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4928 &pc_tree->vertical[0]);
4929 pc_tree->vertical[0].mic = *xd->mi[0];
4930 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4931 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4932 pc_tree->vertical[0].skip = x->skip;
4934 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
4935 load_pred_mv(x, ctx);
4936 pc_tree->vertical[1].pred_pixel_ready = 1;
4937 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc,
4938 subsize, &pc_tree->vertical[1]);
4939 pc_tree->vertical[1].mic = *xd->mi[0];
4940 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4941 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4942 pc_tree->vertical[1].skip = x->skip;
4944 if (this_rdc.rate == INT_MAX) {
4945 vp9_rd_cost_reset(&sum_rdc);
4947 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4948 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
4949 sum_rdc.rate += this_rdc.rate;
4950 sum_rdc.dist += this_rdc.dist;
4952 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4956 if (sum_rdc.rdcost < best_rdc.rdcost) {
4958 pc_tree->partitioning = PARTITION_VERT;
4960 pred_pixel_ready_reset(pc_tree, bsize);
4964 *rd_cost = best_rdc;
4966 if (best_rdc.rate == INT_MAX) {
4967 vp9_rd_cost_reset(rd_cost);
4971 // update mode info array
4972 fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
4974 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
4975 int output_enabled = (bsize == BLOCK_64X64);
4976 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4980 if (bsize == BLOCK_64X64 && do_recon) {
4981 assert(tp_orig < *tp);
4982 assert(best_rdc.rate < INT_MAX);
4983 assert(best_rdc.dist < INT64_MAX);
4985 assert(tp_orig == *tp);
4989 static void nonrd_select_partition(VP9_COMP *cpi, ThreadData *td,
4990 TileDataEnc *tile_data, MODE_INFO **mi,
4991 TOKENEXTRA **tp, int mi_row, int mi_col,
4992 BLOCK_SIZE bsize, int output_enabled,
4993 RD_COST *rd_cost, PC_TREE *pc_tree) {
4994 VP9_COMMON *const cm = &cpi->common;
4995 TileInfo *const tile_info = &tile_data->tile_info;
4996 MACROBLOCK *const x = &td->mb;
4997 MACROBLOCKD *const xd = &x->e_mbd;
4998 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4999 const int mis = cm->mi_stride;
5000 PARTITION_TYPE partition;
5003 BLOCK_SIZE subsize_ref =
5004 (cpi->sf.adapt_partition_source_sad) ? BLOCK_8X8 : BLOCK_16X16;
5006 vp9_rd_cost_reset(&this_rdc);
5007 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5009 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5010 partition = partition_lookup[bsl][subsize];
5012 if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
5013 x->max_partition_size = BLOCK_32X32;
5014 x->min_partition_size = BLOCK_16X16;
5015 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5016 0, INT64_MAX, pc_tree);
5017 } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
5018 subsize >= subsize_ref) {
5019 x->max_partition_size = BLOCK_32X32;
5020 x->min_partition_size = BLOCK_8X8;
5021 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5022 0, INT64_MAX, pc_tree);
5023 } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
5024 x->max_partition_size = BLOCK_16X16;
5025 x->min_partition_size = BLOCK_8X8;
5026 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5027 0, INT64_MAX, pc_tree);
5029 switch (partition) {
5030 case PARTITION_NONE:
5031 pc_tree->none.pred_pixel_ready = 1;
5032 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5034 pc_tree->none.mic = *xd->mi[0];
5035 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5036 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5037 pc_tree->none.skip = x->skip;
5039 case PARTITION_VERT:
5040 pc_tree->vertical[0].pred_pixel_ready = 1;
5041 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5042 &pc_tree->vertical[0]);
5043 pc_tree->vertical[0].mic = *xd->mi[0];
5044 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5045 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5046 pc_tree->vertical[0].skip = x->skip;
5047 if (mi_col + hbs < cm->mi_cols) {
5048 pc_tree->vertical[1].pred_pixel_ready = 1;
5049 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
5050 &this_rdc, subsize, &pc_tree->vertical[1]);
5051 pc_tree->vertical[1].mic = *xd->mi[0];
5052 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5053 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5054 pc_tree->vertical[1].skip = x->skip;
5055 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5056 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5057 rd_cost->rate += this_rdc.rate;
5058 rd_cost->dist += this_rdc.dist;
5062 case PARTITION_HORZ:
5063 pc_tree->horizontal[0].pred_pixel_ready = 1;
5064 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5065 &pc_tree->horizontal[0]);
5066 pc_tree->horizontal[0].mic = *xd->mi[0];
5067 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5068 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5069 pc_tree->horizontal[0].skip = x->skip;
5070 if (mi_row + hbs < cm->mi_rows) {
5071 pc_tree->horizontal[1].pred_pixel_ready = 1;
5072 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
5073 &this_rdc, subsize, &pc_tree->horizontal[1]);
5074 pc_tree->horizontal[1].mic = *xd->mi[0];
5075 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5076 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5077 pc_tree->horizontal[1].skip = x->skip;
5078 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5079 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5080 rd_cost->rate += this_rdc.rate;
5081 rd_cost->dist += this_rdc.dist;
5086 assert(partition == PARTITION_SPLIT);
5087 subsize = get_subsize(bsize, PARTITION_SPLIT);
5088 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5089 subsize, output_enabled, rd_cost,
5091 nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5092 mi_col + hbs, subsize, output_enabled, &this_rdc,
5094 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5095 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5096 rd_cost->rate += this_rdc.rate;
5097 rd_cost->dist += this_rdc.dist;
5099 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5100 mi_row + hbs, mi_col, subsize, output_enabled,
5101 &this_rdc, pc_tree->split[2]);
5102 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5103 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5104 rd_cost->rate += this_rdc.rate;
5105 rd_cost->dist += this_rdc.dist;
5107 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5108 mi_row + hbs, mi_col + hbs, subsize,
5109 output_enabled, &this_rdc, pc_tree->split[3]);
5110 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5111 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5112 rd_cost->rate += this_rdc.rate;
5113 rd_cost->dist += this_rdc.dist;
5119 if (bsize == BLOCK_64X64 && output_enabled)
5120 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
5123 static void nonrd_use_partition(VP9_COMP *cpi, ThreadData *td,
5124 TileDataEnc *tile_data, MODE_INFO **mi,
5125 TOKENEXTRA **tp, int mi_row, int mi_col,
5126 BLOCK_SIZE bsize, int output_enabled,
5127 RD_COST *dummy_cost, PC_TREE *pc_tree) {
5128 VP9_COMMON *const cm = &cpi->common;
5129 TileInfo *tile_info = &tile_data->tile_info;
5130 MACROBLOCK *const x = &td->mb;
5131 MACROBLOCKD *const xd = &x->e_mbd;
5132 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5133 const int mis = cm->mi_stride;
5134 PARTITION_TYPE partition;
5137 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5139 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5140 partition = partition_lookup[bsl][subsize];
5142 if (output_enabled && bsize != BLOCK_4X4) {
5143 int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
5144 td->counts->partition[ctx][partition]++;
5147 switch (partition) {
5148 case PARTITION_NONE:
5149 pc_tree->none.pred_pixel_ready = 1;
5150 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5151 subsize, &pc_tree->none);
5152 pc_tree->none.mic = *xd->mi[0];
5153 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5154 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5155 pc_tree->none.skip = x->skip;
5156 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5157 subsize, &pc_tree->none);
5159 case PARTITION_VERT:
5160 pc_tree->vertical[0].pred_pixel_ready = 1;
5161 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5162 subsize, &pc_tree->vertical[0]);
5163 pc_tree->vertical[0].mic = *xd->mi[0];
5164 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5165 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5166 pc_tree->vertical[0].skip = x->skip;
5167 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5168 subsize, &pc_tree->vertical[0]);
5169 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
5170 pc_tree->vertical[1].pred_pixel_ready = 1;
5171 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost,
5172 subsize, &pc_tree->vertical[1]);
5173 pc_tree->vertical[1].mic = *xd->mi[0];
5174 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5175 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5176 pc_tree->vertical[1].skip = x->skip;
5177 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
5178 output_enabled, subsize, &pc_tree->vertical[1]);
5181 case PARTITION_HORZ:
5182 pc_tree->horizontal[0].pred_pixel_ready = 1;
5183 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5184 subsize, &pc_tree->horizontal[0]);
5185 pc_tree->horizontal[0].mic = *xd->mi[0];
5186 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5187 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5188 pc_tree->horizontal[0].skip = x->skip;
5189 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5190 subsize, &pc_tree->horizontal[0]);
5192 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
5193 pc_tree->horizontal[1].pred_pixel_ready = 1;
5194 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost,
5195 subsize, &pc_tree->horizontal[1]);
5196 pc_tree->horizontal[1].mic = *xd->mi[0];
5197 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5198 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5199 pc_tree->horizontal[1].skip = x->skip;
5200 encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
5201 output_enabled, subsize, &pc_tree->horizontal[1]);
5205 assert(partition == PARTITION_SPLIT);
5206 subsize = get_subsize(bsize, PARTITION_SPLIT);
5207 if (bsize == BLOCK_8X8) {
5208 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5209 subsize, pc_tree->leaf_split[0]);
5210 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5211 subsize, pc_tree->leaf_split[0]);
5213 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, subsize,
5214 output_enabled, dummy_cost, pc_tree->split[0]);
5215 nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5216 mi_col + hbs, subsize, output_enabled, dummy_cost,
5218 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5219 mi_row + hbs, mi_col, subsize, output_enabled,
5220 dummy_cost, pc_tree->split[2]);
5221 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5222 mi_row + hbs, mi_col + hbs, subsize, output_enabled,
5223 dummy_cost, pc_tree->split[3]);
5228 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
5229 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
5232 // Get a prediction(stored in x->est_pred) for the whole 64x64 superblock.
5233 static void get_estimated_pred(VP9_COMP *cpi, const TileInfo *const tile,
5234 MACROBLOCK *x, int mi_row, int mi_col) {
5235 VP9_COMMON *const cm = &cpi->common;
5236 const int is_key_frame = frame_is_intra_only(cm);
5237 MACROBLOCKD *xd = &x->e_mbd;
5239 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
5241 if (!is_key_frame) {
5242 MODE_INFO *mi = xd->mi[0];
5243 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
5244 const YV12_BUFFER_CONFIG *yv12_g = NULL;
5245 const BLOCK_SIZE bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
5246 (mi_row + 4 < cm->mi_rows);
5247 unsigned int y_sad_g, y_sad_thr;
5248 unsigned int y_sad = UINT_MAX;
5250 assert(yv12 != NULL);
5252 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
5253 cpi->svc.use_gf_temporal_ref_current_layer) {
5254 // For now, GOLDEN will not be used for non-zero spatial layers, since
5255 // it may not be a temporal reference.
5256 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
5259 // Only compute y_sad_g (sad for golden reference) for speed < 8.
5260 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
5261 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
5262 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5263 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5264 y_sad_g = cpi->fn_ptr[bsize].sdf(
5265 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
5266 xd->plane[0].pre[0].stride);
5271 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
5272 cpi->rc.is_src_frame_alt_ref) {
5273 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
5274 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5275 &cm->frame_refs[ALTREF_FRAME - 1].sf);
5276 mi->ref_frame[0] = ALTREF_FRAME;
5279 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5280 &cm->frame_refs[LAST_FRAME - 1].sf);
5281 mi->ref_frame[0] = LAST_FRAME;
5283 mi->ref_frame[1] = NONE;
5284 mi->sb_type = BLOCK_64X64;
5285 mi->mv[0].as_int = 0;
5286 mi->interp_filter = BILINEAR;
5289 const MV dummy_mv = { 0, 0 };
5290 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
5292 x->sb_use_mv_part = 1;
5293 x->sb_mvcol_part = mi->mv[0].as_mv.col;
5294 x->sb_mvrow_part = mi->mv[0].as_mv.row;
5297 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
5298 // are close if short_circuit_low_temp_var is on.
5299 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
5300 if (y_sad_g < y_sad_thr) {
5301 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5302 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5303 mi->ref_frame[0] = GOLDEN_FRAME;
5304 mi->mv[0].as_int = 0;
5306 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
5309 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
5310 xd->plane[0].dst.buf = x->est_pred;
5311 xd->plane[0].dst.stride = 64;
5312 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
5314 #if CONFIG_VP9_HIGHBITDEPTH
5316 case 8: memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); break;
5318 memset(x->est_pred, 128 * 4, 64 * 64 * sizeof(x->est_pred[0]));
5321 memset(x->est_pred, 128 * 16, 64 * 64 * sizeof(x->est_pred[0]));
5325 memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0]));
5326 #endif // CONFIG_VP9_HIGHBITDEPTH
5330 static void encode_nonrd_sb_row(VP9_COMP *cpi, ThreadData *td,
5331 TileDataEnc *tile_data, int mi_row,
5333 SPEED_FEATURES *const sf = &cpi->sf;
5334 VP9_COMMON *const cm = &cpi->common;
5335 TileInfo *const tile_info = &tile_data->tile_info;
5336 MACROBLOCK *const x = &td->mb;
5337 MACROBLOCKD *const xd = &x->e_mbd;
5338 const int mi_col_start = tile_info->mi_col_start;
5339 const int mi_col_end = tile_info->mi_col_end;
5341 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
5342 const int num_sb_cols =
5343 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
5346 // Initialize the left context for the new SB row
5347 memset(&xd->left_context, 0, sizeof(xd->left_context));
5348 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
5350 // Code each SB in the row
5351 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
5352 mi_col += MI_BLOCK_SIZE, ++sb_col_in_tile) {
5353 const struct segmentation *const seg = &cm->seg;
5355 const int idx_str = cm->mi_stride * mi_row + mi_col;
5356 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
5357 PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
5358 BLOCK_SIZE bsize = BLOCK_64X64;
5362 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
5365 if (cpi->use_skin_detection) {
5366 vp9_compute_skin_sb(cpi, BLOCK_16X16, mi_row, mi_col);
5369 x->source_variance = UINT_MAX;
5370 for (i = 0; i < MAX_REF_FRAMES; ++i) {
5371 x->pred_mv[i].row = INT16_MAX;
5372 x->pred_mv[i].col = INT16_MAX;
5374 vp9_rd_cost_init(&dummy_rdc);
5375 x->color_sensitivity[0] = 0;
5376 x->color_sensitivity[1] = 0;
5378 x->skip_low_source_sad = 0;
5379 x->lowvar_highsumdiff = 0;
5380 x->content_state_sb = 0;
5381 x->zero_temp_sad_source = 0;
5382 x->sb_use_mv_part = 0;
5383 x->sb_mvcol_part = 0;
5384 x->sb_mvrow_part = 0;
5385 x->sb_pickmode_part = 0;
5386 x->arf_frame_usage = 0;
5387 x->lastgolden_frame_usage = 0;
5390 const uint8_t *const map =
5391 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
5392 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
5393 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
5395 partition_search_type = FIXED_PARTITION;
5399 if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
5400 int shift = cpi->Source->y_stride * (mi_row << 3) + (mi_col << 3);
5401 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5402 int64_t source_sad = avg_source_sad(cpi, x, shift, sb_offset2);
5403 if (sf->adapt_partition_source_sad &&
5404 (cpi->oxcf.rc_mode == VPX_VBR && !cpi->rc.is_src_frame_alt_ref &&
5405 source_sad > sf->adapt_partition_thresh &&
5406 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)))
5407 partition_search_type = REFERENCE_PARTITION;
5410 // Set the partition type of the 64X64 block
5411 switch (partition_search_type) {
5412 case VAR_BASED_PARTITION:
5413 // TODO(jingning, marpan): The mode decision and encoding process
5414 // support both intra and inter sub8x8 block coding for RTC mode.
5415 // Tune the thresholds accordingly to use sub8x8 block coding for
5416 // coding performance improvement.
5417 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5418 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5419 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5421 case ML_BASED_PARTITION:
5422 get_estimated_pred(cpi, tile_info, x, mi_row, mi_col);
5423 x->max_partition_size = BLOCK_64X64;
5424 x->min_partition_size = BLOCK_8X8;
5425 x->sb_pickmode_part = 1;
5426 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5427 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5430 case SOURCE_VAR_BASED_PARTITION:
5431 set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
5432 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5433 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5435 case FIXED_PARTITION:
5436 if (!seg_skip) bsize = sf->always_this_block_size;
5437 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
5438 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5439 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5442 assert(partition_search_type == REFERENCE_PARTITION);
5443 x->sb_pickmode_part = 1;
5444 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
5445 // Use nonrd_pick_partition on scene-cut for VBR mode.
5446 // nonrd_pick_partition does not support 4x4 partition, so avoid it
5447 // on key frame for now.
5448 if ((cpi->oxcf.rc_mode == VPX_VBR && cpi->rc.high_source_sad &&
5449 cpi->oxcf.speed < 6 && !frame_is_intra_only(cm) &&
5450 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
5451 // Use lower max_partition_size for low resoultions.
5452 if (cm->width <= 352 && cm->height <= 288)
5453 x->max_partition_size = BLOCK_32X32;
5455 x->max_partition_size = BLOCK_64X64;
5456 x->min_partition_size = BLOCK_8X8;
5457 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5458 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5461 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5462 // TODO(marpan): Seems like nonrd_select_partition does not support
5463 // 4x4 partition. Since 4x4 is used on key frame, use this switch
5465 if (frame_is_intra_only(cm))
5466 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5467 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5469 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5470 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5476 // Update ref_frame usage for inter frame if this group is ARF group.
5477 if (!cpi->rc.is_src_frame_alt_ref && !cpi->refresh_golden_frame &&
5478 !cpi->refresh_alt_ref_frame && cpi->rc.alt_ref_gf_group &&
5479 cpi->sf.use_altref_onepass) {
5480 int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5481 if (cpi->count_arf_frame_usage != NULL)
5482 cpi->count_arf_frame_usage[sboffset] = x->arf_frame_usage;
5483 if (cpi->count_lastgolden_frame_usage != NULL)
5484 cpi->count_lastgolden_frame_usage[sboffset] = x->lastgolden_frame_usage;
5487 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
5488 sb_col_in_tile, num_sb_cols);
5491 // end RTC play code
5493 static INLINE uint32_t variance(const diff *const d) {
5494 return d->sse - (uint32_t)(((int64_t)d->sum * d->sum) >> 8);
5497 #if CONFIG_VP9_HIGHBITDEPTH
5498 static INLINE uint32_t variance_highbd(diff *const d) {
5499 const int64_t var = (int64_t)d->sse - (((int64_t)d->sum * d->sum) >> 8);
5500 return (var >= 0) ? (uint32_t)var : 0;
5502 #endif // CONFIG_VP9_HIGHBITDEPTH
5504 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
5505 const SPEED_FEATURES *const sf = &cpi->sf;
5506 const VP9_COMMON *const cm = &cpi->common;
5508 const uint8_t *src = cpi->Source->y_buffer;
5509 const uint8_t *last_src = cpi->Last_Source->y_buffer;
5510 const int src_stride = cpi->Source->y_stride;
5511 const int last_stride = cpi->Last_Source->y_stride;
5513 // Pick cutoff threshold
5514 const int cutoff = (VPXMIN(cm->width, cm->height) >= 720)
5515 ? (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100)
5516 : (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
5517 DECLARE_ALIGNED(16, int, hist[VAR_HIST_BINS]);
5518 diff *var16 = cpi->source_diff_var;
5523 memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
5525 for (i = 0; i < cm->mb_rows; i++) {
5526 for (j = 0; j < cm->mb_cols; j++) {
5527 #if CONFIG_VP9_HIGHBITDEPTH
5528 if (cm->use_highbitdepth) {
5529 switch (cm->bit_depth) {
5531 vpx_highbd_8_get16x16var(src, src_stride, last_src, last_stride,
5532 &var16->sse, &var16->sum);
5533 var16->var = variance(var16);
5536 vpx_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
5537 &var16->sse, &var16->sum);
5538 var16->var = variance_highbd(var16);
5541 assert(cm->bit_depth == VPX_BITS_12);
5542 vpx_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
5543 &var16->sse, &var16->sum);
5544 var16->var = variance_highbd(var16);
5548 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5550 var16->var = variance(var16);
5553 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5555 var16->var = variance(var16);
5556 #endif // CONFIG_VP9_HIGHBITDEPTH
5558 if (var16->var >= VAR_HIST_MAX_BG_VAR)
5559 hist[VAR_HIST_BINS - 1]++;
5561 hist[var16->var / VAR_HIST_FACTOR]++;
5568 src = src - cm->mb_cols * 16 + 16 * src_stride;
5569 last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
5572 cpi->source_var_thresh = 0;
5574 if (hist[VAR_HIST_BINS - 1] < cutoff) {
5575 for (i = 0; i < VAR_HIST_BINS - 1; i++) {
5579 cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
5585 return sf->search_type_check_frequency;
5588 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
5589 VP9_COMMON *const cm = &cpi->common;
5590 SPEED_FEATURES *const sf = &cpi->sf;
5592 if (cm->frame_type == KEY_FRAME) {
5593 // For key frame, use SEARCH_PARTITION.
5594 sf->partition_search_type = SEARCH_PARTITION;
5595 } else if (cm->intra_only) {
5596 sf->partition_search_type = FIXED_PARTITION;
5598 if (cm->last_width != cm->width || cm->last_height != cm->height) {
5599 if (cpi->source_diff_var) vpx_free(cpi->source_diff_var);
5601 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
5602 vpx_calloc(cm->MBs, sizeof(diff)));
5605 if (!cpi->frames_till_next_var_check)
5606 cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
5608 if (cpi->frames_till_next_var_check > 0) {
5609 sf->partition_search_type = FIXED_PARTITION;
5610 cpi->frames_till_next_var_check--;
5615 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
5616 unsigned int intra_count = 0, inter_count = 0;
5619 for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
5620 intra_count += td->counts->intra_inter[j][0];
5621 inter_count += td->counts->intra_inter[j][1];
5624 return (intra_count << 2) < inter_count && cm->frame_type != KEY_FRAME &&
5628 void vp9_init_tile_data(VP9_COMP *cpi) {
5629 VP9_COMMON *const cm = &cpi->common;
5630 const int tile_cols = 1 << cm->log2_tile_cols;
5631 const int tile_rows = 1 << cm->log2_tile_rows;
5632 int tile_col, tile_row;
5633 TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
5634 TOKENLIST *tplist = cpi->tplist[0][0];
5636 int tplist_count = 0;
5638 if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
5639 if (cpi->tile_data != NULL) vpx_free(cpi->tile_data);
5642 vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
5643 cpi->allocated_tiles = tile_cols * tile_rows;
5645 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5646 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5647 TileDataEnc *tile_data =
5648 &cpi->tile_data[tile_row * tile_cols + tile_col];
5650 for (i = 0; i < BLOCK_SIZES; ++i) {
5651 for (j = 0; j < MAX_MODES; ++j) {
5652 tile_data->thresh_freq_fact[i][j] = RD_THRESH_INIT_FACT;
5653 #if CONFIG_CONSISTENT_RECODE
5654 tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5656 tile_data->mode_map[i][j] = j;
5659 #if CONFIG_MULTITHREAD
5660 tile_data->row_base_thresh_freq_fact = NULL;
5665 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
5666 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5667 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5668 TileInfo *tile_info = &this_tile->tile_info;
5669 if (cpi->sf.adaptive_rd_thresh_row_mt &&
5670 this_tile->row_base_thresh_freq_fact == NULL)
5671 vp9_row_mt_alloc_rd_thresh(cpi, this_tile);
5672 vp9_tile_init(tile_info, cm, tile_row, tile_col);
5674 cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
5675 pre_tok = cpi->tile_tok[tile_row][tile_col];
5676 tile_tok = allocated_tokens(*tile_info);
5678 cpi->tplist[tile_row][tile_col] = tplist + tplist_count;
5679 tplist = cpi->tplist[tile_row][tile_col];
5680 tplist_count = get_num_vert_units(*tile_info, MI_BLOCK_SIZE_LOG2);
5685 void vp9_encode_sb_row(VP9_COMP *cpi, ThreadData *td, int tile_row,
5686 int tile_col, int mi_row) {
5687 VP9_COMMON *const cm = &cpi->common;
5688 const int tile_cols = 1 << cm->log2_tile_cols;
5689 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5690 const TileInfo *const tile_info = &this_tile->tile_info;
5691 TOKENEXTRA *tok = NULL;
5693 int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
5695 tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile_info->mi_row_start) >>
5697 get_start_tok(cpi, tile_row, tile_col, mi_row, &tok);
5698 cpi->tplist[tile_row][tile_col][tile_sb_row].start = tok;
5700 if (cpi->sf.use_nonrd_pick_mode)
5701 encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5703 encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
5705 cpi->tplist[tile_row][tile_col][tile_sb_row].stop = tok;
5706 cpi->tplist[tile_row][tile_col][tile_sb_row].count =
5707 (unsigned int)(cpi->tplist[tile_row][tile_col][tile_sb_row].stop -
5708 cpi->tplist[tile_row][tile_col][tile_sb_row].start);
5709 assert(tok - cpi->tplist[tile_row][tile_col][tile_sb_row].start <=
5710 get_token_alloc(MI_BLOCK_SIZE >> 1, tile_mb_cols));
5715 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td, int tile_row,
5717 VP9_COMMON *const cm = &cpi->common;
5718 const int tile_cols = 1 << cm->log2_tile_cols;
5719 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5720 const TileInfo *const tile_info = &this_tile->tile_info;
5721 const int mi_row_start = tile_info->mi_row_start;
5722 const int mi_row_end = tile_info->mi_row_end;
5725 for (mi_row = mi_row_start; mi_row < mi_row_end; mi_row += MI_BLOCK_SIZE)
5726 vp9_encode_sb_row(cpi, td, tile_row, tile_col, mi_row);
5729 static void encode_tiles(VP9_COMP *cpi) {
5730 VP9_COMMON *const cm = &cpi->common;
5731 const int tile_cols = 1 << cm->log2_tile_cols;
5732 const int tile_rows = 1 << cm->log2_tile_rows;
5733 int tile_col, tile_row;
5735 vp9_init_tile_data(cpi);
5737 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5738 for (tile_col = 0; tile_col < tile_cols; ++tile_col)
5739 vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
5742 #if CONFIG_FP_MB_STATS
5743 static int input_fpmb_stats(FIRSTPASS_MB_STATS *firstpass_mb_stats,
5744 VP9_COMMON *cm, uint8_t **this_frame_mb_stats) {
5745 uint8_t *mb_stats_in = firstpass_mb_stats->mb_stats_start +
5746 cm->current_video_frame * cm->MBs * sizeof(uint8_t);
5748 if (mb_stats_in > firstpass_mb_stats->mb_stats_end) return EOF;
5750 *this_frame_mb_stats = mb_stats_in;
5756 static int compare_kmeans_data(const void *a, const void *b) {
5757 if (((const KMEANS_DATA *)a)->value > ((const KMEANS_DATA *)b)->value) {
5759 } else if (((const KMEANS_DATA *)a)->value <
5760 ((const KMEANS_DATA *)b)->value) {
5767 static void compute_boundary_ls(const double *ctr_ls, int k,
5768 double *boundary_ls) {
5769 // boundary_ls[j] is the upper bound of data centered at ctr_ls[j]
5771 for (j = 0; j < k - 1; ++j) {
5772 boundary_ls[j] = (ctr_ls[j] + ctr_ls[j + 1]) / 2.;
5774 boundary_ls[k - 1] = DBL_MAX;
5777 int vp9_get_group_idx(double value, double *boundary_ls, int k) {
5779 while (value >= boundary_ls[group_idx]) {
5781 if (group_idx == k - 1) {
5788 void vp9_kmeans(double *ctr_ls, double *boundary_ls, int *count_ls, int k,
5789 KMEANS_DATA *arr, int size) {
5798 vpx_clear_system_state();
5800 assert(k >= 2 && k <= MAX_KMEANS_GROUPS);
5802 qsort(arr, size, sizeof(*arr), compare_kmeans_data);
5805 max = arr[size - 1].value;
5807 // initialize the center points
5808 step = (max - min) * 1. / k;
5809 for (j = 0; j < k; ++j) {
5810 ctr_ls[j] = min + j * step + step / 2;
5813 for (itr = 0; itr < 10; ++itr) {
5814 compute_boundary_ls(ctr_ls, k, boundary_ls);
5818 for (i = 0; i < size; ++i) {
5819 while (arr[i].value >= boundary_ls[group_idx]) {
5821 if (group_idx == k - 1) {
5826 sum += arr[i].value;
5829 if (i + 1 == size || arr[i + 1].value >= boundary_ls[group_idx]) {
5831 ctr_ls[group_idx] = sum / count;
5839 // compute group_idx, boundary_ls and count_ls
5840 for (j = 0; j < k; ++j) {
5843 compute_boundary_ls(ctr_ls, k, boundary_ls);
5845 for (i = 0; i < size; ++i) {
5846 while (arr[i].value >= boundary_ls[group_idx]) {
5848 if (group_idx == k - 1) {
5852 arr[i].group_idx = group_idx;
5853 ++count_ls[group_idx];
5857 static void encode_frame_internal(VP9_COMP *cpi) {
5858 SPEED_FEATURES *const sf = &cpi->sf;
5859 ThreadData *const td = &cpi->td;
5860 MACROBLOCK *const x = &td->mb;
5861 VP9_COMMON *const cm = &cpi->common;
5862 MACROBLOCKD *const xd = &x->e_mbd;
5863 const int gf_group_index = cpi->twopass.gf_group.index;
5865 xd->mi = cm->mi_grid_visible;
5867 vp9_zero(*td->counts);
5868 vp9_zero(cpi->td.rd_counts);
5870 xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
5871 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
5873 #if CONFIG_VP9_HIGHBITDEPTH
5874 if (cm->use_highbitdepth)
5875 x->fwd_txfm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
5877 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5878 x->highbd_inv_txfm_add =
5879 xd->lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
5881 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5882 #endif // CONFIG_VP9_HIGHBITDEPTH
5883 x->inv_txfm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
5884 #if CONFIG_CONSISTENT_RECODE
5885 x->optimize = sf->optimize_coefficients == 1 && cpi->oxcf.pass != 1;
5887 if (xd->lossless) x->optimize = 0;
5888 x->sharpness = cpi->oxcf.sharpness;
5889 x->adjust_rdmult_by_segment = (cpi->oxcf.aq_mode == VARIANCE_AQ);
5891 cm->tx_mode = select_tx_mode(cpi, xd);
5893 vp9_frame_init_quantizer(cpi);
5895 vp9_initialize_rd_consts(cpi);
5896 vp9_initialize_me_consts(cpi, x, cm->base_qindex);
5897 init_encode_frame_mb_context(cpi);
5898 cm->use_prev_frame_mvs =
5899 !cm->error_resilient_mode && cm->width == cm->last_width &&
5900 cm->height == cm->last_height && !cm->intra_only && cm->last_show_frame;
5901 // Special case: set prev_mi to NULL when the previous mode info
5902 // context cannot be used.
5904 cm->use_prev_frame_mvs ? cm->prev_mip + cm->mi_stride + 1 : NULL;
5906 x->quant_fp = cpi->sf.use_quant_fp;
5907 vp9_zero(x->skip_txfm);
5908 if (sf->use_nonrd_pick_mode) {
5909 // Initialize internal buffer pointers for rtc coding, where non-RD
5910 // mode decision is used and hence no buffer pointer swap needed.
5912 struct macroblock_plane *const p = x->plane;
5913 struct macroblockd_plane *const pd = xd->plane;
5914 PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
5916 for (i = 0; i < MAX_MB_PLANE; ++i) {
5917 p[i].coeff = ctx->coeff_pbuf[i][0];
5918 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
5919 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
5920 p[i].eobs = ctx->eobs_pbuf[i][0];
5922 vp9_zero(x->zcoeff_blk);
5924 if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0 &&
5925 !(cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) &&
5927 cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
5929 if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
5930 source_var_based_partition_search_method(cpi);
5931 } else if (gf_group_index && gf_group_index < MAX_ARF_GOP_SIZE &&
5932 cpi->sf.enable_tpl_model) {
5933 TplDepFrame *tpl_frame = &cpi->tpl_stats[cpi->twopass.gf_group.index];
5934 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
5936 int tpl_stride = tpl_frame->stride;
5937 int64_t intra_cost_base = 0;
5938 int64_t mc_dep_cost_base = 0;
5941 for (row = 0; row < cm->mi_rows && tpl_frame->is_valid; ++row) {
5942 for (col = 0; col < cm->mi_cols; ++col) {
5943 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
5944 intra_cost_base += this_stats->intra_cost;
5945 mc_dep_cost_base += this_stats->mc_dep_cost;
5949 vpx_clear_system_state();
5951 if (tpl_frame->is_valid)
5952 cpi->rd.r0 = (double)intra_cost_base / mc_dep_cost_base;
5955 // Frame segmentation
5956 if (cpi->sf.enable_wiener_variance) build_kmeans_segmentation(cpi);
5959 struct vpx_usec_timer emr_timer;
5960 vpx_usec_timer_start(&emr_timer);
5962 #if CONFIG_FP_MB_STATS
5963 if (cpi->use_fp_mb_stats) {
5964 input_fpmb_stats(&cpi->twopass.firstpass_mb_stats, cm,
5965 &cpi->twopass.this_frame_mb_stats);
5970 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
5971 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
5972 // If allowed, encoding tiles in parallel with one thread handling one
5973 // tile when row based multi-threading is disabled.
5974 if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
5975 vp9_encode_tiles_mt(cpi);
5979 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
5980 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
5981 vp9_encode_tiles_row_mt(cpi);
5984 vpx_usec_timer_mark(&emr_timer);
5985 cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
5988 sf->skip_encode_frame =
5989 sf->skip_encode_sb ? get_skip_encode_frame(cm, td) : 0;
5992 // Keep record of the total distortion this time around for future use
5993 cpi->last_frame_distortion = cpi->frame_distortion;
5997 static INTERP_FILTER get_interp_filter(
5998 const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
5999 if (!is_alt_ref && threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
6000 threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
6001 threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
6002 return EIGHTTAP_SMOOTH;
6003 } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
6004 threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
6005 return EIGHTTAP_SHARP;
6006 } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
6013 static int compute_frame_aq_offset(struct VP9_COMP *cpi) {
6014 VP9_COMMON *const cm = &cpi->common;
6015 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
6016 struct segmentation *const seg = &cm->seg;
6024 for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
6025 MODE_INFO **mi_8x8 = mi_8x8_ptr;
6026 for (mi_col = 0; mi_col < cm->mi_cols; mi_col++, mi_8x8++) {
6027 segment_id = mi_8x8[0]->segment_id;
6028 qdelta_index = get_segdata(seg, segment_id, SEG_LVL_ALT_Q);
6029 sum_delta += qdelta_index;
6032 mi_8x8_ptr += cm->mi_stride;
6035 return sum_delta / (cm->mi_rows * cm->mi_cols);
6038 #if CONFIG_CONSISTENT_RECODE
6039 static void restore_encode_params(VP9_COMP *cpi) {
6040 VP9_COMMON *const cm = &cpi->common;
6041 const int tile_cols = 1 << cm->log2_tile_cols;
6042 const int tile_rows = 1 << cm->log2_tile_rows;
6043 int tile_col, tile_row;
6045 RD_OPT *rd_opt = &cpi->rd;
6046 for (i = 0; i < MAX_REF_FRAMES; i++) {
6047 for (j = 0; j < REFERENCE_MODES; j++)
6048 rd_opt->prediction_type_threshes[i][j] =
6049 rd_opt->prediction_type_threshes_prev[i][j];
6051 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
6052 rd_opt->filter_threshes[i][j] = rd_opt->filter_threshes_prev[i][j];
6055 if (cpi->tile_data != NULL) {
6056 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
6057 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
6058 TileDataEnc *tile_data =
6059 &cpi->tile_data[tile_row * tile_cols + tile_col];
6060 for (i = 0; i < BLOCK_SIZES; ++i) {
6061 for (j = 0; j < MAX_MODES; ++j) {
6062 tile_data->thresh_freq_fact[i][j] =
6063 tile_data->thresh_freq_fact_prev[i][j];
6069 cm->interp_filter = cpi->sf.default_interp_filter;
6073 void vp9_encode_frame(VP9_COMP *cpi) {
6074 VP9_COMMON *const cm = &cpi->common;
6076 #if CONFIG_CONSISTENT_RECODE
6077 restore_encode_params(cpi);
6080 // In the longer term the encoder should be generalized to match the
6081 // decoder such that we allow compound where one of the 3 buffers has a
6082 // different sign bias and that buffer is then the fixed ref. However, this
6083 // requires further work in the rd loop. For now the only supported encoder
6084 // side behavior is where the ALT ref buffer has opposite sign bias to
6086 if (!frame_is_intra_only(cm)) {
6087 if (vp9_compound_reference_allowed(cm)) {
6088 cpi->allow_comp_inter_inter = 1;
6089 vp9_setup_compound_reference_mode(cm);
6091 cpi->allow_comp_inter_inter = 0;
6095 if (cpi->sf.frame_parameter_update) {
6097 RD_OPT *const rd_opt = &cpi->rd;
6098 FRAME_COUNTS *counts = cpi->td.counts;
6099 RD_COUNTS *const rdc = &cpi->td.rd_counts;
6101 // This code does a single RD pass over the whole frame assuming
6102 // either compound, single or hybrid prediction as per whatever has
6103 // worked best for that type of frame in the past.
6104 // It also predicts whether another coding mode would have worked
6105 // better than this coding mode. If that is the case, it remembers
6106 // that for subsequent frames.
6107 // It also does the same analysis for transform size selection.
6108 const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
6109 int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
6110 int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
6111 const int is_alt_ref = frame_type == ALTREF_FRAME;
6113 /* prediction (compound, single or hybrid) mode selection */
6114 if (is_alt_ref || !cpi->allow_comp_inter_inter)
6115 cm->reference_mode = SINGLE_REFERENCE;
6116 else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
6117 mode_thrs[COMPOUND_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT] &&
6118 check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
6119 cm->reference_mode = COMPOUND_REFERENCE;
6120 else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
6121 cm->reference_mode = SINGLE_REFERENCE;
6123 cm->reference_mode = REFERENCE_MODE_SELECT;
6125 if (cm->interp_filter == SWITCHABLE)
6126 cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
6128 encode_frame_internal(cpi);
6130 for (i = 0; i < REFERENCE_MODES; ++i)
6131 mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
6133 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
6134 filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
6136 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6137 int single_count_zero = 0;
6138 int comp_count_zero = 0;
6140 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6141 single_count_zero += counts->comp_inter[i][0];
6142 comp_count_zero += counts->comp_inter[i][1];
6145 if (comp_count_zero == 0) {
6146 cm->reference_mode = SINGLE_REFERENCE;
6147 vp9_zero(counts->comp_inter);
6148 } else if (single_count_zero == 0) {
6149 cm->reference_mode = COMPOUND_REFERENCE;
6150 vp9_zero(counts->comp_inter);
6154 if (cm->tx_mode == TX_MODE_SELECT) {
6156 int count8x8_lp = 0, count8x8_8x8p = 0;
6157 int count16x16_16x16p = 0, count16x16_lp = 0;
6160 for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
6161 count4x4 += counts->tx.p32x32[i][TX_4X4];
6162 count4x4 += counts->tx.p16x16[i][TX_4X4];
6163 count4x4 += counts->tx.p8x8[i][TX_4X4];
6165 count8x8_lp += counts->tx.p32x32[i][TX_8X8];
6166 count8x8_lp += counts->tx.p16x16[i][TX_8X8];
6167 count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
6169 count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
6170 count16x16_lp += counts->tx.p32x32[i][TX_16X16];
6171 count32x32 += counts->tx.p32x32[i][TX_32X32];
6173 if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
6175 cm->tx_mode = ALLOW_8X8;
6176 reset_skip_tx_size(cm, TX_8X8);
6177 } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
6178 count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
6179 cm->tx_mode = ONLY_4X4;
6180 reset_skip_tx_size(cm, TX_4X4);
6181 } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
6182 cm->tx_mode = ALLOW_32X32;
6183 } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
6184 cm->tx_mode = ALLOW_16X16;
6185 reset_skip_tx_size(cm, TX_16X16);
6189 FRAME_COUNTS *counts = cpi->td.counts;
6190 cm->reference_mode = SINGLE_REFERENCE;
6191 if (cpi->allow_comp_inter_inter && cpi->sf.use_compound_nonrd_pickmode &&
6192 cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
6193 cm->frame_type != KEY_FRAME)
6194 cm->reference_mode = REFERENCE_MODE_SELECT;
6196 encode_frame_internal(cpi);
6198 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6199 int single_count_zero = 0;
6200 int comp_count_zero = 0;
6202 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6203 single_count_zero += counts->comp_inter[i][0];
6204 comp_count_zero += counts->comp_inter[i][1];
6206 if (comp_count_zero == 0) {
6207 cm->reference_mode = SINGLE_REFERENCE;
6208 vp9_zero(counts->comp_inter);
6209 } else if (single_count_zero == 0) {
6210 cm->reference_mode = COMPOUND_REFERENCE;
6211 vp9_zero(counts->comp_inter);
6216 // If segmented AQ is enabled compute the average AQ weighting.
6217 if (cm->seg.enabled && (cpi->oxcf.aq_mode != NO_AQ) &&
6218 (cm->seg.update_map || cm->seg.update_data)) {
6219 cm->seg.aq_av_offset = compute_frame_aq_offset(cpi);
6223 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
6224 const PREDICTION_MODE y_mode = mi->mode;
6225 const PREDICTION_MODE uv_mode = mi->uv_mode;
6226 const BLOCK_SIZE bsize = mi->sb_type;
6228 if (bsize < BLOCK_8X8) {
6230 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
6231 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
6232 for (idy = 0; idy < 2; idy += num_4x4_h)
6233 for (idx = 0; idx < 2; idx += num_4x4_w)
6234 ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
6236 ++counts->y_mode[size_group_lookup[bsize]][y_mode];
6239 ++counts->uv_mode[y_mode][uv_mode];
6242 static void update_zeromv_cnt(VP9_COMP *const cpi, const MODE_INFO *const mi,
6243 int mi_row, int mi_col, BLOCK_SIZE bsize) {
6244 const VP9_COMMON *const cm = &cpi->common;
6245 MV mv = mi->mv[0].as_mv;
6246 const int bw = num_8x8_blocks_wide_lookup[bsize];
6247 const int bh = num_8x8_blocks_high_lookup[bsize];
6248 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
6249 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
6250 const int block_index = mi_row * cm->mi_cols + mi_col;
6252 for (y = 0; y < ymis; y++)
6253 for (x = 0; x < xmis; x++) {
6254 int map_offset = block_index + y * cm->mi_cols + x;
6255 if (mi->ref_frame[0] == LAST_FRAME && is_inter_block(mi) &&
6256 mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
6257 if (abs(mv.row) < 8 && abs(mv.col) < 8) {
6258 if (cpi->consec_zero_mv[map_offset] < 255)
6259 cpi->consec_zero_mv[map_offset]++;
6261 cpi->consec_zero_mv[map_offset] = 0;
6267 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
6268 int output_enabled, int mi_row, int mi_col,
6269 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
6270 VP9_COMMON *const cm = &cpi->common;
6271 MACROBLOCK *const x = &td->mb;
6272 MACROBLOCKD *const xd = &x->e_mbd;
6273 MODE_INFO *mi = xd->mi[0];
6274 const int seg_skip =
6275 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP);
6276 x->skip_recode = !x->select_tx_size && mi->sb_type >= BLOCK_8X8 &&
6277 cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
6278 cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
6279 cpi->sf.allow_skip_recode;
6281 if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
6282 memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
6284 x->skip_optimize = ctx->is_coded;
6286 x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
6287 x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
6288 x->q_index < QIDX_SKIP_THRESH);
6290 if (x->skip_encode) return;
6292 if (!is_inter_block(mi)) {
6294 #if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6295 if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
6296 (xd->above_mi == NULL || xd->left_mi == NULL) &&
6297 need_top_left[mi->uv_mode])
6299 #endif // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6301 for (plane = 0; plane < MAX_MB_PLANE; ++plane)
6302 vp9_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane, 1);
6303 if (output_enabled) sum_intra_stats(td->counts, mi);
6304 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6305 VPXMAX(bsize, BLOCK_8X8));
6308 const int is_compound = has_second_ref(mi);
6309 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
6310 for (ref = 0; ref < 1 + is_compound; ++ref) {
6311 YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, mi->ref_frame[ref]);
6312 assert(cfg != NULL);
6313 vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
6314 &xd->block_refs[ref]->sf);
6316 if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
6317 vp9_build_inter_predictors_sby(xd, mi_row, mi_col,
6318 VPXMAX(bsize, BLOCK_8X8));
6320 vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col,
6321 VPXMAX(bsize, BLOCK_8X8));
6323 vp9_encode_sb(x, VPXMAX(bsize, BLOCK_8X8));
6324 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6325 VPXMAX(bsize, BLOCK_8X8));
6332 if (output_enabled) {
6333 if (cm->tx_mode == TX_MODE_SELECT && mi->sb_type >= BLOCK_8X8 &&
6334 !(is_inter_block(mi) && mi->skip)) {
6335 ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
6336 &td->counts->tx)[mi->tx_size];
6338 // The new intra coding scheme requires no change of transform size
6339 if (is_inter_block(mi)) {
6340 mi->tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
6341 max_txsize_lookup[bsize]);
6343 mi->tx_size = (bsize >= BLOCK_8X8) ? mi->tx_size : TX_4X4;
6347 ++td->counts->tx.tx_totals[mi->tx_size];
6348 ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])];
6349 if (cm->seg.enabled && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
6350 vp9_cyclic_refresh_update_sb_postencode(cpi, mi, mi_row, mi_col, bsize);
6351 if (cpi->oxcf.pass == 0 && cpi->svc.temporal_layer_id == 0 &&
6354 !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
6355 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)))
6356 update_zeromv_cnt(cpi, mi, mi_row, mi_col, bsize);