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 #if CONFIG_MISMATCH_DEBUG
26 #include "vpx_util/vpx_debug_util.h"
27 #endif // CONFIG_MISMATCH_DEBUG
29 #include "vp9/common/vp9_common.h"
30 #include "vp9/common/vp9_entropy.h"
31 #include "vp9/common/vp9_entropymode.h"
32 #include "vp9/common/vp9_idct.h"
33 #include "vp9/common/vp9_mvref_common.h"
34 #include "vp9/common/vp9_pred_common.h"
35 #include "vp9/common/vp9_quant_common.h"
36 #include "vp9/common/vp9_reconintra.h"
37 #include "vp9/common/vp9_reconinter.h"
38 #include "vp9/common/vp9_seg_common.h"
39 #include "vp9/common/vp9_tile_common.h"
40 #if !CONFIG_REALTIME_ONLY
41 #include "vp9/encoder/vp9_aq_360.h"
42 #include "vp9/encoder/vp9_aq_complexity.h"
44 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
45 #if !CONFIG_REALTIME_ONLY
46 #include "vp9/encoder/vp9_aq_variance.h"
48 #include "vp9/encoder/vp9_encodeframe.h"
49 #include "vp9/encoder/vp9_encodemb.h"
50 #include "vp9/encoder/vp9_encodemv.h"
51 #include "vp9/encoder/vp9_ethread.h"
52 #include "vp9/encoder/vp9_extend.h"
53 #include "vp9/encoder/vp9_multi_thread.h"
54 #include "vp9/encoder/vp9_partition_models.h"
55 #include "vp9/encoder/vp9_pickmode.h"
56 #include "vp9/encoder/vp9_rd.h"
57 #include "vp9/encoder/vp9_rdopt.h"
58 #include "vp9/encoder/vp9_segmentation.h"
59 #include "vp9/encoder/vp9_tokenize.h"
61 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
62 int output_enabled, int mi_row, int mi_col,
63 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx);
65 // This is used as a reference when computing the source variance for the
66 // purpose of activity masking.
67 // Eventually this should be replaced by custom no-reference routines,
68 // which will be faster.
69 static const uint8_t VP9_VAR_OFFS[64] = {
70 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
71 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
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
77 #if CONFIG_VP9_HIGHBITDEPTH
78 static const uint16_t VP9_HIGH_VAR_OFFS_8[64] = {
79 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
80 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
81 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
82 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
83 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
86 static const uint16_t VP9_HIGH_VAR_OFFS_10[64] = {
87 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
88 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
89 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
90 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
91 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
92 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
93 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
94 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4
97 static const uint16_t VP9_HIGH_VAR_OFFS_12[64] = {
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,
100 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
101 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
102 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
103 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
104 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
105 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
106 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
109 #endif // CONFIG_VP9_HIGHBITDEPTH
111 unsigned int vp9_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
114 const unsigned int var =
115 cpi->fn_ptr[bs].vf(ref->buf, ref->stride, VP9_VAR_OFFS, 0, &sse);
119 #if CONFIG_VP9_HIGHBITDEPTH
120 unsigned int vp9_high_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
121 BLOCK_SIZE bs, int bd) {
122 unsigned int var, sse;
126 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
127 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10), 0, &sse);
131 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
132 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12), 0, &sse);
137 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
138 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8), 0, &sse);
143 #endif // CONFIG_VP9_HIGHBITDEPTH
145 unsigned int vp9_get_sby_perpixel_variance(VP9_COMP *cpi,
146 const struct buf_2d *ref,
148 return ROUND_POWER_OF_TWO(vp9_get_sby_variance(cpi, ref, bs),
149 num_pels_log2_lookup[bs]);
152 #if CONFIG_VP9_HIGHBITDEPTH
153 unsigned int vp9_high_get_sby_perpixel_variance(VP9_COMP *cpi,
154 const struct buf_2d *ref,
155 BLOCK_SIZE bs, int bd) {
156 return (unsigned int)ROUND64_POWER_OF_TWO(
157 (int64_t)vp9_high_get_sby_variance(cpi, ref, bs, bd),
158 num_pels_log2_lookup[bs]);
160 #endif // CONFIG_VP9_HIGHBITDEPTH
162 static void set_segment_index(VP9_COMP *cpi, MACROBLOCK *const x, int mi_row,
163 int mi_col, BLOCK_SIZE bsize, int segment_index) {
164 VP9_COMMON *const cm = &cpi->common;
165 const struct segmentation *const seg = &cm->seg;
166 MACROBLOCKD *const xd = &x->e_mbd;
167 MODE_INFO *mi = xd->mi[0];
169 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
170 const uint8_t *const map =
171 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
173 // Initialize the segmentation index as 0.
176 // Skip the rest if AQ mode is disabled.
177 if (!seg->enabled) return;
180 case CYCLIC_REFRESH_AQ:
181 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
183 #if !CONFIG_REALTIME_ONLY
185 if (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
186 cpi->force_update_segmentation ||
187 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
190 // Get sub block energy range
191 if (bsize >= BLOCK_32X32) {
192 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
195 min_energy = bsize <= BLOCK_16X16 ? x->mb_energy
196 : vp9_block_energy(cpi, x, bsize);
198 mi->segment_id = vp9_vaq_segment_id(min_energy);
200 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
204 if (cm->frame_type == KEY_FRAME || cpi->force_update_segmentation)
205 mi->segment_id = vp9_360aq_segment_id(mi_row, cm->mi_rows);
207 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
211 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
213 case PSNR_AQ: mi->segment_id = segment_index; break;
214 case PERCEPTUAL_AQ: mi->segment_id = x->segment_id; break;
220 // Set segment index from ROI map if it's enabled.
221 if (cpi->roi.enabled)
222 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
224 vp9_init_plane_quantizers(cpi, x);
227 // Lighter version of set_offsets that only sets the mode info
229 static INLINE void set_mode_info_offsets(VP9_COMMON *const cm,
231 MACROBLOCKD *const xd, int mi_row,
233 const int idx_str = xd->mi_stride * mi_row + mi_col;
234 xd->mi = cm->mi_grid_visible + idx_str;
235 xd->mi[0] = cm->mi + idx_str;
236 x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
239 static void set_ssim_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
240 const BLOCK_SIZE bsize, const int mi_row,
241 const int mi_col, int *const rdmult) {
242 const VP9_COMMON *const cm = &cpi->common;
244 const int bsize_base = BLOCK_16X16;
245 const int num_8x8_w = num_8x8_blocks_wide_lookup[bsize_base];
246 const int num_8x8_h = num_8x8_blocks_high_lookup[bsize_base];
247 const int num_cols = (cm->mi_cols + num_8x8_w - 1) / num_8x8_w;
248 const int num_rows = (cm->mi_rows + num_8x8_h - 1) / num_8x8_h;
249 const int num_bcols =
250 (num_8x8_blocks_wide_lookup[bsize] + num_8x8_w - 1) / num_8x8_w;
251 const int num_brows =
252 (num_8x8_blocks_high_lookup[bsize] + num_8x8_h - 1) / num_8x8_h;
254 double num_of_mi = 0.0;
255 double geom_mean_of_scale = 0.0;
257 assert(cpi->oxcf.tuning == VP8_TUNE_SSIM);
259 for (row = mi_row / num_8x8_w;
260 row < num_rows && row < mi_row / num_8x8_w + num_brows; ++row) {
261 for (col = mi_col / num_8x8_h;
262 col < num_cols && col < mi_col / num_8x8_h + num_bcols; ++col) {
263 const int index = row * num_cols + col;
264 geom_mean_of_scale += log(cpi->mi_ssim_rdmult_scaling_factors[index]);
268 geom_mean_of_scale = exp(geom_mean_of_scale / num_of_mi);
270 *rdmult = (int)((double)(*rdmult) * geom_mean_of_scale);
271 *rdmult = VPXMAX(*rdmult, 0);
272 set_error_per_bit(x, *rdmult);
273 vpx_clear_system_state();
276 static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
277 MACROBLOCK *const x, int mi_row, int mi_col,
279 VP9_COMMON *const cm = &cpi->common;
280 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
281 MACROBLOCKD *const xd = &x->e_mbd;
282 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
283 const int mi_height = num_8x8_blocks_high_lookup[bsize];
284 MvLimits *const mv_limits = &x->mv_limits;
286 set_skip_context(xd, mi_row, mi_col);
288 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
290 // Set up destination pointers.
291 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
293 // Set up limit values for MV components.
294 // Mv beyond the range do not produce new/different prediction block.
295 mv_limits->row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
296 mv_limits->col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
297 mv_limits->row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
298 mv_limits->col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
300 // Set up distance of MB to edge of frame in 1/8th pel units.
301 assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
302 set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width, cm->mi_rows,
305 // Set up source buffers.
306 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
309 x->rddiv = cpi->rd.RDDIV;
310 x->rdmult = cpi->rd.RDMULT;
311 if (oxcf->tuning == VP8_TUNE_SSIM) {
312 set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
315 // required by vp9_append_sub8x8_mvs_for_idx() and vp9_find_best_ref_mvs()
319 static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
320 int mi_row, int mi_col,
322 const int block_width =
323 VPXMIN(num_8x8_blocks_wide_lookup[bsize], cm->mi_cols - mi_col);
324 const int block_height =
325 VPXMIN(num_8x8_blocks_high_lookup[bsize], cm->mi_rows - mi_row);
326 const int mi_stride = xd->mi_stride;
327 MODE_INFO *const src_mi = xd->mi[0];
330 for (j = 0; j < block_height; ++j)
331 for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
334 static void set_block_size(VP9_COMP *const cpi, MACROBLOCK *const x,
335 MACROBLOCKD *const xd, int mi_row, int mi_col,
337 if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
338 set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
339 xd->mi[0]->sb_type = bsize;
344 // This struct is used for computing variance in choose_partitioning(), where
345 // the max number of samples within a superblock is 16x16 (with 4x4 avg). Even
346 // in high bitdepth, uint32_t is enough for sum_square_error (2^12 * 2^12 * 16
348 uint32_t sum_square_error;
358 } partition_variance;
361 partition_variance part_variances;
366 partition_variance part_variances;
371 partition_variance part_variances;
376 partition_variance part_variances;
381 partition_variance part_variances;
386 partition_variance *part_variances;
396 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
398 node->part_variances = NULL;
401 v64x64 *vt = (v64x64 *)data;
402 node->part_variances = &vt->part_variances;
403 for (i = 0; i < 4; i++)
404 node->split[i] = &vt->split[i].part_variances.none;
408 v32x32 *vt = (v32x32 *)data;
409 node->part_variances = &vt->part_variances;
410 for (i = 0; i < 4; i++)
411 node->split[i] = &vt->split[i].part_variances.none;
415 v16x16 *vt = (v16x16 *)data;
416 node->part_variances = &vt->part_variances;
417 for (i = 0; i < 4; i++)
418 node->split[i] = &vt->split[i].part_variances.none;
422 v8x8 *vt = (v8x8 *)data;
423 node->part_variances = &vt->part_variances;
424 for (i = 0; i < 4; i++)
425 node->split[i] = &vt->split[i].part_variances.none;
429 v4x4 *vt = (v4x4 *)data;
430 assert(bsize == BLOCK_4X4);
431 node->part_variances = &vt->part_variances;
432 for (i = 0; i < 4; i++) node->split[i] = &vt->split[i];
438 // Set variance values given sum square error, sum error, count.
439 static void fill_variance(uint32_t s2, int32_t s, int c, var *v) {
440 v->sum_square_error = s2;
445 static void get_variance(var *v) {
447 (int)(256 * (v->sum_square_error -
448 (uint32_t)(((int64_t)v->sum_error * v->sum_error) >>
453 static void sum_2_variances(const var *a, const var *b, var *r) {
454 assert(a->log2_count == b->log2_count);
455 fill_variance(a->sum_square_error + b->sum_square_error,
456 a->sum_error + b->sum_error, a->log2_count + 1, r);
459 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
461 memset(&node, 0, sizeof(node));
462 tree_to_node(data, bsize, &node);
463 sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
464 sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
465 sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
466 sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
467 sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
468 &node.part_variances->none);
471 static int set_vt_partitioning(VP9_COMP *cpi, MACROBLOCK *const x,
472 MACROBLOCKD *const xd, void *data,
473 BLOCK_SIZE bsize, int mi_row, int mi_col,
474 int64_t threshold, BLOCK_SIZE bsize_min,
476 VP9_COMMON *const cm = &cpi->common;
478 const int block_width = num_8x8_blocks_wide_lookup[bsize];
479 const int block_height = num_8x8_blocks_high_lookup[bsize];
481 assert(block_height == block_width);
482 tree_to_node(data, bsize, &vt);
484 if (force_split == 1) return 0;
486 // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
487 // variance is below threshold, otherwise split will be selected.
488 // No check for vert/horiz split as too few samples for variance.
489 if (bsize == bsize_min) {
490 // Variance already computed to set the force_split.
491 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
492 if (mi_col + block_width / 2 < cm->mi_cols &&
493 mi_row + block_height / 2 < cm->mi_rows &&
494 vt.part_variances->none.variance < threshold) {
495 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
499 } else if (bsize > bsize_min) {
500 // Variance already computed to set the force_split.
501 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
502 // For key frame: take split for bsize above 32X32 or very high variance.
503 if (frame_is_intra_only(cm) &&
504 (bsize > BLOCK_32X32 ||
505 vt.part_variances->none.variance > (threshold << 4))) {
508 // If variance is low, take the bsize (no split).
509 if (mi_col + block_width / 2 < cm->mi_cols &&
510 mi_row + block_height / 2 < cm->mi_rows &&
511 vt.part_variances->none.variance < threshold) {
512 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
516 // Check vertical split.
517 if (mi_row + block_height / 2 < cm->mi_rows) {
518 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
519 get_variance(&vt.part_variances->vert[0]);
520 get_variance(&vt.part_variances->vert[1]);
521 if (vt.part_variances->vert[0].variance < threshold &&
522 vt.part_variances->vert[1].variance < threshold &&
523 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
524 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
525 set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
529 // Check horizontal split.
530 if (mi_col + block_width / 2 < cm->mi_cols) {
531 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
532 get_variance(&vt.part_variances->horz[0]);
533 get_variance(&vt.part_variances->horz[1]);
534 if (vt.part_variances->horz[0].variance < threshold &&
535 vt.part_variances->horz[1].variance < threshold &&
536 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
537 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
538 set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
548 static int64_t scale_part_thresh_sumdiff(int64_t threshold_base, int speed,
549 int width, int height,
552 if (width <= 640 && height <= 480)
553 return (5 * threshold_base) >> 2;
554 else if ((content_state == kLowSadLowSumdiff) ||
555 (content_state == kHighSadLowSumdiff) ||
556 (content_state == kLowVarHighSumdiff))
557 return (5 * threshold_base) >> 2;
558 } else if (speed == 7) {
559 if ((content_state == kLowSadLowSumdiff) ||
560 (content_state == kHighSadLowSumdiff) ||
561 (content_state == kLowVarHighSumdiff)) {
562 return (5 * threshold_base) >> 2;
565 return threshold_base;
568 // Set the variance split thresholds for following the block sizes:
569 // 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
570 // 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
571 // currently only used on key frame.
572 static void set_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q,
574 VP9_COMMON *const cm = &cpi->common;
575 const int is_key_frame = frame_is_intra_only(cm);
576 const int threshold_multiplier =
577 is_key_frame ? 20 : cpi->sf.variance_part_thresh_mult;
578 int64_t threshold_base =
579 (int64_t)(threshold_multiplier * cpi->y_dequant[q][1]);
582 thresholds[0] = threshold_base;
583 thresholds[1] = threshold_base >> 2;
584 thresholds[2] = threshold_base >> 2;
585 thresholds[3] = threshold_base << 2;
587 // Increase base variance threshold based on estimated noise level.
588 if (cpi->noise_estimate.enabled && cm->width >= 640 && cm->height >= 480) {
589 NOISE_LEVEL noise_level =
590 vp9_noise_estimate_extract_level(&cpi->noise_estimate);
591 if (noise_level == kHigh)
592 threshold_base = 3 * threshold_base;
593 else if (noise_level == kMedium)
594 threshold_base = threshold_base << 1;
595 else if (noise_level < kLow)
596 threshold_base = (7 * threshold_base) >> 3;
598 #if CONFIG_VP9_TEMPORAL_DENOISING
599 if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
600 cpi->oxcf.speed > 5 && cpi->denoiser.denoising_level >= kDenLow)
602 vp9_scale_part_thresh(threshold_base, cpi->denoiser.denoising_level,
603 content_state, cpi->svc.temporal_layer_id);
606 scale_part_thresh_sumdiff(threshold_base, cpi->oxcf.speed, cm->width,
607 cm->height, content_state);
609 // Increase base variance threshold based on content_state/sum_diff level.
610 threshold_base = scale_part_thresh_sumdiff(
611 threshold_base, cpi->oxcf.speed, cm->width, cm->height, content_state);
613 thresholds[0] = threshold_base;
614 thresholds[2] = threshold_base << cpi->oxcf.speed;
615 if (cm->width >= 1280 && cm->height >= 720 && cpi->oxcf.speed < 7)
616 thresholds[2] = thresholds[2] << 1;
617 if (cm->width <= 352 && cm->height <= 288) {
618 thresholds[0] = threshold_base >> 3;
619 thresholds[1] = threshold_base >> 1;
620 thresholds[2] = threshold_base << 3;
621 if (cpi->rc.avg_frame_qindex[INTER_FRAME] > 220)
622 thresholds[2] = thresholds[2] << 2;
623 else if (cpi->rc.avg_frame_qindex[INTER_FRAME] > 200)
624 thresholds[2] = thresholds[2] << 1;
625 } else if (cm->width < 1280 && cm->height < 720) {
626 thresholds[1] = (5 * threshold_base) >> 2;
627 } else if (cm->width < 1920 && cm->height < 1080) {
628 thresholds[1] = threshold_base << 1;
630 thresholds[1] = (5 * threshold_base) >> 1;
632 if (cpi->sf.disable_16x16part_nonkey) thresholds[2] = INT64_MAX;
636 void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q,
638 VP9_COMMON *const cm = &cpi->common;
639 SPEED_FEATURES *const sf = &cpi->sf;
640 const int is_key_frame = frame_is_intra_only(cm);
641 if (sf->partition_search_type != VAR_BASED_PARTITION &&
642 sf->partition_search_type != REFERENCE_PARTITION) {
645 set_vbp_thresholds(cpi, cpi->vbp_thresholds, q, content_state);
646 // The thresholds below are not changed locally.
648 cpi->vbp_threshold_sad = 0;
649 cpi->vbp_threshold_copy = 0;
650 cpi->vbp_bsize_min = BLOCK_8X8;
652 if (cm->width <= 352 && cm->height <= 288)
653 cpi->vbp_threshold_sad = 10;
655 cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000
656 ? (cpi->y_dequant[q][1] << 1)
658 cpi->vbp_bsize_min = BLOCK_16X16;
659 if (cm->width <= 352 && cm->height <= 288)
660 cpi->vbp_threshold_copy = 4000;
661 else if (cm->width <= 640 && cm->height <= 360)
662 cpi->vbp_threshold_copy = 8000;
664 cpi->vbp_threshold_copy = (cpi->y_dequant[q][1] << 3) > 8000
665 ? (cpi->y_dequant[q][1] << 3)
667 if (cpi->rc.high_source_sad ||
668 (cpi->use_svc && cpi->svc.high_source_sad_superframe)) {
669 cpi->vbp_threshold_sad = 0;
670 cpi->vbp_threshold_copy = 0;
673 cpi->vbp_threshold_minmax = 15 + (q >> 3);
677 // Compute the minmax over the 8x8 subblocks.
678 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
679 int dp, int x16_idx, int y16_idx,
680 #if CONFIG_VP9_HIGHBITDEPTH
683 int pixels_wide, int pixels_high) {
686 int minmax_min = 255;
687 // Loop over the 4 8x8 subblocks.
688 for (k = 0; k < 4; k++) {
689 int x8_idx = x16_idx + ((k & 1) << 3);
690 int y8_idx = y16_idx + ((k >> 1) << 3);
693 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
694 #if CONFIG_VP9_HIGHBITDEPTH
695 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
696 vpx_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
697 d + y8_idx * dp + x8_idx, dp, &min, &max);
699 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx,
703 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx, dp,
706 if ((max - min) > minmax_max) minmax_max = (max - min);
707 if ((max - min) < minmax_min) minmax_min = (max - min);
710 return (minmax_max - minmax_min);
713 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
714 int dp, int x8_idx, int y8_idx, v8x8 *vst,
715 #if CONFIG_VP9_HIGHBITDEPTH
718 int pixels_wide, int pixels_high,
721 for (k = 0; k < 4; k++) {
722 int x4_idx = x8_idx + ((k & 1) << 2);
723 int y4_idx = y8_idx + ((k >> 1) << 2);
724 unsigned int sse = 0;
726 if (x4_idx < pixels_wide && y4_idx < pixels_high) {
729 #if CONFIG_VP9_HIGHBITDEPTH
730 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
731 s_avg = vpx_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
733 d_avg = vpx_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
735 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
736 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
739 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
740 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
745 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
749 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
750 int dp, int x16_idx, int y16_idx, v16x16 *vst,
751 #if CONFIG_VP9_HIGHBITDEPTH
754 int pixels_wide, int pixels_high,
757 for (k = 0; k < 4; k++) {
758 int x8_idx = x16_idx + ((k & 1) << 3);
759 int y8_idx = y16_idx + ((k >> 1) << 3);
760 unsigned int sse = 0;
762 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
765 #if CONFIG_VP9_HIGHBITDEPTH
766 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
767 s_avg = vpx_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
769 d_avg = vpx_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
771 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
772 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
775 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
776 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
781 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
785 // Check if most of the superblock is skin content, and if so, force split to
786 // 32x32, and set x->sb_is_skin for use in mode selection.
787 static int skin_sb_split(VP9_COMP *cpi, const int low_res, int mi_row,
788 int mi_col, int *force_split) {
789 VP9_COMMON *const cm = &cpi->common;
790 #if CONFIG_VP9_HIGHBITDEPTH
791 if (cm->use_highbitdepth) return 0;
793 // Avoid checking superblocks on/near boundary and avoid low resolutions.
794 // Note superblock may still pick 64X64 if y_sad is very small
795 // (i.e., y_sad < cpi->vbp_threshold_sad) below. For now leave this as is.
796 if (!low_res && (mi_col >= 8 && mi_col + 8 < cm->mi_cols && mi_row >= 8 &&
797 mi_row + 8 < cm->mi_rows)) {
798 int num_16x16_skin = 0;
799 int num_16x16_nonskin = 0;
800 const int block_index = mi_row * cm->mi_cols + mi_col;
801 const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
802 const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
803 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
804 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
805 // Loop through the 16x16 sub-blocks.
807 for (i = 0; i < ymis; i += 2) {
808 for (j = 0; j < xmis; j += 2) {
809 int bl_index = block_index + i * cm->mi_cols + j;
810 int is_skin = cpi->skin_map[bl_index];
811 num_16x16_skin += is_skin;
812 num_16x16_nonskin += (1 - is_skin);
813 if (num_16x16_nonskin > 3) {
814 // Exit loop if at least 4 of the 16x16 blocks are not skin.
820 if (num_16x16_skin > 12) {
828 static void set_low_temp_var_flag(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
829 v64x64 *vt, int64_t thresholds[],
830 MV_REFERENCE_FRAME ref_frame_partition,
831 int mi_col, int mi_row) {
833 VP9_COMMON *const cm = &cpi->common;
834 const int mv_thr = cm->width > 640 ? 8 : 4;
835 // Check temporal variance for bsize >= 16x16, if LAST_FRAME was selected and
836 // int_pro mv is small. If the temporal variance is small set the flag
837 // variance_low for the block. The variance threshold can be adjusted, the
838 // higher the more aggressive.
839 if (ref_frame_partition == LAST_FRAME &&
840 (cpi->sf.short_circuit_low_temp_var == 1 ||
841 (xd->mi[0]->mv[0].as_mv.col < mv_thr &&
842 xd->mi[0]->mv[0].as_mv.col > -mv_thr &&
843 xd->mi[0]->mv[0].as_mv.row < mv_thr &&
844 xd->mi[0]->mv[0].as_mv.row > -mv_thr))) {
845 if (xd->mi[0]->sb_type == BLOCK_64X64) {
846 if ((vt->part_variances).none.variance < (thresholds[0] >> 1))
847 x->variance_low[0] = 1;
848 } else if (xd->mi[0]->sb_type == BLOCK_64X32) {
849 for (i = 0; i < 2; i++) {
850 if (vt->part_variances.horz[i].variance < (thresholds[0] >> 2))
851 x->variance_low[i + 1] = 1;
853 } else if (xd->mi[0]->sb_type == BLOCK_32X64) {
854 for (i = 0; i < 2; i++) {
855 if (vt->part_variances.vert[i].variance < (thresholds[0] >> 2))
856 x->variance_low[i + 3] = 1;
859 for (i = 0; i < 4; i++) {
860 const int idx[4][2] = { { 0, 0 }, { 0, 4 }, { 4, 0 }, { 4, 4 } };
862 cm->mi_stride * (mi_row + idx[i][0]) + mi_col + idx[i][1];
863 MODE_INFO **this_mi = cm->mi_grid_visible + idx_str;
865 if (cm->mi_cols <= mi_col + idx[i][1] ||
866 cm->mi_rows <= mi_row + idx[i][0])
869 if ((*this_mi)->sb_type == BLOCK_32X32) {
870 int64_t threshold_32x32 = (cpi->sf.short_circuit_low_temp_var == 1 ||
871 cpi->sf.short_circuit_low_temp_var == 3)
872 ? ((5 * thresholds[1]) >> 3)
873 : (thresholds[1] >> 1);
874 if (vt->split[i].part_variances.none.variance < threshold_32x32)
875 x->variance_low[i + 5] = 1;
876 } else if (cpi->sf.short_circuit_low_temp_var >= 2) {
877 // For 32x16 and 16x32 blocks, the flag is set on each 16x16 block
879 if ((*this_mi)->sb_type == BLOCK_16X16 ||
880 (*this_mi)->sb_type == BLOCK_32X16 ||
881 (*this_mi)->sb_type == BLOCK_16X32) {
882 for (j = 0; j < 4; j++) {
883 if (vt->split[i].split[j].part_variances.none.variance <
884 (thresholds[2] >> 8))
885 x->variance_low[(i << 2) + j + 9] = 1;
894 static void copy_partitioning_helper(VP9_COMP *cpi, MACROBLOCK *x,
895 MACROBLOCKD *xd, BLOCK_SIZE bsize,
896 int mi_row, int mi_col) {
897 VP9_COMMON *const cm = &cpi->common;
898 BLOCK_SIZE *prev_part = cpi->prev_partition;
899 int start_pos = mi_row * cm->mi_stride + mi_col;
901 const int bsl = b_width_log2_lookup[bsize];
902 const int bs = (1 << bsl) >> 2;
904 PARTITION_TYPE partition;
906 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
908 partition = partition_lookup[bsl][prev_part[start_pos]];
909 subsize = get_subsize(bsize, partition);
911 if (subsize < BLOCK_8X8) {
912 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
916 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
919 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
920 set_block_size(cpi, x, xd, mi_row + bs, mi_col, subsize);
923 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
924 set_block_size(cpi, x, xd, mi_row, mi_col + bs, subsize);
927 assert(partition == PARTITION_SPLIT);
928 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col);
929 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col);
930 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col + bs);
931 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col + bs);
937 static int copy_partitioning(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
938 int mi_row, int mi_col, int segment_id,
940 int svc_copy_allowed = 1;
941 int frames_since_key_thresh = 1;
943 // For SVC, don't allow copy if base spatial layer is key frame, or if
944 // frame is not a temporal enhancement layer frame.
945 int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
946 cpi->svc.number_temporal_layers);
947 const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
948 if (lc->is_key_frame || !cpi->svc.non_reference_frame) svc_copy_allowed = 0;
949 frames_since_key_thresh = cpi->svc.number_spatial_layers << 1;
951 if (cpi->rc.frames_since_key > frames_since_key_thresh && svc_copy_allowed &&
952 !cpi->resize_pending && segment_id == CR_SEGMENT_ID_BASE &&
953 cpi->prev_segment_id[sb_offset] == CR_SEGMENT_ID_BASE &&
954 cpi->copied_frame_cnt[sb_offset] < cpi->max_copied_frame) {
955 if (cpi->prev_partition != NULL) {
956 copy_partitioning_helper(cpi, x, xd, BLOCK_64X64, mi_row, mi_col);
957 cpi->copied_frame_cnt[sb_offset] += 1;
958 memcpy(x->variance_low, &(cpi->prev_variance_low[sb_offset * 25]),
959 sizeof(x->variance_low));
967 static int scale_partitioning_svc(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
968 BLOCK_SIZE bsize, int mi_row, int mi_col,
969 int mi_row_high, int mi_col_high) {
970 VP9_COMMON *const cm = &cpi->common;
971 SVC *const svc = &cpi->svc;
972 BLOCK_SIZE *prev_part = svc->prev_partition_svc;
973 // Variables with _high are for higher resolution.
975 int subsize_high = 0;
976 const int bsl_high = b_width_log2_lookup[bsize];
977 const int bs_high = (1 << bsl_high) >> 2;
978 const int has_rows = (mi_row_high + bs_high) < cm->mi_rows;
979 const int has_cols = (mi_col_high + bs_high) < cm->mi_cols;
981 const int row_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 1, 0,
984 const int col_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 2, 2,
988 BLOCK_SIZE bsize_low;
989 PARTITION_TYPE partition_high;
991 if (mi_row_high >= cm->mi_rows || mi_col_high >= cm->mi_cols) return 0;
992 if (mi_row >= svc->mi_rows[svc->spatial_layer_id - 1] ||
993 mi_col >= svc->mi_cols[svc->spatial_layer_id - 1])
996 // Find corresponding (mi_col/mi_row) block down-scaled by 2x2.
997 start_pos = mi_row * (svc->mi_stride[svc->spatial_layer_id - 1]) + mi_col;
998 bsize_low = prev_part[start_pos];
999 // The block size is too big for boundaries. Do variance based partitioning.
1000 if ((!has_rows || !has_cols) && bsize_low > BLOCK_16X16) return 1;
1002 // For reference frames: return 1 (do variance-based partitioning) if the
1003 // superblock is not low source sad and lower-resoln bsize is below 32x32.
1004 if (!cpi->svc.non_reference_frame && !x->skip_low_source_sad &&
1005 bsize_low < BLOCK_32X32)
1008 // Scale up block size by 2x2. Force 64x64 for size larger than 32x32.
1009 if (bsize_low < BLOCK_32X32) {
1010 bsize_high = bsize_low + 3;
1011 } else if (bsize_low >= BLOCK_32X32) {
1012 bsize_high = BLOCK_64X64;
1014 // Scale up blocks on boundary.
1015 if (!has_cols && has_rows) {
1016 bsize_high = bsize_low + row_boundary_block_scale_factor[bsize_low];
1017 } else if (has_cols && !has_rows) {
1018 bsize_high = bsize_low + col_boundary_block_scale_factor[bsize_low];
1019 } else if (!has_cols && !has_rows) {
1020 bsize_high = bsize_low;
1023 partition_high = partition_lookup[bsl_high][bsize_high];
1024 subsize_high = get_subsize(bsize, partition_high);
1026 if (subsize_high < BLOCK_8X8) {
1027 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1029 const int bsl = b_width_log2_lookup[bsize];
1030 const int bs = (1 << bsl) >> 2;
1031 switch (partition_high) {
1032 case PARTITION_NONE:
1033 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1035 case PARTITION_HORZ:
1036 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1037 if (subsize_high < BLOCK_64X64)
1038 set_block_size(cpi, x, xd, mi_row_high + bs_high, mi_col_high,
1041 case PARTITION_VERT:
1042 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1043 if (subsize_high < BLOCK_64X64)
1044 set_block_size(cpi, x, xd, mi_row_high, mi_col_high + bs_high,
1048 assert(partition_high == PARTITION_SPLIT);
1049 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row, mi_col,
1050 mi_row_high, mi_col_high))
1052 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1053 mi_col, mi_row_high + bs_high, mi_col_high))
1055 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row,
1056 mi_col + (bs >> 1), mi_row_high,
1057 mi_col_high + bs_high))
1059 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1060 mi_col + (bs >> 1), mi_row_high + bs_high,
1061 mi_col_high + bs_high))
1070 static void update_partition_svc(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
1072 VP9_COMMON *const cm = &cpi->common;
1073 BLOCK_SIZE *prev_part = cpi->svc.prev_partition_svc;
1074 int start_pos = mi_row * cm->mi_stride + mi_col;
1075 const int bsl = b_width_log2_lookup[bsize];
1076 const int bs = (1 << bsl) >> 2;
1078 PARTITION_TYPE partition;
1079 const MODE_INFO *mi = NULL;
1082 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1084 mi = cm->mi_grid_visible[start_pos];
1085 partition = partition_lookup[bsl][mi->sb_type];
1086 subsize = get_subsize(bsize, partition);
1087 if (subsize < BLOCK_8X8) {
1088 prev_part[start_pos] = bsize;
1090 switch (partition) {
1091 case PARTITION_NONE:
1092 prev_part[start_pos] = bsize;
1093 if (bsize == BLOCK_64X64) {
1094 for (xx = 0; xx < 8; xx += 4)
1095 for (yy = 0; yy < 8; yy += 4) {
1096 if ((mi_row + xx < cm->mi_rows) && (mi_col + yy < cm->mi_cols))
1097 prev_part[start_pos + xx * cm->mi_stride + yy] = bsize;
1101 case PARTITION_HORZ:
1102 prev_part[start_pos] = subsize;
1103 if (mi_row + bs < cm->mi_rows)
1104 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1106 case PARTITION_VERT:
1107 prev_part[start_pos] = subsize;
1108 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1111 assert(partition == PARTITION_SPLIT);
1112 update_partition_svc(cpi, subsize, mi_row, mi_col);
1113 update_partition_svc(cpi, subsize, mi_row + bs, mi_col);
1114 update_partition_svc(cpi, subsize, mi_row, mi_col + bs);
1115 update_partition_svc(cpi, subsize, mi_row + bs, mi_col + bs);
1121 static void update_prev_partition_helper(VP9_COMP *cpi, BLOCK_SIZE bsize,
1122 int mi_row, int mi_col) {
1123 VP9_COMMON *const cm = &cpi->common;
1124 BLOCK_SIZE *prev_part = cpi->prev_partition;
1125 int start_pos = mi_row * cm->mi_stride + mi_col;
1126 const int bsl = b_width_log2_lookup[bsize];
1127 const int bs = (1 << bsl) >> 2;
1129 PARTITION_TYPE partition;
1130 const MODE_INFO *mi = NULL;
1132 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1134 mi = cm->mi_grid_visible[start_pos];
1135 partition = partition_lookup[bsl][mi->sb_type];
1136 subsize = get_subsize(bsize, partition);
1137 if (subsize < BLOCK_8X8) {
1138 prev_part[start_pos] = bsize;
1140 switch (partition) {
1141 case PARTITION_NONE: prev_part[start_pos] = bsize; break;
1142 case PARTITION_HORZ:
1143 prev_part[start_pos] = subsize;
1144 if (mi_row + bs < cm->mi_rows)
1145 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1147 case PARTITION_VERT:
1148 prev_part[start_pos] = subsize;
1149 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1152 assert(partition == PARTITION_SPLIT);
1153 update_prev_partition_helper(cpi, subsize, mi_row, mi_col);
1154 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col);
1155 update_prev_partition_helper(cpi, subsize, mi_row, mi_col + bs);
1156 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col + bs);
1162 static void update_prev_partition(VP9_COMP *cpi, MACROBLOCK *x, int segment_id,
1163 int mi_row, int mi_col, int sb_offset) {
1164 update_prev_partition_helper(cpi, BLOCK_64X64, mi_row, mi_col);
1165 cpi->prev_segment_id[sb_offset] = segment_id;
1166 memcpy(&(cpi->prev_variance_low[sb_offset * 25]), x->variance_low,
1167 sizeof(x->variance_low));
1168 // Reset the counter for copy partitioning
1169 cpi->copied_frame_cnt[sb_offset] = 0;
1172 static void chroma_check(VP9_COMP *cpi, MACROBLOCK *x, int bsize,
1173 unsigned int y_sad, int is_key_frame,
1174 int scene_change_detected) {
1176 MACROBLOCKD *xd = &x->e_mbd;
1179 if (is_key_frame) return;
1181 // For speed > 8, avoid the chroma check if y_sad is above threshold.
1182 if (cpi->oxcf.speed > 8) {
1183 if (y_sad > cpi->vbp_thresholds[1] &&
1184 (!cpi->noise_estimate.enabled ||
1185 vp9_noise_estimate_extract_level(&cpi->noise_estimate) < kMedium))
1189 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN && scene_change_detected)
1192 for (i = 1; i <= 2; ++i) {
1193 unsigned int uv_sad = UINT_MAX;
1194 struct macroblock_plane *p = &x->plane[i];
1195 struct macroblockd_plane *pd = &xd->plane[i];
1196 const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
1198 if (bs != BLOCK_INVALID)
1199 uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride, pd->dst.buf,
1202 // TODO(marpan): Investigate if we should lower this threshold if
1203 // superblock is detected as skin.
1204 x->color_sensitivity[i - 1] = uv_sad > (y_sad >> shift);
1208 static uint64_t avg_source_sad(VP9_COMP *cpi, MACROBLOCK *x, int shift,
1210 unsigned int tmp_sse;
1212 unsigned int tmp_variance;
1213 const BLOCK_SIZE bsize = BLOCK_64X64;
1214 uint8_t *src_y = cpi->Source->y_buffer;
1215 int src_ystride = cpi->Source->y_stride;
1216 uint8_t *last_src_y = cpi->Last_Source->y_buffer;
1217 int last_src_ystride = cpi->Last_Source->y_stride;
1218 uint64_t avg_source_sad_threshold = 10000;
1219 uint64_t avg_source_sad_threshold2 = 12000;
1220 #if CONFIG_VP9_HIGHBITDEPTH
1221 if (cpi->common.use_highbitdepth) return 0;
1224 last_src_y += shift;
1226 cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y, last_src_ystride);
1227 tmp_variance = vpx_variance64x64(src_y, src_ystride, last_src_y,
1228 last_src_ystride, &tmp_sse);
1229 // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1230 if (tmp_sad < avg_source_sad_threshold)
1231 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kLowSadLowSumdiff
1232 : kLowSadHighSumdiff;
1234 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kHighSadLowSumdiff
1235 : kHighSadHighSumdiff;
1237 // Detect large lighting change.
1238 if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
1239 cpi->oxcf.rc_mode == VPX_CBR && tmp_variance < (tmp_sse >> 3) &&
1240 (tmp_sse - tmp_variance) > 10000)
1241 x->content_state_sb = kLowVarHighSumdiff;
1242 else if (tmp_sad > (avg_source_sad_threshold << 1))
1243 x->content_state_sb = kVeryHighSad;
1245 if (cpi->content_state_sb_fd != NULL) {
1246 if (tmp_sad < avg_source_sad_threshold2) {
1247 // Cap the increment to 255.
1248 if (cpi->content_state_sb_fd[sb_offset] < 255)
1249 cpi->content_state_sb_fd[sb_offset]++;
1251 cpi->content_state_sb_fd[sb_offset] = 0;
1254 if (tmp_sad == 0) x->zero_temp_sad_source = 1;
1258 // This function chooses partitioning based on the variance between source and
1259 // reconstructed last, where variance is computed for down-sampled inputs.
1260 static int choose_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1261 MACROBLOCK *x, int mi_row, int mi_col) {
1262 VP9_COMMON *const cm = &cpi->common;
1263 MACROBLOCKD *xd = &x->e_mbd;
1267 int force_split[21];
1269 int max_var_32x32 = 0;
1270 int min_var_32x32 = INT_MAX;
1273 int maxvar_16x16[4];
1274 int minvar_16x16[4];
1275 int64_t threshold_4x4avg;
1276 NOISE_LEVEL noise_level = kLow;
1277 int content_state = 0;
1282 int compute_minmax_variance = 1;
1283 unsigned int y_sad = UINT_MAX;
1284 BLOCK_SIZE bsize = BLOCK_64X64;
1285 // Ref frame used in partitioning.
1286 MV_REFERENCE_FRAME ref_frame_partition = LAST_FRAME;
1287 int pixels_wide = 64, pixels_high = 64;
1288 int64_t thresholds[4] = { cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
1289 cpi->vbp_thresholds[2], cpi->vbp_thresholds[3] };
1290 int scene_change_detected =
1291 cpi->rc.high_source_sad ||
1292 (cpi->use_svc && cpi->svc.high_source_sad_superframe);
1293 int force_64_split = scene_change_detected ||
1294 (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1295 cpi->compute_source_sad_onepass &&
1296 cpi->sf.use_source_sad && !x->zero_temp_sad_source);
1298 // For the variance computation under SVC mode, we treat the frame as key if
1299 // the reference (base layer frame) is key frame (i.e., is_key_frame == 1).
1301 (frame_is_intra_only(cm) ||
1302 (is_one_pass_cbr_svc(cpi) &&
1303 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame));
1304 // Always use 4x4 partition for key frame.
1305 const int use_4x4_partition = frame_is_intra_only(cm);
1306 const int low_res = (cm->width <= 352 && cm->height <= 288);
1307 int variance4x4downsample[16];
1309 int sb_offset = (cm->mi_stride >> 3) * (mi_row >> 3) + (mi_col >> 3);
1311 // For SVC: check if LAST frame is NULL or if the resolution of LAST is
1312 // different than the current frame resolution, and if so, treat this frame
1313 // as a key frame, for the purpose of the superblock partitioning.
1314 // LAST == NULL can happen in some cases where enhancement spatial layers are
1315 // enabled dyanmically in the stream and the only reference is the spatial
1316 // reference (GOLDEN).
1318 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, LAST_FRAME);
1319 if (ref == NULL || ref->y_crop_height != cm->height ||
1320 ref->y_crop_width != cm->width)
1324 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
1325 set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
1326 segment_id = xd->mi[0]->segment_id;
1328 if (cpi->oxcf.speed >= 8 || (cpi->use_svc && cpi->svc.non_reference_frame))
1329 compute_minmax_variance = 0;
1331 memset(x->variance_low, 0, sizeof(x->variance_low));
1333 if (cpi->sf.use_source_sad && !is_key_frame) {
1334 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1335 content_state = x->content_state_sb;
1336 x->skip_low_source_sad = (content_state == kLowSadLowSumdiff ||
1337 content_state == kLowSadHighSumdiff)
1340 x->lowvar_highsumdiff = (content_state == kLowVarHighSumdiff) ? 1 : 0;
1341 if (cpi->content_state_sb_fd != NULL)
1342 x->last_sb_high_content = cpi->content_state_sb_fd[sb_offset2];
1344 // For SVC on top spatial layer: use/scale the partition from
1345 // the lower spatial resolution if svc_use_lowres_part is enabled.
1346 if (cpi->sf.svc_use_lowres_part &&
1347 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1348 cpi->svc.prev_partition_svc != NULL && content_state != kVeryHighSad) {
1349 if (!scale_partitioning_svc(cpi, x, xd, BLOCK_64X64, mi_row >> 1,
1350 mi_col >> 1, mi_row, mi_col)) {
1351 if (cpi->sf.copy_partition_flag) {
1352 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1357 // If source_sad is low copy the partition without computing the y_sad.
1358 if (x->skip_low_source_sad && cpi->sf.copy_partition_flag &&
1360 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1361 x->sb_use_mv_part = 1;
1362 if (cpi->sf.svc_use_lowres_part &&
1363 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1364 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1369 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
1370 cyclic_refresh_segment_id_boosted(segment_id)) {
1371 int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
1372 set_vbp_thresholds(cpi, thresholds, q, content_state);
1374 set_vbp_thresholds(cpi, thresholds, cm->base_qindex, content_state);
1376 // Decrease 32x32 split threshold for screen on base layer, for scene
1377 // change/high motion frames.
1378 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1379 cpi->svc.spatial_layer_id == 0 && force_64_split)
1380 thresholds[1] = 3 * thresholds[1] >> 2;
1382 // For non keyframes, disable 4x4 average for low resolution when speed = 8
1383 threshold_4x4avg = (cpi->oxcf.speed < 8) ? thresholds[1] << 1 : INT64_MAX;
1385 if (xd->mb_to_right_edge < 0) pixels_wide += (xd->mb_to_right_edge >> 3);
1386 if (xd->mb_to_bottom_edge < 0) pixels_high += (xd->mb_to_bottom_edge >> 3);
1388 s = x->plane[0].src.buf;
1389 sp = x->plane[0].src.stride;
1391 // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
1392 // 5-20 for the 16x16 blocks.
1393 force_split[0] = force_64_split;
1395 if (!is_key_frame) {
1396 // In the case of spatial/temporal scalable coding, the assumption here is
1397 // that the temporal reference frame will always be of type LAST_FRAME.
1398 // TODO(marpan): If that assumption is broken, we need to revisit this code.
1399 MODE_INFO *mi = xd->mi[0];
1400 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1402 const YV12_BUFFER_CONFIG *yv12_g = NULL;
1403 unsigned int y_sad_g, y_sad_thr, y_sad_last;
1404 bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
1405 (mi_row + 4 < cm->mi_rows);
1407 assert(yv12 != NULL);
1409 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
1410 cpi->svc.use_gf_temporal_ref_current_layer) {
1411 // For now, GOLDEN will not be used for non-zero spatial layers, since
1412 // it may not be a temporal reference.
1413 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1416 // Only compute y_sad_g (sad for golden reference) for speed < 8.
1417 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
1418 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
1419 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1420 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1421 y_sad_g = cpi->fn_ptr[bsize].sdf(
1422 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1423 xd->plane[0].pre[0].stride);
1428 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
1429 cpi->rc.is_src_frame_alt_ref) {
1430 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
1431 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1432 &cm->frame_refs[ALTREF_FRAME - 1].sf);
1433 mi->ref_frame[0] = ALTREF_FRAME;
1436 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1437 &cm->frame_refs[LAST_FRAME - 1].sf);
1438 mi->ref_frame[0] = LAST_FRAME;
1440 mi->ref_frame[1] = NONE;
1441 mi->sb_type = BLOCK_64X64;
1442 mi->mv[0].as_int = 0;
1443 mi->interp_filter = BILINEAR;
1445 if (cpi->oxcf.speed >= 8 && !low_res &&
1446 x->content_state_sb != kVeryHighSad) {
1447 y_sad = cpi->fn_ptr[bsize].sdf(
1448 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1449 xd->plane[0].pre[0].stride);
1451 const MV dummy_mv = { 0, 0 };
1452 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
1454 x->sb_use_mv_part = 1;
1455 x->sb_mvcol_part = mi->mv[0].as_mv.col;
1456 x->sb_mvrow_part = mi->mv[0].as_mv.row;
1457 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1458 cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
1459 cpi->svc.high_num_blocks_with_motion && !x->zero_temp_sad_source &&
1460 cm->width > 640 && cm->height > 480) {
1461 // Disable split below 16x16 block size when scroll motion (horz or
1462 // vert) is detected.
1463 // TODO(marpan/jianj): Improve this condition: issue is that search
1464 // range is hard-coded/limited in vp9_int_pro_motion_estimation() so
1465 // scroll motion may not be detected here.
1466 if (((abs(x->sb_mvrow_part) >= 48 && abs(x->sb_mvcol_part) <= 8) ||
1467 (abs(x->sb_mvcol_part) >= 48 && abs(x->sb_mvrow_part) <= 8)) &&
1469 compute_minmax_variance = 0;
1470 thresholds[2] = INT64_MAX;
1476 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
1477 // are close if short_circuit_low_temp_var is on.
1478 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
1479 if (y_sad_g < y_sad_thr) {
1480 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1481 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1482 mi->ref_frame[0] = GOLDEN_FRAME;
1483 mi->mv[0].as_int = 0;
1485 ref_frame_partition = GOLDEN_FRAME;
1487 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
1488 ref_frame_partition = LAST_FRAME;
1491 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
1492 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
1494 if (cpi->use_skin_detection)
1495 x->sb_is_skin = skin_sb_split(cpi, low_res, mi_row, mi_col, force_split);
1497 d = xd->plane[0].dst.buf;
1498 dp = xd->plane[0].dst.stride;
1500 // If the y_sad is very small, take 64x64 as partition and exit.
1501 // Don't check on boosted segment for now, as 64x64 is suppressed there.
1502 if (segment_id == CR_SEGMENT_ID_BASE && y_sad < cpi->vbp_threshold_sad) {
1503 const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
1504 const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
1505 if (mi_col + block_width / 2 < cm->mi_cols &&
1506 mi_row + block_height / 2 < cm->mi_rows) {
1507 set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
1508 x->variance_low[0] = 1;
1509 chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1510 if (cpi->sf.svc_use_lowres_part &&
1511 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1512 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1513 if (cpi->sf.copy_partition_flag) {
1514 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1520 // If the y_sad is small enough, copy the partition of the superblock in the
1521 // last frame to current frame only if the last frame is not a keyframe.
1522 // Stop the copy every cpi->max_copied_frame to refresh the partition.
1523 // TODO(jianj) : tune the threshold.
1524 if (cpi->sf.copy_partition_flag && y_sad_last < cpi->vbp_threshold_copy &&
1525 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1526 chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1527 if (cpi->sf.svc_use_lowres_part &&
1528 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1529 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1535 #if CONFIG_VP9_HIGHBITDEPTH
1536 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1538 case 10: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10); break;
1539 case 12: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12); break;
1541 default: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8); break;
1544 #endif // CONFIG_VP9_HIGHBITDEPTH
1547 if (low_res && threshold_4x4avg < INT64_MAX)
1548 CHECK_MEM_ERROR(cm, vt2, vpx_calloc(16, sizeof(*vt2)));
1549 // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
1551 for (i = 0; i < 4; i++) {
1552 const int x32_idx = ((i & 1) << 5);
1553 const int y32_idx = ((i >> 1) << 5);
1554 const int i2 = i << 2;
1555 force_split[i + 1] = 0;
1557 maxvar_16x16[i] = 0;
1558 minvar_16x16[i] = INT_MAX;
1559 for (j = 0; j < 4; j++) {
1560 const int x16_idx = x32_idx + ((j & 1) << 4);
1561 const int y16_idx = y32_idx + ((j >> 1) << 4);
1562 const int split_index = 5 + i2 + j;
1563 v16x16 *vst = &vt.split[i].split[j];
1564 force_split[split_index] = 0;
1565 variance4x4downsample[i2 + j] = 0;
1566 if (!is_key_frame) {
1567 fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
1568 #if CONFIG_VP9_HIGHBITDEPTH
1571 pixels_wide, pixels_high, is_key_frame);
1572 fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1573 get_variance(&vt.split[i].split[j].part_variances.none);
1574 avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance;
1575 if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i])
1576 minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1577 if (vt.split[i].split[j].part_variances.none.variance > maxvar_16x16[i])
1578 maxvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1579 if (vt.split[i].split[j].part_variances.none.variance > thresholds[2]) {
1580 // 16X16 variance is above threshold for split, so force split to 8x8
1581 // for this 16x16 block (this also forces splits for upper levels).
1582 force_split[split_index] = 1;
1583 force_split[i + 1] = 1;
1585 } else if (compute_minmax_variance &&
1586 vt.split[i].split[j].part_variances.none.variance >
1588 !cyclic_refresh_segment_id_boosted(segment_id)) {
1589 // We have some nominal amount of 16x16 variance (based on average),
1590 // compute the minmax over the 8x8 sub-blocks, and if above threshold,
1591 // force split to 8x8 block for this 16x16 block.
1592 int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
1593 #if CONFIG_VP9_HIGHBITDEPTH
1596 pixels_wide, pixels_high);
1597 int thresh_minmax = (int)cpi->vbp_threshold_minmax;
1598 if (x->content_state_sb == kVeryHighSad)
1599 thresh_minmax = thresh_minmax << 1;
1600 if (minmax > thresh_minmax) {
1601 force_split[split_index] = 1;
1602 force_split[i + 1] = 1;
1608 (low_res && vt.split[i].split[j].part_variances.none.variance >
1609 threshold_4x4avg)) {
1610 force_split[split_index] = 0;
1611 // Go down to 4x4 down-sampling for variance.
1612 variance4x4downsample[i2 + j] = 1;
1613 for (k = 0; k < 4; k++) {
1614 int x8_idx = x16_idx + ((k & 1) << 3);
1615 int y8_idx = y16_idx + ((k >> 1) << 3);
1616 v8x8 *vst2 = is_key_frame ? &vst->split[k] : &vt2[i2 + j].split[k];
1617 fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
1618 #if CONFIG_VP9_HIGHBITDEPTH
1621 pixels_wide, pixels_high, is_key_frame);
1626 if (cpi->noise_estimate.enabled)
1627 noise_level = vp9_noise_estimate_extract_level(&cpi->noise_estimate);
1628 // Fill the rest of the variance tree by summing split partition values.
1630 for (i = 0; i < 4; i++) {
1631 const int i2 = i << 2;
1632 for (j = 0; j < 4; j++) {
1633 if (variance4x4downsample[i2 + j] == 1) {
1634 v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] : &vt.split[i].split[j];
1635 for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
1636 fill_variance_tree(vtemp, BLOCK_16X16);
1637 // If variance of this 16x16 block is above the threshold, force block
1638 // to split. This also forces a split on the upper levels.
1639 get_variance(&vtemp->part_variances.none);
1640 if (vtemp->part_variances.none.variance > thresholds[2]) {
1641 force_split[5 + i2 + j] = 1;
1642 force_split[i + 1] = 1;
1647 fill_variance_tree(&vt.split[i], BLOCK_32X32);
1648 // If variance of this 32x32 block is above the threshold, or if its above
1649 // (some threshold of) the average variance over the sub-16x16 blocks, then
1650 // force this block to split. This also forces a split on the upper
1652 if (!force_split[i + 1]) {
1653 get_variance(&vt.split[i].part_variances.none);
1654 var_32x32 = vt.split[i].part_variances.none.variance;
1655 max_var_32x32 = VPXMAX(var_32x32, max_var_32x32);
1656 min_var_32x32 = VPXMIN(var_32x32, min_var_32x32);
1657 if (vt.split[i].part_variances.none.variance > thresholds[1] ||
1659 vt.split[i].part_variances.none.variance > (thresholds[1] >> 1) &&
1660 vt.split[i].part_variances.none.variance > (avg_16x16[i] >> 1))) {
1661 force_split[i + 1] = 1;
1663 } else if (!is_key_frame && noise_level < kLow && cm->height <= 360 &&
1664 (maxvar_16x16[i] - minvar_16x16[i]) > (thresholds[1] >> 1) &&
1665 maxvar_16x16[i] > thresholds[1]) {
1666 force_split[i + 1] = 1;
1669 avg_32x32 += var_32x32;
1672 if (!force_split[0]) {
1673 fill_variance_tree(&vt, BLOCK_64X64);
1674 get_variance(&vt.part_variances.none);
1675 // If variance of this 64x64 block is above (some threshold of) the average
1676 // variance over the sub-32x32 blocks, then force this block to split.
1677 // Only checking this for noise level >= medium for now.
1678 if (!is_key_frame && noise_level >= kMedium &&
1679 vt.part_variances.none.variance > (9 * avg_32x32) >> 5)
1681 // Else if the maximum 32x32 variance minus the miniumum 32x32 variance in
1682 // a 64x64 block is greater than threshold and the maximum 32x32 variance is
1683 // above a miniumum threshold, then force the split of a 64x64 block
1684 // Only check this for low noise.
1685 else if (!is_key_frame && noise_level < kMedium &&
1686 (max_var_32x32 - min_var_32x32) > 3 * (thresholds[0] >> 3) &&
1687 max_var_32x32 > thresholds[0] >> 1)
1691 // Now go through the entire structure, splitting every block size until
1692 // we get to one that's got a variance lower than our threshold.
1693 if (mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
1694 !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
1695 thresholds[0], BLOCK_16X16, force_split[0])) {
1696 for (i = 0; i < 4; ++i) {
1697 const int x32_idx = ((i & 1) << 2);
1698 const int y32_idx = ((i >> 1) << 2);
1699 const int i2 = i << 2;
1700 if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
1701 (mi_row + y32_idx), (mi_col + x32_idx),
1702 thresholds[1], BLOCK_16X16,
1703 force_split[i + 1])) {
1704 for (j = 0; j < 4; ++j) {
1705 const int x16_idx = ((j & 1) << 1);
1706 const int y16_idx = ((j >> 1) << 1);
1707 // For inter frames: if variance4x4downsample[] == 1 for this 16x16
1708 // block, then the variance is based on 4x4 down-sampling, so use vt2
1709 // in set_vt_partioning(), otherwise use vt.
1710 v16x16 *vtemp = (!is_key_frame && variance4x4downsample[i2 + j] == 1)
1712 : &vt.split[i].split[j];
1713 if (!set_vt_partitioning(
1714 cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx,
1715 mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min,
1716 force_split[5 + i2 + j])) {
1717 for (k = 0; k < 4; ++k) {
1718 const int x8_idx = (k & 1);
1719 const int y8_idx = (k >> 1);
1720 if (use_4x4_partition) {
1721 if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
1723 mi_row + y32_idx + y16_idx + y8_idx,
1724 mi_col + x32_idx + x16_idx + x8_idx,
1725 thresholds[3], BLOCK_8X8, 0)) {
1727 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1728 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_4X4);
1732 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1733 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_8X8);
1742 if (!frame_is_intra_only(cm) && cpi->sf.copy_partition_flag) {
1743 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1746 if (!frame_is_intra_only(cm) && cpi->sf.svc_use_lowres_part &&
1747 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1748 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1750 if (cpi->sf.short_circuit_low_temp_var) {
1751 set_low_temp_var_flag(cpi, x, xd, &vt, thresholds, ref_frame_partition,
1755 chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1756 if (vt2) vpx_free(vt2);
1760 #if !CONFIG_REALTIME_ONLY
1761 static void update_state(VP9_COMP *cpi, ThreadData *td, PICK_MODE_CONTEXT *ctx,
1762 int mi_row, int mi_col, BLOCK_SIZE bsize,
1763 int output_enabled) {
1765 VP9_COMMON *const cm = &cpi->common;
1766 RD_COUNTS *const rdc = &td->rd_counts;
1767 MACROBLOCK *const x = &td->mb;
1768 MACROBLOCKD *const xd = &x->e_mbd;
1769 struct macroblock_plane *const p = x->plane;
1770 struct macroblockd_plane *const pd = xd->plane;
1771 MODE_INFO *mi = &ctx->mic;
1772 MODE_INFO *const xdmi = xd->mi[0];
1773 MODE_INFO *mi_addr = xd->mi[0];
1774 const struct segmentation *const seg = &cm->seg;
1775 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
1776 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
1777 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1778 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1779 MV_REF *const frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1782 const int mis = cm->mi_stride;
1783 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
1784 const int mi_height = num_8x8_blocks_high_lookup[bsize];
1787 assert(mi->sb_type == bsize);
1790 *x->mbmi_ext = ctx->mbmi_ext;
1792 // If segmentation in use
1794 // For in frame complexity AQ copy the segment id from the segment map.
1795 if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1796 const uint8_t *const map =
1797 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1798 mi_addr->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1800 // Else for cyclic refresh mode update the segment map, set the segment id
1801 // and then update the quantizer.
1802 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
1803 cpi->cyclic_refresh->content_mode) {
1804 vp9_cyclic_refresh_update_segment(cpi, xd->mi[0], mi_row, mi_col, bsize,
1805 ctx->rate, ctx->dist, x->skip, p);
1809 max_plane = is_inter_block(xdmi) ? MAX_MB_PLANE : 1;
1810 for (i = 0; i < max_plane; ++i) {
1811 p[i].coeff = ctx->coeff_pbuf[i][1];
1812 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1813 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1814 p[i].eobs = ctx->eobs_pbuf[i][1];
1817 for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1818 p[i].coeff = ctx->coeff_pbuf[i][2];
1819 p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1820 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1821 p[i].eobs = ctx->eobs_pbuf[i][2];
1824 // Restore the coding context of the MB to that that was in place
1825 // when the mode was picked for it
1826 for (y = 0; y < mi_height; y++)
1827 for (x_idx = 0; x_idx < mi_width; x_idx++)
1828 if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx &&
1829 (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1830 xd->mi[x_idx + y * mis] = mi_addr;
1833 if (cpi->oxcf.aq_mode != NO_AQ) vp9_init_plane_quantizers(cpi, x);
1835 if (is_inter_block(xdmi) && xdmi->sb_type < BLOCK_8X8) {
1836 xdmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1837 xdmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1840 x->skip = ctx->skip;
1841 memcpy(x->zcoeff_blk[xdmi->tx_size], ctx->zcoeff_blk,
1842 sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1844 if (!output_enabled) return;
1846 #if CONFIG_INTERNAL_STATS
1847 if (frame_is_intra_only(cm)) {
1848 static const int kf_mode_index[] = {
1849 THR_DC /*DC_PRED*/, THR_V_PRED /*V_PRED*/,
1850 THR_H_PRED /*H_PRED*/, THR_D45_PRED /*D45_PRED*/,
1851 THR_D135_PRED /*D135_PRED*/, THR_D117_PRED /*D117_PRED*/,
1852 THR_D153_PRED /*D153_PRED*/, THR_D207_PRED /*D207_PRED*/,
1853 THR_D63_PRED /*D63_PRED*/, THR_TM /*TM_PRED*/,
1855 ++cpi->mode_chosen_counts[kf_mode_index[xdmi->mode]];
1857 // Note how often each mode chosen as best
1858 ++cpi->mode_chosen_counts[ctx->best_mode_index];
1861 if (!frame_is_intra_only(cm)) {
1862 if (is_inter_block(xdmi)) {
1863 vp9_update_mv_count(td);
1865 if (cm->interp_filter == SWITCHABLE) {
1866 const int ctx = get_pred_context_switchable_interp(xd);
1867 ++td->counts->switchable_interp[ctx][xdmi->interp_filter];
1871 rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1872 rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1873 rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1875 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1876 rdc->filter_diff[i] += ctx->best_filter_diff[i];
1879 for (h = 0; h < y_mis; ++h) {
1880 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1881 for (w = 0; w < x_mis; ++w) {
1882 MV_REF *const mv = frame_mv + w;
1883 mv->ref_frame[0] = mi->ref_frame[0];
1884 mv->ref_frame[1] = mi->ref_frame[1];
1885 mv->mv[0].as_int = mi->mv[0].as_int;
1886 mv->mv[1].as_int = mi->mv[1].as_int;
1890 #endif // !CONFIG_REALTIME_ONLY
1892 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1893 int mi_row, int mi_col) {
1894 uint8_t *const buffers[3] = { src->y_buffer, src->u_buffer, src->v_buffer };
1895 const int strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
1898 // Set current frame pointer.
1899 x->e_mbd.cur_buf = src;
1901 for (i = 0; i < MAX_MB_PLANE; i++)
1902 setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1903 NULL, x->e_mbd.plane[i].subsampling_x,
1904 x->e_mbd.plane[i].subsampling_y);
1907 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1908 RD_COST *rd_cost, BLOCK_SIZE bsize) {
1909 MACROBLOCKD *const xd = &x->e_mbd;
1910 MODE_INFO *const mi = xd->mi[0];
1911 INTERP_FILTER filter_ref;
1913 filter_ref = get_pred_context_switchable_interp(xd);
1914 if (filter_ref == SWITCHABLE_FILTERS) filter_ref = EIGHTTAP;
1916 mi->sb_type = bsize;
1919 VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[tx_mode]);
1921 mi->uv_mode = DC_PRED;
1922 mi->ref_frame[0] = LAST_FRAME;
1923 mi->ref_frame[1] = NONE;
1924 mi->mv[0].as_int = 0;
1925 mi->interp_filter = filter_ref;
1927 xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1930 vp9_rd_cost_init(rd_cost);
1933 #if !CONFIG_REALTIME_ONLY
1934 static void set_segment_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
1935 int mi_row, int mi_col, BLOCK_SIZE bsize,
1937 VP9_COMMON *const cm = &cpi->common;
1938 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1939 const uint8_t *const map =
1940 cm->seg.update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1942 vp9_init_plane_quantizers(cpi, x);
1943 vpx_clear_system_state();
1945 if (aq_mode == NO_AQ || aq_mode == PSNR_AQ) {
1946 if (cpi->sf.enable_tpl_model) x->rdmult = x->cb_rdmult;
1947 } else if (aq_mode == PERCEPTUAL_AQ) {
1948 x->rdmult = x->cb_rdmult;
1949 } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1950 // If segment is boosted, use rdmult for that segment.
1951 if (cyclic_refresh_segment_id_boosted(
1952 get_segment_id(cm, map, bsize, mi_row, mi_col)))
1953 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1955 x->rdmult = vp9_compute_rd_mult(cpi, cm->base_qindex + cm->y_dc_delta_q);
1958 if (oxcf->tuning == VP8_TUNE_SSIM) {
1959 set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
1963 static void rd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
1964 MACROBLOCK *const x, int mi_row, int mi_col,
1965 RD_COST *rd_cost, BLOCK_SIZE bsize,
1966 PICK_MODE_CONTEXT *ctx, int rate_in_best_rd,
1967 int64_t dist_in_best_rd) {
1968 VP9_COMMON *const cm = &cpi->common;
1969 TileInfo *const tile_info = &tile_data->tile_info;
1970 MACROBLOCKD *const xd = &x->e_mbd;
1972 struct macroblock_plane *const p = x->plane;
1973 struct macroblockd_plane *const pd = xd->plane;
1974 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1976 int64_t best_rd = INT64_MAX;
1978 vpx_clear_system_state();
1980 // Use the lower precision, but faster, 32x32 fdct for mode selection.
1981 x->use_lp32x32fdct = 1;
1983 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1985 mi->sb_type = bsize;
1987 for (i = 0; i < MAX_MB_PLANE; ++i) {
1988 p[i].coeff = ctx->coeff_pbuf[i][0];
1989 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1990 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1991 p[i].eobs = ctx->eobs_pbuf[i][0];
1995 ctx->pred_pixel_ready = 0;
1998 // Set to zero to make sure we do not use the previous encoded frame stats
2001 #if CONFIG_VP9_HIGHBITDEPTH
2002 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2003 x->source_variance = vp9_high_get_sby_perpixel_variance(
2004 cpi, &x->plane[0].src, bsize, xd->bd);
2006 x->source_variance =
2007 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2010 x->source_variance =
2011 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2012 #endif // CONFIG_VP9_HIGHBITDEPTH
2014 // Save rdmult before it might be changed, so it can be restored later.
2015 orig_rdmult = x->rdmult;
2017 if ((cpi->sf.tx_domain_thresh > 0.0) || (cpi->sf.quant_opt_thresh > 0.0)) {
2018 double logvar = vp9_log_block_var(cpi, x, bsize);
2019 // Check block complexity as part of descision on using pixel or transform
2020 // domain distortion in rd tests.
2021 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion &&
2022 (logvar >= cpi->sf.tx_domain_thresh);
2024 // Check block complexity as part of descision on using quantized
2025 // coefficient optimisation inside the rd loop.
2026 x->block_qcoeff_opt =
2027 cpi->sf.allow_quant_coeff_opt && (logvar <= cpi->sf.quant_opt_thresh);
2029 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion;
2030 x->block_qcoeff_opt = cpi->sf.allow_quant_coeff_opt;
2033 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
2034 set_segment_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode);
2035 if (rate_in_best_rd < INT_MAX && dist_in_best_rd < INT64_MAX) {
2036 best_rd = vp9_calculate_rd_cost(x->rdmult, x->rddiv, rate_in_best_rd,
2040 // Find best coding mode & reconstruct the MB so it is available
2041 // as a predictor for MBs that follow in the SB
2042 if (frame_is_intra_only(cm)) {
2043 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
2045 if (bsize >= BLOCK_8X8) {
2046 if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
2047 vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
2050 vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2051 bsize, ctx, best_rd);
2053 vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2054 bsize, ctx, best_rd);
2058 // Examine the resulting rate and for AQ mode 2 make a segment choice.
2059 if ((rd_cost->rate != INT_MAX) && (aq_mode == COMPLEXITY_AQ) &&
2060 (bsize >= BLOCK_16X16) &&
2061 (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
2062 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
2063 vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
2066 // TODO(jingning) The rate-distortion optimization flow needs to be
2067 // refactored to provide proper exit/return handle.
2068 if (rd_cost->rate == INT_MAX || rd_cost->dist == INT64_MAX)
2069 rd_cost->rdcost = INT64_MAX;
2071 rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2073 x->rdmult = orig_rdmult;
2075 ctx->rate = rd_cost->rate;
2076 ctx->dist = rd_cost->dist;
2078 #endif // !CONFIG_REALTIME_ONLY
2080 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
2081 const MACROBLOCK *x = &td->mb;
2082 const MACROBLOCKD *const xd = &x->e_mbd;
2083 const MODE_INFO *const mi = xd->mi[0];
2084 const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2085 const BLOCK_SIZE bsize = mi->sb_type;
2087 if (!frame_is_intra_only(cm)) {
2088 FRAME_COUNTS *const counts = td->counts;
2089 const int inter_block = is_inter_block(mi);
2090 const int seg_ref_active =
2091 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_REF_FRAME);
2092 if (!seg_ref_active) {
2093 counts->intra_inter[get_intra_inter_context(xd)][inter_block]++;
2094 // If the segment reference feature is enabled we have only a single
2095 // reference frame allowed for the segment so exclude it from
2096 // the reference frame counts used to work out probabilities.
2098 const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
2099 if (cm->reference_mode == REFERENCE_MODE_SELECT)
2100 counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
2101 [has_second_ref(mi)]++;
2103 if (has_second_ref(mi)) {
2104 const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
2105 const int ctx = vp9_get_pred_context_comp_ref_p(cm, xd);
2106 const int bit = mi->ref_frame[!idx] == cm->comp_var_ref[1];
2107 counts->comp_ref[ctx][bit]++;
2109 counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
2110 [ref0 != LAST_FRAME]++;
2111 if (ref0 != LAST_FRAME)
2112 counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
2113 [ref0 != GOLDEN_FRAME]++;
2118 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP)) {
2119 const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
2120 if (bsize >= BLOCK_8X8) {
2121 const PREDICTION_MODE mode = mi->mode;
2122 ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
2124 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2125 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2127 for (idy = 0; idy < 2; idy += num_4x4_h) {
2128 for (idx = 0; idx < 2; idx += num_4x4_w) {
2129 const int j = idy * 2 + idx;
2130 const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
2131 ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
2139 #if !CONFIG_REALTIME_ONLY
2140 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
2141 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2142 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2143 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2145 MACROBLOCKD *const xd = &x->e_mbd;
2147 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2148 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2149 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2150 int mi_height = num_8x8_blocks_high_lookup[bsize];
2151 for (p = 0; p < MAX_MB_PLANE; p++) {
2152 memcpy(xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
2153 a + num_4x4_blocks_wide * p,
2154 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2155 xd->plane[p].subsampling_x);
2156 memcpy(xd->left_context[p] +
2157 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2158 l + num_4x4_blocks_high * p,
2159 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2160 xd->plane[p].subsampling_y);
2162 memcpy(xd->above_seg_context + mi_col, sa,
2163 sizeof(*xd->above_seg_context) * mi_width);
2164 memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
2165 sizeof(xd->left_seg_context[0]) * mi_height);
2168 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
2169 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2170 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2171 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2173 const MACROBLOCKD *const xd = &x->e_mbd;
2175 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2176 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2177 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2178 int mi_height = num_8x8_blocks_high_lookup[bsize];
2180 // buffer the above/left context information of the block in search.
2181 for (p = 0; p < MAX_MB_PLANE; ++p) {
2182 memcpy(a + num_4x4_blocks_wide * p,
2183 xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
2184 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2185 xd->plane[p].subsampling_x);
2186 memcpy(l + num_4x4_blocks_high * p,
2187 xd->left_context[p] +
2188 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2189 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2190 xd->plane[p].subsampling_y);
2192 memcpy(sa, xd->above_seg_context + mi_col,
2193 sizeof(*xd->above_seg_context) * mi_width);
2194 memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
2195 sizeof(xd->left_seg_context[0]) * mi_height);
2198 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile, ThreadData *td,
2199 TOKENEXTRA **tp, int mi_row, int mi_col,
2200 int output_enabled, BLOCK_SIZE bsize,
2201 PICK_MODE_CONTEXT *ctx) {
2202 MACROBLOCK *const x = &td->mb;
2203 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2205 if (cpi->sf.enable_tpl_model &&
2206 (cpi->oxcf.aq_mode == NO_AQ || cpi->oxcf.aq_mode == PERCEPTUAL_AQ)) {
2207 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2208 x->rdmult = x->cb_rdmult;
2209 if (oxcf->tuning == VP8_TUNE_SSIM) {
2210 set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
2214 update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
2215 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2217 if (output_enabled) {
2218 update_stats(&cpi->common, td);
2220 (*tp)->token = EOSB_TOKEN;
2225 static void encode_sb(VP9_COMP *cpi, ThreadData *td, const TileInfo *const tile,
2226 TOKENEXTRA **tp, int mi_row, int mi_col,
2227 int output_enabled, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2228 VP9_COMMON *const cm = &cpi->common;
2229 MACROBLOCK *const x = &td->mb;
2230 MACROBLOCKD *const xd = &x->e_mbd;
2232 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2234 PARTITION_TYPE partition;
2235 BLOCK_SIZE subsize = bsize;
2237 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2239 if (bsize >= BLOCK_8X8) {
2240 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2241 subsize = get_subsize(bsize, pc_tree->partitioning);
2244 subsize = BLOCK_4X4;
2247 partition = partition_lookup[bsl][subsize];
2248 if (output_enabled && bsize != BLOCK_4X4)
2249 td->counts->partition[ctx][partition]++;
2251 switch (partition) {
2252 case PARTITION_NONE:
2253 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2256 case PARTITION_VERT:
2257 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2258 &pc_tree->vertical[0]);
2259 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2260 encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
2261 subsize, &pc_tree->vertical[1]);
2264 case PARTITION_HORZ:
2265 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2266 &pc_tree->horizontal[0]);
2267 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2268 encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
2269 subsize, &pc_tree->horizontal[1]);
2273 assert(partition == PARTITION_SPLIT);
2274 if (bsize == BLOCK_8X8) {
2275 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2276 pc_tree->leaf_split[0]);
2278 encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2280 encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2281 subsize, pc_tree->split[1]);
2282 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2283 subsize, pc_tree->split[2]);
2284 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
2285 subsize, pc_tree->split[3]);
2290 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2291 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2293 #endif // !CONFIG_REALTIME_ONLY
2295 // Check to see if the given partition size is allowed for a specified number
2296 // of 8x8 block rows and columns remaining in the image.
2297 // If not then return the largest allowed partition size
2298 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
2299 int cols_left, int *bh, int *bw) {
2300 if (rows_left <= 0 || cols_left <= 0) {
2301 return VPXMIN(bsize, BLOCK_8X8);
2303 for (; bsize > 0; bsize -= 3) {
2304 *bh = num_8x8_blocks_high_lookup[bsize];
2305 *bw = num_8x8_blocks_wide_lookup[bsize];
2306 if ((*bh <= rows_left) && (*bw <= cols_left)) {
2314 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis, int bh_in,
2315 int bw_in, int row8x8_remaining,
2316 int col8x8_remaining, BLOCK_SIZE bsize,
2317 MODE_INFO **mi_8x8) {
2320 for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
2322 for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
2323 const int index = r * mis + c;
2324 mi_8x8[index] = mi + index;
2325 mi_8x8[index]->sb_type = find_partition_size(
2326 bsize, row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
2331 // This function attempts to set all mode info entries in a given SB64
2332 // to the same block partition size.
2333 // However, at the bottom and right borders of the image the requested size
2334 // may not be allowed in which case this code attempts to choose the largest
2335 // allowable partition.
2336 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
2337 MODE_INFO **mi_8x8, int mi_row, int mi_col,
2339 VP9_COMMON *const cm = &cpi->common;
2340 const int mis = cm->mi_stride;
2341 const int row8x8_remaining = tile->mi_row_end - mi_row;
2342 const int col8x8_remaining = tile->mi_col_end - mi_col;
2343 int block_row, block_col;
2344 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2345 int bh = num_8x8_blocks_high_lookup[bsize];
2346 int bw = num_8x8_blocks_wide_lookup[bsize];
2348 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2350 // Apply the requested partition size to the SB64 if it is all "in image"
2351 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2352 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2353 for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
2354 for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
2355 int index = block_row * mis + block_col;
2356 mi_8x8[index] = mi_upper_left + index;
2357 mi_8x8[index]->sb_type = bsize;
2361 // Else this is a partial SB64.
2362 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2363 col8x8_remaining, bsize, mi_8x8);
2367 static const struct {
2370 } coord_lookup[16] = {
2393 static void set_source_var_based_partition(VP9_COMP *cpi,
2394 const TileInfo *const tile,
2395 MACROBLOCK *const x,
2396 MODE_INFO **mi_8x8, int mi_row,
2398 VP9_COMMON *const cm = &cpi->common;
2399 const int mis = cm->mi_stride;
2400 const int row8x8_remaining = tile->mi_row_end - mi_row;
2401 const int col8x8_remaining = tile->mi_col_end - mi_col;
2402 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2404 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
2406 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2409 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2410 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2414 const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
2415 int is_larger_better = 0;
2417 unsigned int thr = cpi->source_var_thresh;
2419 memset(d32, 0, 4 * sizeof(diff));
2421 for (i = 0; i < 4; i++) {
2424 for (j = 0; j < 4; j++) {
2425 int b_mi_row = coord_lookup[i * 4 + j].row;
2426 int b_mi_col = coord_lookup[i * 4 + j].col;
2427 int boffset = b_mi_row / 2 * cm->mb_cols + b_mi_col / 2;
2429 d16[j] = cpi->source_diff_var + offset + boffset;
2431 index = b_mi_row * mis + b_mi_col;
2432 mi_8x8[index] = mi_upper_left + index;
2433 mi_8x8[index]->sb_type = BLOCK_16X16;
2435 // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
2436 // size to further improve quality.
2439 is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
2440 (d16[2]->var < thr) && (d16[3]->var < thr);
2442 // Use 32x32 partition
2443 if (is_larger_better) {
2446 for (j = 0; j < 4; j++) {
2447 d32[i].sse += d16[j]->sse;
2448 d32[i].sum += d16[j]->sum;
2452 (unsigned int)(d32[i].sse -
2453 (unsigned int)(((int64_t)d32[i].sum * d32[i].sum) >>
2456 index = coord_lookup[i * 4].row * mis + coord_lookup[i * 4].col;
2457 mi_8x8[index] = mi_upper_left + index;
2458 mi_8x8[index]->sb_type = BLOCK_32X32;
2462 if (use32x32 == 4) {
2464 is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
2465 (d32[2].var < thr) && (d32[3].var < thr);
2467 // Use 64x64 partition
2468 if (is_larger_better) {
2469 mi_8x8[0] = mi_upper_left;
2470 mi_8x8[0]->sb_type = BLOCK_64X64;
2473 } else { // partial in-image SB64
2474 int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
2475 int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
2476 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2477 col8x8_remaining, BLOCK_16X16, mi_8x8);
2481 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
2482 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
2484 VP9_COMMON *const cm = &cpi->common;
2485 MACROBLOCK *const x = &td->mb;
2486 MACROBLOCKD *const xd = &x->e_mbd;
2487 MODE_INFO *const mi = xd->mi[0];
2488 struct macroblock_plane *const p = x->plane;
2489 const struct segmentation *const seg = &cm->seg;
2490 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
2491 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
2492 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
2493 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
2495 *(xd->mi[0]) = ctx->mic;
2496 *(x->mbmi_ext) = ctx->mbmi_ext;
2498 if (seg->enabled && (cpi->oxcf.aq_mode != NO_AQ || cpi->roi.enabled)) {
2499 // Setting segmentation map for cyclic_refresh.
2500 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
2501 cpi->cyclic_refresh->content_mode) {
2502 vp9_cyclic_refresh_update_segment(cpi, mi, mi_row, mi_col, bsize,
2503 ctx->rate, ctx->dist, x->skip, p);
2505 const uint8_t *const map =
2506 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
2507 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
2509 vp9_init_plane_quantizers(cpi, x);
2512 if (is_inter_block(mi)) {
2513 vp9_update_mv_count(td);
2514 if (cm->interp_filter == SWITCHABLE) {
2515 const int pred_ctx = get_pred_context_switchable_interp(xd);
2516 ++td->counts->switchable_interp[pred_ctx][mi->interp_filter];
2519 if (mi->sb_type < BLOCK_8X8) {
2520 mi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
2521 mi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
2525 if (cm->use_prev_frame_mvs || !cm->error_resilient_mode ||
2526 (cpi->svc.use_base_mv && cpi->svc.number_spatial_layers > 1 &&
2527 cpi->svc.spatial_layer_id != cpi->svc.number_spatial_layers - 1)) {
2528 MV_REF *const frame_mvs =
2529 cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
2532 for (h = 0; h < y_mis; ++h) {
2533 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
2534 for (w = 0; w < x_mis; ++w) {
2535 MV_REF *const mv = frame_mv + w;
2536 mv->ref_frame[0] = mi->ref_frame[0];
2537 mv->ref_frame[1] = mi->ref_frame[1];
2538 mv->mv[0].as_int = mi->mv[0].as_int;
2539 mv->mv[1].as_int = mi->mv[1].as_int;
2544 x->skip = ctx->skip;
2545 x->skip_txfm[0] = (mi->segment_id || xd->lossless) ? 0 : ctx->skip_txfm[0];
2548 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
2549 const TileInfo *const tile, TOKENEXTRA **tp, int mi_row,
2550 int mi_col, int output_enabled, BLOCK_SIZE bsize,
2551 PICK_MODE_CONTEXT *ctx) {
2552 MACROBLOCK *const x = &td->mb;
2553 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2554 update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
2556 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2557 update_stats(&cpi->common, td);
2559 (*tp)->token = EOSB_TOKEN;
2563 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
2564 const TileInfo *const tile, TOKENEXTRA **tp,
2565 int mi_row, int mi_col, int output_enabled,
2566 BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2567 VP9_COMMON *const cm = &cpi->common;
2568 MACROBLOCK *const x = &td->mb;
2569 MACROBLOCKD *const xd = &x->e_mbd;
2571 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2573 PARTITION_TYPE partition;
2576 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2578 if (bsize >= BLOCK_8X8) {
2579 const int idx_str = xd->mi_stride * mi_row + mi_col;
2580 MODE_INFO **mi_8x8 = cm->mi_grid_visible + idx_str;
2581 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2582 subsize = mi_8x8[0]->sb_type;
2585 subsize = BLOCK_4X4;
2588 partition = partition_lookup[bsl][subsize];
2589 if (output_enabled && bsize != BLOCK_4X4)
2590 td->counts->partition[ctx][partition]++;
2592 switch (partition) {
2593 case PARTITION_NONE:
2594 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2597 case PARTITION_VERT:
2598 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2599 &pc_tree->vertical[0]);
2600 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2601 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2602 subsize, &pc_tree->vertical[1]);
2605 case PARTITION_HORZ:
2606 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2607 &pc_tree->horizontal[0]);
2608 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2609 encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2610 subsize, &pc_tree->horizontal[1]);
2614 assert(partition == PARTITION_SPLIT);
2615 subsize = get_subsize(bsize, PARTITION_SPLIT);
2616 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2618 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2619 subsize, pc_tree->split[1]);
2620 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2621 subsize, pc_tree->split[2]);
2622 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
2623 output_enabled, subsize, pc_tree->split[3]);
2627 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2628 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2631 #if !CONFIG_REALTIME_ONLY
2632 static void rd_use_partition(VP9_COMP *cpi, ThreadData *td,
2633 TileDataEnc *tile_data, MODE_INFO **mi_8x8,
2634 TOKENEXTRA **tp, int mi_row, int mi_col,
2635 BLOCK_SIZE bsize, int *rate, int64_t *dist,
2636 int do_recon, PC_TREE *pc_tree) {
2637 VP9_COMMON *const cm = &cpi->common;
2638 TileInfo *const tile_info = &tile_data->tile_info;
2639 MACROBLOCK *const x = &td->mb;
2640 MACROBLOCKD *const xd = &x->e_mbd;
2641 const int mis = cm->mi_stride;
2642 const int bsl = b_width_log2_lookup[bsize];
2643 const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
2644 const int bss = (1 << bsl) / 4;
2646 PARTITION_TYPE partition = PARTITION_NONE;
2648 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2649 PARTITION_CONTEXT sl[8], sa[8];
2650 RD_COST last_part_rdc, none_rdc, chosen_rdc;
2651 BLOCK_SIZE sub_subsize = BLOCK_4X4;
2652 int splits_below = 0;
2653 BLOCK_SIZE bs_type = mi_8x8[0]->sb_type;
2654 int do_partition_search = 1;
2655 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2657 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2659 assert(num_4x4_blocks_wide_lookup[bsize] ==
2660 num_4x4_blocks_high_lookup[bsize]);
2662 vp9_rd_cost_reset(&last_part_rdc);
2663 vp9_rd_cost_reset(&none_rdc);
2664 vp9_rd_cost_reset(&chosen_rdc);
2666 partition = partition_lookup[bsl][bs_type];
2667 subsize = get_subsize(bsize, partition);
2669 pc_tree->partitioning = partition;
2670 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2672 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ) {
2673 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2674 x->mb_energy = vp9_block_energy(cpi, x, bsize);
2677 if (do_partition_search &&
2678 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2679 cpi->sf.adjust_partitioning_from_last_frame) {
2680 // Check if any of the sub blocks are further split.
2681 if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
2682 sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
2684 for (i = 0; i < 4; i++) {
2685 int jj = i >> 1, ii = i & 0x01;
2686 MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
2687 if (this_mi && this_mi->sb_type >= sub_subsize) {
2693 // If partition is not none try none unless each of the 4 splits are split
2695 if (partition != PARTITION_NONE && !splits_below &&
2696 mi_row + (mi_step >> 1) < cm->mi_rows &&
2697 mi_col + (mi_step >> 1) < cm->mi_cols) {
2698 pc_tree->partitioning = PARTITION_NONE;
2699 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize, ctx,
2700 INT_MAX, INT64_MAX);
2702 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2704 if (none_rdc.rate < INT_MAX) {
2705 none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2707 RDCOST(x->rdmult, x->rddiv, none_rdc.rate, none_rdc.dist);
2710 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2711 mi_8x8[0]->sb_type = bs_type;
2712 pc_tree->partitioning = partition;
2716 switch (partition) {
2717 case PARTITION_NONE:
2718 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc, bsize,
2719 ctx, INT_MAX, INT64_MAX);
2721 case PARTITION_HORZ:
2722 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
2723 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2724 subsize, &pc_tree->horizontal[0], INT_MAX, INT64_MAX);
2725 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2726 mi_row + (mi_step >> 1) < cm->mi_rows) {
2728 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2729 vp9_rd_cost_init(&tmp_rdc);
2730 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2731 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2732 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
2733 rd_pick_sb_modes(cpi, tile_data, x, mi_row + (mi_step >> 1), mi_col,
2734 &tmp_rdc, subsize, &pc_tree->horizontal[1], INT_MAX,
2736 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2737 vp9_rd_cost_reset(&last_part_rdc);
2740 last_part_rdc.rate += tmp_rdc.rate;
2741 last_part_rdc.dist += tmp_rdc.dist;
2742 last_part_rdc.rdcost += tmp_rdc.rdcost;
2745 case PARTITION_VERT:
2746 pc_tree->vertical[0].skip_ref_frame_mask = 0;
2747 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2748 subsize, &pc_tree->vertical[0], INT_MAX, INT64_MAX);
2749 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2750 mi_col + (mi_step >> 1) < cm->mi_cols) {
2752 PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
2753 vp9_rd_cost_init(&tmp_rdc);
2754 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2755 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2756 pc_tree->vertical[bsize > BLOCK_8X8].skip_ref_frame_mask = 0;
2758 cpi, tile_data, x, mi_row, mi_col + (mi_step >> 1), &tmp_rdc,
2759 subsize, &pc_tree->vertical[bsize > BLOCK_8X8], INT_MAX, INT64_MAX);
2760 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2761 vp9_rd_cost_reset(&last_part_rdc);
2764 last_part_rdc.rate += tmp_rdc.rate;
2765 last_part_rdc.dist += tmp_rdc.dist;
2766 last_part_rdc.rdcost += tmp_rdc.rdcost;
2770 assert(partition == PARTITION_SPLIT);
2771 if (bsize == BLOCK_8X8) {
2772 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2773 subsize, pc_tree->leaf_split[0], INT_MAX, INT64_MAX);
2776 last_part_rdc.rate = 0;
2777 last_part_rdc.dist = 0;
2778 last_part_rdc.rdcost = 0;
2779 for (i = 0; i < 4; i++) {
2780 int x_idx = (i & 1) * (mi_step >> 1);
2781 int y_idx = (i >> 1) * (mi_step >> 1);
2782 int jj = i >> 1, ii = i & 0x01;
2784 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2787 vp9_rd_cost_init(&tmp_rdc);
2788 rd_use_partition(cpi, td, tile_data, mi_8x8 + jj * bss * mis + ii * bss,
2789 tp, mi_row + y_idx, mi_col + x_idx, subsize,
2790 &tmp_rdc.rate, &tmp_rdc.dist, i != 3,
2792 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2793 vp9_rd_cost_reset(&last_part_rdc);
2796 last_part_rdc.rate += tmp_rdc.rate;
2797 last_part_rdc.dist += tmp_rdc.dist;
2802 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2803 if (last_part_rdc.rate < INT_MAX) {
2804 last_part_rdc.rate += cpi->partition_cost[pl][partition];
2805 last_part_rdc.rdcost =
2806 RDCOST(x->rdmult, x->rddiv, last_part_rdc.rate, last_part_rdc.dist);
2809 if (do_partition_search && cpi->sf.adjust_partitioning_from_last_frame &&
2810 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2811 partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
2812 (mi_row + mi_step < cm->mi_rows ||
2813 mi_row + (mi_step >> 1) == cm->mi_rows) &&
2814 (mi_col + mi_step < cm->mi_cols ||
2815 mi_col + (mi_step >> 1) == cm->mi_cols)) {
2816 BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2817 chosen_rdc.rate = 0;
2818 chosen_rdc.dist = 0;
2819 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2820 pc_tree->partitioning = PARTITION_SPLIT;
2823 for (i = 0; i < 4; i++) {
2824 int x_idx = (i & 1) * (mi_step >> 1);
2825 int y_idx = (i >> 1) * (mi_step >> 1);
2827 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2828 PARTITION_CONTEXT sl[8], sa[8];
2830 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2833 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2834 pc_tree->split[i]->partitioning = PARTITION_NONE;
2835 rd_pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2836 &tmp_rdc, split_subsize, &pc_tree->split[i]->none,
2837 INT_MAX, INT64_MAX);
2839 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2841 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2842 vp9_rd_cost_reset(&chosen_rdc);
2846 chosen_rdc.rate += tmp_rdc.rate;
2847 chosen_rdc.dist += tmp_rdc.dist;
2850 encode_sb(cpi, td, tile_info, tp, mi_row + y_idx, mi_col + x_idx, 0,
2851 split_subsize, pc_tree->split[i]);
2853 pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2855 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2857 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2858 if (chosen_rdc.rate < INT_MAX) {
2859 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2861 RDCOST(x->rdmult, x->rddiv, chosen_rdc.rate, chosen_rdc.dist);
2865 // If last_part is better set the partitioning to that.
2866 if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2867 mi_8x8[0]->sb_type = bsize;
2868 if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2869 chosen_rdc = last_part_rdc;
2871 // If none was better set the partitioning to that.
2872 if (none_rdc.rdcost < chosen_rdc.rdcost) {
2873 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2874 chosen_rdc = none_rdc;
2877 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2879 // We must have chosen a partitioning and encoding or we'll fail later on.
2880 // No other opportunities for success.
2881 if (bsize == BLOCK_64X64)
2882 assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2885 int output_enabled = (bsize == BLOCK_64X64);
2886 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2890 *rate = chosen_rdc.rate;
2891 *dist = chosen_rdc.dist;
2894 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2895 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2896 BLOCK_4X4, BLOCK_8X8, BLOCK_8X8, BLOCK_8X8, BLOCK_16X16,
2897 BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
2900 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2901 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2902 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2903 BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
2906 // Look at all the mode_info entries for blocks that are part of this
2907 // partition and find the min and max values for sb_type.
2908 // At the moment this is designed to work on a 64x64 SB but could be
2909 // adjusted to use a size parameter.
2911 // The min and max are assumed to have been initialized prior to calling this
2912 // function so repeat calls can accumulate a min and max of more than one sb64.
2913 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2914 BLOCK_SIZE *min_block_size,
2915 BLOCK_SIZE *max_block_size,
2916 int bs_hist[BLOCK_SIZES]) {
2917 int sb_width_in_blocks = MI_BLOCK_SIZE;
2918 int sb_height_in_blocks = MI_BLOCK_SIZE;
2922 // Check the sb_type for each block that belongs to this region.
2923 for (i = 0; i < sb_height_in_blocks; ++i) {
2924 for (j = 0; j < sb_width_in_blocks; ++j) {
2925 MODE_INFO *mi = mi_8x8[index + j];
2926 BLOCK_SIZE sb_type = mi ? mi->sb_type : 0;
2928 *min_block_size = VPXMIN(*min_block_size, sb_type);
2929 *max_block_size = VPXMAX(*max_block_size, sb_type);
2931 index += xd->mi_stride;
2935 // Next square block size less or equal than current block size.
2936 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2937 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_8X8, BLOCK_8X8,
2938 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2939 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64
2942 // Look at neighboring blocks and set a min and max partition size based on
2944 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2945 MACROBLOCKD *const xd, int mi_row,
2946 int mi_col, BLOCK_SIZE *min_block_size,
2947 BLOCK_SIZE *max_block_size) {
2948 VP9_COMMON *const cm = &cpi->common;
2949 MODE_INFO **mi = xd->mi;
2950 const int left_in_image = !!xd->left_mi;
2951 const int above_in_image = !!xd->above_mi;
2952 const int row8x8_remaining = tile->mi_row_end - mi_row;
2953 const int col8x8_remaining = tile->mi_col_end - mi_col;
2955 BLOCK_SIZE min_size = BLOCK_4X4;
2956 BLOCK_SIZE max_size = BLOCK_64X64;
2957 int bs_hist[BLOCK_SIZES] = { 0 };
2959 // Trap case where we do not have a prediction.
2960 if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2961 // Default "min to max" and "max to min"
2962 min_size = BLOCK_64X64;
2963 max_size = BLOCK_4X4;
2965 // NOTE: each call to get_sb_partition_size_range() uses the previous
2966 // passed in values for min and max as a starting point.
2967 // Find the min and max partition used in previous frame at this location
2968 if (cm->frame_type != KEY_FRAME) {
2969 MODE_INFO **prev_mi =
2970 &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2971 get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2973 // Find the min and max partition sizes used in the left SB64
2974 if (left_in_image) {
2975 MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2976 get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2979 // Find the min and max partition sizes used in the above SB64.
2980 if (above_in_image) {
2981 MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2982 get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2986 // Adjust observed min and max for "relaxed" auto partition case.
2987 if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2988 min_size = min_partition_size[min_size];
2989 max_size = max_partition_size[max_size];
2993 // Check border cases where max and min from neighbors may not be legal.
2994 max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
2996 // Test for blocks at the edge of the active image.
2997 // This may be the actual edge of the image or where there are formatting
2999 if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
3000 min_size = BLOCK_4X4;
3003 VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
3006 // When use_square_partition_only is true, make sure at least one square
3007 // partition is allowed by selecting the next smaller square size as
3009 if (cpi->sf.use_square_partition_only &&
3010 next_square_size[max_size] < min_size) {
3011 min_size = next_square_size[max_size];
3014 *min_block_size = min_size;
3015 *max_block_size = max_size;
3018 // TODO(jingning) refactor functions setting partition search range
3019 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd, int mi_row,
3020 int mi_col, BLOCK_SIZE bsize,
3021 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
3022 int mi_width = num_8x8_blocks_wide_lookup[bsize];
3023 int mi_height = num_8x8_blocks_high_lookup[bsize];
3027 const int idx_str = cm->mi_stride * mi_row + mi_col;
3028 MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
3029 BLOCK_SIZE bs, min_size, max_size;
3031 min_size = BLOCK_64X64;
3032 max_size = BLOCK_4X4;
3035 for (idy = 0; idy < mi_height; ++idy) {
3036 for (idx = 0; idx < mi_width; ++idx) {
3037 mi = prev_mi[idy * cm->mi_stride + idx];
3038 bs = mi ? mi->sb_type : bsize;
3039 min_size = VPXMIN(min_size, bs);
3040 max_size = VPXMAX(max_size, bs);
3046 for (idy = 0; idy < mi_height; ++idy) {
3047 mi = xd->mi[idy * cm->mi_stride - 1];
3048 bs = mi ? mi->sb_type : bsize;
3049 min_size = VPXMIN(min_size, bs);
3050 max_size = VPXMAX(max_size, bs);
3055 for (idx = 0; idx < mi_width; ++idx) {
3056 mi = xd->mi[idx - cm->mi_stride];
3057 bs = mi ? mi->sb_type : bsize;
3058 min_size = VPXMIN(min_size, bs);
3059 max_size = VPXMAX(max_size, bs);
3063 if (min_size == max_size) {
3064 min_size = min_partition_size[min_size];
3065 max_size = max_partition_size[max_size];
3071 #endif // !CONFIG_REALTIME_ONLY
3073 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3074 memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
3077 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3078 memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
3081 // Calculate prediction based on the given input features and neural net config.
3082 // Assume there are no more than NN_MAX_NODES_PER_LAYER nodes in each hidden
3084 static void nn_predict(const float *features, const NN_CONFIG *nn_config,
3086 int num_input_nodes = nn_config->num_inputs;
3088 float buf[2][NN_MAX_NODES_PER_LAYER];
3089 const float *input_nodes = features;
3091 // Propagate hidden layers.
3092 const int num_layers = nn_config->num_hidden_layers;
3094 assert(num_layers <= NN_MAX_HIDDEN_LAYERS);
3095 for (layer = 0; layer < num_layers; ++layer) {
3096 const float *weights = nn_config->weights[layer];
3097 const float *bias = nn_config->bias[layer];
3098 float *output_nodes = buf[buf_index];
3099 const int num_output_nodes = nn_config->num_hidden_nodes[layer];
3100 assert(num_output_nodes < NN_MAX_NODES_PER_LAYER);
3101 for (node = 0; node < num_output_nodes; ++node) {
3103 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3105 // ReLU as activation function.
3106 val = VPXMAX(val, 0.0f);
3107 output_nodes[node] = val;
3108 weights += num_input_nodes;
3110 num_input_nodes = num_output_nodes;
3111 input_nodes = output_nodes;
3112 buf_index = 1 - buf_index;
3115 // Final output layer.
3117 const float *weights = nn_config->weights[num_layers];
3118 for (node = 0; node < nn_config->num_outputs; ++node) {
3119 const float *bias = nn_config->bias[num_layers];
3121 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3122 output[node] = val + bias[node];
3123 weights += num_input_nodes;
3128 #if !CONFIG_REALTIME_ONLY
3130 // Machine-learning based partition search early termination.
3131 // Return 1 to skip split and rect partitions.
3132 static int ml_pruning_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
3133 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
3136 abs(ctx->mic.mv[0].as_mv.col) + abs(ctx->mic.mv[0].as_mv.row);
3137 const int left_in_image = !!xd->left_mi;
3138 const int above_in_image = !!xd->above_mi;
3139 MODE_INFO **prev_mi =
3140 &cm->prev_mi_grid_visible[mi_col + cm->mi_stride * mi_row];
3141 int above_par = 0; // above_partitioning
3142 int left_par = 0; // left_partitioning
3143 int last_par = 0; // last_partitioning
3146 BLOCK_SIZE context_size;
3147 const NN_CONFIG *nn_config = NULL;
3148 const float *mean, *sd, *linear_weights;
3149 float nn_score, linear_score;
3150 float features[FEATURES];
3152 assert(b_width_log2_lookup[bsize] == b_height_log2_lookup[bsize]);
3153 vpx_clear_system_state();
3158 nn_config = &vp9_partition_nnconfig_64x64;
3162 nn_config = &vp9_partition_nnconfig_32x32;
3166 nn_config = &vp9_partition_nnconfig_16x16;
3168 default: assert(0 && "Unexpected block size."); return 0;
3171 if (above_in_image) {
3172 context_size = xd->above_mi->sb_type;
3173 if (context_size < bsize)
3175 else if (context_size == bsize)
3179 if (left_in_image) {
3180 context_size = xd->left_mi->sb_type;
3181 if (context_size < bsize)
3183 else if (context_size == bsize)
3188 context_size = prev_mi[0]->sb_type;
3189 if (context_size < bsize)
3191 else if (context_size == bsize)
3195 mean = &vp9_partition_feature_mean[offset];
3196 sd = &vp9_partition_feature_std[offset];
3197 features[0] = ((float)ctx->rate - mean[0]) / sd[0];
3198 features[1] = ((float)ctx->dist - mean[1]) / sd[1];
3199 features[2] = ((float)mag_mv / 2 - mean[2]) * sd[2];
3200 features[3] = ((float)(left_par + above_par) / 2 - mean[3]) * sd[3];
3201 features[4] = ((float)ctx->sum_y_eobs - mean[4]) / sd[4];
3202 features[5] = ((float)cm->base_qindex - mean[5]) * sd[5];
3203 features[6] = ((float)last_par - mean[6]) * sd[6];
3205 // Predict using linear model.
3206 linear_weights = &vp9_partition_linear_weights[offset];
3207 linear_score = linear_weights[FEATURES];
3208 for (i = 0; i < FEATURES; ++i)
3209 linear_score += linear_weights[i] * features[i];
3210 if (linear_score > 0.1f) return 0;
3212 // Predict using neural net model.
3213 nn_predict(features, nn_config, &nn_score);
3215 if (linear_score < -0.0f && nn_score < 0.1f) return 1;
3216 if (nn_score < -0.0f && linear_score < 0.1f) return 1;
3222 // ML-based partition search breakout.
3223 static int ml_predict_breakout(VP9_COMP *const cpi, BLOCK_SIZE bsize,
3224 const MACROBLOCK *const x,
3225 const RD_COST *const rd_cost) {
3226 DECLARE_ALIGNED(16, static const uint8_t, vp9_64_zeros[64]) = { 0 };
3227 const VP9_COMMON *const cm = &cpi->common;
3228 float features[FEATURES];
3229 const float *linear_weights = NULL; // Linear model weights.
3230 float linear_score = 0.0f;
3231 const int qindex = cm->base_qindex;
3232 const int q_ctx = qindex >= 200 ? 0 : (qindex >= 150 ? 1 : 2);
3233 const int is_720p_or_larger = VPXMIN(cm->width, cm->height) >= 720;
3234 const int resolution_ctx = is_720p_or_larger ? 1 : 0;
3238 linear_weights = vp9_partition_breakout_weights_64[resolution_ctx][q_ctx];
3241 linear_weights = vp9_partition_breakout_weights_32[resolution_ctx][q_ctx];
3244 linear_weights = vp9_partition_breakout_weights_16[resolution_ctx][q_ctx];
3247 linear_weights = vp9_partition_breakout_weights_8[resolution_ctx][q_ctx];
3249 default: assert(0 && "Unexpected block size."); return 0;
3251 if (!linear_weights) return 0;
3253 { // Generate feature values.
3254 #if CONFIG_VP9_HIGHBITDEPTH
3256 vp9_ac_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3258 const int ac_q = vp9_ac_quant(qindex, 0, cm->bit_depth);
3259 #endif // CONFIG_VP9_HIGHBITDEPTH
3260 const int num_pels_log2 = num_pels_log2_lookup[bsize];
3261 int feature_index = 0;
3262 unsigned int var, sse;
3263 float rate_f, dist_f;
3265 #if CONFIG_VP9_HIGHBITDEPTH
3266 if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3268 vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, x->e_mbd.bd);
3270 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3271 vp9_64_zeros, 0, &sse);
3274 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3275 vp9_64_zeros, 0, &sse);
3277 var = var >> num_pels_log2;
3279 vpx_clear_system_state();
3281 rate_f = (float)VPXMIN(rd_cost->rate, INT_MAX);
3282 dist_f = (float)(VPXMIN(rd_cost->dist, INT_MAX) >> num_pels_log2);
3284 ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
3287 features[feature_index++] = rate_f;
3288 features[feature_index++] = dist_f;
3289 features[feature_index++] = (float)var;
3290 features[feature_index++] = (float)ac_q;
3291 assert(feature_index == FEATURES);
3294 { // Calculate the output score.
3296 linear_score = linear_weights[FEATURES];
3297 for (i = 0; i < FEATURES; ++i)
3298 linear_score += linear_weights[i] * features[i];
3301 return linear_score >= cpi->sf.rd_ml_partition.search_breakout_thresh[q_ctx];
3307 static void ml_prune_rect_partition(VP9_COMP *const cpi, MACROBLOCK *const x,
3309 const PC_TREE *const pc_tree,
3310 int *allow_horz, int *allow_vert,
3312 const NN_CONFIG *nn_config = NULL;
3313 float score[LABELS] = {
3320 if (ref_rd <= 0 || ref_rd > 1000000000) return;
3323 case BLOCK_8X8: break;
3325 nn_config = &vp9_rect_part_nnconfig_16;
3326 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[1];
3329 nn_config = &vp9_rect_part_nnconfig_32;
3330 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[2];
3333 nn_config = &vp9_rect_part_nnconfig_64;
3334 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[3];
3336 default: assert(0 && "Unexpected block size."); return;
3338 if (!nn_config || thresh < 0) return;
3340 // Feature extraction and model score calculation.
3342 const VP9_COMMON *const cm = &cpi->common;
3343 #if CONFIG_VP9_HIGHBITDEPTH
3345 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3347 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3348 #endif // CONFIG_VP9_HIGHBITDEPTH
3349 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3350 int feature_index = 0;
3351 float features[FEATURES];
3353 features[feature_index++] = logf((float)dc_q + 1.0f);
3354 features[feature_index++] =
3355 (float)(pc_tree->partitioning == PARTITION_NONE);
3356 features[feature_index++] = logf((float)ref_rd / bs / bs + 1.0f);
3359 const float norm_factor = 1.0f / ((float)ref_rd + 1.0f);
3360 const int64_t none_rdcost = pc_tree->none.rdcost;
3361 float rd_ratio = 2.0f;
3362 if (none_rdcost > 0 && none_rdcost < 1000000000)
3363 rd_ratio = (float)none_rdcost * norm_factor;
3364 features[feature_index++] = VPXMIN(rd_ratio, 2.0f);
3366 for (i = 0; i < 4; ++i) {
3367 const int64_t this_rd = pc_tree->split[i]->none.rdcost;
3368 const int rd_valid = this_rd > 0 && this_rd < 1000000000;
3369 // Ratio between sub-block RD and whole block RD.
3370 features[feature_index++] =
3371 rd_valid ? (float)this_rd * norm_factor : 1.0f;
3375 assert(feature_index == FEATURES);
3376 nn_predict(features, nn_config, score);
3379 // Make decisions based on the model score.
3381 int max_score = -1000;
3382 int horz = 0, vert = 0;
3383 int int_score[LABELS];
3384 for (i = 0; i < LABELS; ++i) {
3385 int_score[i] = (int)(100 * score[i]);
3386 max_score = VPXMAX(int_score[i], max_score);
3388 thresh = max_score - thresh;
3389 for (i = 0; i < LABELS; ++i) {
3390 if (int_score[i] >= thresh) {
3391 if ((i >> 0) & 1) horz = 1;
3392 if ((i >> 1) & 1) vert = 1;
3395 *allow_horz = *allow_horz && horz;
3396 *allow_vert = *allow_vert && vert;
3402 // Perform fast and coarse motion search for the given block. This is a
3403 // pre-processing step for the ML based partition search speedup.
3404 static void simple_motion_search(const VP9_COMP *const cpi, MACROBLOCK *const x,
3405 BLOCK_SIZE bsize, int mi_row, int mi_col,
3406 MV ref_mv, MV_REFERENCE_FRAME ref,
3407 uint8_t *const pred_buf) {
3408 const VP9_COMMON *const cm = &cpi->common;
3409 MACROBLOCKD *const xd = &x->e_mbd;
3410 MODE_INFO *const mi = xd->mi[0];
3411 const YV12_BUFFER_CONFIG *const yv12 = get_ref_frame_buffer(cpi, ref);
3412 const int step_param = 1;
3413 const MvLimits tmp_mv_limits = x->mv_limits;
3414 const SEARCH_METHODS search_method = NSTEP;
3415 const int sadpb = x->sadperbit16;
3416 MV ref_mv_full = { ref_mv.row >> 3, ref_mv.col >> 3 };
3417 MV best_mv = { 0, 0 };
3420 assert(yv12 != NULL);
3422 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
3423 &cm->frame_refs[ref - 1].sf);
3424 mi->ref_frame[0] = ref;
3425 mi->ref_frame[1] = NONE;
3426 mi->sb_type = bsize;
3427 vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
3428 vp9_full_pixel_search(cpi, x, bsize, &ref_mv_full, step_param, search_method,
3429 sadpb, cond_cost_list(cpi, cost_list), &ref_mv,
3433 x->mv_limits = tmp_mv_limits;
3434 mi->mv[0].as_mv = best_mv;
3436 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3437 xd->plane[0].dst.buf = pred_buf;
3438 xd->plane[0].dst.stride = 64;
3439 vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
3442 // Use a neural net model to prune partition-none and partition-split search.
3443 // Features used: QP; spatial block size contexts; variance of prediction
3444 // residue after simple_motion_search.
3446 static void ml_predict_var_rd_paritioning(const VP9_COMP *const cpi,
3447 MACROBLOCK *const x,
3448 PC_TREE *const pc_tree,
3449 BLOCK_SIZE bsize, int mi_row,
3450 int mi_col, int *none, int *split) {
3451 const VP9_COMMON *const cm = &cpi->common;
3452 const NN_CONFIG *nn_config = NULL;
3453 #if CONFIG_VP9_HIGHBITDEPTH
3454 MACROBLOCKD *xd = &x->e_mbd;
3455 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64 * 2]);
3456 uint8_t *const pred_buf = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
3457 ? (CONVERT_TO_BYTEPTR(pred_buffer))
3460 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64]);
3461 uint8_t *const pred_buf = pred_buffer;
3462 #endif // CONFIG_VP9_HIGHBITDEPTH
3463 const int speed = cpi->oxcf.speed;
3464 float thresh = 0.0f;
3468 nn_config = &vp9_part_split_nnconfig_64;
3469 thresh = speed > 0 ? 2.8f : 3.0f;
3472 nn_config = &vp9_part_split_nnconfig_32;
3473 thresh = speed > 0 ? 3.5f : 3.0f;
3476 nn_config = &vp9_part_split_nnconfig_16;
3477 thresh = speed > 0 ? 3.8f : 4.0f;
3480 nn_config = &vp9_part_split_nnconfig_8;
3481 if (cm->width >= 720 && cm->height >= 720)
3482 thresh = speed > 0 ? 2.5f : 2.0f;
3484 thresh = speed > 0 ? 3.8f : 2.0f;
3486 default: assert(0 && "Unexpected block size."); return;
3489 if (!nn_config) return;
3491 // Do a simple single motion search to find a prediction for current block.
3492 // The variance of the residue will be used as input features.
3495 const MV_REFERENCE_FRAME ref =
3496 cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
3497 // If bsize is 64x64, use zero MV as reference; otherwise, use MV result
3498 // of previous(larger) block as reference.
3499 if (bsize == BLOCK_64X64)
3500 ref_mv.row = ref_mv.col = 0;
3502 ref_mv = pc_tree->mv;
3503 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
3504 simple_motion_search(cpi, x, bsize, mi_row, mi_col, ref_mv, ref, pred_buf);
3505 pc_tree->mv = x->e_mbd.mi[0]->mv[0].as_mv;
3508 vpx_clear_system_state();
3511 float features[FEATURES] = { 0.0f };
3512 #if CONFIG_VP9_HIGHBITDEPTH
3514 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (xd->bd - 8);
3516 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3517 #endif // CONFIG_VP9_HIGHBITDEPTH
3518 int feature_idx = 0;
3521 // Generate model input features.
3522 features[feature_idx++] = logf((float)dc_q + 1.0f);
3524 // Get the variance of the residue as input features.
3526 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3527 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3528 const uint8_t *pred = pred_buf;
3529 const uint8_t *src = x->plane[0].src.buf;
3530 const int src_stride = x->plane[0].src.stride;
3531 const int pred_stride = 64;
3533 // Variance of whole block.
3534 const unsigned int var =
3535 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
3536 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
3537 const MACROBLOCKD *const xd = &x->e_mbd;
3538 const int has_above = !!xd->above_mi;
3539 const int has_left = !!xd->left_mi;
3540 const BLOCK_SIZE above_bsize = has_above ? xd->above_mi->sb_type : bsize;
3541 const BLOCK_SIZE left_bsize = has_left ? xd->left_mi->sb_type : bsize;
3544 features[feature_idx++] = (float)has_above;
3545 features[feature_idx++] = (float)b_width_log2_lookup[above_bsize];
3546 features[feature_idx++] = (float)b_height_log2_lookup[above_bsize];
3547 features[feature_idx++] = (float)has_left;
3548 features[feature_idx++] = (float)b_width_log2_lookup[left_bsize];
3549 features[feature_idx++] = (float)b_height_log2_lookup[left_bsize];
3550 features[feature_idx++] = logf((float)var + 1.0f);
3551 for (i = 0; i < 4; ++i) {
3552 const int x_idx = (i & 1) * bs / 2;
3553 const int y_idx = (i >> 1) * bs / 2;
3554 const int src_offset = y_idx * src_stride + x_idx;
3555 const int pred_offset = y_idx * pred_stride + x_idx;
3556 // Variance of quarter block.
3557 const unsigned int sub_var =
3558 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
3559 pred + pred_offset, pred_stride, &sse);
3560 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
3561 features[feature_idx++] = var_ratio;
3564 assert(feature_idx == FEATURES);
3566 // Feed the features into the model to get the confidence score.
3567 nn_predict(features, nn_config, &score);
3569 // Higher score means that the model has higher confidence that the split
3570 // partition is better than the non-split partition. So if the score is
3571 // high enough, we skip the none-split partition search; if the score is
3572 // low enough, we skip the split partition search.
3573 if (score > thresh) *none = 0;
3574 if (score < -thresh) *split = 0;
3578 #endif // !CONFIG_REALTIME_ONLY
3580 static double log_wiener_var(int64_t wiener_variance) {
3581 return log(1.0 + wiener_variance) / log(2.0);
3584 static void build_kmeans_segmentation(VP9_COMP *cpi) {
3585 VP9_COMMON *cm = &cpi->common;
3586 BLOCK_SIZE bsize = BLOCK_64X64;
3587 KMEANS_DATA *kmeans_data;
3589 vp9_disable_segmentation(&cm->seg);
3590 if (cm->show_frame) {
3592 cpi->kmeans_data_size = 0;
3593 cpi->kmeans_ctr_num = 8;
3595 for (mi_row = 0; mi_row < cm->mi_rows; mi_row += MI_BLOCK_SIZE) {
3596 for (mi_col = 0; mi_col < cm->mi_cols; mi_col += MI_BLOCK_SIZE) {
3597 int mb_row_start = mi_row >> 1;
3598 int mb_col_start = mi_col >> 1;
3599 int mb_row_end = VPXMIN(
3600 (mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3601 int mb_col_end = VPXMIN(
3602 (mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3604 int64_t wiener_variance = 0;
3606 for (row = mb_row_start; row < mb_row_end; ++row)
3607 for (col = mb_col_start; col < mb_col_end; ++col)
3608 wiener_variance += cpi->mb_wiener_variance[row * cm->mb_cols + col];
3611 (mb_row_end - mb_row_start) * (mb_col_end - mb_col_start);
3613 #if CONFIG_MULTITHREAD
3614 pthread_mutex_lock(&cpi->kmeans_mutex);
3615 #endif // CONFIG_MULTITHREAD
3617 kmeans_data = &cpi->kmeans_data_arr[cpi->kmeans_data_size++];
3618 kmeans_data->value = log_wiener_var(wiener_variance);
3619 kmeans_data->pos = mi_row * cpi->kmeans_data_stride + mi_col;
3620 #if CONFIG_MULTITHREAD
3621 pthread_mutex_unlock(&cpi->kmeans_mutex);
3622 #endif // CONFIG_MULTITHREAD
3626 vp9_kmeans(cpi->kmeans_ctr_ls, cpi->kmeans_boundary_ls,
3627 cpi->kmeans_count_ls, cpi->kmeans_ctr_num, cpi->kmeans_data_arr,
3628 cpi->kmeans_data_size);
3630 vp9_perceptual_aq_mode_setup(cpi, &cm->seg);
3634 #if !CONFIG_REALTIME_ONLY
3635 static int wiener_var_segment(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3637 VP9_COMMON *cm = &cpi->common;
3638 int mb_row_start = mi_row >> 1;
3639 int mb_col_start = mi_col >> 1;
3641 VPXMIN((mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3643 VPXMIN((mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3645 int64_t wiener_variance = 0;
3647 int8_t seg_hist[MAX_SEGMENTS] = { 0 };
3648 int8_t max_count = 0, max_index = -1;
3650 vpx_clear_system_state();
3652 assert(cpi->norm_wiener_variance > 0);
3654 for (row = mb_row_start; row < mb_row_end; ++row) {
3655 for (col = mb_col_start; col < mb_col_end; ++col) {
3656 wiener_variance = cpi->mb_wiener_variance[row * cm->mb_cols + col];
3658 vp9_get_group_idx(log_wiener_var(wiener_variance),
3659 cpi->kmeans_boundary_ls, cpi->kmeans_ctr_num);
3660 ++seg_hist[segment_id];
3664 for (idx = 0; idx < cpi->kmeans_ctr_num; ++idx) {
3665 if (seg_hist[idx] > max_count) {
3666 max_count = seg_hist[idx];
3671 assert(max_index >= 0);
3672 segment_id = max_index;
3677 static int get_rdmult_delta(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3678 int mi_col, int orig_rdmult) {
3679 const int gf_group_index = cpi->twopass.gf_group.index;
3680 int64_t intra_cost = 0;
3681 int64_t mc_dep_cost = 0;
3682 int mi_wide = num_8x8_blocks_wide_lookup[bsize];
3683 int mi_high = num_8x8_blocks_high_lookup[bsize];
3688 double r0, rk, beta;
3690 TplDepFrame *tpl_frame;
3691 TplDepStats *tpl_stats;
3694 if (gf_group_index >= MAX_ARF_GOP_SIZE) return orig_rdmult;
3695 tpl_frame = &cpi->tpl_stats[gf_group_index];
3697 if (tpl_frame->is_valid == 0) return orig_rdmult;
3698 tpl_stats = tpl_frame->tpl_stats_ptr;
3699 tpl_stride = tpl_frame->stride;
3701 if (cpi->twopass.gf_group.layer_depth[gf_group_index] > 1) return orig_rdmult;
3703 for (row = mi_row; row < mi_row + mi_high; ++row) {
3704 for (col = mi_col; col < mi_col + mi_wide; ++col) {
3705 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
3707 if (row >= cpi->common.mi_rows || col >= cpi->common.mi_cols) continue;
3709 intra_cost += this_stats->intra_cost;
3710 mc_dep_cost += this_stats->mc_dep_cost;
3716 vpx_clear_system_state();
3719 rk = (double)intra_cost / mc_dep_cost;
3721 dr = vp9_get_adaptive_rdmult(cpi, beta);
3723 dr = VPXMIN(dr, orig_rdmult * 3 / 2);
3724 dr = VPXMAX(dr, orig_rdmult * 1 / 2);
3730 #endif // !CONFIG_REALTIME_ONLY
3732 #if CONFIG_RATE_CTRL
3733 static void assign_partition_info(
3734 const int row_start_4x4, const int col_start_4x4, const int block_width_4x4,
3735 const int block_height_4x4, const int num_unit_rows,
3736 const int num_unit_cols, PARTITION_INFO *partition_info) {
3738 for (i = 0; i < block_height_4x4; ++i) {
3739 for (j = 0; j < block_width_4x4; ++j) {
3740 const int row_4x4 = row_start_4x4 + i;
3741 const int col_4x4 = col_start_4x4 + j;
3742 const int unit_index = row_4x4 * num_unit_cols + col_4x4;
3743 if (row_4x4 >= num_unit_rows || col_4x4 >= num_unit_cols) continue;
3744 partition_info[unit_index].row = row_4x4 << 2;
3745 partition_info[unit_index].column = col_4x4 << 2;
3746 partition_info[unit_index].row_start = row_start_4x4 << 2;
3747 partition_info[unit_index].column_start = col_start_4x4 << 2;
3748 partition_info[unit_index].width = block_width_4x4 << 2;
3749 partition_info[unit_index].height = block_height_4x4 << 2;
3754 static void assign_motion_vector_info(const int block_width_4x4,
3755 const int block_height_4x4,
3756 const int row_start_4x4,
3757 const int col_start_4x4,
3758 const int num_unit_rows,
3759 const int num_unit_cols, MV *source_mv[2],
3760 MV_REFERENCE_FRAME source_ref_frame[2],
3761 MOTION_VECTOR_INFO *motion_vector_info) {
3763 for (i = 0; i < block_height_4x4; ++i) {
3764 for (j = 0; j < block_width_4x4; ++j) {
3765 const int row_4x4 = row_start_4x4 + i;
3766 const int col_4x4 = col_start_4x4 + j;
3767 const int unit_index = row_4x4 * num_unit_cols + col_4x4;
3768 if (row_4x4 >= num_unit_rows || col_4x4 >= num_unit_cols) continue;
3769 if (source_ref_frame[1] == NONE) {
3770 assert(source_mv[1]->row == 0 && source_mv[1]->col == 0);
3772 motion_vector_info[unit_index].ref_frame[0] = source_ref_frame[0];
3773 motion_vector_info[unit_index].ref_frame[1] = source_ref_frame[1];
3774 motion_vector_info[unit_index].mv[0].as_mv.row = source_mv[0]->row;
3775 motion_vector_info[unit_index].mv[0].as_mv.col = source_mv[0]->col;
3776 motion_vector_info[unit_index].mv[1].as_mv.row = source_mv[1]->row;
3777 motion_vector_info[unit_index].mv[1].as_mv.col = source_mv[1]->col;
3782 static void store_superblock_info(
3783 const PC_TREE *const pc_tree, MODE_INFO **mi_grid_visible,
3784 const int mi_stride, const int square_size_4x4, const int num_unit_rows,
3785 const int num_unit_cols, const int row_start_4x4, const int col_start_4x4,
3786 PARTITION_INFO *partition_info, MOTION_VECTOR_INFO *motion_vector_info) {
3787 const int subblock_square_size_4x4 = square_size_4x4 >> 1;
3788 if (row_start_4x4 >= num_unit_rows || col_start_4x4 >= num_unit_cols) return;
3789 assert(pc_tree->partitioning != PARTITION_INVALID);
3790 // End node, no split.
3791 if (pc_tree->partitioning == PARTITION_NONE ||
3792 pc_tree->partitioning == PARTITION_HORZ ||
3793 pc_tree->partitioning == PARTITION_VERT || square_size_4x4 == 1) {
3794 const int mi_row = row_start_4x4 >> 1;
3795 const int mi_col = col_start_4x4 >> 1;
3796 const int mi_idx = mi_stride * mi_row + mi_col;
3797 MODE_INFO **mi = mi_grid_visible + mi_idx;
3799 MV_REFERENCE_FRAME source_ref_frame[2];
3802 const int block_width_4x4 = (pc_tree->partitioning == PARTITION_VERT)
3803 ? square_size_4x4 >> 1
3805 const int block_height_4x4 = (pc_tree->partitioning == PARTITION_HORZ)
3806 ? square_size_4x4 >> 1
3808 assign_partition_info(row_start_4x4, col_start_4x4, block_width_4x4,
3809 block_height_4x4, num_unit_rows, num_unit_cols,
3811 if (pc_tree->partitioning == PARTITION_VERT) {
3812 assign_partition_info(row_start_4x4, col_start_4x4 + block_width_4x4,
3813 block_width_4x4, block_height_4x4, num_unit_rows,
3814 num_unit_cols, partition_info);
3815 } else if (pc_tree->partitioning == PARTITION_HORZ) {
3816 assign_partition_info(row_start_4x4 + block_height_4x4, col_start_4x4,
3817 block_width_4x4, block_height_4x4, num_unit_rows,
3818 num_unit_cols, partition_info);
3821 // motion vector info
3822 if (pc_tree->partitioning == PARTITION_HORZ) {
3823 int is_valid_second_rectangle = 0;
3824 assert(square_size_4x4 > 1);
3826 source_ref_frame[0] = mi[0]->ref_frame[0];
3827 source_ref_frame[1] = mi[0]->ref_frame[1];
3828 source_mv[0] = &mi[0]->mv[0].as_mv;
3829 source_mv[1] = &mi[0]->mv[1].as_mv;
3830 assign_motion_vector_info(block_width_4x4, block_height_4x4,
3831 row_start_4x4, col_start_4x4, num_unit_rows,
3832 num_unit_cols, source_mv, source_ref_frame,
3833 motion_vector_info);
3834 // Second rectangle.
3835 if (square_size_4x4 == 2) {
3836 is_valid_second_rectangle = 1;
3837 source_ref_frame[0] = mi[0]->ref_frame[0];
3838 source_ref_frame[1] = mi[0]->ref_frame[1];
3839 source_mv[0] = &mi[0]->bmi[2].as_mv[0].as_mv;
3840 source_mv[1] = &mi[0]->bmi[2].as_mv[1].as_mv;
3842 const int mi_row_2 = mi_row + (block_height_4x4 >> 1);
3843 const int mi_col_2 = mi_col;
3844 if (mi_row_2 * 2 < num_unit_rows && mi_col_2 * 2 < num_unit_cols) {
3845 const int mi_idx_2 = mi_stride * mi_row_2 + mi_col_2;
3846 is_valid_second_rectangle = 1;
3847 mi = mi_grid_visible + mi_idx_2;
3848 source_ref_frame[0] = mi[0]->ref_frame[0];
3849 source_ref_frame[1] = mi[0]->ref_frame[1];
3850 source_mv[0] = &mi[0]->mv[0].as_mv;
3851 source_mv[1] = &mi[0]->mv[1].as_mv;
3854 if (is_valid_second_rectangle) {
3855 assign_motion_vector_info(
3856 block_width_4x4, block_height_4x4, row_start_4x4 + block_height_4x4,
3857 col_start_4x4, num_unit_rows, num_unit_cols, source_mv,
3858 source_ref_frame, motion_vector_info);
3860 } else if (pc_tree->partitioning == PARTITION_VERT) {
3861 int is_valid_second_rectangle = 0;
3862 assert(square_size_4x4 > 1);
3864 source_ref_frame[0] = mi[0]->ref_frame[0];
3865 source_ref_frame[1] = mi[0]->ref_frame[1];
3866 source_mv[0] = &mi[0]->mv[0].as_mv;
3867 source_mv[1] = &mi[0]->mv[1].as_mv;
3868 assign_motion_vector_info(block_width_4x4, block_height_4x4,
3869 row_start_4x4, col_start_4x4, num_unit_rows,
3870 num_unit_cols, source_mv, source_ref_frame,
3871 motion_vector_info);
3872 // Second rectangle.
3873 if (square_size_4x4 == 2) {
3874 is_valid_second_rectangle = 1;
3875 source_ref_frame[0] = mi[0]->ref_frame[0];
3876 source_ref_frame[1] = mi[0]->ref_frame[1];
3877 source_mv[0] = &mi[0]->bmi[1].as_mv[0].as_mv;
3878 source_mv[1] = &mi[0]->bmi[1].as_mv[1].as_mv;
3880 const int mi_row_2 = mi_row;
3881 const int mi_col_2 = mi_col + (block_width_4x4 >> 1);
3882 if (mi_row_2 * 2 < num_unit_rows && mi_col_2 * 2 < num_unit_cols) {
3883 const int mi_idx_2 = mi_stride * mi_row_2 + mi_col_2;
3884 is_valid_second_rectangle = 1;
3885 mi = mi_grid_visible + mi_idx_2;
3886 source_ref_frame[0] = mi[0]->ref_frame[0];
3887 source_ref_frame[1] = mi[0]->ref_frame[1];
3888 source_mv[0] = &mi[0]->mv[0].as_mv;
3889 source_mv[1] = &mi[0]->mv[1].as_mv;
3892 if (is_valid_second_rectangle) {
3893 assign_motion_vector_info(
3894 block_width_4x4, block_height_4x4, row_start_4x4,
3895 col_start_4x4 + block_width_4x4, num_unit_rows, num_unit_cols,
3896 source_mv, source_ref_frame, motion_vector_info);
3899 assert(pc_tree->partitioning == PARTITION_NONE || square_size_4x4 == 1);
3900 source_ref_frame[0] = mi[0]->ref_frame[0];
3901 source_ref_frame[1] = mi[0]->ref_frame[1];
3902 if (square_size_4x4 == 1) {
3903 const int sub8x8_row = row_start_4x4 % 2;
3904 const int sub8x8_col = col_start_4x4 % 2;
3905 const int sub8x8_idx = sub8x8_row * 2 + sub8x8_col;
3906 source_mv[0] = &mi[0]->bmi[sub8x8_idx].as_mv[0].as_mv;
3907 source_mv[1] = &mi[0]->bmi[sub8x8_idx].as_mv[1].as_mv;
3909 source_mv[0] = &mi[0]->mv[0].as_mv;
3910 source_mv[1] = &mi[0]->mv[1].as_mv;
3912 assign_motion_vector_info(block_width_4x4, block_height_4x4,
3913 row_start_4x4, col_start_4x4, num_unit_rows,
3914 num_unit_cols, source_mv, source_ref_frame,
3915 motion_vector_info);
3920 // recursively traverse partition tree when partition is split.
3921 assert(pc_tree->partitioning == PARTITION_SPLIT);
3922 store_superblock_info(pc_tree->split[0], mi_grid_visible, mi_stride,
3923 subblock_square_size_4x4, num_unit_rows, num_unit_cols,
3924 row_start_4x4, col_start_4x4, partition_info,
3925 motion_vector_info);
3926 store_superblock_info(pc_tree->split[1], mi_grid_visible, mi_stride,
3927 subblock_square_size_4x4, num_unit_rows, num_unit_cols,
3928 row_start_4x4, col_start_4x4 + subblock_square_size_4x4,
3929 partition_info, motion_vector_info);
3930 store_superblock_info(pc_tree->split[2], mi_grid_visible, mi_stride,
3931 subblock_square_size_4x4, num_unit_rows, num_unit_cols,
3932 row_start_4x4 + subblock_square_size_4x4, col_start_4x4,
3933 partition_info, motion_vector_info);
3934 store_superblock_info(pc_tree->split[3], mi_grid_visible, mi_stride,
3935 subblock_square_size_4x4, num_unit_rows, num_unit_cols,
3936 row_start_4x4 + subblock_square_size_4x4,
3937 col_start_4x4 + subblock_square_size_4x4,
3938 partition_info, motion_vector_info);
3940 #endif // CONFIG_RATE_CTRL
3942 #if !CONFIG_REALTIME_ONLY
3943 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
3944 // unlikely to be selected depending on previous rate-distortion optimization
3945 // results, for encoding speed-up.
3946 static int rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3947 TileDataEnc *tile_data, TOKENEXTRA **tp,
3948 int mi_row, int mi_col, BLOCK_SIZE bsize,
3949 RD_COST *rd_cost, RD_COST best_rdc,
3951 VP9_COMMON *const cm = &cpi->common;
3952 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3953 TileInfo *const tile_info = &tile_data->tile_info;
3954 MACROBLOCK *const x = &td->mb;
3955 MACROBLOCKD *const xd = &x->e_mbd;
3956 const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
3957 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
3958 PARTITION_CONTEXT sl[8], sa[8];
3959 TOKENEXTRA *tp_orig = *tp;
3960 PICK_MODE_CONTEXT *const ctx = &pc_tree->none;
3962 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3964 RD_COST this_rdc, sum_rdc;
3965 int do_split = bsize >= BLOCK_8X8;
3967 INTERP_FILTER pred_interp_filter;
3969 // Override skipping rectangular partition operations for edge blocks
3970 const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
3971 const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
3972 const int xss = x->e_mbd.plane[1].subsampling_x;
3973 const int yss = x->e_mbd.plane[1].subsampling_y;
3975 BLOCK_SIZE min_size = x->min_partition_size;
3976 BLOCK_SIZE max_size = x->max_partition_size;
3978 int partition_none_allowed = !force_horz_split && !force_vert_split;
3979 int partition_horz_allowed =
3980 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
3981 int partition_vert_allowed =
3982 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
3984 int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_thr.dist;
3985 int rate_breakout_thr = cpi->sf.partition_search_breakout_thr.rate;
3987 int should_encode_sb = 0;
3989 // Ref frames picked in the [i_th] quarter subblock during square partition
3990 // RD search. It may be used to prune ref frame selection of rect partitions.
3991 uint8_t ref_frames_used[4] = { 0, 0, 0, 0 };
3993 int partition_mul = x->cb_rdmult;
3997 assert(num_8x8_blocks_wide_lookup[bsize] ==
3998 num_8x8_blocks_high_lookup[bsize]);
4000 dist_breakout_thr >>=
4001 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4003 rate_breakout_thr *= num_pels_log2_lookup[bsize];
4005 vp9_rd_cost_init(&this_rdc);
4006 vp9_rd_cost_init(&sum_rdc);
4008 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4010 if (oxcf->tuning == VP8_TUNE_SSIM) {
4011 set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &partition_mul);
4013 vp9_rd_cost_update(partition_mul, x->rddiv, &best_rdc);
4015 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ &&
4016 cpi->oxcf.aq_mode != LOOKAHEAD_AQ)
4017 x->mb_energy = vp9_block_energy(cpi, x, bsize);
4019 if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
4020 int cb_partition_search_ctrl =
4021 ((pc_tree->index == 0 || pc_tree->index == 3) +
4022 get_chessboard_index(cm->current_video_frame)) &
4025 if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
4026 set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
4029 // Get sub block energy range
4030 if (bsize >= BLOCK_16X16) {
4031 int min_energy, max_energy;
4032 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
4034 must_split = (min_energy < -3) && (max_energy - min_energy > 2);
4037 // Determine partition types in search according to the speed features.
4038 // The threshold set here has to be of square block size.
4039 if (cpi->sf.auto_min_max_partition_size) {
4040 partition_none_allowed &= (bsize <= max_size);
4041 partition_horz_allowed &=
4042 ((bsize <= max_size && bsize > min_size) || force_horz_split);
4043 partition_vert_allowed &=
4044 ((bsize <= max_size && bsize > min_size) || force_vert_split);
4045 do_split &= bsize > min_size;
4048 if (cpi->sf.use_square_partition_only &&
4049 (bsize > cpi->sf.use_square_only_thresh_high ||
4050 bsize < cpi->sf.use_square_only_thresh_low)) {
4052 if (!vp9_active_h_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
4053 partition_horz_allowed &= force_horz_split;
4054 if (!vp9_active_v_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
4055 partition_vert_allowed &= force_vert_split;
4057 partition_horz_allowed &= force_horz_split;
4058 partition_vert_allowed &= force_vert_split;
4062 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4064 pc_tree->partitioning = PARTITION_NONE;
4066 if (cpi->sf.rd_ml_partition.var_pruning && !frame_is_intra_only(cm)) {
4067 const int do_rd_ml_partition_var_pruning =
4068 partition_none_allowed && do_split &&
4069 mi_row + num_8x8_blocks_high_lookup[bsize] <= cm->mi_rows &&
4070 mi_col + num_8x8_blocks_wide_lookup[bsize] <= cm->mi_cols;
4071 if (do_rd_ml_partition_var_pruning) {
4072 ml_predict_var_rd_paritioning(cpi, x, pc_tree, bsize, mi_row, mi_col,
4073 &partition_none_allowed, &do_split);
4075 vp9_zero(pc_tree->mv);
4077 if (bsize > BLOCK_8X8) { // Store MV result as reference for subblocks.
4078 for (i = 0; i < 4; ++i) pc_tree->split[i]->mv = pc_tree->mv;
4083 if (partition_none_allowed) {
4084 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize, ctx,
4085 best_rdc.rate, best_rdc.dist);
4086 ctx->rdcost = this_rdc.rdcost;
4087 if (this_rdc.rate != INT_MAX) {
4088 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4089 const int ref1 = ctx->mic.ref_frame[0];
4090 const int ref2 = ctx->mic.ref_frame[1];
4091 for (i = 0; i < 4; ++i) {
4092 ref_frames_used[i] |= (1 << ref1);
4093 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4096 if (bsize >= BLOCK_8X8) {
4097 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4098 vp9_rd_cost_update(partition_mul, x->rddiv, &this_rdc);
4101 if (this_rdc.rdcost < best_rdc.rdcost) {
4102 MODE_INFO *mi = xd->mi[0];
4104 best_rdc = this_rdc;
4105 should_encode_sb = 1;
4106 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4108 if (cpi->sf.rd_ml_partition.search_early_termination) {
4109 // Currently, the machine-learning based partition search early
4110 // termination is only used while bsize is 16x16, 32x32 or 64x64,
4111 // VPXMIN(cm->width, cm->height) >= 480, and speed = 0.
4112 if (!x->e_mbd.lossless &&
4113 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP) &&
4114 ctx->mic.mode >= INTRA_MODES && bsize >= BLOCK_16X16) {
4115 if (ml_pruning_partition(cm, xd, ctx, mi_row, mi_col, bsize)) {
4122 if ((do_split || do_rect) && !x->e_mbd.lossless && ctx->skippable) {
4123 const int use_ml_based_breakout =
4124 cpi->sf.rd_ml_partition.search_breakout && cm->base_qindex >= 100;
4125 if (use_ml_based_breakout) {
4126 if (ml_predict_breakout(cpi, bsize, x, &this_rdc)) {
4131 if (!cpi->sf.rd_ml_partition.search_early_termination) {
4132 if ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4133 (best_rdc.dist < dist_breakout_thr &&
4134 best_rdc.rate < rate_breakout_thr)) {
4143 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4145 vp9_zero(ctx->pred_mv);
4146 ctx->mic.interp_filter = EIGHTTAP;
4149 // store estimated motion vector
4150 store_pred_mv(x, ctx);
4152 // If the interp_filter is marked as SWITCHABLE_FILTERS, it was for an
4153 // intra block and used for context purposes.
4154 if (ctx->mic.interp_filter == SWITCHABLE_FILTERS) {
4155 pred_interp_filter = EIGHTTAP;
4157 pred_interp_filter = ctx->mic.interp_filter;
4161 // TODO(jingning): use the motion vectors given by the above search as
4162 // the starting point of motion search in the following partition type check.
4163 pc_tree->split[0]->none.rdcost = 0;
4164 pc_tree->split[1]->none.rdcost = 0;
4165 pc_tree->split[2]->none.rdcost = 0;
4166 pc_tree->split[3]->none.rdcost = 0;
4167 if (do_split || must_split) {
4168 subsize = get_subsize(bsize, PARTITION_SPLIT);
4169 load_pred_mv(x, ctx);
4170 if (bsize == BLOCK_8X8) {
4172 if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
4173 pc_tree->leaf_split[0]->pred_interp_filter = pred_interp_filter;
4174 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4175 pc_tree->leaf_split[0], best_rdc.rate, best_rdc.dist);
4176 if (sum_rdc.rate == INT_MAX) {
4177 sum_rdc.rdcost = INT64_MAX;
4179 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4180 const int ref1 = pc_tree->leaf_split[0]->mic.ref_frame[0];
4181 const int ref2 = pc_tree->leaf_split[0]->mic.ref_frame[1];
4182 for (i = 0; i < 4; ++i) {
4183 ref_frames_used[i] |= (1 << ref1);
4184 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4189 for (i = 0; (i < 4) && ((sum_rdc.rdcost < best_rdc.rdcost) || must_split);
4191 const int x_idx = (i & 1) * mi_step;
4192 const int y_idx = (i >> 1) * mi_step;
4193 int found_best_rd = 0;
4194 RD_COST best_rdc_split;
4195 vp9_rd_cost_reset(&best_rdc_split);
4197 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX) {
4198 // A must split test here increases the number of sub
4199 // partitions but hurts metrics results quite a bit,
4200 // so this extra test is commented out pending
4201 // further tests on whether it adds much in terms of
4203 // (must_split) ? best_rdc.rate
4204 // : best_rdc.rate - sum_rdc.rate,
4205 // (must_split) ? best_rdc.dist
4206 // : best_rdc.dist - sum_rdc.dist,
4207 best_rdc_split.rate = best_rdc.rate - sum_rdc.rate;
4208 best_rdc_split.dist = best_rdc.dist - sum_rdc.dist;
4211 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4214 pc_tree->split[i]->index = i;
4215 if (cpi->sf.prune_ref_frame_for_rect_partitions)
4216 pc_tree->split[i]->none.rate = INT_MAX;
4217 found_best_rd = rd_pick_partition(
4218 cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx, subsize,
4219 &this_rdc, best_rdc_split, pc_tree->split[i]);
4221 if (found_best_rd == 0) {
4222 sum_rdc.rdcost = INT64_MAX;
4225 if (cpi->sf.prune_ref_frame_for_rect_partitions &&
4226 pc_tree->split[i]->none.rate != INT_MAX) {
4227 const int ref1 = pc_tree->split[i]->none.mic.ref_frame[0];
4228 const int ref2 = pc_tree->split[i]->none.mic.ref_frame[1];
4229 ref_frames_used[i] |= (1 << ref1);
4230 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4232 sum_rdc.rate += this_rdc.rate;
4233 sum_rdc.dist += this_rdc.dist;
4234 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4239 if (((sum_rdc.rdcost < best_rdc.rdcost) || must_split) && i == 4) {
4240 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4241 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4243 if ((sum_rdc.rdcost < best_rdc.rdcost) ||
4244 (must_split && (sum_rdc.dist < best_rdc.dist))) {
4246 should_encode_sb = 1;
4247 pc_tree->partitioning = PARTITION_SPLIT;
4249 // Rate and distortion based partition search termination clause.
4250 if (!cpi->sf.rd_ml_partition.search_early_termination &&
4251 !x->e_mbd.lossless &&
4252 ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4253 (best_rdc.dist < dist_breakout_thr &&
4254 best_rdc.rate < rate_breakout_thr))) {
4259 // skip rectangular partition test when larger block size
4260 // gives better rd cost
4261 if (cpi->sf.less_rectangular_check &&
4262 (bsize > cpi->sf.use_square_only_thresh_high ||
4263 best_rdc.dist < dist_breakout_thr))
4264 do_rect &= !partition_none_allowed;
4266 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4269 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
4270 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
4271 pc_tree->vertical[0].skip_ref_frame_mask = 0;
4272 pc_tree->vertical[1].skip_ref_frame_mask = 0;
4273 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4274 uint8_t used_frames;
4275 used_frames = ref_frames_used[0] | ref_frames_used[1];
4277 pc_tree->horizontal[0].skip_ref_frame_mask = ~used_frames & 0xff;
4279 used_frames = ref_frames_used[2] | ref_frames_used[3];
4281 pc_tree->horizontal[1].skip_ref_frame_mask = ~used_frames & 0xff;
4283 used_frames = ref_frames_used[0] | ref_frames_used[2];
4285 pc_tree->vertical[0].skip_ref_frame_mask = ~used_frames & 0xff;
4287 used_frames = ref_frames_used[1] | ref_frames_used[3];
4289 pc_tree->vertical[1].skip_ref_frame_mask = ~used_frames & 0xff;
4294 const int do_ml_rect_partition_pruning =
4295 !frame_is_intra_only(cm) && !force_horz_split && !force_vert_split &&
4296 (partition_horz_allowed || partition_vert_allowed) && bsize > BLOCK_8X8;
4297 if (do_ml_rect_partition_pruning) {
4298 ml_prune_rect_partition(cpi, x, bsize, pc_tree, &partition_horz_allowed,
4299 &partition_vert_allowed, best_rdc.rdcost);
4304 if (partition_horz_allowed &&
4305 (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
4306 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_HORZ];
4307 subsize = get_subsize(bsize, PARTITION_HORZ);
4308 load_pred_mv(x, ctx);
4309 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4310 partition_none_allowed)
4311 pc_tree->horizontal[0].pred_interp_filter = pred_interp_filter;
4312 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4313 &pc_tree->horizontal[0], best_rdc.rate - part_mode_rate,
4315 if (sum_rdc.rdcost < INT64_MAX) {
4316 sum_rdc.rate += part_mode_rate;
4317 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4320 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
4321 bsize > BLOCK_8X8) {
4322 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
4323 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
4324 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
4325 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4326 partition_none_allowed)
4327 pc_tree->horizontal[1].pred_interp_filter = pred_interp_filter;
4328 rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col, &this_rdc,
4329 subsize, &pc_tree->horizontal[1],
4330 best_rdc.rate - sum_rdc.rate,
4331 best_rdc.dist - sum_rdc.dist);
4332 if (this_rdc.rate == INT_MAX) {
4333 sum_rdc.rdcost = INT64_MAX;
4335 sum_rdc.rate += this_rdc.rate;
4336 sum_rdc.dist += this_rdc.dist;
4337 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4341 if (sum_rdc.rdcost < best_rdc.rdcost) {
4343 should_encode_sb = 1;
4344 pc_tree->partitioning = PARTITION_HORZ;
4346 if (cpi->sf.less_rectangular_check &&
4347 bsize > cpi->sf.use_square_only_thresh_high)
4350 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4354 if (partition_vert_allowed &&
4355 (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
4356 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_VERT];
4357 subsize = get_subsize(bsize, PARTITION_VERT);
4358 load_pred_mv(x, ctx);
4359 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4360 partition_none_allowed)
4361 pc_tree->vertical[0].pred_interp_filter = pred_interp_filter;
4362 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4363 &pc_tree->vertical[0], best_rdc.rate - part_mode_rate,
4365 if (sum_rdc.rdcost < INT64_MAX) {
4366 sum_rdc.rate += part_mode_rate;
4367 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4370 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
4371 bsize > BLOCK_8X8) {
4372 update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
4373 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
4374 &pc_tree->vertical[0]);
4375 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4376 partition_none_allowed)
4377 pc_tree->vertical[1].pred_interp_filter = pred_interp_filter;
4378 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step, &this_rdc,
4379 subsize, &pc_tree->vertical[1],
4380 best_rdc.rate - sum_rdc.rate,
4381 best_rdc.dist - sum_rdc.dist);
4382 if (this_rdc.rate == INT_MAX) {
4383 sum_rdc.rdcost = INT64_MAX;
4385 sum_rdc.rate += this_rdc.rate;
4386 sum_rdc.dist += this_rdc.dist;
4387 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4391 if (sum_rdc.rdcost < best_rdc.rdcost) {
4393 should_encode_sb = 1;
4394 pc_tree->partitioning = PARTITION_VERT;
4396 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4399 *rd_cost = best_rdc;
4401 if (should_encode_sb && pc_tree->index != 3) {
4402 int output_enabled = (bsize == BLOCK_64X64);
4403 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4405 #if CONFIG_RATE_CTRL
4406 if (oxcf->use_simple_encode_api) {
4407 // Store partition, motion vector of the superblock.
4408 if (output_enabled) {
4409 const int num_unit_rows =
4410 get_num_unit_4x4(cpi->frame_info.frame_height);
4411 const int num_unit_cols = get_num_unit_4x4(cpi->frame_info.frame_width);
4412 store_superblock_info(pc_tree, cm->mi_grid_visible, cm->mi_stride,
4413 num_4x4_blocks_wide_lookup[BLOCK_64X64],
4414 num_unit_rows, num_unit_cols, mi_row << 1,
4415 mi_col << 1, cpi->partition_info,
4416 cpi->motion_vector_info);
4419 #endif // CONFIG_RATE_CTRL
4422 if (bsize == BLOCK_64X64) {
4423 assert(tp_orig < *tp);
4424 assert(best_rdc.rate < INT_MAX);
4425 assert(best_rdc.dist < INT64_MAX);
4427 assert(tp_orig == *tp);
4430 return should_encode_sb;
4433 static void encode_rd_sb_row(VP9_COMP *cpi, ThreadData *td,
4434 TileDataEnc *tile_data, int mi_row,
4436 VP9_COMMON *const cm = &cpi->common;
4437 TileInfo *const tile_info = &tile_data->tile_info;
4438 MACROBLOCK *const x = &td->mb;
4439 MACROBLOCKD *const xd = &x->e_mbd;
4440 SPEED_FEATURES *const sf = &cpi->sf;
4441 const int mi_col_start = tile_info->mi_col_start;
4442 const int mi_col_end = tile_info->mi_col_end;
4444 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
4445 const int num_sb_cols =
4446 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
4449 // Initialize the left context for the new SB row
4450 memset(&xd->left_context, 0, sizeof(xd->left_context));
4451 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
4453 // Code each SB in the row
4454 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
4455 mi_col += MI_BLOCK_SIZE, sb_col_in_tile++) {
4456 const struct segmentation *const seg = &cm->seg;
4462 int orig_rdmult = cpi->rd.RDMULT;
4464 const int idx_str = cm->mi_stride * mi_row + mi_col;
4465 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
4467 vp9_rd_cost_reset(&dummy_rdc);
4468 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
4471 if (sf->adaptive_pred_interp_filter) {
4472 for (i = 0; i < 64; ++i) td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
4474 for (i = 0; i < 64; ++i) {
4475 td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
4476 td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
4477 td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
4478 td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
4482 for (i = 0; i < MAX_REF_FRAMES; ++i) {
4483 x->pred_mv[i].row = INT16_MAX;
4484 x->pred_mv[i].col = INT16_MAX;
4486 td->pc_root->index = 0;
4489 const uint8_t *const map =
4490 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
4491 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
4492 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
4495 x->source_variance = UINT_MAX;
4497 x->cb_rdmult = orig_rdmult;
4499 if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
4500 const BLOCK_SIZE bsize =
4501 seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
4502 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4503 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4504 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4505 &dummy_rate, &dummy_dist, 1, td->pc_root);
4506 } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
4507 cm->frame_type != KEY_FRAME) {
4508 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
4509 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4510 &dummy_rate, &dummy_dist, 1, td->pc_root);
4512 if (cpi->twopass.gf_group.index > 0 && cpi->sf.enable_tpl_model) {
4514 get_rdmult_delta(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4518 if (cpi->oxcf.aq_mode == PERCEPTUAL_AQ && cm->show_frame) {
4519 x->segment_id = wiener_var_segment(cpi, BLOCK_64X64, mi_row, mi_col);
4520 x->cb_rdmult = vp9_compute_rd_mult(
4521 cpi, vp9_get_qindex(&cm->seg, x->segment_id, cm->base_qindex));
4524 // If required set upper and lower partition size limits
4525 if (sf->auto_min_max_partition_size) {
4526 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4527 rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
4528 &x->min_partition_size, &x->max_partition_size);
4530 td->pc_root->none.rdcost = 0;
4531 rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
4532 &dummy_rdc, dummy_rdc, td->pc_root);
4534 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
4535 sb_col_in_tile, num_sb_cols);
4538 #endif // !CONFIG_REALTIME_ONLY
4540 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
4541 MACROBLOCK *const x = &cpi->td.mb;
4542 VP9_COMMON *const cm = &cpi->common;
4543 MACROBLOCKD *const xd = &x->e_mbd;
4544 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
4546 // Copy data over into macro block data structures.
4547 vp9_setup_src_planes(x, cpi->Source, 0, 0);
4549 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
4551 // Note: this memset assumes above_context[0], [1] and [2]
4552 // are allocated as part of the same buffer.
4553 memset(xd->above_context[0], 0,
4554 sizeof(*xd->above_context[0]) * 2 * aligned_mi_cols * MAX_MB_PLANE);
4555 memset(xd->above_seg_context, 0,
4556 sizeof(*xd->above_seg_context) * aligned_mi_cols);
4559 static int check_dual_ref_flags(VP9_COMP *cpi) {
4560 const int ref_flags = cpi->ref_frame_flags;
4562 if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
4565 return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG) +
4566 !!(ref_flags & VP9_ALT_FLAG)) >= 2;
4570 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
4572 const int mis = cm->mi_stride;
4573 MODE_INFO **mi_ptr = cm->mi_grid_visible;
4575 for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
4576 for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
4577 if (mi_ptr[mi_col]->tx_size > max_tx_size)
4578 mi_ptr[mi_col]->tx_size = max_tx_size;
4583 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
4584 if (frame_is_intra_only(&cpi->common))
4586 else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
4587 return ALTREF_FRAME;
4588 else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
4589 return GOLDEN_FRAME;
4594 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
4595 if (xd->lossless) return ONLY_4X4;
4596 if (cpi->common.frame_type == KEY_FRAME && cpi->sf.use_nonrd_pick_mode)
4598 if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
4600 else if (cpi->sf.tx_size_search_method == USE_FULL_RD ||
4601 cpi->sf.tx_size_search_method == USE_TX_8X8)
4602 return TX_MODE_SELECT;
4604 return cpi->common.tx_mode;
4607 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
4608 RD_COST *rd_cost, BLOCK_SIZE bsize,
4609 PICK_MODE_CONTEXT *ctx) {
4610 if (!cpi->sf.nonrd_keyframe && bsize < BLOCK_16X16)
4611 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4613 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4616 static void hybrid_search_svc_baseiskey(VP9_COMP *cpi, MACROBLOCK *const x,
4617 RD_COST *rd_cost, BLOCK_SIZE bsize,
4618 PICK_MODE_CONTEXT *ctx,
4619 TileDataEnc *tile_data, int mi_row,
4621 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4622 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4624 if (cpi->svc.disable_inter_layer_pred == INTER_LAYER_PRED_OFF)
4625 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4626 else if (bsize >= BLOCK_8X8)
4627 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4630 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4634 static void hybrid_search_scene_change(VP9_COMP *cpi, MACROBLOCK *const x,
4635 RD_COST *rd_cost, BLOCK_SIZE bsize,
4636 PICK_MODE_CONTEXT *ctx,
4637 TileDataEnc *tile_data, int mi_row,
4639 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4640 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4642 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize, ctx);
4646 static void nonrd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
4647 MACROBLOCK *const x, int mi_row, int mi_col,
4648 RD_COST *rd_cost, BLOCK_SIZE bsize,
4649 PICK_MODE_CONTEXT *ctx) {
4650 VP9_COMMON *const cm = &cpi->common;
4651 TileInfo *const tile_info = &tile_data->tile_info;
4652 MACROBLOCKD *const xd = &x->e_mbd;
4654 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
4655 BLOCK_SIZE bs = VPXMAX(bsize, BLOCK_8X8); // processing unit block size
4656 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bs];
4657 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bs];
4660 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4662 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
4665 mi->sb_type = bsize;
4667 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4668 struct macroblockd_plane *pd = &xd->plane[plane];
4669 memcpy(a + num_4x4_blocks_wide * plane, pd->above_context,
4670 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4671 memcpy(l + num_4x4_blocks_high * plane, pd->left_context,
4672 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4675 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
4676 if (cyclic_refresh_segment_id_boosted(mi->segment_id))
4677 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
4679 if (frame_is_intra_only(cm))
4680 hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
4681 else if (cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
4682 hybrid_search_svc_baseiskey(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4684 else if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
4685 set_mode_info_seg_skip(x, cm->tx_mode, rd_cost, bsize);
4686 else if (bsize >= BLOCK_8X8) {
4687 if (cpi->rc.hybrid_intra_scene_change)
4688 hybrid_search_scene_change(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4691 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4694 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4697 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4699 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4700 struct macroblockd_plane *pd = &xd->plane[plane];
4701 memcpy(pd->above_context, a + num_4x4_blocks_wide * plane,
4702 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4703 memcpy(pd->left_context, l + num_4x4_blocks_high * plane,
4704 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4707 if (rd_cost->rate == INT_MAX) vp9_rd_cost_reset(rd_cost);
4709 ctx->rate = rd_cost->rate;
4710 ctx->dist = rd_cost->dist;
4713 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x, int mi_row,
4714 int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4715 MACROBLOCKD *xd = &x->e_mbd;
4716 int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4717 PARTITION_TYPE partition = pc_tree->partitioning;
4718 BLOCK_SIZE subsize = get_subsize(bsize, partition);
4720 assert(bsize >= BLOCK_8X8);
4722 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4724 switch (partition) {
4725 case PARTITION_NONE:
4726 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4727 *(xd->mi[0]) = pc_tree->none.mic;
4728 *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
4729 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4731 case PARTITION_VERT:
4732 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4733 *(xd->mi[0]) = pc_tree->vertical[0].mic;
4734 *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
4735 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4737 if (mi_col + hbs < cm->mi_cols) {
4738 set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
4739 *(xd->mi[0]) = pc_tree->vertical[1].mic;
4740 *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
4741 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
4744 case PARTITION_HORZ:
4745 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4746 *(xd->mi[0]) = pc_tree->horizontal[0].mic;
4747 *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
4748 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4749 if (mi_row + hbs < cm->mi_rows) {
4750 set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
4751 *(xd->mi[0]) = pc_tree->horizontal[1].mic;
4752 *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
4753 duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
4756 case PARTITION_SPLIT: {
4757 fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
4758 fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
4760 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
4762 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
4770 // Reset the prediction pixel ready flag recursively.
4771 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
4772 pc_tree->none.pred_pixel_ready = 0;
4773 pc_tree->horizontal[0].pred_pixel_ready = 0;
4774 pc_tree->horizontal[1].pred_pixel_ready = 0;
4775 pc_tree->vertical[0].pred_pixel_ready = 0;
4776 pc_tree->vertical[1].pred_pixel_ready = 0;
4778 if (bsize > BLOCK_8X8) {
4779 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4781 for (i = 0; i < 4; ++i) pred_pixel_ready_reset(pc_tree->split[i], subsize);
4787 static int ml_predict_var_paritioning(VP9_COMP *cpi, MACROBLOCK *x,
4788 BLOCK_SIZE bsize, int mi_row,
4790 VP9_COMMON *const cm = &cpi->common;
4791 const NN_CONFIG *nn_config = NULL;
4794 case BLOCK_64X64: nn_config = &vp9_var_part_nnconfig_64; break;
4795 case BLOCK_32X32: nn_config = &vp9_var_part_nnconfig_32; break;
4796 case BLOCK_16X16: nn_config = &vp9_var_part_nnconfig_16; break;
4797 case BLOCK_8X8: break;
4798 default: assert(0 && "Unexpected block size."); return -1;
4801 if (!nn_config) return -1;
4803 vpx_clear_system_state();
4806 const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
4807 float features[FEATURES] = { 0.0f };
4808 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
4809 int feature_idx = 0;
4810 float score[LABELS];
4812 features[feature_idx++] = logf((float)(dc_q * dc_q) / 256.0f + 1.0f);
4813 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
4815 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
4816 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4817 const int sb_offset_row = 8 * (mi_row & 7);
4818 const int sb_offset_col = 8 * (mi_col & 7);
4819 const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
4820 const uint8_t *src = x->plane[0].src.buf;
4821 const int src_stride = x->plane[0].src.stride;
4822 const int pred_stride = 64;
4825 // Variance of whole block.
4826 const unsigned int var =
4827 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
4828 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
4830 features[feature_idx++] = logf((float)var + 1.0f);
4831 for (i = 0; i < 4; ++i) {
4832 const int x_idx = (i & 1) * bs / 2;
4833 const int y_idx = (i >> 1) * bs / 2;
4834 const int src_offset = y_idx * src_stride + x_idx;
4835 const int pred_offset = y_idx * pred_stride + x_idx;
4836 // Variance of quarter block.
4837 const unsigned int sub_var =
4838 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
4839 pred + pred_offset, pred_stride, &sse);
4840 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
4841 features[feature_idx++] = var_ratio;
4845 assert(feature_idx == FEATURES);
4846 nn_predict(features, nn_config, score);
4847 if (score[0] > thresh) return PARTITION_SPLIT;
4848 if (score[0] < -thresh) return PARTITION_NONE;
4855 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
4856 TileDataEnc *tile_data, TOKENEXTRA **tp,
4857 int mi_row, int mi_col, BLOCK_SIZE bsize,
4858 RD_COST *rd_cost, int do_recon,
4859 int64_t best_rd, PC_TREE *pc_tree) {
4860 const SPEED_FEATURES *const sf = &cpi->sf;
4861 VP9_COMMON *const cm = &cpi->common;
4862 TileInfo *const tile_info = &tile_data->tile_info;
4863 MACROBLOCK *const x = &td->mb;
4864 MACROBLOCKD *const xd = &x->e_mbd;
4865 const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
4866 TOKENEXTRA *tp_orig = *tp;
4867 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
4869 BLOCK_SIZE subsize = bsize;
4870 RD_COST this_rdc, sum_rdc, best_rdc;
4871 int do_split = bsize >= BLOCK_8X8;
4873 // Override skipping rectangular partition operations for edge blocks
4874 const int force_horz_split = (mi_row + ms >= cm->mi_rows);
4875 const int force_vert_split = (mi_col + ms >= cm->mi_cols);
4876 const int xss = x->e_mbd.plane[1].subsampling_x;
4877 const int yss = x->e_mbd.plane[1].subsampling_y;
4879 int partition_none_allowed = !force_horz_split && !force_vert_split;
4880 int partition_horz_allowed =
4881 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
4882 int partition_vert_allowed =
4883 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
4884 const int use_ml_based_partitioning =
4885 sf->partition_search_type == ML_BASED_PARTITION;
4889 // Avoid checking for rectangular partitions for speed >= 5.
4890 if (cpi->oxcf.speed >= 5) do_rect = 0;
4892 assert(num_8x8_blocks_wide_lookup[bsize] ==
4893 num_8x8_blocks_high_lookup[bsize]);
4895 vp9_rd_cost_init(&sum_rdc);
4896 vp9_rd_cost_reset(&best_rdc);
4897 best_rdc.rdcost = best_rd;
4899 // Determine partition types in search according to the speed features.
4900 // The threshold set here has to be of square block size.
4901 if (sf->auto_min_max_partition_size) {
4902 partition_none_allowed &=
4903 (bsize <= x->max_partition_size && bsize >= x->min_partition_size);
4904 partition_horz_allowed &=
4905 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4907 partition_vert_allowed &=
4908 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4910 do_split &= bsize > x->min_partition_size;
4912 if (sf->use_square_partition_only) {
4913 partition_horz_allowed &= force_horz_split;
4914 partition_vert_allowed &= force_vert_split;
4917 if (use_ml_based_partitioning) {
4918 if (partition_none_allowed || do_split) do_rect = 0;
4919 if (partition_none_allowed && do_split) {
4920 const int ml_predicted_partition =
4921 ml_predict_var_paritioning(cpi, x, bsize, mi_row, mi_col);
4922 if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
4923 if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
4927 if (!partition_none_allowed && !do_split) do_rect = 1;
4929 ctx->pred_pixel_ready =
4930 !(partition_vert_allowed || partition_horz_allowed || do_split);
4933 if (partition_none_allowed) {
4934 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
4936 ctx->mic = *xd->mi[0];
4937 ctx->mbmi_ext = *x->mbmi_ext;
4938 ctx->skip_txfm[0] = x->skip_txfm[0];
4939 ctx->skip = x->skip;
4941 if (this_rdc.rate != INT_MAX) {
4942 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4943 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4945 RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
4946 if (this_rdc.rdcost < best_rdc.rdcost) {
4947 best_rdc = this_rdc;
4948 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4950 if (!use_ml_based_partitioning) {
4951 int64_t dist_breakout_thr = sf->partition_search_breakout_thr.dist;
4952 int64_t rate_breakout_thr = sf->partition_search_breakout_thr.rate;
4953 dist_breakout_thr >>=
4954 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4955 rate_breakout_thr *= num_pels_log2_lookup[bsize];
4956 if (!x->e_mbd.lossless && this_rdc.rate < rate_breakout_thr &&
4957 this_rdc.dist < dist_breakout_thr) {
4966 // store estimated motion vector
4967 store_pred_mv(x, ctx);
4971 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4972 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4973 sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4974 subsize = get_subsize(bsize, PARTITION_SPLIT);
4975 for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
4976 const int x_idx = (i & 1) * ms;
4977 const int y_idx = (i >> 1) * ms;
4979 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4981 load_pred_mv(x, ctx);
4982 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4983 mi_col + x_idx, subsize, &this_rdc, 0,
4984 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4986 if (this_rdc.rate == INT_MAX) {
4987 vp9_rd_cost_reset(&sum_rdc);
4989 sum_rdc.rate += this_rdc.rate;
4990 sum_rdc.dist += this_rdc.dist;
4991 sum_rdc.rdcost += this_rdc.rdcost;
4995 if (sum_rdc.rdcost < best_rdc.rdcost) {
4997 pc_tree->partitioning = PARTITION_SPLIT;
4999 // skip rectangular partition test when larger block size
5000 // gives better rd cost
5001 if (sf->less_rectangular_check) do_rect &= !partition_none_allowed;
5006 if (partition_horz_allowed && do_rect) {
5007 subsize = get_subsize(bsize, PARTITION_HORZ);
5008 load_pred_mv(x, ctx);
5009 pc_tree->horizontal[0].pred_pixel_ready = 1;
5010 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
5011 &pc_tree->horizontal[0]);
5013 pc_tree->horizontal[0].mic = *xd->mi[0];
5014 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5015 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5016 pc_tree->horizontal[0].skip = x->skip;
5018 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
5019 load_pred_mv(x, ctx);
5020 pc_tree->horizontal[1].pred_pixel_ready = 1;
5021 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc,
5022 subsize, &pc_tree->horizontal[1]);
5024 pc_tree->horizontal[1].mic = *xd->mi[0];
5025 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5026 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5027 pc_tree->horizontal[1].skip = x->skip;
5029 if (this_rdc.rate == INT_MAX) {
5030 vp9_rd_cost_reset(&sum_rdc);
5032 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
5033 this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
5034 sum_rdc.rate += this_rdc.rate;
5035 sum_rdc.dist += this_rdc.dist;
5037 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
5041 if (sum_rdc.rdcost < best_rdc.rdcost) {
5043 pc_tree->partitioning = PARTITION_HORZ;
5045 pred_pixel_ready_reset(pc_tree, bsize);
5050 if (partition_vert_allowed && do_rect) {
5051 subsize = get_subsize(bsize, PARTITION_VERT);
5052 load_pred_mv(x, ctx);
5053 pc_tree->vertical[0].pred_pixel_ready = 1;
5054 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
5055 &pc_tree->vertical[0]);
5056 pc_tree->vertical[0].mic = *xd->mi[0];
5057 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5058 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5059 pc_tree->vertical[0].skip = x->skip;
5061 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
5062 load_pred_mv(x, ctx);
5063 pc_tree->vertical[1].pred_pixel_ready = 1;
5064 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc,
5065 subsize, &pc_tree->vertical[1]);
5066 pc_tree->vertical[1].mic = *xd->mi[0];
5067 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5068 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5069 pc_tree->vertical[1].skip = x->skip;
5071 if (this_rdc.rate == INT_MAX) {
5072 vp9_rd_cost_reset(&sum_rdc);
5074 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
5075 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
5076 sum_rdc.rate += this_rdc.rate;
5077 sum_rdc.dist += this_rdc.dist;
5079 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
5083 if (sum_rdc.rdcost < best_rdc.rdcost) {
5085 pc_tree->partitioning = PARTITION_VERT;
5087 pred_pixel_ready_reset(pc_tree, bsize);
5091 *rd_cost = best_rdc;
5093 if (best_rdc.rate == INT_MAX) {
5094 vp9_rd_cost_reset(rd_cost);
5098 // update mode info array
5099 fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
5101 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
5102 int output_enabled = (bsize == BLOCK_64X64);
5103 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
5107 if (bsize == BLOCK_64X64 && do_recon) {
5108 assert(tp_orig < *tp);
5109 assert(best_rdc.rate < INT_MAX);
5110 assert(best_rdc.dist < INT64_MAX);
5112 assert(tp_orig == *tp);
5116 static void nonrd_select_partition(VP9_COMP *cpi, ThreadData *td,
5117 TileDataEnc *tile_data, MODE_INFO **mi,
5118 TOKENEXTRA **tp, int mi_row, int mi_col,
5119 BLOCK_SIZE bsize, int output_enabled,
5120 RD_COST *rd_cost, PC_TREE *pc_tree) {
5121 VP9_COMMON *const cm = &cpi->common;
5122 TileInfo *const tile_info = &tile_data->tile_info;
5123 MACROBLOCK *const x = &td->mb;
5124 MACROBLOCKD *const xd = &x->e_mbd;
5125 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5126 const int mis = cm->mi_stride;
5127 PARTITION_TYPE partition;
5130 BLOCK_SIZE subsize_ref =
5131 (cpi->sf.adapt_partition_source_sad) ? BLOCK_8X8 : BLOCK_16X16;
5133 vp9_rd_cost_reset(&this_rdc);
5134 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5136 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5137 partition = partition_lookup[bsl][subsize];
5139 if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
5140 x->max_partition_size = BLOCK_32X32;
5141 x->min_partition_size = BLOCK_16X16;
5142 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5143 0, INT64_MAX, pc_tree);
5144 } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
5145 subsize >= subsize_ref) {
5146 x->max_partition_size = BLOCK_32X32;
5147 x->min_partition_size = BLOCK_8X8;
5148 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5149 0, INT64_MAX, pc_tree);
5150 } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
5151 x->max_partition_size = BLOCK_16X16;
5152 x->min_partition_size = BLOCK_8X8;
5153 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5154 0, INT64_MAX, pc_tree);
5156 switch (partition) {
5157 case PARTITION_NONE:
5158 pc_tree->none.pred_pixel_ready = 1;
5159 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5161 pc_tree->none.mic = *xd->mi[0];
5162 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5163 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5164 pc_tree->none.skip = x->skip;
5166 case PARTITION_VERT:
5167 pc_tree->vertical[0].pred_pixel_ready = 1;
5168 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5169 &pc_tree->vertical[0]);
5170 pc_tree->vertical[0].mic = *xd->mi[0];
5171 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5172 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5173 pc_tree->vertical[0].skip = x->skip;
5174 if (mi_col + hbs < cm->mi_cols) {
5175 pc_tree->vertical[1].pred_pixel_ready = 1;
5176 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
5177 &this_rdc, subsize, &pc_tree->vertical[1]);
5178 pc_tree->vertical[1].mic = *xd->mi[0];
5179 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5180 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5181 pc_tree->vertical[1].skip = x->skip;
5182 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5183 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5184 rd_cost->rate += this_rdc.rate;
5185 rd_cost->dist += this_rdc.dist;
5189 case PARTITION_HORZ:
5190 pc_tree->horizontal[0].pred_pixel_ready = 1;
5191 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5192 &pc_tree->horizontal[0]);
5193 pc_tree->horizontal[0].mic = *xd->mi[0];
5194 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5195 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5196 pc_tree->horizontal[0].skip = x->skip;
5197 if (mi_row + hbs < cm->mi_rows) {
5198 pc_tree->horizontal[1].pred_pixel_ready = 1;
5199 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
5200 &this_rdc, subsize, &pc_tree->horizontal[1]);
5201 pc_tree->horizontal[1].mic = *xd->mi[0];
5202 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5203 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5204 pc_tree->horizontal[1].skip = x->skip;
5205 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5206 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5207 rd_cost->rate += this_rdc.rate;
5208 rd_cost->dist += this_rdc.dist;
5213 assert(partition == PARTITION_SPLIT);
5214 subsize = get_subsize(bsize, PARTITION_SPLIT);
5215 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5216 subsize, output_enabled, rd_cost,
5218 nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5219 mi_col + hbs, subsize, output_enabled, &this_rdc,
5221 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5222 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5223 rd_cost->rate += this_rdc.rate;
5224 rd_cost->dist += this_rdc.dist;
5226 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5227 mi_row + hbs, mi_col, subsize, output_enabled,
5228 &this_rdc, pc_tree->split[2]);
5229 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5230 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5231 rd_cost->rate += this_rdc.rate;
5232 rd_cost->dist += this_rdc.dist;
5234 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5235 mi_row + hbs, mi_col + hbs, subsize,
5236 output_enabled, &this_rdc, pc_tree->split[3]);
5237 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5238 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5239 rd_cost->rate += this_rdc.rate;
5240 rd_cost->dist += this_rdc.dist;
5246 if (bsize == BLOCK_64X64 && output_enabled)
5247 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
5250 static void nonrd_use_partition(VP9_COMP *cpi, ThreadData *td,
5251 TileDataEnc *tile_data, MODE_INFO **mi,
5252 TOKENEXTRA **tp, int mi_row, int mi_col,
5253 BLOCK_SIZE bsize, int output_enabled,
5254 RD_COST *dummy_cost, PC_TREE *pc_tree) {
5255 VP9_COMMON *const cm = &cpi->common;
5256 TileInfo *tile_info = &tile_data->tile_info;
5257 MACROBLOCK *const x = &td->mb;
5258 MACROBLOCKD *const xd = &x->e_mbd;
5259 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5260 const int mis = cm->mi_stride;
5261 PARTITION_TYPE partition;
5264 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5266 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5267 partition = partition_lookup[bsl][subsize];
5269 if (output_enabled && bsize != BLOCK_4X4) {
5270 int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
5271 td->counts->partition[ctx][partition]++;
5274 switch (partition) {
5275 case PARTITION_NONE:
5276 pc_tree->none.pred_pixel_ready = 1;
5277 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5278 subsize, &pc_tree->none);
5279 pc_tree->none.mic = *xd->mi[0];
5280 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5281 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5282 pc_tree->none.skip = x->skip;
5283 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5284 subsize, &pc_tree->none);
5286 case PARTITION_VERT:
5287 pc_tree->vertical[0].pred_pixel_ready = 1;
5288 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5289 subsize, &pc_tree->vertical[0]);
5290 pc_tree->vertical[0].mic = *xd->mi[0];
5291 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5292 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5293 pc_tree->vertical[0].skip = x->skip;
5294 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5295 subsize, &pc_tree->vertical[0]);
5296 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
5297 pc_tree->vertical[1].pred_pixel_ready = 1;
5298 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost,
5299 subsize, &pc_tree->vertical[1]);
5300 pc_tree->vertical[1].mic = *xd->mi[0];
5301 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5302 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5303 pc_tree->vertical[1].skip = x->skip;
5304 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
5305 output_enabled, subsize, &pc_tree->vertical[1]);
5308 case PARTITION_HORZ:
5309 pc_tree->horizontal[0].pred_pixel_ready = 1;
5310 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5311 subsize, &pc_tree->horizontal[0]);
5312 pc_tree->horizontal[0].mic = *xd->mi[0];
5313 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5314 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5315 pc_tree->horizontal[0].skip = x->skip;
5316 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5317 subsize, &pc_tree->horizontal[0]);
5319 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
5320 pc_tree->horizontal[1].pred_pixel_ready = 1;
5321 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost,
5322 subsize, &pc_tree->horizontal[1]);
5323 pc_tree->horizontal[1].mic = *xd->mi[0];
5324 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5325 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5326 pc_tree->horizontal[1].skip = x->skip;
5327 encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
5328 output_enabled, subsize, &pc_tree->horizontal[1]);
5332 assert(partition == PARTITION_SPLIT);
5333 subsize = get_subsize(bsize, PARTITION_SPLIT);
5334 if (bsize == BLOCK_8X8) {
5335 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5336 subsize, pc_tree->leaf_split[0]);
5337 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5338 subsize, pc_tree->leaf_split[0]);
5340 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, subsize,
5341 output_enabled, dummy_cost, pc_tree->split[0]);
5342 nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5343 mi_col + hbs, subsize, output_enabled, dummy_cost,
5345 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5346 mi_row + hbs, mi_col, subsize, output_enabled,
5347 dummy_cost, pc_tree->split[2]);
5348 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5349 mi_row + hbs, mi_col + hbs, subsize, output_enabled,
5350 dummy_cost, pc_tree->split[3]);
5355 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
5356 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
5359 // Get a prediction(stored in x->est_pred) for the whole 64x64 superblock.
5360 static void get_estimated_pred(VP9_COMP *cpi, const TileInfo *const tile,
5361 MACROBLOCK *x, int mi_row, int mi_col) {
5362 VP9_COMMON *const cm = &cpi->common;
5363 const int is_key_frame = frame_is_intra_only(cm);
5364 MACROBLOCKD *xd = &x->e_mbd;
5366 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
5368 if (!is_key_frame) {
5369 MODE_INFO *mi = xd->mi[0];
5370 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
5371 const YV12_BUFFER_CONFIG *yv12_g = NULL;
5372 const BLOCK_SIZE bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
5373 (mi_row + 4 < cm->mi_rows);
5374 unsigned int y_sad_g, y_sad_thr;
5375 unsigned int y_sad = UINT_MAX;
5377 assert(yv12 != NULL);
5379 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
5380 cpi->svc.use_gf_temporal_ref_current_layer) {
5381 // For now, GOLDEN will not be used for non-zero spatial layers, since
5382 // it may not be a temporal reference.
5383 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
5386 // Only compute y_sad_g (sad for golden reference) for speed < 8.
5387 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
5388 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
5389 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5390 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5391 y_sad_g = cpi->fn_ptr[bsize].sdf(
5392 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
5393 xd->plane[0].pre[0].stride);
5398 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
5399 cpi->rc.is_src_frame_alt_ref) {
5400 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
5401 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5402 &cm->frame_refs[ALTREF_FRAME - 1].sf);
5403 mi->ref_frame[0] = ALTREF_FRAME;
5406 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5407 &cm->frame_refs[LAST_FRAME - 1].sf);
5408 mi->ref_frame[0] = LAST_FRAME;
5410 mi->ref_frame[1] = NONE;
5411 mi->sb_type = BLOCK_64X64;
5412 mi->mv[0].as_int = 0;
5413 mi->interp_filter = BILINEAR;
5416 const MV dummy_mv = { 0, 0 };
5417 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
5419 x->sb_use_mv_part = 1;
5420 x->sb_mvcol_part = mi->mv[0].as_mv.col;
5421 x->sb_mvrow_part = mi->mv[0].as_mv.row;
5424 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
5425 // are close if short_circuit_low_temp_var is on.
5426 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
5427 if (y_sad_g < y_sad_thr) {
5428 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5429 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5430 mi->ref_frame[0] = GOLDEN_FRAME;
5431 mi->mv[0].as_int = 0;
5433 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
5436 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
5437 xd->plane[0].dst.buf = x->est_pred;
5438 xd->plane[0].dst.stride = 64;
5439 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
5441 #if CONFIG_VP9_HIGHBITDEPTH
5443 case 8: memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); break;
5445 memset(x->est_pred, 128 * 4, 64 * 64 * sizeof(x->est_pred[0]));
5448 memset(x->est_pred, 128 * 16, 64 * 64 * sizeof(x->est_pred[0]));
5452 memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0]));
5453 #endif // CONFIG_VP9_HIGHBITDEPTH
5457 static void encode_nonrd_sb_row(VP9_COMP *cpi, ThreadData *td,
5458 TileDataEnc *tile_data, int mi_row,
5460 SPEED_FEATURES *const sf = &cpi->sf;
5461 VP9_COMMON *const cm = &cpi->common;
5462 TileInfo *const tile_info = &tile_data->tile_info;
5463 MACROBLOCK *const x = &td->mb;
5464 MACROBLOCKD *const xd = &x->e_mbd;
5465 const int mi_col_start = tile_info->mi_col_start;
5466 const int mi_col_end = tile_info->mi_col_end;
5468 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
5469 const int num_sb_cols =
5470 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
5473 // Initialize the left context for the new SB row
5474 memset(&xd->left_context, 0, sizeof(xd->left_context));
5475 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
5477 // Code each SB in the row
5478 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
5479 mi_col += MI_BLOCK_SIZE, ++sb_col_in_tile) {
5480 const struct segmentation *const seg = &cm->seg;
5482 const int idx_str = cm->mi_stride * mi_row + mi_col;
5483 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
5484 PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
5485 BLOCK_SIZE bsize = BLOCK_64X64;
5489 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
5492 if (cpi->use_skin_detection) {
5493 vp9_compute_skin_sb(cpi, BLOCK_16X16, mi_row, mi_col);
5496 x->source_variance = UINT_MAX;
5497 for (i = 0; i < MAX_REF_FRAMES; ++i) {
5498 x->pred_mv[i].row = INT16_MAX;
5499 x->pred_mv[i].col = INT16_MAX;
5501 vp9_rd_cost_init(&dummy_rdc);
5502 x->color_sensitivity[0] = 0;
5503 x->color_sensitivity[1] = 0;
5505 x->skip_low_source_sad = 0;
5506 x->lowvar_highsumdiff = 0;
5507 x->content_state_sb = 0;
5508 x->zero_temp_sad_source = 0;
5509 x->sb_use_mv_part = 0;
5510 x->sb_mvcol_part = 0;
5511 x->sb_mvrow_part = 0;
5512 x->sb_pickmode_part = 0;
5513 x->arf_frame_usage = 0;
5514 x->lastgolden_frame_usage = 0;
5516 if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
5517 int shift = cpi->Source->y_stride * (mi_row << 3) + (mi_col << 3);
5518 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5519 int64_t source_sad = avg_source_sad(cpi, x, shift, sb_offset2);
5520 if (sf->adapt_partition_source_sad &&
5521 (cpi->oxcf.rc_mode == VPX_VBR && !cpi->rc.is_src_frame_alt_ref &&
5522 source_sad > sf->adapt_partition_thresh &&
5523 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)))
5524 partition_search_type = REFERENCE_PARTITION;
5528 const uint8_t *const map =
5529 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
5530 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
5531 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
5533 if (cpi->roi.enabled && cpi->roi.skip[BACKGROUND_SEG_SKIP_ID] &&
5534 cpi->rc.frames_since_key > FRAMES_NO_SKIPPING_AFTER_KEY &&
5535 x->content_state_sb > kLowSadLowSumdiff) {
5536 // For ROI with skip, force segment = 0 (no skip) over whole
5537 // superblock to avoid artifacts if temporal change in source_sad is
5540 const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
5541 const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
5542 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
5543 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
5544 const int block_index = mi_row * cm->mi_cols + mi_col;
5545 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
5546 for (yi = 0; yi < ymis; yi++)
5547 for (xi = 0; xi < xmis; xi++) {
5548 int map_offset = block_index + yi * cm->mi_cols + xi;
5549 cpi->segmentation_map[map_offset] = 0;
5551 set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
5555 partition_search_type = FIXED_PARTITION;
5559 // Set the partition type of the 64X64 block
5560 switch (partition_search_type) {
5561 case VAR_BASED_PARTITION:
5562 // TODO(jingning, marpan): The mode decision and encoding process
5563 // support both intra and inter sub8x8 block coding for RTC mode.
5564 // Tune the thresholds accordingly to use sub8x8 block coding for
5565 // coding performance improvement.
5566 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5567 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5568 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5570 case ML_BASED_PARTITION:
5571 get_estimated_pred(cpi, tile_info, x, mi_row, mi_col);
5572 x->max_partition_size = BLOCK_64X64;
5573 x->min_partition_size = BLOCK_8X8;
5574 x->sb_pickmode_part = 1;
5575 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5576 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5579 case SOURCE_VAR_BASED_PARTITION:
5580 set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
5581 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5582 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5584 case FIXED_PARTITION:
5585 if (!seg_skip) bsize = sf->always_this_block_size;
5586 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
5587 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5588 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5591 assert(partition_search_type == REFERENCE_PARTITION);
5592 x->sb_pickmode_part = 1;
5593 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
5594 // Use nonrd_pick_partition on scene-cut for VBR mode.
5595 // nonrd_pick_partition does not support 4x4 partition, so avoid it
5596 // on key frame for now.
5597 if ((cpi->oxcf.rc_mode == VPX_VBR && cpi->rc.high_source_sad &&
5598 cpi->oxcf.speed < 6 && !frame_is_intra_only(cm) &&
5599 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
5600 // Use lower max_partition_size for low resoultions.
5601 if (cm->width <= 352 && cm->height <= 288)
5602 x->max_partition_size = BLOCK_32X32;
5604 x->max_partition_size = BLOCK_64X64;
5605 x->min_partition_size = BLOCK_8X8;
5606 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5607 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5610 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5611 // TODO(marpan): Seems like nonrd_select_partition does not support
5612 // 4x4 partition. Since 4x4 is used on key frame, use this switch
5614 if (frame_is_intra_only(cm))
5615 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5616 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5618 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5619 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5625 // Update ref_frame usage for inter frame if this group is ARF group.
5626 if (!cpi->rc.is_src_frame_alt_ref && !cpi->refresh_golden_frame &&
5627 !cpi->refresh_alt_ref_frame && cpi->rc.alt_ref_gf_group &&
5628 cpi->sf.use_altref_onepass) {
5629 int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5630 if (cpi->count_arf_frame_usage != NULL)
5631 cpi->count_arf_frame_usage[sboffset] = x->arf_frame_usage;
5632 if (cpi->count_lastgolden_frame_usage != NULL)
5633 cpi->count_lastgolden_frame_usage[sboffset] = x->lastgolden_frame_usage;
5636 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
5637 sb_col_in_tile, num_sb_cols);
5640 // end RTC play code
5642 static INLINE uint32_t variance(const diff *const d) {
5643 return d->sse - (uint32_t)(((int64_t)d->sum * d->sum) >> 8);
5646 #if CONFIG_VP9_HIGHBITDEPTH
5647 static INLINE uint32_t variance_highbd(diff *const d) {
5648 const int64_t var = (int64_t)d->sse - (((int64_t)d->sum * d->sum) >> 8);
5649 return (var >= 0) ? (uint32_t)var : 0;
5651 #endif // CONFIG_VP9_HIGHBITDEPTH
5653 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
5654 const SPEED_FEATURES *const sf = &cpi->sf;
5655 const VP9_COMMON *const cm = &cpi->common;
5657 const uint8_t *src = cpi->Source->y_buffer;
5658 const uint8_t *last_src = cpi->Last_Source->y_buffer;
5659 const int src_stride = cpi->Source->y_stride;
5660 const int last_stride = cpi->Last_Source->y_stride;
5662 // Pick cutoff threshold
5663 const int cutoff = (VPXMIN(cm->width, cm->height) >= 720)
5664 ? (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100)
5665 : (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
5666 DECLARE_ALIGNED(16, int, hist[VAR_HIST_BINS]);
5667 diff *var16 = cpi->source_diff_var;
5672 memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
5674 for (i = 0; i < cm->mb_rows; i++) {
5675 for (j = 0; j < cm->mb_cols; j++) {
5676 #if CONFIG_VP9_HIGHBITDEPTH
5677 if (cm->use_highbitdepth) {
5678 switch (cm->bit_depth) {
5680 vpx_highbd_8_get16x16var(src, src_stride, last_src, last_stride,
5681 &var16->sse, &var16->sum);
5682 var16->var = variance(var16);
5685 vpx_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
5686 &var16->sse, &var16->sum);
5687 var16->var = variance_highbd(var16);
5690 assert(cm->bit_depth == VPX_BITS_12);
5691 vpx_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
5692 &var16->sse, &var16->sum);
5693 var16->var = variance_highbd(var16);
5697 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5699 var16->var = variance(var16);
5702 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5704 var16->var = variance(var16);
5705 #endif // CONFIG_VP9_HIGHBITDEPTH
5707 if (var16->var >= VAR_HIST_MAX_BG_VAR)
5708 hist[VAR_HIST_BINS - 1]++;
5710 hist[var16->var / VAR_HIST_FACTOR]++;
5717 src = src - cm->mb_cols * 16 + 16 * src_stride;
5718 last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
5721 cpi->source_var_thresh = 0;
5723 if (hist[VAR_HIST_BINS - 1] < cutoff) {
5724 for (i = 0; i < VAR_HIST_BINS - 1; i++) {
5728 cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
5734 return sf->search_type_check_frequency;
5737 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
5738 VP9_COMMON *const cm = &cpi->common;
5739 SPEED_FEATURES *const sf = &cpi->sf;
5741 if (cm->frame_type == KEY_FRAME) {
5742 // For key frame, use SEARCH_PARTITION.
5743 sf->partition_search_type = SEARCH_PARTITION;
5744 } else if (cm->intra_only) {
5745 sf->partition_search_type = FIXED_PARTITION;
5747 if (cm->last_width != cm->width || cm->last_height != cm->height) {
5748 if (cpi->source_diff_var) vpx_free(cpi->source_diff_var);
5750 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
5751 vpx_calloc(cm->MBs, sizeof(diff)));
5754 if (!cpi->frames_till_next_var_check)
5755 cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
5757 if (cpi->frames_till_next_var_check > 0) {
5758 sf->partition_search_type = FIXED_PARTITION;
5759 cpi->frames_till_next_var_check--;
5764 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
5765 unsigned int intra_count = 0, inter_count = 0;
5768 for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
5769 intra_count += td->counts->intra_inter[j][0];
5770 inter_count += td->counts->intra_inter[j][1];
5773 return (intra_count << 2) < inter_count && cm->frame_type != KEY_FRAME &&
5777 void vp9_init_tile_data(VP9_COMP *cpi) {
5778 VP9_COMMON *const cm = &cpi->common;
5779 const int tile_cols = 1 << cm->log2_tile_cols;
5780 const int tile_rows = 1 << cm->log2_tile_rows;
5781 int tile_col, tile_row;
5782 TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
5783 TOKENLIST *tplist = cpi->tplist[0][0];
5785 int tplist_count = 0;
5787 if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
5788 if (cpi->tile_data != NULL) vpx_free(cpi->tile_data);
5791 vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
5792 cpi->allocated_tiles = tile_cols * tile_rows;
5794 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5795 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5796 TileDataEnc *tile_data =
5797 &cpi->tile_data[tile_row * tile_cols + tile_col];
5799 for (i = 0; i < BLOCK_SIZES; ++i) {
5800 for (j = 0; j < MAX_MODES; ++j) {
5801 tile_data->thresh_freq_fact[i][j] = RD_THRESH_INIT_FACT;
5802 #if CONFIG_RATE_CTRL
5803 if (cpi->oxcf.use_simple_encode_api) {
5804 tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5806 #endif // CONFIG_RATE_CTRL
5807 #if CONFIG_CONSISTENT_RECODE
5808 tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5809 #endif // CONFIG_CONSISTENT_RECODE
5810 tile_data->mode_map[i][j] = j;
5813 #if CONFIG_MULTITHREAD
5814 tile_data->row_base_thresh_freq_fact = NULL;
5819 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
5820 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5821 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5822 TileInfo *tile_info = &this_tile->tile_info;
5823 if (cpi->sf.adaptive_rd_thresh_row_mt &&
5824 this_tile->row_base_thresh_freq_fact == NULL)
5825 vp9_row_mt_alloc_rd_thresh(cpi, this_tile);
5826 vp9_tile_init(tile_info, cm, tile_row, tile_col);
5828 cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
5829 pre_tok = cpi->tile_tok[tile_row][tile_col];
5830 tile_tok = allocated_tokens(*tile_info);
5832 cpi->tplist[tile_row][tile_col] = tplist + tplist_count;
5833 tplist = cpi->tplist[tile_row][tile_col];
5834 tplist_count = get_num_vert_units(*tile_info, MI_BLOCK_SIZE_LOG2);
5839 void vp9_encode_sb_row(VP9_COMP *cpi, ThreadData *td, int tile_row,
5840 int tile_col, int mi_row) {
5841 VP9_COMMON *const cm = &cpi->common;
5842 const int tile_cols = 1 << cm->log2_tile_cols;
5843 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5844 const TileInfo *const tile_info = &this_tile->tile_info;
5845 TOKENEXTRA *tok = NULL;
5847 int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
5849 tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile_info->mi_row_start) >>
5851 get_start_tok(cpi, tile_row, tile_col, mi_row, &tok);
5852 cpi->tplist[tile_row][tile_col][tile_sb_row].start = tok;
5854 if (cpi->sf.use_nonrd_pick_mode)
5855 encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5856 #if !CONFIG_REALTIME_ONLY
5858 encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
5861 cpi->tplist[tile_row][tile_col][tile_sb_row].stop = tok;
5862 cpi->tplist[tile_row][tile_col][tile_sb_row].count =
5863 (unsigned int)(cpi->tplist[tile_row][tile_col][tile_sb_row].stop -
5864 cpi->tplist[tile_row][tile_col][tile_sb_row].start);
5865 assert(tok - cpi->tplist[tile_row][tile_col][tile_sb_row].start <=
5866 get_token_alloc(MI_BLOCK_SIZE >> 1, tile_mb_cols));
5871 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td, int tile_row,
5873 VP9_COMMON *const cm = &cpi->common;
5874 const int tile_cols = 1 << cm->log2_tile_cols;
5875 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5876 const TileInfo *const tile_info = &this_tile->tile_info;
5877 const int mi_row_start = tile_info->mi_row_start;
5878 const int mi_row_end = tile_info->mi_row_end;
5881 for (mi_row = mi_row_start; mi_row < mi_row_end; mi_row += MI_BLOCK_SIZE)
5882 vp9_encode_sb_row(cpi, td, tile_row, tile_col, mi_row);
5885 static void encode_tiles(VP9_COMP *cpi) {
5886 VP9_COMMON *const cm = &cpi->common;
5887 const int tile_cols = 1 << cm->log2_tile_cols;
5888 const int tile_rows = 1 << cm->log2_tile_rows;
5889 int tile_col, tile_row;
5891 vp9_init_tile_data(cpi);
5893 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5894 for (tile_col = 0; tile_col < tile_cols; ++tile_col)
5895 vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
5898 static int compare_kmeans_data(const void *a, const void *b) {
5899 if (((const KMEANS_DATA *)a)->value > ((const KMEANS_DATA *)b)->value) {
5901 } else if (((const KMEANS_DATA *)a)->value <
5902 ((const KMEANS_DATA *)b)->value) {
5909 static void compute_boundary_ls(const double *ctr_ls, int k,
5910 double *boundary_ls) {
5911 // boundary_ls[j] is the upper bound of data centered at ctr_ls[j]
5913 for (j = 0; j < k - 1; ++j) {
5914 boundary_ls[j] = (ctr_ls[j] + ctr_ls[j + 1]) / 2.;
5916 boundary_ls[k - 1] = DBL_MAX;
5919 int vp9_get_group_idx(double value, double *boundary_ls, int k) {
5921 while (value >= boundary_ls[group_idx]) {
5923 if (group_idx == k - 1) {
5930 void vp9_kmeans(double *ctr_ls, double *boundary_ls, int *count_ls, int k,
5931 KMEANS_DATA *arr, int size) {
5935 double sum[MAX_KMEANS_GROUPS];
5936 int count[MAX_KMEANS_GROUPS];
5938 vpx_clear_system_state();
5940 assert(k >= 2 && k <= MAX_KMEANS_GROUPS);
5942 qsort(arr, size, sizeof(*arr), compare_kmeans_data);
5944 // initialize the center points
5945 for (j = 0; j < k; ++j) {
5946 ctr_ls[j] = arr[(size * (2 * j + 1)) / (2 * k)].value;
5949 for (itr = 0; itr < 10; ++itr) {
5950 compute_boundary_ls(ctr_ls, k, boundary_ls);
5951 for (i = 0; i < MAX_KMEANS_GROUPS; ++i) {
5956 // Both the data and centers are sorted in ascending order.
5957 // As each data point is processed in order, its corresponding group index
5958 // can only increase. So we only need to reset the group index to zero here.
5960 for (i = 0; i < size; ++i) {
5961 while (arr[i].value >= boundary_ls[group_idx]) {
5962 // place samples into clusters
5964 if (group_idx == k - 1) {
5968 sum[group_idx] += arr[i].value;
5972 for (group_idx = 0; group_idx < k; ++group_idx) {
5973 if (count[group_idx] > 0)
5974 ctr_ls[group_idx] = sum[group_idx] / count[group_idx];
5977 count[group_idx] = 0;
5981 // compute group_idx, boundary_ls and count_ls
5982 for (j = 0; j < k; ++j) {
5985 compute_boundary_ls(ctr_ls, k, boundary_ls);
5987 for (i = 0; i < size; ++i) {
5988 while (arr[i].value >= boundary_ls[group_idx]) {
5990 if (group_idx == k - 1) {
5994 arr[i].group_idx = group_idx;
5995 ++count_ls[group_idx];
5999 static void encode_frame_internal(VP9_COMP *cpi) {
6000 SPEED_FEATURES *const sf = &cpi->sf;
6001 ThreadData *const td = &cpi->td;
6002 MACROBLOCK *const x = &td->mb;
6003 VP9_COMMON *const cm = &cpi->common;
6004 MACROBLOCKD *const xd = &x->e_mbd;
6005 const int gf_group_index = cpi->twopass.gf_group.index;
6007 xd->mi = cm->mi_grid_visible;
6009 vp9_zero(*td->counts);
6010 vp9_zero(cpi->td.rd_counts);
6012 xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
6013 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
6015 #if CONFIG_VP9_HIGHBITDEPTH
6016 if (cm->use_highbitdepth)
6017 x->fwd_txfm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
6019 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
6020 x->highbd_inv_txfm_add =
6021 xd->lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
6023 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
6024 #endif // CONFIG_VP9_HIGHBITDEPTH
6025 x->inv_txfm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
6026 #if CONFIG_CONSISTENT_RECODE
6027 x->optimize = sf->optimize_coefficients == 1 && cpi->oxcf.pass != 1;
6029 if (xd->lossless) x->optimize = 0;
6030 x->sharpness = cpi->oxcf.sharpness;
6031 x->adjust_rdmult_by_segment = (cpi->oxcf.aq_mode == VARIANCE_AQ);
6033 cm->tx_mode = select_tx_mode(cpi, xd);
6035 vp9_frame_init_quantizer(cpi);
6037 vp9_initialize_rd_consts(cpi);
6038 vp9_initialize_me_consts(cpi, x, cm->base_qindex);
6039 init_encode_frame_mb_context(cpi);
6040 cm->use_prev_frame_mvs =
6041 !cm->error_resilient_mode && cm->width == cm->last_width &&
6042 cm->height == cm->last_height && !cm->intra_only && cm->last_show_frame;
6043 // Special case: set prev_mi to NULL when the previous mode info
6044 // context cannot be used.
6046 cm->use_prev_frame_mvs ? cm->prev_mip + cm->mi_stride + 1 : NULL;
6048 x->quant_fp = cpi->sf.use_quant_fp;
6049 vp9_zero(x->skip_txfm);
6050 if (sf->use_nonrd_pick_mode) {
6051 // Initialize internal buffer pointers for rtc coding, where non-RD
6052 // mode decision is used and hence no buffer pointer swap needed.
6054 struct macroblock_plane *const p = x->plane;
6055 struct macroblockd_plane *const pd = xd->plane;
6056 PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
6058 for (i = 0; i < MAX_MB_PLANE; ++i) {
6059 p[i].coeff = ctx->coeff_pbuf[i][0];
6060 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
6061 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
6062 p[i].eobs = ctx->eobs_pbuf[i][0];
6064 vp9_zero(x->zcoeff_blk);
6066 if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0 &&
6067 !(cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) &&
6069 cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
6071 if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
6072 source_var_based_partition_search_method(cpi);
6073 } else if (gf_group_index && gf_group_index < MAX_ARF_GOP_SIZE &&
6074 cpi->sf.enable_tpl_model) {
6075 TplDepFrame *tpl_frame = &cpi->tpl_stats[cpi->twopass.gf_group.index];
6076 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
6078 int tpl_stride = tpl_frame->stride;
6079 int64_t intra_cost_base = 0;
6080 int64_t mc_dep_cost_base = 0;
6083 for (row = 0; row < cm->mi_rows && tpl_frame->is_valid; ++row) {
6084 for (col = 0; col < cm->mi_cols; ++col) {
6085 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
6086 intra_cost_base += this_stats->intra_cost;
6087 mc_dep_cost_base += this_stats->mc_dep_cost;
6091 vpx_clear_system_state();
6093 if (tpl_frame->is_valid)
6094 cpi->rd.r0 = (double)intra_cost_base / mc_dep_cost_base;
6097 // Frame segmentation
6098 if (cpi->oxcf.aq_mode == PERCEPTUAL_AQ) build_kmeans_segmentation(cpi);
6101 struct vpx_usec_timer emr_timer;
6102 vpx_usec_timer_start(&emr_timer);
6105 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
6106 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
6107 // If allowed, encoding tiles in parallel with one thread handling one
6108 // tile when row based multi-threading is disabled.
6109 if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
6110 vp9_encode_tiles_mt(cpi);
6114 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
6115 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
6116 vp9_encode_tiles_row_mt(cpi);
6119 vpx_usec_timer_mark(&emr_timer);
6120 cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
6123 sf->skip_encode_frame =
6124 sf->skip_encode_sb ? get_skip_encode_frame(cm, td) : 0;
6127 // Keep record of the total distortion this time around for future use
6128 cpi->last_frame_distortion = cpi->frame_distortion;
6132 static INTERP_FILTER get_interp_filter(
6133 const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
6134 if (!is_alt_ref && threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
6135 threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
6136 threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
6137 return EIGHTTAP_SMOOTH;
6138 } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
6139 threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
6140 return EIGHTTAP_SHARP;
6141 } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
6148 static int compute_frame_aq_offset(struct VP9_COMP *cpi) {
6149 VP9_COMMON *const cm = &cpi->common;
6150 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
6151 struct segmentation *const seg = &cm->seg;
6159 for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
6160 MODE_INFO **mi_8x8 = mi_8x8_ptr;
6161 for (mi_col = 0; mi_col < cm->mi_cols; mi_col++, mi_8x8++) {
6162 segment_id = mi_8x8[0]->segment_id;
6163 qdelta_index = get_segdata(seg, segment_id, SEG_LVL_ALT_Q);
6164 sum_delta += qdelta_index;
6167 mi_8x8_ptr += cm->mi_stride;
6170 return sum_delta / (cm->mi_rows * cm->mi_cols);
6173 #if CONFIG_CONSISTENT_RECODE || CONFIG_RATE_CTRL
6174 static void restore_encode_params(VP9_COMP *cpi) {
6175 VP9_COMMON *const cm = &cpi->common;
6176 const int tile_cols = 1 << cm->log2_tile_cols;
6177 const int tile_rows = 1 << cm->log2_tile_rows;
6178 int tile_col, tile_row;
6180 RD_OPT *rd_opt = &cpi->rd;
6181 for (i = 0; i < MAX_REF_FRAMES; i++) {
6182 for (j = 0; j < REFERENCE_MODES; j++)
6183 rd_opt->prediction_type_threshes[i][j] =
6184 rd_opt->prediction_type_threshes_prev[i][j];
6186 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
6187 rd_opt->filter_threshes[i][j] = rd_opt->filter_threshes_prev[i][j];
6190 if (cpi->tile_data != NULL) {
6191 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
6192 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
6193 TileDataEnc *tile_data =
6194 &cpi->tile_data[tile_row * tile_cols + tile_col];
6195 for (i = 0; i < BLOCK_SIZES; ++i) {
6196 for (j = 0; j < MAX_MODES; ++j) {
6197 tile_data->thresh_freq_fact[i][j] =
6198 tile_data->thresh_freq_fact_prev[i][j];
6204 cm->interp_filter = cpi->sf.default_interp_filter;
6206 #endif // CONFIG_CONSISTENT_RECODE || CONFIG_RATE_CTRL
6208 void vp9_encode_frame(VP9_COMP *cpi) {
6209 VP9_COMMON *const cm = &cpi->common;
6211 #if CONFIG_RATE_CTRL
6212 if (cpi->oxcf.use_simple_encode_api) {
6213 restore_encode_params(cpi);
6215 #endif // CONFIG_RATE_CTRL
6216 #if CONFIG_CONSISTENT_RECODE
6217 restore_encode_params(cpi);
6220 #if CONFIG_MISMATCH_DEBUG
6221 mismatch_reset_frame(MAX_MB_PLANE);
6224 // In the longer term the encoder should be generalized to match the
6225 // decoder such that we allow compound where one of the 3 buffers has a
6226 // different sign bias and that buffer is then the fixed ref. However, this
6227 // requires further work in the rd loop. For now the only supported encoder
6228 // side behavior is where the ALT ref buffer has opposite sign bias to
6230 if (!frame_is_intra_only(cm)) {
6231 if (vp9_compound_reference_allowed(cm)) {
6232 cpi->allow_comp_inter_inter = 1;
6233 vp9_setup_compound_reference_mode(cm);
6235 cpi->allow_comp_inter_inter = 0;
6239 if (cpi->sf.frame_parameter_update) {
6241 RD_OPT *const rd_opt = &cpi->rd;
6242 FRAME_COUNTS *counts = cpi->td.counts;
6243 RD_COUNTS *const rdc = &cpi->td.rd_counts;
6245 // This code does a single RD pass over the whole frame assuming
6246 // either compound, single or hybrid prediction as per whatever has
6247 // worked best for that type of frame in the past.
6248 // It also predicts whether another coding mode would have worked
6249 // better than this coding mode. If that is the case, it remembers
6250 // that for subsequent frames.
6251 // It also does the same analysis for transform size selection.
6252 const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
6253 int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
6254 int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
6255 const int is_alt_ref = frame_type == ALTREF_FRAME;
6257 /* prediction (compound, single or hybrid) mode selection */
6258 if (is_alt_ref || !cpi->allow_comp_inter_inter)
6259 cm->reference_mode = SINGLE_REFERENCE;
6260 else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
6261 mode_thrs[COMPOUND_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT] &&
6262 check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
6263 cm->reference_mode = COMPOUND_REFERENCE;
6264 else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
6265 cm->reference_mode = SINGLE_REFERENCE;
6267 cm->reference_mode = REFERENCE_MODE_SELECT;
6269 if (cm->interp_filter == SWITCHABLE)
6270 cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
6272 encode_frame_internal(cpi);
6274 for (i = 0; i < REFERENCE_MODES; ++i)
6275 mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
6277 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
6278 filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
6280 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6281 int single_count_zero = 0;
6282 int comp_count_zero = 0;
6284 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6285 single_count_zero += counts->comp_inter[i][0];
6286 comp_count_zero += counts->comp_inter[i][1];
6289 if (comp_count_zero == 0) {
6290 cm->reference_mode = SINGLE_REFERENCE;
6291 vp9_zero(counts->comp_inter);
6292 } else if (single_count_zero == 0) {
6293 cm->reference_mode = COMPOUND_REFERENCE;
6294 vp9_zero(counts->comp_inter);
6298 if (cm->tx_mode == TX_MODE_SELECT) {
6300 int count8x8_lp = 0, count8x8_8x8p = 0;
6301 int count16x16_16x16p = 0, count16x16_lp = 0;
6304 for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
6305 count4x4 += counts->tx.p32x32[i][TX_4X4];
6306 count4x4 += counts->tx.p16x16[i][TX_4X4];
6307 count4x4 += counts->tx.p8x8[i][TX_4X4];
6309 count8x8_lp += counts->tx.p32x32[i][TX_8X8];
6310 count8x8_lp += counts->tx.p16x16[i][TX_8X8];
6311 count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
6313 count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
6314 count16x16_lp += counts->tx.p32x32[i][TX_16X16];
6315 count32x32 += counts->tx.p32x32[i][TX_32X32];
6317 if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
6319 cm->tx_mode = ALLOW_8X8;
6320 reset_skip_tx_size(cm, TX_8X8);
6321 } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
6322 count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
6323 cm->tx_mode = ONLY_4X4;
6324 reset_skip_tx_size(cm, TX_4X4);
6325 } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
6326 cm->tx_mode = ALLOW_32X32;
6327 } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
6328 cm->tx_mode = ALLOW_16X16;
6329 reset_skip_tx_size(cm, TX_16X16);
6333 FRAME_COUNTS *counts = cpi->td.counts;
6334 cm->reference_mode = SINGLE_REFERENCE;
6335 if (cpi->allow_comp_inter_inter && cpi->sf.use_compound_nonrd_pickmode &&
6336 cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
6337 cm->frame_type != KEY_FRAME)
6338 cm->reference_mode = REFERENCE_MODE_SELECT;
6340 encode_frame_internal(cpi);
6342 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6343 int single_count_zero = 0;
6344 int comp_count_zero = 0;
6346 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6347 single_count_zero += counts->comp_inter[i][0];
6348 comp_count_zero += counts->comp_inter[i][1];
6350 if (comp_count_zero == 0) {
6351 cm->reference_mode = SINGLE_REFERENCE;
6352 vp9_zero(counts->comp_inter);
6353 } else if (single_count_zero == 0) {
6354 cm->reference_mode = COMPOUND_REFERENCE;
6355 vp9_zero(counts->comp_inter);
6360 // If segmented AQ is enabled compute the average AQ weighting.
6361 if (cm->seg.enabled && (cpi->oxcf.aq_mode != NO_AQ) &&
6362 (cm->seg.update_map || cm->seg.update_data)) {
6363 cm->seg.aq_av_offset = compute_frame_aq_offset(cpi);
6367 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
6368 const PREDICTION_MODE y_mode = mi->mode;
6369 const PREDICTION_MODE uv_mode = mi->uv_mode;
6370 const BLOCK_SIZE bsize = mi->sb_type;
6372 if (bsize < BLOCK_8X8) {
6374 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
6375 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
6376 for (idy = 0; idy < 2; idy += num_4x4_h)
6377 for (idx = 0; idx < 2; idx += num_4x4_w)
6378 ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
6380 ++counts->y_mode[size_group_lookup[bsize]][y_mode];
6383 ++counts->uv_mode[y_mode][uv_mode];
6386 static void update_zeromv_cnt(VP9_COMP *const cpi, const MODE_INFO *const mi,
6387 int mi_row, int mi_col, BLOCK_SIZE bsize) {
6388 const VP9_COMMON *const cm = &cpi->common;
6389 MV mv = mi->mv[0].as_mv;
6390 const int bw = num_8x8_blocks_wide_lookup[bsize];
6391 const int bh = num_8x8_blocks_high_lookup[bsize];
6392 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
6393 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
6394 const int block_index = mi_row * cm->mi_cols + mi_col;
6396 for (y = 0; y < ymis; y++)
6397 for (x = 0; x < xmis; x++) {
6398 int map_offset = block_index + y * cm->mi_cols + x;
6399 if (mi->ref_frame[0] == LAST_FRAME && is_inter_block(mi) &&
6400 mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
6401 if (abs(mv.row) < 8 && abs(mv.col) < 8) {
6402 if (cpi->consec_zero_mv[map_offset] < 255)
6403 cpi->consec_zero_mv[map_offset]++;
6405 cpi->consec_zero_mv[map_offset] = 0;
6411 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
6412 int output_enabled, int mi_row, int mi_col,
6413 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
6414 VP9_COMMON *const cm = &cpi->common;
6415 MACROBLOCK *const x = &td->mb;
6416 MACROBLOCKD *const xd = &x->e_mbd;
6417 MODE_INFO *mi = xd->mi[0];
6418 const int seg_skip =
6419 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP);
6420 x->skip_recode = !x->select_tx_size && mi->sb_type >= BLOCK_8X8 &&
6421 cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
6422 cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
6423 cpi->sf.allow_skip_recode;
6425 if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
6426 memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
6428 x->skip_optimize = ctx->is_coded;
6430 x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
6431 x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
6432 x->q_index < QIDX_SKIP_THRESH);
6434 if (x->skip_encode) return;
6436 if (!is_inter_block(mi)) {
6438 #if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6439 if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
6440 (xd->above_mi == NULL || xd->left_mi == NULL) &&
6441 need_top_left[mi->uv_mode])
6443 #endif // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6445 for (plane = 0; plane < MAX_MB_PLANE; ++plane)
6446 vp9_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane, 1);
6447 if (output_enabled) sum_intra_stats(td->counts, mi);
6448 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6449 VPXMAX(bsize, BLOCK_8X8));
6452 const int is_compound = has_second_ref(mi);
6453 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
6454 for (ref = 0; ref < 1 + is_compound; ++ref) {
6455 YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, mi->ref_frame[ref]);
6456 assert(cfg != NULL);
6457 vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
6458 &xd->block_refs[ref]->sf);
6460 if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
6461 vp9_build_inter_predictors_sby(xd, mi_row, mi_col,
6462 VPXMAX(bsize, BLOCK_8X8));
6464 vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col,
6465 VPXMAX(bsize, BLOCK_8X8));
6467 #if CONFIG_MISMATCH_DEBUG
6468 if (output_enabled) {
6470 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
6471 const struct macroblockd_plane *pd = &xd->plane[plane];
6472 int pixel_c, pixel_r;
6473 const BLOCK_SIZE plane_bsize =
6474 get_plane_block_size(VPXMAX(bsize, BLOCK_8X8), &xd->plane[plane]);
6475 const int bw = get_block_width(plane_bsize);
6476 const int bh = get_block_height(plane_bsize);
6477 mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, 0, 0,
6478 pd->subsampling_x, pd->subsampling_y);
6480 mismatch_record_block_pre(pd->dst.buf, pd->dst.stride, plane, pixel_c,
6482 xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
6487 vp9_encode_sb(x, VPXMAX(bsize, BLOCK_8X8), mi_row, mi_col, output_enabled);
6488 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6489 VPXMAX(bsize, BLOCK_8X8));
6496 if (output_enabled) {
6497 if (cm->tx_mode == TX_MODE_SELECT && mi->sb_type >= BLOCK_8X8 &&
6498 !(is_inter_block(mi) && mi->skip)) {
6499 ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
6500 &td->counts->tx)[mi->tx_size];
6502 // The new intra coding scheme requires no change of transform size
6503 if (is_inter_block(mi)) {
6504 mi->tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
6505 max_txsize_lookup[bsize]);
6507 mi->tx_size = (bsize >= BLOCK_8X8) ? mi->tx_size : TX_4X4;
6511 ++td->counts->tx.tx_totals[mi->tx_size];
6512 ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])];
6513 if (cm->seg.enabled && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
6514 cpi->cyclic_refresh->content_mode)
6515 vp9_cyclic_refresh_update_sb_postencode(cpi, mi, mi_row, mi_col, bsize);
6516 if (cpi->oxcf.pass == 0 && cpi->svc.temporal_layer_id == 0 &&
6519 !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
6520 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)))
6521 update_zeromv_cnt(cpi, mi, mi_row, mi_col, bsize);