2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
16 #include "./vp9_rtcd.h"
17 #include "./vpx_dsp_rtcd.h"
18 #include "./vpx_config.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_ports/mem.h"
22 #include "vpx_ports/vpx_timer.h"
23 #include "vpx_ports/system_state.h"
25 #include "vp9/common/vp9_common.h"
26 #include "vp9/common/vp9_entropy.h"
27 #include "vp9/common/vp9_entropymode.h"
28 #include "vp9/common/vp9_idct.h"
29 #include "vp9/common/vp9_mvref_common.h"
30 #include "vp9/common/vp9_pred_common.h"
31 #include "vp9/common/vp9_quant_common.h"
32 #include "vp9/common/vp9_reconintra.h"
33 #include "vp9/common/vp9_reconinter.h"
34 #include "vp9/common/vp9_seg_common.h"
35 #include "vp9/common/vp9_tile_common.h"
37 #include "vp9/encoder/vp9_aq_360.h"
38 #include "vp9/encoder/vp9_aq_complexity.h"
39 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
40 #include "vp9/encoder/vp9_aq_variance.h"
41 #include "vp9/encoder/vp9_encodeframe.h"
42 #include "vp9/encoder/vp9_encodemb.h"
43 #include "vp9/encoder/vp9_encodemv.h"
44 #include "vp9/encoder/vp9_ethread.h"
45 #include "vp9/encoder/vp9_extend.h"
46 #include "vp9/encoder/vp9_multi_thread.h"
47 #include "vp9/encoder/vp9_partition_models.h"
48 #include "vp9/encoder/vp9_pickmode.h"
49 #include "vp9/encoder/vp9_rd.h"
50 #include "vp9/encoder/vp9_rdopt.h"
51 #include "vp9/encoder/vp9_segmentation.h"
52 #include "vp9/encoder/vp9_tokenize.h"
54 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
55 int output_enabled, int mi_row, int mi_col,
56 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx);
58 // This is used as a reference when computing the source variance for the
59 // purpose of activity masking.
60 // Eventually this should be replaced by custom no-reference routines,
61 // which will be faster.
62 static const uint8_t VP9_VAR_OFFS[64] = {
63 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
64 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
65 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
66 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
67 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
70 #if CONFIG_VP9_HIGHBITDEPTH
71 static const uint16_t VP9_HIGH_VAR_OFFS_8[64] = {
72 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
73 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
74 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
75 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
76 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
79 static const uint16_t VP9_HIGH_VAR_OFFS_10[64] = {
80 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
81 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
82 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
83 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
84 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
85 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
86 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
87 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4
90 static const uint16_t VP9_HIGH_VAR_OFFS_12[64] = {
91 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
92 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
93 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
94 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
95 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
96 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
97 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
98 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
99 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
102 #endif // CONFIG_VP9_HIGHBITDEPTH
104 unsigned int vp9_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
107 const unsigned int var =
108 cpi->fn_ptr[bs].vf(ref->buf, ref->stride, VP9_VAR_OFFS, 0, &sse);
112 #if CONFIG_VP9_HIGHBITDEPTH
113 unsigned int vp9_high_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
114 BLOCK_SIZE bs, int bd) {
115 unsigned int var, sse;
119 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
120 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10), 0, &sse);
124 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
125 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12), 0, &sse);
130 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
131 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8), 0, &sse);
136 #endif // CONFIG_VP9_HIGHBITDEPTH
138 unsigned int vp9_get_sby_perpixel_variance(VP9_COMP *cpi,
139 const struct buf_2d *ref,
141 return ROUND_POWER_OF_TWO(vp9_get_sby_variance(cpi, ref, bs),
142 num_pels_log2_lookup[bs]);
145 #if CONFIG_VP9_HIGHBITDEPTH
146 unsigned int vp9_high_get_sby_perpixel_variance(VP9_COMP *cpi,
147 const struct buf_2d *ref,
148 BLOCK_SIZE bs, int bd) {
149 return (unsigned int)ROUND64_POWER_OF_TWO(
150 (int64_t)vp9_high_get_sby_variance(cpi, ref, bs, bd),
151 num_pels_log2_lookup[bs]);
153 #endif // CONFIG_VP9_HIGHBITDEPTH
155 static unsigned int get_sby_perpixel_diff_variance(VP9_COMP *cpi,
156 const struct buf_2d *ref,
157 int mi_row, int mi_col,
159 unsigned int sse, var;
161 const YV12_BUFFER_CONFIG *last = get_ref_frame_buffer(cpi, LAST_FRAME);
163 assert(last != NULL);
165 &last->y_buffer[mi_row * MI_SIZE * last->y_stride + mi_col * MI_SIZE];
166 var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride, last_y, last->y_stride, &sse);
167 return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
170 static BLOCK_SIZE get_rd_var_based_fixed_partition(VP9_COMP *cpi, MACROBLOCK *x,
171 int mi_row, int mi_col) {
172 unsigned int var = get_sby_perpixel_diff_variance(
173 cpi, &x->plane[0].src, mi_row, mi_col, BLOCK_64X64);
184 static void set_segment_index(VP9_COMP *cpi, MACROBLOCK *const x, int mi_row,
185 int mi_col, BLOCK_SIZE bsize, int segment_index) {
186 VP9_COMMON *const cm = &cpi->common;
187 const struct segmentation *const seg = &cm->seg;
188 MACROBLOCKD *const xd = &x->e_mbd;
189 MODE_INFO *mi = xd->mi[0];
191 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
192 const uint8_t *const map =
193 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
195 // Initialize the segmentation index as 0.
198 // Skip the rest if AQ mode is disabled.
199 if (!seg->enabled) return;
202 case CYCLIC_REFRESH_AQ:
203 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
206 if (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
207 cpi->force_update_segmentation ||
208 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
211 // Get sub block energy range
212 if (bsize >= BLOCK_32X32) {
213 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
216 min_energy = bsize <= BLOCK_16X16 ? x->mb_energy
217 : vp9_block_energy(cpi, x, bsize);
219 mi->segment_id = vp9_vaq_segment_id(min_energy);
221 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
225 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
228 if (cm->frame_type == KEY_FRAME || cpi->force_update_segmentation)
229 mi->segment_id = vp9_360aq_segment_id(mi_row, cm->mi_rows);
231 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
233 case PSNR_AQ: mi->segment_id = segment_index; break;
239 // Set segment index from ROI map if it's enabled.
240 if (cpi->roi.enabled)
241 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
243 vp9_init_plane_quantizers(cpi, x);
246 // Lighter version of set_offsets that only sets the mode info
248 static INLINE void set_mode_info_offsets(VP9_COMMON *const cm,
250 MACROBLOCKD *const xd, int mi_row,
252 const int idx_str = xd->mi_stride * mi_row + mi_col;
253 xd->mi = cm->mi_grid_visible + idx_str;
254 xd->mi[0] = cm->mi + idx_str;
255 x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
258 static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
259 MACROBLOCK *const x, int mi_row, int mi_col,
261 VP9_COMMON *const cm = &cpi->common;
262 MACROBLOCKD *const xd = &x->e_mbd;
263 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
264 const int mi_height = num_8x8_blocks_high_lookup[bsize];
265 MvLimits *const mv_limits = &x->mv_limits;
267 set_skip_context(xd, mi_row, mi_col);
269 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
271 // Set up destination pointers.
272 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
274 // Set up limit values for MV components.
275 // Mv beyond the range do not produce new/different prediction block.
276 mv_limits->row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
277 mv_limits->col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
278 mv_limits->row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
279 mv_limits->col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
281 // Set up distance of MB to edge of frame in 1/8th pel units.
282 assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
283 set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width, cm->mi_rows,
286 // Set up source buffers.
287 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
290 x->rddiv = cpi->rd.RDDIV;
291 x->rdmult = cpi->rd.RDMULT;
293 // required by vp9_append_sub8x8_mvs_for_idx() and vp9_find_best_ref_mvs()
297 static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
298 int mi_row, int mi_col,
300 const int block_width =
301 VPXMIN(num_8x8_blocks_wide_lookup[bsize], cm->mi_cols - mi_col);
302 const int block_height =
303 VPXMIN(num_8x8_blocks_high_lookup[bsize], cm->mi_rows - mi_row);
304 const int mi_stride = xd->mi_stride;
305 MODE_INFO *const src_mi = xd->mi[0];
308 for (j = 0; j < block_height; ++j)
309 for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
312 static void set_block_size(VP9_COMP *const cpi, MACROBLOCK *const x,
313 MACROBLOCKD *const xd, int mi_row, int mi_col,
315 if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
316 set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
317 xd->mi[0]->sb_type = bsize;
322 // This struct is used for computing variance in choose_partitioning(), where
323 // the max number of samples within a superblock is 16x16 (with 4x4 avg). Even
324 // in high bitdepth, uint32_t is enough for sum_square_error (2^12 * 2^12 * 16
326 uint32_t sum_square_error;
336 } partition_variance;
339 partition_variance part_variances;
344 partition_variance part_variances;
349 partition_variance part_variances;
354 partition_variance part_variances;
359 partition_variance part_variances;
364 partition_variance *part_variances;
374 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
376 node->part_variances = NULL;
379 v64x64 *vt = (v64x64 *)data;
380 node->part_variances = &vt->part_variances;
381 for (i = 0; i < 4; i++)
382 node->split[i] = &vt->split[i].part_variances.none;
386 v32x32 *vt = (v32x32 *)data;
387 node->part_variances = &vt->part_variances;
388 for (i = 0; i < 4; i++)
389 node->split[i] = &vt->split[i].part_variances.none;
393 v16x16 *vt = (v16x16 *)data;
394 node->part_variances = &vt->part_variances;
395 for (i = 0; i < 4; i++)
396 node->split[i] = &vt->split[i].part_variances.none;
400 v8x8 *vt = (v8x8 *)data;
401 node->part_variances = &vt->part_variances;
402 for (i = 0; i < 4; i++)
403 node->split[i] = &vt->split[i].part_variances.none;
407 v4x4 *vt = (v4x4 *)data;
408 assert(bsize == BLOCK_4X4);
409 node->part_variances = &vt->part_variances;
410 for (i = 0; i < 4; i++) node->split[i] = &vt->split[i];
416 // Set variance values given sum square error, sum error, count.
417 static void fill_variance(uint32_t s2, int32_t s, int c, var *v) {
418 v->sum_square_error = s2;
423 static void get_variance(var *v) {
425 (int)(256 * (v->sum_square_error -
426 (uint32_t)(((int64_t)v->sum_error * v->sum_error) >>
431 static void sum_2_variances(const var *a, const var *b, var *r) {
432 assert(a->log2_count == b->log2_count);
433 fill_variance(a->sum_square_error + b->sum_square_error,
434 a->sum_error + b->sum_error, a->log2_count + 1, r);
437 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
439 memset(&node, 0, sizeof(node));
440 tree_to_node(data, bsize, &node);
441 sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
442 sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
443 sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
444 sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
445 sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
446 &node.part_variances->none);
449 static int set_vt_partitioning(VP9_COMP *cpi, MACROBLOCK *const x,
450 MACROBLOCKD *const xd, void *data,
451 BLOCK_SIZE bsize, int mi_row, int mi_col,
452 int64_t threshold, BLOCK_SIZE bsize_min,
454 VP9_COMMON *const cm = &cpi->common;
456 const int block_width = num_8x8_blocks_wide_lookup[bsize];
457 const int block_height = num_8x8_blocks_high_lookup[bsize];
459 assert(block_height == block_width);
460 tree_to_node(data, bsize, &vt);
462 if (force_split == 1) return 0;
464 // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
465 // variance is below threshold, otherwise split will be selected.
466 // No check for vert/horiz split as too few samples for variance.
467 if (bsize == bsize_min) {
468 // Variance already computed to set the force_split.
469 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
470 if (mi_col + block_width / 2 < cm->mi_cols &&
471 mi_row + block_height / 2 < cm->mi_rows &&
472 vt.part_variances->none.variance < threshold) {
473 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
477 } else if (bsize > bsize_min) {
478 // Variance already computed to set the force_split.
479 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
480 // For key frame: take split for bsize above 32X32 or very high variance.
481 if (frame_is_intra_only(cm) &&
482 (bsize > BLOCK_32X32 ||
483 vt.part_variances->none.variance > (threshold << 4))) {
486 // If variance is low, take the bsize (no split).
487 if (mi_col + block_width / 2 < cm->mi_cols &&
488 mi_row + block_height / 2 < cm->mi_rows &&
489 vt.part_variances->none.variance < threshold) {
490 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
494 // Check vertical split.
495 if (mi_row + block_height / 2 < cm->mi_rows) {
496 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
497 get_variance(&vt.part_variances->vert[0]);
498 get_variance(&vt.part_variances->vert[1]);
499 if (vt.part_variances->vert[0].variance < threshold &&
500 vt.part_variances->vert[1].variance < threshold &&
501 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
502 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
503 set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
507 // Check horizontal split.
508 if (mi_col + block_width / 2 < cm->mi_cols) {
509 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
510 get_variance(&vt.part_variances->horz[0]);
511 get_variance(&vt.part_variances->horz[1]);
512 if (vt.part_variances->horz[0].variance < threshold &&
513 vt.part_variances->horz[1].variance < threshold &&
514 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
515 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
516 set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
526 static int64_t scale_part_thresh_sumdiff(int64_t threshold_base, int speed,
527 int width, int height,
530 if (width <= 640 && height <= 480)
531 return (5 * threshold_base) >> 2;
532 else if ((content_state == kLowSadLowSumdiff) ||
533 (content_state == kHighSadLowSumdiff) ||
534 (content_state == kLowVarHighSumdiff))
535 return (5 * threshold_base) >> 2;
536 } else if (speed == 7) {
537 if ((content_state == kLowSadLowSumdiff) ||
538 (content_state == kHighSadLowSumdiff) ||
539 (content_state == kLowVarHighSumdiff)) {
540 return (5 * threshold_base) >> 2;
543 return threshold_base;
546 // Set the variance split thresholds for following the block sizes:
547 // 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
548 // 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
549 // currently only used on key frame.
550 static void set_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q,
552 VP9_COMMON *const cm = &cpi->common;
553 const int is_key_frame = frame_is_intra_only(cm);
554 const int threshold_multiplier = is_key_frame ? 20 : 1;
555 int64_t threshold_base =
556 (int64_t)(threshold_multiplier * cpi->y_dequant[q][1]);
559 thresholds[0] = threshold_base;
560 thresholds[1] = threshold_base >> 2;
561 thresholds[2] = threshold_base >> 2;
562 thresholds[3] = threshold_base << 2;
564 // Increase base variance threshold based on estimated noise level.
565 if (cpi->noise_estimate.enabled && cm->width >= 640 && cm->height >= 480) {
566 NOISE_LEVEL noise_level =
567 vp9_noise_estimate_extract_level(&cpi->noise_estimate);
568 if (noise_level == kHigh)
569 threshold_base = 3 * threshold_base;
570 else if (noise_level == kMedium)
571 threshold_base = threshold_base << 1;
572 else if (noise_level < kLow)
573 threshold_base = (7 * threshold_base) >> 3;
575 #if CONFIG_VP9_TEMPORAL_DENOISING
576 if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
577 cpi->oxcf.speed > 5 && cpi->denoiser.denoising_level >= kDenLow)
579 vp9_scale_part_thresh(threshold_base, cpi->denoiser.denoising_level,
580 content_state, cpi->svc.temporal_layer_id);
583 scale_part_thresh_sumdiff(threshold_base, cpi->oxcf.speed, cm->width,
584 cm->height, content_state);
586 // Increase base variance threshold based on content_state/sum_diff level.
587 threshold_base = scale_part_thresh_sumdiff(
588 threshold_base, cpi->oxcf.speed, cm->width, cm->height, content_state);
590 thresholds[0] = threshold_base;
591 thresholds[2] = threshold_base << cpi->oxcf.speed;
592 if (cm->width >= 1280 && cm->height >= 720 && cpi->oxcf.speed < 7)
593 thresholds[2] = thresholds[2] << 1;
594 if (cm->width <= 352 && cm->height <= 288) {
595 thresholds[0] = threshold_base >> 3;
596 thresholds[1] = threshold_base >> 1;
597 thresholds[2] = threshold_base << 3;
598 } else if (cm->width < 1280 && cm->height < 720) {
599 thresholds[1] = (5 * threshold_base) >> 2;
600 } else if (cm->width < 1920 && cm->height < 1080) {
601 thresholds[1] = threshold_base << 1;
603 thresholds[1] = (5 * threshold_base) >> 1;
605 if (cpi->sf.disable_16x16part_nonkey) thresholds[2] = INT64_MAX;
609 void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q,
611 VP9_COMMON *const cm = &cpi->common;
612 SPEED_FEATURES *const sf = &cpi->sf;
613 const int is_key_frame = frame_is_intra_only(cm);
614 if (sf->partition_search_type != VAR_BASED_PARTITION &&
615 sf->partition_search_type != REFERENCE_PARTITION) {
618 set_vbp_thresholds(cpi, cpi->vbp_thresholds, q, content_state);
619 // The thresholds below are not changed locally.
621 cpi->vbp_threshold_sad = 0;
622 cpi->vbp_threshold_copy = 0;
623 cpi->vbp_bsize_min = BLOCK_8X8;
625 if (cm->width <= 352 && cm->height <= 288)
626 cpi->vbp_threshold_sad = 10;
628 cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000
629 ? (cpi->y_dequant[q][1] << 1)
631 cpi->vbp_bsize_min = BLOCK_16X16;
632 if (cm->width <= 352 && cm->height <= 288)
633 cpi->vbp_threshold_copy = 4000;
634 else if (cm->width <= 640 && cm->height <= 360)
635 cpi->vbp_threshold_copy = 8000;
637 cpi->vbp_threshold_copy = (cpi->y_dequant[q][1] << 3) > 8000
638 ? (cpi->y_dequant[q][1] << 3)
640 if (cpi->rc.high_source_sad ||
641 (cpi->use_svc && cpi->svc.high_source_sad_superframe)) {
642 cpi->vbp_threshold_sad = 0;
643 cpi->vbp_threshold_copy = 0;
646 cpi->vbp_threshold_minmax = 15 + (q >> 3);
650 // Compute the minmax over the 8x8 subblocks.
651 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
652 int dp, int x16_idx, int y16_idx,
653 #if CONFIG_VP9_HIGHBITDEPTH
656 int pixels_wide, int pixels_high) {
659 int minmax_min = 255;
660 // Loop over the 4 8x8 subblocks.
661 for (k = 0; k < 4; k++) {
662 int x8_idx = x16_idx + ((k & 1) << 3);
663 int y8_idx = y16_idx + ((k >> 1) << 3);
666 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
667 #if CONFIG_VP9_HIGHBITDEPTH
668 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
669 vpx_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
670 d + y8_idx * dp + x8_idx, dp, &min, &max);
672 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx,
676 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx, dp,
679 if ((max - min) > minmax_max) minmax_max = (max - min);
680 if ((max - min) < minmax_min) minmax_min = (max - min);
683 return (minmax_max - minmax_min);
686 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
687 int dp, int x8_idx, int y8_idx, v8x8 *vst,
688 #if CONFIG_VP9_HIGHBITDEPTH
691 int pixels_wide, int pixels_high,
694 for (k = 0; k < 4; k++) {
695 int x4_idx = x8_idx + ((k & 1) << 2);
696 int y4_idx = y8_idx + ((k >> 1) << 2);
697 unsigned int sse = 0;
699 if (x4_idx < pixels_wide && y4_idx < pixels_high) {
702 #if CONFIG_VP9_HIGHBITDEPTH
703 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
704 s_avg = vpx_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
706 d_avg = vpx_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
708 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
709 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
712 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
713 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
718 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
722 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
723 int dp, int x16_idx, int y16_idx, v16x16 *vst,
724 #if CONFIG_VP9_HIGHBITDEPTH
727 int pixels_wide, int pixels_high,
730 for (k = 0; k < 4; k++) {
731 int x8_idx = x16_idx + ((k & 1) << 3);
732 int y8_idx = y16_idx + ((k >> 1) << 3);
733 unsigned int sse = 0;
735 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
738 #if CONFIG_VP9_HIGHBITDEPTH
739 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
740 s_avg = vpx_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
742 d_avg = vpx_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
744 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
745 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
748 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
749 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
754 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
758 // Check if most of the superblock is skin content, and if so, force split to
759 // 32x32, and set x->sb_is_skin for use in mode selection.
760 static int skin_sb_split(VP9_COMP *cpi, MACROBLOCK *x, const int low_res,
761 int mi_row, int mi_col, int *force_split) {
762 VP9_COMMON *const cm = &cpi->common;
763 #if CONFIG_VP9_HIGHBITDEPTH
764 if (cm->use_highbitdepth) return 0;
766 // Avoid checking superblocks on/near boundary and avoid low resolutions.
767 // Note superblock may still pick 64X64 if y_sad is very small
768 // (i.e., y_sad < cpi->vbp_threshold_sad) below. For now leave this as is.
769 if (!low_res && (mi_col >= 8 && mi_col + 8 < cm->mi_cols && mi_row >= 8 &&
770 mi_row + 8 < cm->mi_rows)) {
771 int num_16x16_skin = 0;
772 int num_16x16_nonskin = 0;
773 uint8_t *ysignal = x->plane[0].src.buf;
774 uint8_t *usignal = x->plane[1].src.buf;
775 uint8_t *vsignal = x->plane[2].src.buf;
776 int sp = x->plane[0].src.stride;
777 int spuv = x->plane[1].src.stride;
778 const int block_index = mi_row * cm->mi_cols + mi_col;
779 const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
780 const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
781 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
782 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
783 // Loop through the 16x16 sub-blocks.
785 for (i = 0; i < ymis; i += 2) {
786 for (j = 0; j < xmis; j += 2) {
787 int bl_index = block_index + i * cm->mi_cols + j;
788 int is_skin = cpi->skin_map[bl_index];
789 num_16x16_skin += is_skin;
790 num_16x16_nonskin += (1 - is_skin);
791 if (num_16x16_nonskin > 3) {
792 // Exit loop if at least 4 of the 16x16 blocks are not skin.
800 ysignal += (sp << 4) - 64;
801 usignal += (spuv << 3) - 32;
802 vsignal += (spuv << 3) - 32;
804 if (num_16x16_skin > 12) {
812 static void set_low_temp_var_flag(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
813 v64x64 *vt, int64_t thresholds[],
814 MV_REFERENCE_FRAME ref_frame_partition,
815 int mi_col, int mi_row) {
817 VP9_COMMON *const cm = &cpi->common;
818 const int mv_thr = cm->width > 640 ? 8 : 4;
819 // Check temporal variance for bsize >= 16x16, if LAST_FRAME was selected and
820 // int_pro mv is small. If the temporal variance is small set the flag
821 // variance_low for the block. The variance threshold can be adjusted, the
822 // higher the more aggressive.
823 if (ref_frame_partition == LAST_FRAME &&
824 (cpi->sf.short_circuit_low_temp_var == 1 ||
825 (xd->mi[0]->mv[0].as_mv.col < mv_thr &&
826 xd->mi[0]->mv[0].as_mv.col > -mv_thr &&
827 xd->mi[0]->mv[0].as_mv.row < mv_thr &&
828 xd->mi[0]->mv[0].as_mv.row > -mv_thr))) {
829 if (xd->mi[0]->sb_type == BLOCK_64X64) {
830 if ((vt->part_variances).none.variance < (thresholds[0] >> 1))
831 x->variance_low[0] = 1;
832 } else if (xd->mi[0]->sb_type == BLOCK_64X32) {
833 for (i = 0; i < 2; i++) {
834 if (vt->part_variances.horz[i].variance < (thresholds[0] >> 2))
835 x->variance_low[i + 1] = 1;
837 } else if (xd->mi[0]->sb_type == BLOCK_32X64) {
838 for (i = 0; i < 2; i++) {
839 if (vt->part_variances.vert[i].variance < (thresholds[0] >> 2))
840 x->variance_low[i + 3] = 1;
843 for (i = 0; i < 4; i++) {
844 const int idx[4][2] = { { 0, 0 }, { 0, 4 }, { 4, 0 }, { 4, 4 } };
846 cm->mi_stride * (mi_row + idx[i][0]) + mi_col + idx[i][1];
847 MODE_INFO **this_mi = cm->mi_grid_visible + idx_str;
849 if (cm->mi_cols <= mi_col + idx[i][1] ||
850 cm->mi_rows <= mi_row + idx[i][0])
853 if ((*this_mi)->sb_type == BLOCK_32X32) {
854 int64_t threshold_32x32 = (cpi->sf.short_circuit_low_temp_var == 1 ||
855 cpi->sf.short_circuit_low_temp_var == 3)
856 ? ((5 * thresholds[1]) >> 3)
857 : (thresholds[1] >> 1);
858 if (vt->split[i].part_variances.none.variance < threshold_32x32)
859 x->variance_low[i + 5] = 1;
860 } else if (cpi->sf.short_circuit_low_temp_var >= 2) {
861 // For 32x16 and 16x32 blocks, the flag is set on each 16x16 block
863 if ((*this_mi)->sb_type == BLOCK_16X16 ||
864 (*this_mi)->sb_type == BLOCK_32X16 ||
865 (*this_mi)->sb_type == BLOCK_16X32) {
866 for (j = 0; j < 4; j++) {
867 if (vt->split[i].split[j].part_variances.none.variance <
868 (thresholds[2] >> 8))
869 x->variance_low[(i << 2) + j + 9] = 1;
878 static void copy_partitioning_helper(VP9_COMP *cpi, MACROBLOCK *x,
879 MACROBLOCKD *xd, BLOCK_SIZE bsize,
880 int mi_row, int mi_col) {
881 VP9_COMMON *const cm = &cpi->common;
882 BLOCK_SIZE *prev_part = cpi->prev_partition;
883 int start_pos = mi_row * cm->mi_stride + mi_col;
885 const int bsl = b_width_log2_lookup[bsize];
886 const int bs = (1 << bsl) >> 2;
888 PARTITION_TYPE partition;
890 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
892 partition = partition_lookup[bsl][prev_part[start_pos]];
893 subsize = get_subsize(bsize, partition);
895 if (subsize < BLOCK_8X8) {
896 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
900 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
903 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
904 set_block_size(cpi, x, xd, mi_row + bs, mi_col, subsize);
907 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
908 set_block_size(cpi, x, xd, mi_row, mi_col + bs, subsize);
911 assert(partition == PARTITION_SPLIT);
912 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col);
913 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col);
914 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col + bs);
915 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col + bs);
921 static int copy_partitioning(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
922 int mi_row, int mi_col, int segment_id,
924 int svc_copy_allowed = 1;
925 int frames_since_key_thresh = 1;
927 // For SVC, don't allow copy if base spatial layer is key frame, or if
928 // frame is not a temporal enhancement layer frame.
929 int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
930 cpi->svc.number_temporal_layers);
931 const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
932 if (lc->is_key_frame || !cpi->svc.non_reference_frame) svc_copy_allowed = 0;
933 frames_since_key_thresh = cpi->svc.number_spatial_layers << 1;
935 if (cpi->rc.frames_since_key > frames_since_key_thresh && svc_copy_allowed &&
936 !cpi->resize_pending && segment_id == CR_SEGMENT_ID_BASE &&
937 cpi->prev_segment_id[sb_offset] == CR_SEGMENT_ID_BASE &&
938 cpi->copied_frame_cnt[sb_offset] < cpi->max_copied_frame) {
939 if (cpi->prev_partition != NULL) {
940 copy_partitioning_helper(cpi, x, xd, BLOCK_64X64, mi_row, mi_col);
941 cpi->copied_frame_cnt[sb_offset] += 1;
942 memcpy(x->variance_low, &(cpi->prev_variance_low[sb_offset * 25]),
943 sizeof(x->variance_low));
951 static int scale_partitioning_svc(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
952 BLOCK_SIZE bsize, int mi_row, int mi_col,
953 int mi_row_high, int mi_col_high) {
954 VP9_COMMON *const cm = &cpi->common;
955 SVC *const svc = &cpi->svc;
956 BLOCK_SIZE *prev_part = svc->prev_partition_svc;
957 // Variables with _high are for higher resolution.
959 int subsize_high = 0;
960 const int bsl_high = b_width_log2_lookup[bsize];
961 const int bs_high = (1 << bsl_high) >> 2;
962 const int has_rows = (mi_row_high + bs_high) < cm->mi_rows;
963 const int has_cols = (mi_col_high + bs_high) < cm->mi_cols;
965 const int row_boundary_block_scale_factor[BLOCK_SIZES] = {
966 13, 13, 13, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0
968 const int col_boundary_block_scale_factor[BLOCK_SIZES] = {
969 13, 13, 13, 2, 2, 0, 2, 2, 0, 2, 2, 0, 0
972 BLOCK_SIZE bsize_low;
973 PARTITION_TYPE partition_high;
975 if (mi_row_high >= cm->mi_rows || mi_col_high >= cm->mi_cols) return 0;
976 if (mi_row >= svc->mi_rows[svc->spatial_layer_id - 1] ||
977 mi_col >= svc->mi_cols[svc->spatial_layer_id - 1])
980 // Find corresponding (mi_col/mi_row) block down-scaled by 2x2.
981 start_pos = mi_row * (svc->mi_stride[svc->spatial_layer_id - 1]) + mi_col;
982 bsize_low = prev_part[start_pos];
983 // The block size is too big for boundaries. Do variance based partitioning.
984 if ((!has_rows || !has_cols) && bsize_low > BLOCK_16X16) return 1;
986 // For reference frames: return 1 (do variance-based partitioning) if the
987 // superblock is not low source sad and lower-resoln bsize is below 32x32.
988 if (!cpi->svc.non_reference_frame && !x->skip_low_source_sad &&
989 bsize_low < BLOCK_32X32)
992 // Scale up block size by 2x2. Force 64x64 for size larger than 32x32.
993 if (bsize_low < BLOCK_32X32) {
994 bsize_high = bsize_low + 3;
995 } else if (bsize_low >= BLOCK_32X32) {
996 bsize_high = BLOCK_64X64;
998 // Scale up blocks on boundary.
999 if (!has_cols && has_rows) {
1000 bsize_high = bsize_low + row_boundary_block_scale_factor[bsize_low];
1001 } else if (has_cols && !has_rows) {
1002 bsize_high = bsize_low + col_boundary_block_scale_factor[bsize_low];
1003 } else if (!has_cols && !has_rows) {
1004 bsize_high = bsize_low;
1007 partition_high = partition_lookup[bsl_high][bsize_high];
1008 subsize_high = get_subsize(bsize, partition_high);
1010 if (subsize_high < BLOCK_8X8) {
1011 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1013 const int bsl = b_width_log2_lookup[bsize];
1014 const int bs = (1 << bsl) >> 2;
1015 switch (partition_high) {
1016 case PARTITION_NONE:
1017 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1019 case PARTITION_HORZ:
1020 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1021 if (subsize_high < BLOCK_64X64)
1022 set_block_size(cpi, x, xd, mi_row_high + bs_high, mi_col_high,
1025 case PARTITION_VERT:
1026 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1027 if (subsize_high < BLOCK_64X64)
1028 set_block_size(cpi, x, xd, mi_row_high, mi_col_high + bs_high,
1032 assert(partition_high == PARTITION_SPLIT);
1033 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row, mi_col,
1034 mi_row_high, mi_col_high))
1036 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1037 mi_col, mi_row_high + bs_high, mi_col_high))
1039 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row,
1040 mi_col + (bs >> 1), mi_row_high,
1041 mi_col_high + bs_high))
1043 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1044 mi_col + (bs >> 1), mi_row_high + bs_high,
1045 mi_col_high + bs_high))
1054 static void update_partition_svc(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
1056 VP9_COMMON *const cm = &cpi->common;
1057 BLOCK_SIZE *prev_part = cpi->svc.prev_partition_svc;
1058 int start_pos = mi_row * cm->mi_stride + mi_col;
1059 const int bsl = b_width_log2_lookup[bsize];
1060 const int bs = (1 << bsl) >> 2;
1062 PARTITION_TYPE partition;
1063 const MODE_INFO *mi = NULL;
1066 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1068 mi = cm->mi_grid_visible[start_pos];
1069 partition = partition_lookup[bsl][mi->sb_type];
1070 subsize = get_subsize(bsize, partition);
1071 if (subsize < BLOCK_8X8) {
1072 prev_part[start_pos] = bsize;
1074 switch (partition) {
1075 case PARTITION_NONE:
1076 prev_part[start_pos] = bsize;
1077 if (bsize == BLOCK_64X64) {
1078 for (xx = 0; xx < 8; xx += 4)
1079 for (yy = 0; yy < 8; yy += 4) {
1080 if ((mi_row + xx < cm->mi_rows) && (mi_col + yy < cm->mi_cols))
1081 prev_part[start_pos + xx * cm->mi_stride + yy] = bsize;
1085 case PARTITION_HORZ:
1086 prev_part[start_pos] = subsize;
1087 if (mi_row + bs < cm->mi_rows)
1088 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1090 case PARTITION_VERT:
1091 prev_part[start_pos] = subsize;
1092 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1095 assert(partition == PARTITION_SPLIT);
1096 update_partition_svc(cpi, subsize, mi_row, mi_col);
1097 update_partition_svc(cpi, subsize, mi_row + bs, mi_col);
1098 update_partition_svc(cpi, subsize, mi_row, mi_col + bs);
1099 update_partition_svc(cpi, subsize, mi_row + bs, mi_col + bs);
1105 static void update_prev_partition_helper(VP9_COMP *cpi, BLOCK_SIZE bsize,
1106 int mi_row, int mi_col) {
1107 VP9_COMMON *const cm = &cpi->common;
1108 BLOCK_SIZE *prev_part = cpi->prev_partition;
1109 int start_pos = mi_row * cm->mi_stride + mi_col;
1110 const int bsl = b_width_log2_lookup[bsize];
1111 const int bs = (1 << bsl) >> 2;
1113 PARTITION_TYPE partition;
1114 const MODE_INFO *mi = NULL;
1116 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1118 mi = cm->mi_grid_visible[start_pos];
1119 partition = partition_lookup[bsl][mi->sb_type];
1120 subsize = get_subsize(bsize, partition);
1121 if (subsize < BLOCK_8X8) {
1122 prev_part[start_pos] = bsize;
1124 switch (partition) {
1125 case PARTITION_NONE: prev_part[start_pos] = bsize; break;
1126 case PARTITION_HORZ:
1127 prev_part[start_pos] = subsize;
1128 if (mi_row + bs < cm->mi_rows)
1129 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1131 case PARTITION_VERT:
1132 prev_part[start_pos] = subsize;
1133 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1136 assert(partition == PARTITION_SPLIT);
1137 update_prev_partition_helper(cpi, subsize, mi_row, mi_col);
1138 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col);
1139 update_prev_partition_helper(cpi, subsize, mi_row, mi_col + bs);
1140 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col + bs);
1146 static void update_prev_partition(VP9_COMP *cpi, MACROBLOCK *x, int segment_id,
1147 int mi_row, int mi_col, int sb_offset) {
1148 update_prev_partition_helper(cpi, BLOCK_64X64, mi_row, mi_col);
1149 cpi->prev_segment_id[sb_offset] = segment_id;
1150 memcpy(&(cpi->prev_variance_low[sb_offset * 25]), x->variance_low,
1151 sizeof(x->variance_low));
1152 // Reset the counter for copy partitioning
1153 cpi->copied_frame_cnt[sb_offset] = 0;
1156 static void chroma_check(VP9_COMP *cpi, MACROBLOCK *x, int bsize,
1157 unsigned int y_sad, int is_key_frame) {
1159 MACROBLOCKD *xd = &x->e_mbd;
1161 if (is_key_frame) return;
1163 // For speed >= 8, avoid the chroma check if y_sad is above threshold.
1164 if (cpi->oxcf.speed >= 8) {
1165 if (y_sad > cpi->vbp_thresholds[1] &&
1166 (!cpi->noise_estimate.enabled ||
1167 vp9_noise_estimate_extract_level(&cpi->noise_estimate) < kMedium))
1171 for (i = 1; i <= 2; ++i) {
1172 unsigned int uv_sad = UINT_MAX;
1173 struct macroblock_plane *p = &x->plane[i];
1174 struct macroblockd_plane *pd = &xd->plane[i];
1175 const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
1177 if (bs != BLOCK_INVALID)
1178 uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride, pd->dst.buf,
1181 // TODO(marpan): Investigate if we should lower this threshold if
1182 // superblock is detected as skin.
1183 x->color_sensitivity[i - 1] = uv_sad > (y_sad >> 2);
1187 static uint64_t avg_source_sad(VP9_COMP *cpi, MACROBLOCK *x, int shift,
1189 unsigned int tmp_sse;
1191 unsigned int tmp_variance;
1192 const BLOCK_SIZE bsize = BLOCK_64X64;
1193 uint8_t *src_y = cpi->Source->y_buffer;
1194 int src_ystride = cpi->Source->y_stride;
1195 uint8_t *last_src_y = cpi->Last_Source->y_buffer;
1196 int last_src_ystride = cpi->Last_Source->y_stride;
1197 uint64_t avg_source_sad_threshold = 10000;
1198 uint64_t avg_source_sad_threshold2 = 12000;
1199 #if CONFIG_VP9_HIGHBITDEPTH
1200 if (cpi->common.use_highbitdepth) return 0;
1203 last_src_y += shift;
1205 cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y, last_src_ystride);
1206 tmp_variance = vpx_variance64x64(src_y, src_ystride, last_src_y,
1207 last_src_ystride, &tmp_sse);
1208 // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1209 if (tmp_sad < avg_source_sad_threshold)
1210 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kLowSadLowSumdiff
1211 : kLowSadHighSumdiff;
1213 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kHighSadLowSumdiff
1214 : kHighSadHighSumdiff;
1216 // Detect large lighting change.
1217 if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
1218 cpi->oxcf.rc_mode == VPX_CBR && tmp_variance < (tmp_sse >> 3) &&
1219 (tmp_sse - tmp_variance) > 10000)
1220 x->content_state_sb = kLowVarHighSumdiff;
1221 else if (tmp_sad > (avg_source_sad_threshold << 1))
1222 x->content_state_sb = kVeryHighSad;
1224 if (cpi->content_state_sb_fd != NULL) {
1225 if (tmp_sad < avg_source_sad_threshold2) {
1226 // Cap the increment to 255.
1227 if (cpi->content_state_sb_fd[sb_offset] < 255)
1228 cpi->content_state_sb_fd[sb_offset]++;
1230 cpi->content_state_sb_fd[sb_offset] = 0;
1233 if (tmp_sad == 0) x->zero_temp_sad_source = 1;
1237 // This function chooses partitioning based on the variance between source and
1238 // reconstructed last, where variance is computed for down-sampled inputs.
1239 static int choose_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1240 MACROBLOCK *x, int mi_row, int mi_col) {
1241 VP9_COMMON *const cm = &cpi->common;
1242 MACROBLOCKD *xd = &x->e_mbd;
1246 int force_split[21];
1248 int max_var_32x32 = 0;
1249 int min_var_32x32 = INT_MAX;
1252 int maxvar_16x16[4];
1253 int minvar_16x16[4];
1254 int64_t threshold_4x4avg;
1255 NOISE_LEVEL noise_level = kLow;
1256 int content_state = 0;
1261 int compute_minmax_variance = 1;
1262 unsigned int y_sad = UINT_MAX;
1263 BLOCK_SIZE bsize = BLOCK_64X64;
1264 // Ref frame used in partitioning.
1265 MV_REFERENCE_FRAME ref_frame_partition = LAST_FRAME;
1266 int pixels_wide = 64, pixels_high = 64;
1267 int64_t thresholds[4] = { cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
1268 cpi->vbp_thresholds[2], cpi->vbp_thresholds[3] };
1269 int force_64_split = cpi->rc.high_source_sad ||
1270 (cpi->use_svc && cpi->svc.high_source_sad_superframe) ||
1271 (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1272 cpi->compute_source_sad_onepass &&
1273 cpi->sf.use_source_sad && !x->zero_temp_sad_source);
1275 // For the variance computation under SVC mode, we treat the frame as key if
1276 // the reference (base layer frame) is key frame (i.e., is_key_frame == 1).
1278 (frame_is_intra_only(cm) ||
1279 (is_one_pass_cbr_svc(cpi) &&
1280 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame));
1281 // Always use 4x4 partition for key frame.
1282 const int use_4x4_partition = frame_is_intra_only(cm);
1283 const int low_res = (cm->width <= 352 && cm->height <= 288);
1284 int variance4x4downsample[16];
1286 int sb_offset = (cm->mi_stride >> 3) * (mi_row >> 3) + (mi_col >> 3);
1288 // For SVC: check if LAST frame is NULL or if the resolution of LAST is
1289 // different than the current frame resolution, and if so, treat this frame
1290 // as a key frame, for the purpose of the superblock partitioning.
1291 // LAST == NULL can happen in some cases where enhancement spatial layers are
1292 // enabled dyanmically in the stream and the only reference is the spatial
1293 // reference (GOLDEN).
1295 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, LAST_FRAME);
1296 if (ref == NULL || ref->y_crop_height != cm->height ||
1297 ref->y_crop_width != cm->width)
1301 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
1302 set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
1303 segment_id = xd->mi[0]->segment_id;
1305 if (cpi->oxcf.speed >= 8 || (cpi->use_svc && cpi->svc.non_reference_frame))
1306 compute_minmax_variance = 0;
1308 memset(x->variance_low, 0, sizeof(x->variance_low));
1310 if (cpi->sf.use_source_sad && !is_key_frame) {
1311 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1312 content_state = x->content_state_sb;
1313 x->skip_low_source_sad = (content_state == kLowSadLowSumdiff ||
1314 content_state == kLowSadHighSumdiff)
1317 x->lowvar_highsumdiff = (content_state == kLowVarHighSumdiff) ? 1 : 0;
1318 if (cpi->content_state_sb_fd != NULL)
1319 x->last_sb_high_content = cpi->content_state_sb_fd[sb_offset2];
1321 // For SVC on top spatial layer: use/scale the partition from
1322 // the lower spatial resolution if svc_use_lowres_part is enabled.
1323 if (cpi->sf.svc_use_lowres_part &&
1324 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1325 cpi->svc.prev_partition_svc != NULL && content_state != kVeryHighSad) {
1326 if (!scale_partitioning_svc(cpi, x, xd, BLOCK_64X64, mi_row >> 1,
1327 mi_col >> 1, mi_row, mi_col)) {
1328 if (cpi->sf.copy_partition_flag) {
1329 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1334 // If source_sad is low copy the partition without computing the y_sad.
1335 if (x->skip_low_source_sad && cpi->sf.copy_partition_flag &&
1337 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1338 x->sb_use_mv_part = 1;
1339 if (cpi->sf.svc_use_lowres_part &&
1340 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1341 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1346 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
1347 cyclic_refresh_segment_id_boosted(segment_id)) {
1348 int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
1349 set_vbp_thresholds(cpi, thresholds, q, content_state);
1351 set_vbp_thresholds(cpi, thresholds, cm->base_qindex, content_state);
1354 // For non keyframes, disable 4x4 average for low resolution when speed = 8
1355 threshold_4x4avg = (cpi->oxcf.speed < 8) ? thresholds[1] << 1 : INT64_MAX;
1357 if (xd->mb_to_right_edge < 0) pixels_wide += (xd->mb_to_right_edge >> 3);
1358 if (xd->mb_to_bottom_edge < 0) pixels_high += (xd->mb_to_bottom_edge >> 3);
1360 s = x->plane[0].src.buf;
1361 sp = x->plane[0].src.stride;
1363 // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
1364 // 5-20 for the 16x16 blocks.
1365 force_split[0] = force_64_split;
1367 if (!is_key_frame) {
1368 // In the case of spatial/temporal scalable coding, the assumption here is
1369 // that the temporal reference frame will always be of type LAST_FRAME.
1370 // TODO(marpan): If that assumption is broken, we need to revisit this code.
1371 MODE_INFO *mi = xd->mi[0];
1372 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1374 const YV12_BUFFER_CONFIG *yv12_g = NULL;
1375 unsigned int y_sad_g, y_sad_thr, y_sad_last;
1376 bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
1377 (mi_row + 4 < cm->mi_rows);
1379 assert(yv12 != NULL);
1381 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
1382 cpi->svc.use_gf_temporal_ref_current_layer) {
1383 // For now, GOLDEN will not be used for non-zero spatial layers, since
1384 // it may not be a temporal reference.
1385 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1388 // Only compute y_sad_g (sad for golden reference) for speed < 8.
1389 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
1390 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
1391 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1392 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1393 y_sad_g = cpi->fn_ptr[bsize].sdf(
1394 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1395 xd->plane[0].pre[0].stride);
1400 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
1401 cpi->rc.is_src_frame_alt_ref) {
1402 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
1403 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1404 &cm->frame_refs[ALTREF_FRAME - 1].sf);
1405 mi->ref_frame[0] = ALTREF_FRAME;
1408 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1409 &cm->frame_refs[LAST_FRAME - 1].sf);
1410 mi->ref_frame[0] = LAST_FRAME;
1412 mi->ref_frame[1] = NONE;
1413 mi->sb_type = BLOCK_64X64;
1414 mi->mv[0].as_int = 0;
1415 mi->interp_filter = BILINEAR;
1417 if (cpi->oxcf.speed >= 8 && !low_res &&
1418 x->content_state_sb != kVeryHighSad) {
1419 y_sad = cpi->fn_ptr[bsize].sdf(
1420 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1421 xd->plane[0].pre[0].stride);
1423 const MV dummy_mv = { 0, 0 };
1424 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
1426 x->sb_use_mv_part = 1;
1427 x->sb_mvcol_part = mi->mv[0].as_mv.col;
1428 x->sb_mvrow_part = mi->mv[0].as_mv.row;
1429 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1430 cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
1431 cpi->svc.high_num_blocks_with_motion && !x->zero_temp_sad_source &&
1432 cm->width > 640 && cm->height > 480) {
1433 // Disable split below 16x16 block size when scroll motion (horz or
1434 // vert) is detected.
1435 // TODO(marpan/jianj): Improve this condition: issue is that search
1436 // range is hard-coded/limited in vp9_int_pro_motion_estimation() so
1437 // scroll motion may not be detected here.
1438 if (((abs(x->sb_mvrow_part) >= 48 && abs(x->sb_mvcol_part) <= 8) ||
1439 (abs(x->sb_mvcol_part) >= 48 && abs(x->sb_mvrow_part) <= 8)) &&
1441 compute_minmax_variance = 0;
1442 thresholds[2] = INT64_MAX;
1448 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
1449 // are close if short_circuit_low_temp_var is on.
1450 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
1451 if (y_sad_g < y_sad_thr) {
1452 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1453 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1454 mi->ref_frame[0] = GOLDEN_FRAME;
1455 mi->mv[0].as_int = 0;
1457 ref_frame_partition = GOLDEN_FRAME;
1459 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
1460 ref_frame_partition = LAST_FRAME;
1463 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
1464 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
1466 if (cpi->use_skin_detection)
1468 skin_sb_split(cpi, x, low_res, mi_row, mi_col, force_split);
1470 d = xd->plane[0].dst.buf;
1471 dp = xd->plane[0].dst.stride;
1473 // If the y_sad is very small, take 64x64 as partition and exit.
1474 // Don't check on boosted segment for now, as 64x64 is suppressed there.
1475 if (segment_id == CR_SEGMENT_ID_BASE && y_sad < cpi->vbp_threshold_sad) {
1476 const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
1477 const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
1478 if (mi_col + block_width / 2 < cm->mi_cols &&
1479 mi_row + block_height / 2 < cm->mi_rows) {
1480 set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
1481 x->variance_low[0] = 1;
1482 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1483 if (cpi->sf.svc_use_lowres_part &&
1484 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1485 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1486 if (cpi->sf.copy_partition_flag) {
1487 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1493 // If the y_sad is small enough, copy the partition of the superblock in the
1494 // last frame to current frame only if the last frame is not a keyframe.
1495 // Stop the copy every cpi->max_copied_frame to refresh the partition.
1496 // TODO(jianj) : tune the threshold.
1497 if (cpi->sf.copy_partition_flag && y_sad_last < cpi->vbp_threshold_copy &&
1498 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1499 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1500 if (cpi->sf.svc_use_lowres_part &&
1501 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1502 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1508 #if CONFIG_VP9_HIGHBITDEPTH
1509 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1511 case 10: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10); break;
1512 case 12: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12); break;
1514 default: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8); break;
1517 #endif // CONFIG_VP9_HIGHBITDEPTH
1520 if (low_res && threshold_4x4avg < INT64_MAX)
1521 CHECK_MEM_ERROR(cm, vt2, vpx_calloc(16, sizeof(*vt2)));
1522 // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
1524 for (i = 0; i < 4; i++) {
1525 const int x32_idx = ((i & 1) << 5);
1526 const int y32_idx = ((i >> 1) << 5);
1527 const int i2 = i << 2;
1528 force_split[i + 1] = 0;
1530 maxvar_16x16[i] = 0;
1531 minvar_16x16[i] = INT_MAX;
1532 for (j = 0; j < 4; j++) {
1533 const int x16_idx = x32_idx + ((j & 1) << 4);
1534 const int y16_idx = y32_idx + ((j >> 1) << 4);
1535 const int split_index = 5 + i2 + j;
1536 v16x16 *vst = &vt.split[i].split[j];
1537 force_split[split_index] = 0;
1538 variance4x4downsample[i2 + j] = 0;
1539 if (!is_key_frame) {
1540 fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
1541 #if CONFIG_VP9_HIGHBITDEPTH
1544 pixels_wide, pixels_high, is_key_frame);
1545 fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1546 get_variance(&vt.split[i].split[j].part_variances.none);
1547 avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance;
1548 if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i])
1549 minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1550 if (vt.split[i].split[j].part_variances.none.variance > maxvar_16x16[i])
1551 maxvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1552 if (vt.split[i].split[j].part_variances.none.variance > thresholds[2]) {
1553 // 16X16 variance is above threshold for split, so force split to 8x8
1554 // for this 16x16 block (this also forces splits for upper levels).
1555 force_split[split_index] = 1;
1556 force_split[i + 1] = 1;
1558 } else if (compute_minmax_variance &&
1559 vt.split[i].split[j].part_variances.none.variance >
1561 !cyclic_refresh_segment_id_boosted(segment_id)) {
1562 // We have some nominal amount of 16x16 variance (based on average),
1563 // compute the minmax over the 8x8 sub-blocks, and if above threshold,
1564 // force split to 8x8 block for this 16x16 block.
1565 int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
1566 #if CONFIG_VP9_HIGHBITDEPTH
1569 pixels_wide, pixels_high);
1570 int thresh_minmax = (int)cpi->vbp_threshold_minmax;
1571 if (x->content_state_sb == kVeryHighSad)
1572 thresh_minmax = thresh_minmax << 1;
1573 if (minmax > thresh_minmax) {
1574 force_split[split_index] = 1;
1575 force_split[i + 1] = 1;
1581 (low_res && vt.split[i].split[j].part_variances.none.variance >
1582 threshold_4x4avg)) {
1583 force_split[split_index] = 0;
1584 // Go down to 4x4 down-sampling for variance.
1585 variance4x4downsample[i2 + j] = 1;
1586 for (k = 0; k < 4; k++) {
1587 int x8_idx = x16_idx + ((k & 1) << 3);
1588 int y8_idx = y16_idx + ((k >> 1) << 3);
1589 v8x8 *vst2 = is_key_frame ? &vst->split[k] : &vt2[i2 + j].split[k];
1590 fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
1591 #if CONFIG_VP9_HIGHBITDEPTH
1594 pixels_wide, pixels_high, is_key_frame);
1599 if (cpi->noise_estimate.enabled)
1600 noise_level = vp9_noise_estimate_extract_level(&cpi->noise_estimate);
1601 // Fill the rest of the variance tree by summing split partition values.
1603 for (i = 0; i < 4; i++) {
1604 const int i2 = i << 2;
1605 for (j = 0; j < 4; j++) {
1606 if (variance4x4downsample[i2 + j] == 1) {
1607 v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] : &vt.split[i].split[j];
1608 for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
1609 fill_variance_tree(vtemp, BLOCK_16X16);
1610 // If variance of this 16x16 block is above the threshold, force block
1611 // to split. This also forces a split on the upper levels.
1612 get_variance(&vtemp->part_variances.none);
1613 if (vtemp->part_variances.none.variance > thresholds[2]) {
1614 force_split[5 + i2 + j] = 1;
1615 force_split[i + 1] = 1;
1620 fill_variance_tree(&vt.split[i], BLOCK_32X32);
1621 // If variance of this 32x32 block is above the threshold, or if its above
1622 // (some threshold of) the average variance over the sub-16x16 blocks, then
1623 // force this block to split. This also forces a split on the upper
1625 if (!force_split[i + 1]) {
1626 get_variance(&vt.split[i].part_variances.none);
1627 var_32x32 = vt.split[i].part_variances.none.variance;
1628 max_var_32x32 = VPXMAX(var_32x32, max_var_32x32);
1629 min_var_32x32 = VPXMIN(var_32x32, min_var_32x32);
1630 if (vt.split[i].part_variances.none.variance > thresholds[1] ||
1632 vt.split[i].part_variances.none.variance > (thresholds[1] >> 1) &&
1633 vt.split[i].part_variances.none.variance > (avg_16x16[i] >> 1))) {
1634 force_split[i + 1] = 1;
1636 } else if (!is_key_frame && noise_level < kLow && cm->height <= 360 &&
1637 (maxvar_16x16[i] - minvar_16x16[i]) > (thresholds[1] >> 1) &&
1638 maxvar_16x16[i] > thresholds[1]) {
1639 force_split[i + 1] = 1;
1642 avg_32x32 += var_32x32;
1645 if (!force_split[0]) {
1646 fill_variance_tree(&vt, BLOCK_64X64);
1647 get_variance(&vt.part_variances.none);
1648 // If variance of this 64x64 block is above (some threshold of) the average
1649 // variance over the sub-32x32 blocks, then force this block to split.
1650 // Only checking this for noise level >= medium for now.
1651 if (!is_key_frame && noise_level >= kMedium &&
1652 vt.part_variances.none.variance > (9 * avg_32x32) >> 5)
1654 // Else if the maximum 32x32 variance minus the miniumum 32x32 variance in
1655 // a 64x64 block is greater than threshold and the maximum 32x32 variance is
1656 // above a miniumum threshold, then force the split of a 64x64 block
1657 // Only check this for low noise.
1658 else if (!is_key_frame && noise_level < kMedium &&
1659 (max_var_32x32 - min_var_32x32) > 3 * (thresholds[0] >> 3) &&
1660 max_var_32x32 > thresholds[0] >> 1)
1664 // Now go through the entire structure, splitting every block size until
1665 // we get to one that's got a variance lower than our threshold.
1666 if (mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
1667 !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
1668 thresholds[0], BLOCK_16X16, force_split[0])) {
1669 for (i = 0; i < 4; ++i) {
1670 const int x32_idx = ((i & 1) << 2);
1671 const int y32_idx = ((i >> 1) << 2);
1672 const int i2 = i << 2;
1673 if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
1674 (mi_row + y32_idx), (mi_col + x32_idx),
1675 thresholds[1], BLOCK_16X16,
1676 force_split[i + 1])) {
1677 for (j = 0; j < 4; ++j) {
1678 const int x16_idx = ((j & 1) << 1);
1679 const int y16_idx = ((j >> 1) << 1);
1680 // For inter frames: if variance4x4downsample[] == 1 for this 16x16
1681 // block, then the variance is based on 4x4 down-sampling, so use vt2
1682 // in set_vt_partioning(), otherwise use vt.
1683 v16x16 *vtemp = (!is_key_frame && variance4x4downsample[i2 + j] == 1)
1685 : &vt.split[i].split[j];
1686 if (!set_vt_partitioning(
1687 cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx,
1688 mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min,
1689 force_split[5 + i2 + j])) {
1690 for (k = 0; k < 4; ++k) {
1691 const int x8_idx = (k & 1);
1692 const int y8_idx = (k >> 1);
1693 if (use_4x4_partition) {
1694 if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
1696 mi_row + y32_idx + y16_idx + y8_idx,
1697 mi_col + x32_idx + x16_idx + x8_idx,
1698 thresholds[3], BLOCK_8X8, 0)) {
1700 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1701 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_4X4);
1705 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1706 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_8X8);
1715 if (!frame_is_intra_only(cm) && cpi->sf.copy_partition_flag) {
1716 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1719 if (!frame_is_intra_only(cm) && cpi->sf.svc_use_lowres_part &&
1720 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1721 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1723 if (cpi->sf.short_circuit_low_temp_var) {
1724 set_low_temp_var_flag(cpi, x, xd, &vt, thresholds, ref_frame_partition,
1728 chroma_check(cpi, x, bsize, y_sad, is_key_frame);
1729 if (vt2) vpx_free(vt2);
1733 static void update_state(VP9_COMP *cpi, ThreadData *td, PICK_MODE_CONTEXT *ctx,
1734 int mi_row, int mi_col, BLOCK_SIZE bsize,
1735 int output_enabled) {
1737 VP9_COMMON *const cm = &cpi->common;
1738 RD_COUNTS *const rdc = &td->rd_counts;
1739 MACROBLOCK *const x = &td->mb;
1740 MACROBLOCKD *const xd = &x->e_mbd;
1741 struct macroblock_plane *const p = x->plane;
1742 struct macroblockd_plane *const pd = xd->plane;
1743 MODE_INFO *mi = &ctx->mic;
1744 MODE_INFO *const xdmi = xd->mi[0];
1745 MODE_INFO *mi_addr = xd->mi[0];
1746 const struct segmentation *const seg = &cm->seg;
1747 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
1748 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
1749 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1750 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1751 MV_REF *const frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1754 const int mis = cm->mi_stride;
1755 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
1756 const int mi_height = num_8x8_blocks_high_lookup[bsize];
1759 assert(mi->sb_type == bsize);
1762 *x->mbmi_ext = ctx->mbmi_ext;
1764 // If segmentation in use
1766 // For in frame complexity AQ copy the segment id from the segment map.
1767 if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1768 const uint8_t *const map =
1769 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1770 mi_addr->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1772 // Else for cyclic refresh mode update the segment map, set the segment id
1773 // and then update the quantizer.
1774 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1775 vp9_cyclic_refresh_update_segment(cpi, xd->mi[0], mi_row, mi_col, bsize,
1776 ctx->rate, ctx->dist, x->skip, p);
1780 max_plane = is_inter_block(xdmi) ? MAX_MB_PLANE : 1;
1781 for (i = 0; i < max_plane; ++i) {
1782 p[i].coeff = ctx->coeff_pbuf[i][1];
1783 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1784 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1785 p[i].eobs = ctx->eobs_pbuf[i][1];
1788 for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1789 p[i].coeff = ctx->coeff_pbuf[i][2];
1790 p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1791 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1792 p[i].eobs = ctx->eobs_pbuf[i][2];
1795 // Restore the coding context of the MB to that that was in place
1796 // when the mode was picked for it
1797 for (y = 0; y < mi_height; y++)
1798 for (x_idx = 0; x_idx < mi_width; x_idx++)
1799 if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx &&
1800 (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1801 xd->mi[x_idx + y * mis] = mi_addr;
1804 if (cpi->oxcf.aq_mode != NO_AQ) vp9_init_plane_quantizers(cpi, x);
1806 if (is_inter_block(xdmi) && xdmi->sb_type < BLOCK_8X8) {
1807 xdmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1808 xdmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1811 x->skip = ctx->skip;
1812 memcpy(x->zcoeff_blk[xdmi->tx_size], ctx->zcoeff_blk,
1813 sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1815 if (!output_enabled) return;
1817 #if CONFIG_INTERNAL_STATS
1818 if (frame_is_intra_only(cm)) {
1819 static const int kf_mode_index[] = {
1820 THR_DC /*DC_PRED*/, THR_V_PRED /*V_PRED*/,
1821 THR_H_PRED /*H_PRED*/, THR_D45_PRED /*D45_PRED*/,
1822 THR_D135_PRED /*D135_PRED*/, THR_D117_PRED /*D117_PRED*/,
1823 THR_D153_PRED /*D153_PRED*/, THR_D207_PRED /*D207_PRED*/,
1824 THR_D63_PRED /*D63_PRED*/, THR_TM /*TM_PRED*/,
1826 ++cpi->mode_chosen_counts[kf_mode_index[xdmi->mode]];
1828 // Note how often each mode chosen as best
1829 ++cpi->mode_chosen_counts[ctx->best_mode_index];
1832 if (!frame_is_intra_only(cm)) {
1833 if (is_inter_block(xdmi)) {
1834 vp9_update_mv_count(td);
1836 if (cm->interp_filter == SWITCHABLE) {
1837 const int ctx = get_pred_context_switchable_interp(xd);
1838 ++td->counts->switchable_interp[ctx][xdmi->interp_filter];
1842 rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1843 rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1844 rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1846 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1847 rdc->filter_diff[i] += ctx->best_filter_diff[i];
1850 for (h = 0; h < y_mis; ++h) {
1851 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1852 for (w = 0; w < x_mis; ++w) {
1853 MV_REF *const mv = frame_mv + w;
1854 mv->ref_frame[0] = mi->ref_frame[0];
1855 mv->ref_frame[1] = mi->ref_frame[1];
1856 mv->mv[0].as_int = mi->mv[0].as_int;
1857 mv->mv[1].as_int = mi->mv[1].as_int;
1862 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1863 int mi_row, int mi_col) {
1864 uint8_t *const buffers[3] = { src->y_buffer, src->u_buffer, src->v_buffer };
1865 const int strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
1868 // Set current frame pointer.
1869 x->e_mbd.cur_buf = src;
1871 for (i = 0; i < MAX_MB_PLANE; i++)
1872 setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1873 NULL, x->e_mbd.plane[i].subsampling_x,
1874 x->e_mbd.plane[i].subsampling_y);
1877 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1878 RD_COST *rd_cost, BLOCK_SIZE bsize) {
1879 MACROBLOCKD *const xd = &x->e_mbd;
1880 MODE_INFO *const mi = xd->mi[0];
1881 INTERP_FILTER filter_ref;
1883 filter_ref = get_pred_context_switchable_interp(xd);
1884 if (filter_ref == SWITCHABLE_FILTERS) filter_ref = EIGHTTAP;
1886 mi->sb_type = bsize;
1889 VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[tx_mode]);
1891 mi->uv_mode = DC_PRED;
1892 mi->ref_frame[0] = LAST_FRAME;
1893 mi->ref_frame[1] = NONE;
1894 mi->mv[0].as_int = 0;
1895 mi->interp_filter = filter_ref;
1897 xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1900 vp9_rd_cost_init(rd_cost);
1903 static void set_segment_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
1904 int mi_row, int mi_col, BLOCK_SIZE bsize,
1906 VP9_COMMON *const cm = &cpi->common;
1907 const uint8_t *const map =
1908 cm->seg.update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1910 vp9_init_plane_quantizers(cpi, x);
1911 vpx_clear_system_state();
1913 if (aq_mode == NO_AQ || aq_mode == PSNR_AQ) {
1914 if (cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance)
1915 x->rdmult = x->cb_rdmult;
1919 if (aq_mode == CYCLIC_REFRESH_AQ) {
1920 // If segment is boosted, use rdmult for that segment.
1921 if (cyclic_refresh_segment_id_boosted(
1922 get_segment_id(cm, map, bsize, mi_row, mi_col)))
1923 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1927 x->rdmult = vp9_compute_rd_mult(cpi, cm->base_qindex + cm->y_dc_delta_q);
1930 static void rd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
1931 MACROBLOCK *const x, int mi_row, int mi_col,
1932 RD_COST *rd_cost, BLOCK_SIZE bsize,
1933 PICK_MODE_CONTEXT *ctx, int64_t best_rd) {
1934 VP9_COMMON *const cm = &cpi->common;
1935 TileInfo *const tile_info = &tile_data->tile_info;
1936 MACROBLOCKD *const xd = &x->e_mbd;
1938 struct macroblock_plane *const p = x->plane;
1939 struct macroblockd_plane *const pd = xd->plane;
1940 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1943 vpx_clear_system_state();
1945 // Use the lower precision, but faster, 32x32 fdct for mode selection.
1946 x->use_lp32x32fdct = 1;
1948 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1950 mi->sb_type = bsize;
1952 for (i = 0; i < MAX_MB_PLANE; ++i) {
1953 p[i].coeff = ctx->coeff_pbuf[i][0];
1954 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1955 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1956 p[i].eobs = ctx->eobs_pbuf[i][0];
1960 ctx->pred_pixel_ready = 0;
1963 // Set to zero to make sure we do not use the previous encoded frame stats
1966 #if CONFIG_VP9_HIGHBITDEPTH
1967 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1968 x->source_variance = vp9_high_get_sby_perpixel_variance(
1969 cpi, &x->plane[0].src, bsize, xd->bd);
1971 x->source_variance =
1972 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1975 x->source_variance =
1976 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1977 #endif // CONFIG_VP9_HIGHBITDEPTH
1979 // Save rdmult before it might be changed, so it can be restored later.
1980 orig_rdmult = x->rdmult;
1982 if ((cpi->sf.tx_domain_thresh > 0.0) || (cpi->sf.quant_opt_thresh > 0.0)) {
1983 double logvar = vp9_log_block_var(cpi, x, bsize);
1984 // Check block complexity as part of descision on using pixel or transform
1985 // domain distortion in rd tests.
1986 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion &&
1987 (logvar >= cpi->sf.tx_domain_thresh);
1989 // Check block complexity as part of descision on using quantized
1990 // coefficient optimisation inside the rd loop.
1991 x->block_qcoeff_opt =
1992 cpi->sf.allow_quant_coeff_opt && (logvar <= cpi->sf.quant_opt_thresh);
1994 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion;
1995 x->block_qcoeff_opt = cpi->sf.allow_quant_coeff_opt;
1998 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
1999 set_segment_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode);
2001 // Find best coding mode & reconstruct the MB so it is available
2002 // as a predictor for MBs that follow in the SB
2003 if (frame_is_intra_only(cm)) {
2004 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
2006 if (bsize >= BLOCK_8X8) {
2007 if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
2008 vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
2011 vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2012 bsize, ctx, best_rd);
2014 vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2015 bsize, ctx, best_rd);
2019 // Examine the resulting rate and for AQ mode 2 make a segment choice.
2020 if ((rd_cost->rate != INT_MAX) && (aq_mode == COMPLEXITY_AQ) &&
2021 (bsize >= BLOCK_16X16) &&
2022 (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
2023 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
2024 vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
2027 // TODO(jingning) The rate-distortion optimization flow needs to be
2028 // refactored to provide proper exit/return handle.
2029 if (rd_cost->rate == INT_MAX)
2030 rd_cost->rdcost = INT64_MAX;
2032 rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2034 x->rdmult = orig_rdmult;
2036 ctx->rate = rd_cost->rate;
2037 ctx->dist = rd_cost->dist;
2040 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
2041 const MACROBLOCK *x = &td->mb;
2042 const MACROBLOCKD *const xd = &x->e_mbd;
2043 const MODE_INFO *const mi = xd->mi[0];
2044 const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2045 const BLOCK_SIZE bsize = mi->sb_type;
2047 if (!frame_is_intra_only(cm)) {
2048 FRAME_COUNTS *const counts = td->counts;
2049 const int inter_block = is_inter_block(mi);
2050 const int seg_ref_active =
2051 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_REF_FRAME);
2052 if (!seg_ref_active) {
2053 counts->intra_inter[get_intra_inter_context(xd)][inter_block]++;
2054 // If the segment reference feature is enabled we have only a single
2055 // reference frame allowed for the segment so exclude it from
2056 // the reference frame counts used to work out probabilities.
2058 const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
2059 if (cm->reference_mode == REFERENCE_MODE_SELECT)
2060 counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
2061 [has_second_ref(mi)]++;
2063 if (has_second_ref(mi)) {
2064 const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
2065 const int ctx = vp9_get_pred_context_comp_ref_p(cm, xd);
2066 const int bit = mi->ref_frame[!idx] == cm->comp_var_ref[1];
2067 counts->comp_ref[ctx][bit]++;
2069 counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
2070 [ref0 != LAST_FRAME]++;
2071 if (ref0 != LAST_FRAME)
2072 counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
2073 [ref0 != GOLDEN_FRAME]++;
2078 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP)) {
2079 const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
2080 if (bsize >= BLOCK_8X8) {
2081 const PREDICTION_MODE mode = mi->mode;
2082 ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
2084 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2085 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2087 for (idy = 0; idy < 2; idy += num_4x4_h) {
2088 for (idx = 0; idx < 2; idx += num_4x4_w) {
2089 const int j = idy * 2 + idx;
2090 const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
2091 ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
2099 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
2100 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2101 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2102 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2104 MACROBLOCKD *const xd = &x->e_mbd;
2106 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2107 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2108 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2109 int mi_height = num_8x8_blocks_high_lookup[bsize];
2110 for (p = 0; p < MAX_MB_PLANE; p++) {
2111 memcpy(xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
2112 a + num_4x4_blocks_wide * p,
2113 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2114 xd->plane[p].subsampling_x);
2115 memcpy(xd->left_context[p] +
2116 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2117 l + num_4x4_blocks_high * p,
2118 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2119 xd->plane[p].subsampling_y);
2121 memcpy(xd->above_seg_context + mi_col, sa,
2122 sizeof(*xd->above_seg_context) * mi_width);
2123 memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
2124 sizeof(xd->left_seg_context[0]) * mi_height);
2127 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
2128 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2129 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2130 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2132 const MACROBLOCKD *const xd = &x->e_mbd;
2134 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2135 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2136 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2137 int mi_height = num_8x8_blocks_high_lookup[bsize];
2139 // buffer the above/left context information of the block in search.
2140 for (p = 0; p < MAX_MB_PLANE; ++p) {
2141 memcpy(a + num_4x4_blocks_wide * p,
2142 xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
2143 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2144 xd->plane[p].subsampling_x);
2145 memcpy(l + num_4x4_blocks_high * p,
2146 xd->left_context[p] +
2147 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2148 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2149 xd->plane[p].subsampling_y);
2151 memcpy(sa, xd->above_seg_context + mi_col,
2152 sizeof(*xd->above_seg_context) * mi_width);
2153 memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
2154 sizeof(xd->left_seg_context[0]) * mi_height);
2157 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile, ThreadData *td,
2158 TOKENEXTRA **tp, int mi_row, int mi_col,
2159 int output_enabled, BLOCK_SIZE bsize,
2160 PICK_MODE_CONTEXT *ctx) {
2161 MACROBLOCK *const x = &td->mb;
2162 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2164 if ((cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance) &&
2165 cpi->oxcf.aq_mode == NO_AQ)
2166 x->rdmult = x->cb_rdmult;
2168 update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
2169 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2171 if (output_enabled) {
2172 update_stats(&cpi->common, td);
2174 (*tp)->token = EOSB_TOKEN;
2179 static void encode_sb(VP9_COMP *cpi, ThreadData *td, const TileInfo *const tile,
2180 TOKENEXTRA **tp, int mi_row, int mi_col,
2181 int output_enabled, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2182 VP9_COMMON *const cm = &cpi->common;
2183 MACROBLOCK *const x = &td->mb;
2184 MACROBLOCKD *const xd = &x->e_mbd;
2186 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2188 PARTITION_TYPE partition;
2189 BLOCK_SIZE subsize = bsize;
2191 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2193 if (bsize >= BLOCK_8X8) {
2194 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2195 subsize = get_subsize(bsize, pc_tree->partitioning);
2198 subsize = BLOCK_4X4;
2201 partition = partition_lookup[bsl][subsize];
2202 if (output_enabled && bsize != BLOCK_4X4)
2203 td->counts->partition[ctx][partition]++;
2205 switch (partition) {
2206 case PARTITION_NONE:
2207 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2210 case PARTITION_VERT:
2211 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2212 &pc_tree->vertical[0]);
2213 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2214 encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
2215 subsize, &pc_tree->vertical[1]);
2218 case PARTITION_HORZ:
2219 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2220 &pc_tree->horizontal[0]);
2221 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2222 encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
2223 subsize, &pc_tree->horizontal[1]);
2227 assert(partition == PARTITION_SPLIT);
2228 if (bsize == BLOCK_8X8) {
2229 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2230 pc_tree->leaf_split[0]);
2232 encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2234 encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2235 subsize, pc_tree->split[1]);
2236 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2237 subsize, pc_tree->split[2]);
2238 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
2239 subsize, pc_tree->split[3]);
2244 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2245 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2248 // Check to see if the given partition size is allowed for a specified number
2249 // of 8x8 block rows and columns remaining in the image.
2250 // If not then return the largest allowed partition size
2251 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
2252 int cols_left, int *bh, int *bw) {
2253 if (rows_left <= 0 || cols_left <= 0) {
2254 return VPXMIN(bsize, BLOCK_8X8);
2256 for (; bsize > 0; bsize -= 3) {
2257 *bh = num_8x8_blocks_high_lookup[bsize];
2258 *bw = num_8x8_blocks_wide_lookup[bsize];
2259 if ((*bh <= rows_left) && (*bw <= cols_left)) {
2267 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis, int bh_in,
2268 int bw_in, int row8x8_remaining,
2269 int col8x8_remaining, BLOCK_SIZE bsize,
2270 MODE_INFO **mi_8x8) {
2273 for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
2275 for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
2276 const int index = r * mis + c;
2277 mi_8x8[index] = mi + index;
2278 mi_8x8[index]->sb_type = find_partition_size(
2279 bsize, row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
2284 // This function attempts to set all mode info entries in a given SB64
2285 // to the same block partition size.
2286 // However, at the bottom and right borders of the image the requested size
2287 // may not be allowed in which case this code attempts to choose the largest
2288 // allowable partition.
2289 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
2290 MODE_INFO **mi_8x8, int mi_row, int mi_col,
2292 VP9_COMMON *const cm = &cpi->common;
2293 const int mis = cm->mi_stride;
2294 const int row8x8_remaining = tile->mi_row_end - mi_row;
2295 const int col8x8_remaining = tile->mi_col_end - mi_col;
2296 int block_row, block_col;
2297 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2298 int bh = num_8x8_blocks_high_lookup[bsize];
2299 int bw = num_8x8_blocks_wide_lookup[bsize];
2301 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2303 // Apply the requested partition size to the SB64 if it is all "in image"
2304 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2305 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2306 for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
2307 for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
2308 int index = block_row * mis + block_col;
2309 mi_8x8[index] = mi_upper_left + index;
2310 mi_8x8[index]->sb_type = bsize;
2314 // Else this is a partial SB64.
2315 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2316 col8x8_remaining, bsize, mi_8x8);
2320 static const struct {
2323 } coord_lookup[16] = {
2346 static void set_source_var_based_partition(VP9_COMP *cpi,
2347 const TileInfo *const tile,
2348 MACROBLOCK *const x,
2349 MODE_INFO **mi_8x8, int mi_row,
2351 VP9_COMMON *const cm = &cpi->common;
2352 const int mis = cm->mi_stride;
2353 const int row8x8_remaining = tile->mi_row_end - mi_row;
2354 const int col8x8_remaining = tile->mi_col_end - mi_col;
2355 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2357 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
2359 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2362 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2363 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2367 const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
2368 int is_larger_better = 0;
2370 unsigned int thr = cpi->source_var_thresh;
2372 memset(d32, 0, 4 * sizeof(diff));
2374 for (i = 0; i < 4; i++) {
2377 for (j = 0; j < 4; j++) {
2378 int b_mi_row = coord_lookup[i * 4 + j].row;
2379 int b_mi_col = coord_lookup[i * 4 + j].col;
2380 int boffset = b_mi_row / 2 * cm->mb_cols + b_mi_col / 2;
2382 d16[j] = cpi->source_diff_var + offset + boffset;
2384 index = b_mi_row * mis + b_mi_col;
2385 mi_8x8[index] = mi_upper_left + index;
2386 mi_8x8[index]->sb_type = BLOCK_16X16;
2388 // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
2389 // size to further improve quality.
2392 is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
2393 (d16[2]->var < thr) && (d16[3]->var < thr);
2395 // Use 32x32 partition
2396 if (is_larger_better) {
2399 for (j = 0; j < 4; j++) {
2400 d32[i].sse += d16[j]->sse;
2401 d32[i].sum += d16[j]->sum;
2405 (unsigned int)(d32[i].sse -
2406 (unsigned int)(((int64_t)d32[i].sum * d32[i].sum) >>
2409 index = coord_lookup[i * 4].row * mis + coord_lookup[i * 4].col;
2410 mi_8x8[index] = mi_upper_left + index;
2411 mi_8x8[index]->sb_type = BLOCK_32X32;
2415 if (use32x32 == 4) {
2417 is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
2418 (d32[2].var < thr) && (d32[3].var < thr);
2420 // Use 64x64 partition
2421 if (is_larger_better) {
2422 mi_8x8[0] = mi_upper_left;
2423 mi_8x8[0]->sb_type = BLOCK_64X64;
2426 } else { // partial in-image SB64
2427 int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
2428 int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
2429 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2430 col8x8_remaining, BLOCK_16X16, mi_8x8);
2434 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
2435 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
2437 VP9_COMMON *const cm = &cpi->common;
2438 MACROBLOCK *const x = &td->mb;
2439 MACROBLOCKD *const xd = &x->e_mbd;
2440 MODE_INFO *const mi = xd->mi[0];
2441 struct macroblock_plane *const p = x->plane;
2442 const struct segmentation *const seg = &cm->seg;
2443 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
2444 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
2445 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
2446 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
2448 *(xd->mi[0]) = ctx->mic;
2449 *(x->mbmi_ext) = ctx->mbmi_ext;
2451 if (seg->enabled && (cpi->oxcf.aq_mode != NO_AQ || cpi->roi.enabled)) {
2452 // Setting segmentation map for cyclic_refresh.
2453 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
2454 vp9_cyclic_refresh_update_segment(cpi, mi, mi_row, mi_col, bsize,
2455 ctx->rate, ctx->dist, x->skip, p);
2457 const uint8_t *const map =
2458 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
2459 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
2461 vp9_init_plane_quantizers(cpi, x);
2464 if (is_inter_block(mi)) {
2465 vp9_update_mv_count(td);
2466 if (cm->interp_filter == SWITCHABLE) {
2467 const int pred_ctx = get_pred_context_switchable_interp(xd);
2468 ++td->counts->switchable_interp[pred_ctx][mi->interp_filter];
2471 if (mi->sb_type < BLOCK_8X8) {
2472 mi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
2473 mi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
2477 if (cm->use_prev_frame_mvs || !cm->error_resilient_mode ||
2478 (cpi->svc.use_base_mv && cpi->svc.number_spatial_layers > 1 &&
2479 cpi->svc.spatial_layer_id != cpi->svc.number_spatial_layers - 1)) {
2480 MV_REF *const frame_mvs =
2481 cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
2484 for (h = 0; h < y_mis; ++h) {
2485 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
2486 for (w = 0; w < x_mis; ++w) {
2487 MV_REF *const mv = frame_mv + w;
2488 mv->ref_frame[0] = mi->ref_frame[0];
2489 mv->ref_frame[1] = mi->ref_frame[1];
2490 mv->mv[0].as_int = mi->mv[0].as_int;
2491 mv->mv[1].as_int = mi->mv[1].as_int;
2496 x->skip = ctx->skip;
2497 x->skip_txfm[0] = (mi->segment_id || xd->lossless) ? 0 : ctx->skip_txfm[0];
2500 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
2501 const TileInfo *const tile, TOKENEXTRA **tp, int mi_row,
2502 int mi_col, int output_enabled, BLOCK_SIZE bsize,
2503 PICK_MODE_CONTEXT *ctx) {
2504 MACROBLOCK *const x = &td->mb;
2505 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2506 update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
2508 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2509 update_stats(&cpi->common, td);
2511 (*tp)->token = EOSB_TOKEN;
2515 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
2516 const TileInfo *const tile, TOKENEXTRA **tp,
2517 int mi_row, int mi_col, int output_enabled,
2518 BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2519 VP9_COMMON *const cm = &cpi->common;
2520 MACROBLOCK *const x = &td->mb;
2521 MACROBLOCKD *const xd = &x->e_mbd;
2523 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2525 PARTITION_TYPE partition;
2528 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2530 if (bsize >= BLOCK_8X8) {
2531 const int idx_str = xd->mi_stride * mi_row + mi_col;
2532 MODE_INFO **mi_8x8 = cm->mi_grid_visible + idx_str;
2533 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2534 subsize = mi_8x8[0]->sb_type;
2537 subsize = BLOCK_4X4;
2540 partition = partition_lookup[bsl][subsize];
2541 if (output_enabled && bsize != BLOCK_4X4)
2542 td->counts->partition[ctx][partition]++;
2544 switch (partition) {
2545 case PARTITION_NONE:
2546 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2549 case PARTITION_VERT:
2550 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2551 &pc_tree->vertical[0]);
2552 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2553 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2554 subsize, &pc_tree->vertical[1]);
2557 case PARTITION_HORZ:
2558 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2559 &pc_tree->horizontal[0]);
2560 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2561 encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2562 subsize, &pc_tree->horizontal[1]);
2566 assert(partition == PARTITION_SPLIT);
2567 subsize = get_subsize(bsize, PARTITION_SPLIT);
2568 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2570 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2571 subsize, pc_tree->split[1]);
2572 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2573 subsize, pc_tree->split[2]);
2574 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
2575 output_enabled, subsize, pc_tree->split[3]);
2579 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2580 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2583 static void rd_use_partition(VP9_COMP *cpi, ThreadData *td,
2584 TileDataEnc *tile_data, MODE_INFO **mi_8x8,
2585 TOKENEXTRA **tp, int mi_row, int mi_col,
2586 BLOCK_SIZE bsize, int *rate, int64_t *dist,
2587 int do_recon, PC_TREE *pc_tree) {
2588 VP9_COMMON *const cm = &cpi->common;
2589 TileInfo *const tile_info = &tile_data->tile_info;
2590 MACROBLOCK *const x = &td->mb;
2591 MACROBLOCKD *const xd = &x->e_mbd;
2592 const int mis = cm->mi_stride;
2593 const int bsl = b_width_log2_lookup[bsize];
2594 const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
2595 const int bss = (1 << bsl) / 4;
2597 PARTITION_TYPE partition = PARTITION_NONE;
2599 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2600 PARTITION_CONTEXT sl[8], sa[8];
2601 RD_COST last_part_rdc, none_rdc, chosen_rdc;
2602 BLOCK_SIZE sub_subsize = BLOCK_4X4;
2603 int splits_below = 0;
2604 BLOCK_SIZE bs_type = mi_8x8[0]->sb_type;
2605 int do_partition_search = 1;
2606 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2608 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2610 assert(num_4x4_blocks_wide_lookup[bsize] ==
2611 num_4x4_blocks_high_lookup[bsize]);
2613 vp9_rd_cost_reset(&last_part_rdc);
2614 vp9_rd_cost_reset(&none_rdc);
2615 vp9_rd_cost_reset(&chosen_rdc);
2617 partition = partition_lookup[bsl][bs_type];
2618 subsize = get_subsize(bsize, partition);
2620 pc_tree->partitioning = partition;
2621 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2623 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ) {
2624 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2625 x->mb_energy = vp9_block_energy(cpi, x, bsize);
2628 if (do_partition_search &&
2629 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2630 cpi->sf.adjust_partitioning_from_last_frame) {
2631 // Check if any of the sub blocks are further split.
2632 if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
2633 sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
2635 for (i = 0; i < 4; i++) {
2636 int jj = i >> 1, ii = i & 0x01;
2637 MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
2638 if (this_mi && this_mi->sb_type >= sub_subsize) {
2644 // If partition is not none try none unless each of the 4 splits are split
2646 if (partition != PARTITION_NONE && !splits_below &&
2647 mi_row + (mi_step >> 1) < cm->mi_rows &&
2648 mi_col + (mi_step >> 1) < cm->mi_cols) {
2649 pc_tree->partitioning = PARTITION_NONE;
2650 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize, ctx,
2653 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2655 if (none_rdc.rate < INT_MAX) {
2656 none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2658 RDCOST(x->rdmult, x->rddiv, none_rdc.rate, none_rdc.dist);
2661 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2662 mi_8x8[0]->sb_type = bs_type;
2663 pc_tree->partitioning = partition;
2667 switch (partition) {
2668 case PARTITION_NONE:
2669 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc, bsize,
2672 case PARTITION_HORZ:
2673 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
2674 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2675 subsize, &pc_tree->horizontal[0], INT64_MAX);
2676 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2677 mi_row + (mi_step >> 1) < cm->mi_rows) {
2679 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2680 vp9_rd_cost_init(&tmp_rdc);
2681 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2682 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2683 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
2684 rd_pick_sb_modes(cpi, tile_data, x, mi_row + (mi_step >> 1), mi_col,
2685 &tmp_rdc, subsize, &pc_tree->horizontal[1], INT64_MAX);
2686 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2687 vp9_rd_cost_reset(&last_part_rdc);
2690 last_part_rdc.rate += tmp_rdc.rate;
2691 last_part_rdc.dist += tmp_rdc.dist;
2692 last_part_rdc.rdcost += tmp_rdc.rdcost;
2695 case PARTITION_VERT:
2696 pc_tree->vertical[0].skip_ref_frame_mask = 0;
2697 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2698 subsize, &pc_tree->vertical[0], INT64_MAX);
2699 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2700 mi_col + (mi_step >> 1) < cm->mi_cols) {
2702 PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
2703 vp9_rd_cost_init(&tmp_rdc);
2704 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2705 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2706 pc_tree->vertical[bsize > BLOCK_8X8].skip_ref_frame_mask = 0;
2707 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + (mi_step >> 1),
2709 &pc_tree->vertical[bsize > BLOCK_8X8], INT64_MAX);
2710 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2711 vp9_rd_cost_reset(&last_part_rdc);
2714 last_part_rdc.rate += tmp_rdc.rate;
2715 last_part_rdc.dist += tmp_rdc.dist;
2716 last_part_rdc.rdcost += tmp_rdc.rdcost;
2720 assert(partition == PARTITION_SPLIT);
2721 if (bsize == BLOCK_8X8) {
2722 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2723 subsize, pc_tree->leaf_split[0], INT64_MAX);
2726 last_part_rdc.rate = 0;
2727 last_part_rdc.dist = 0;
2728 last_part_rdc.rdcost = 0;
2729 for (i = 0; i < 4; i++) {
2730 int x_idx = (i & 1) * (mi_step >> 1);
2731 int y_idx = (i >> 1) * (mi_step >> 1);
2732 int jj = i >> 1, ii = i & 0x01;
2734 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2737 vp9_rd_cost_init(&tmp_rdc);
2738 rd_use_partition(cpi, td, tile_data, mi_8x8 + jj * bss * mis + ii * bss,
2739 tp, mi_row + y_idx, mi_col + x_idx, subsize,
2740 &tmp_rdc.rate, &tmp_rdc.dist, i != 3,
2742 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2743 vp9_rd_cost_reset(&last_part_rdc);
2746 last_part_rdc.rate += tmp_rdc.rate;
2747 last_part_rdc.dist += tmp_rdc.dist;
2752 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2753 if (last_part_rdc.rate < INT_MAX) {
2754 last_part_rdc.rate += cpi->partition_cost[pl][partition];
2755 last_part_rdc.rdcost =
2756 RDCOST(x->rdmult, x->rddiv, last_part_rdc.rate, last_part_rdc.dist);
2759 if (do_partition_search && cpi->sf.adjust_partitioning_from_last_frame &&
2760 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2761 partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
2762 (mi_row + mi_step < cm->mi_rows ||
2763 mi_row + (mi_step >> 1) == cm->mi_rows) &&
2764 (mi_col + mi_step < cm->mi_cols ||
2765 mi_col + (mi_step >> 1) == cm->mi_cols)) {
2766 BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2767 chosen_rdc.rate = 0;
2768 chosen_rdc.dist = 0;
2769 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2770 pc_tree->partitioning = PARTITION_SPLIT;
2773 for (i = 0; i < 4; i++) {
2774 int x_idx = (i & 1) * (mi_step >> 1);
2775 int y_idx = (i >> 1) * (mi_step >> 1);
2777 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2778 PARTITION_CONTEXT sl[8], sa[8];
2780 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2783 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2784 pc_tree->split[i]->partitioning = PARTITION_NONE;
2785 rd_pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2786 &tmp_rdc, split_subsize, &pc_tree->split[i]->none,
2789 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2791 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2792 vp9_rd_cost_reset(&chosen_rdc);
2796 chosen_rdc.rate += tmp_rdc.rate;
2797 chosen_rdc.dist += tmp_rdc.dist;
2800 encode_sb(cpi, td, tile_info, tp, mi_row + y_idx, mi_col + x_idx, 0,
2801 split_subsize, pc_tree->split[i]);
2803 pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2805 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2807 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2808 if (chosen_rdc.rate < INT_MAX) {
2809 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2811 RDCOST(x->rdmult, x->rddiv, chosen_rdc.rate, chosen_rdc.dist);
2815 // If last_part is better set the partitioning to that.
2816 if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2817 mi_8x8[0]->sb_type = bsize;
2818 if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2819 chosen_rdc = last_part_rdc;
2821 // If none was better set the partitioning to that.
2822 if (none_rdc.rdcost < chosen_rdc.rdcost) {
2823 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2824 chosen_rdc = none_rdc;
2827 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2829 // We must have chosen a partitioning and encoding or we'll fail later on.
2830 // No other opportunities for success.
2831 if (bsize == BLOCK_64X64)
2832 assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2835 int output_enabled = (bsize == BLOCK_64X64);
2836 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2840 *rate = chosen_rdc.rate;
2841 *dist = chosen_rdc.dist;
2844 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2845 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2846 BLOCK_4X4, BLOCK_8X8, BLOCK_8X8, BLOCK_8X8, BLOCK_16X16,
2847 BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
2850 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2851 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2852 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2853 BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
2856 // Look at all the mode_info entries for blocks that are part of this
2857 // partition and find the min and max values for sb_type.
2858 // At the moment this is designed to work on a 64x64 SB but could be
2859 // adjusted to use a size parameter.
2861 // The min and max are assumed to have been initialized prior to calling this
2862 // function so repeat calls can accumulate a min and max of more than one sb64.
2863 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2864 BLOCK_SIZE *min_block_size,
2865 BLOCK_SIZE *max_block_size,
2866 int bs_hist[BLOCK_SIZES]) {
2867 int sb_width_in_blocks = MI_BLOCK_SIZE;
2868 int sb_height_in_blocks = MI_BLOCK_SIZE;
2872 // Check the sb_type for each block that belongs to this region.
2873 for (i = 0; i < sb_height_in_blocks; ++i) {
2874 for (j = 0; j < sb_width_in_blocks; ++j) {
2875 MODE_INFO *mi = mi_8x8[index + j];
2876 BLOCK_SIZE sb_type = mi ? mi->sb_type : 0;
2878 *min_block_size = VPXMIN(*min_block_size, sb_type);
2879 *max_block_size = VPXMAX(*max_block_size, sb_type);
2881 index += xd->mi_stride;
2885 // Next square block size less or equal than current block size.
2886 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2887 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_8X8, BLOCK_8X8,
2888 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2889 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64
2892 // Look at neighboring blocks and set a min and max partition size based on
2894 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2895 MACROBLOCKD *const xd, int mi_row,
2896 int mi_col, BLOCK_SIZE *min_block_size,
2897 BLOCK_SIZE *max_block_size) {
2898 VP9_COMMON *const cm = &cpi->common;
2899 MODE_INFO **mi = xd->mi;
2900 const int left_in_image = !!xd->left_mi;
2901 const int above_in_image = !!xd->above_mi;
2902 const int row8x8_remaining = tile->mi_row_end - mi_row;
2903 const int col8x8_remaining = tile->mi_col_end - mi_col;
2905 BLOCK_SIZE min_size = BLOCK_4X4;
2906 BLOCK_SIZE max_size = BLOCK_64X64;
2907 int bs_hist[BLOCK_SIZES] = { 0 };
2909 // Trap case where we do not have a prediction.
2910 if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2911 // Default "min to max" and "max to min"
2912 min_size = BLOCK_64X64;
2913 max_size = BLOCK_4X4;
2915 // NOTE: each call to get_sb_partition_size_range() uses the previous
2916 // passed in values for min and max as a starting point.
2917 // Find the min and max partition used in previous frame at this location
2918 if (cm->frame_type != KEY_FRAME) {
2919 MODE_INFO **prev_mi =
2920 &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2921 get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2923 // Find the min and max partition sizes used in the left SB64
2924 if (left_in_image) {
2925 MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2926 get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2929 // Find the min and max partition sizes used in the above SB64.
2930 if (above_in_image) {
2931 MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2932 get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2936 // Adjust observed min and max for "relaxed" auto partition case.
2937 if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2938 min_size = min_partition_size[min_size];
2939 max_size = max_partition_size[max_size];
2943 // Check border cases where max and min from neighbors may not be legal.
2944 max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
2946 // Test for blocks at the edge of the active image.
2947 // This may be the actual edge of the image or where there are formatting
2949 if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
2950 min_size = BLOCK_4X4;
2953 VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
2956 // When use_square_partition_only is true, make sure at least one square
2957 // partition is allowed by selecting the next smaller square size as
2959 if (cpi->sf.use_square_partition_only &&
2960 next_square_size[max_size] < min_size) {
2961 min_size = next_square_size[max_size];
2964 *min_block_size = min_size;
2965 *max_block_size = max_size;
2968 // TODO(jingning) refactor functions setting partition search range
2969 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd, int mi_row,
2970 int mi_col, BLOCK_SIZE bsize,
2971 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
2972 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2973 int mi_height = num_8x8_blocks_high_lookup[bsize];
2977 const int idx_str = cm->mi_stride * mi_row + mi_col;
2978 MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
2979 BLOCK_SIZE bs, min_size, max_size;
2981 min_size = BLOCK_64X64;
2982 max_size = BLOCK_4X4;
2985 for (idy = 0; idy < mi_height; ++idy) {
2986 for (idx = 0; idx < mi_width; ++idx) {
2987 mi = prev_mi[idy * cm->mi_stride + idx];
2988 bs = mi ? mi->sb_type : bsize;
2989 min_size = VPXMIN(min_size, bs);
2990 max_size = VPXMAX(max_size, bs);
2996 for (idy = 0; idy < mi_height; ++idy) {
2997 mi = xd->mi[idy * cm->mi_stride - 1];
2998 bs = mi ? mi->sb_type : bsize;
2999 min_size = VPXMIN(min_size, bs);
3000 max_size = VPXMAX(max_size, bs);
3005 for (idx = 0; idx < mi_width; ++idx) {
3006 mi = xd->mi[idx - cm->mi_stride];
3007 bs = mi ? mi->sb_type : bsize;
3008 min_size = VPXMIN(min_size, bs);
3009 max_size = VPXMAX(max_size, bs);
3013 if (min_size == max_size) {
3014 min_size = min_partition_size[min_size];
3015 max_size = max_partition_size[max_size];
3022 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3023 memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
3026 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3027 memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
3030 #if CONFIG_FP_MB_STATS
3031 const int num_16x16_blocks_wide_lookup[BLOCK_SIZES] = { 1, 1, 1, 1, 1, 1, 1,
3033 const int num_16x16_blocks_high_lookup[BLOCK_SIZES] = { 1, 1, 1, 1, 1, 1, 1,
3035 const int qindex_skip_threshold_lookup[BLOCK_SIZES] = {
3036 0, 10, 10, 30, 40, 40, 60, 80, 80, 90, 100, 100, 120
3038 const int qindex_split_threshold_lookup[BLOCK_SIZES] = {
3039 0, 3, 3, 7, 15, 15, 30, 40, 40, 60, 80, 80, 120
3041 const int complexity_16x16_blocks_threshold[BLOCK_SIZES] = {
3042 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 6
3054 static INLINE MOTION_DIRECTION get_motion_direction_fp(uint8_t fp_byte) {
3055 if (fp_byte & FPMB_MOTION_ZERO_MASK) {
3057 } else if (fp_byte & FPMB_MOTION_LEFT_MASK) {
3059 } else if (fp_byte & FPMB_MOTION_RIGHT_MASK) {
3061 } else if (fp_byte & FPMB_MOTION_UP_MASK) {
3068 static INLINE int get_motion_inconsistency(MOTION_DIRECTION this_mv,
3069 MOTION_DIRECTION that_mv) {
3070 if (this_mv == that_mv) {
3073 return abs(this_mv - that_mv) == 2 ? 2 : 1;
3078 // Calculate prediction based on the given input features and neural net config.
3079 // Assume there are no more than NN_MAX_NODES_PER_LAYER nodes in each hidden
3081 static void nn_predict(const float *features, const NN_CONFIG *nn_config,
3083 int num_input_nodes = nn_config->num_inputs;
3085 float buf[2][NN_MAX_NODES_PER_LAYER];
3086 const float *input_nodes = features;
3088 // Propagate hidden layers.
3089 const int num_layers = nn_config->num_hidden_layers;
3091 assert(num_layers <= NN_MAX_HIDDEN_LAYERS);
3092 for (layer = 0; layer < num_layers; ++layer) {
3093 const float *weights = nn_config->weights[layer];
3094 const float *bias = nn_config->bias[layer];
3095 float *output_nodes = buf[buf_index];
3096 const int num_output_nodes = nn_config->num_hidden_nodes[layer];
3097 assert(num_output_nodes < NN_MAX_NODES_PER_LAYER);
3098 for (node = 0; node < num_output_nodes; ++node) {
3100 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3102 // ReLU as activation function.
3103 val = VPXMAX(val, 0.0f);
3104 output_nodes[node] = val;
3105 weights += num_input_nodes;
3107 num_input_nodes = num_output_nodes;
3108 input_nodes = output_nodes;
3109 buf_index = 1 - buf_index;
3112 // Final output layer.
3114 const float *weights = nn_config->weights[num_layers];
3115 for (node = 0; node < nn_config->num_outputs; ++node) {
3116 const float *bias = nn_config->bias[num_layers];
3118 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3119 output[node] = val + bias[node];
3120 weights += num_input_nodes;
3126 // Machine-learning based partition search early termination.
3127 // Return 1 to skip split and rect partitions.
3128 static int ml_pruning_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
3129 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
3132 abs(ctx->mic.mv[0].as_mv.col) + abs(ctx->mic.mv[0].as_mv.row);
3133 const int left_in_image = !!xd->left_mi;
3134 const int above_in_image = !!xd->above_mi;
3135 MODE_INFO **prev_mi =
3136 &cm->prev_mi_grid_visible[mi_col + cm->mi_stride * mi_row];
3137 int above_par = 0; // above_partitioning
3138 int left_par = 0; // left_partitioning
3139 int last_par = 0; // last_partitioning
3142 BLOCK_SIZE context_size;
3143 const NN_CONFIG *nn_config = NULL;
3144 const float *mean, *sd, *linear_weights;
3145 float nn_score, linear_score;
3146 float features[FEATURES];
3148 assert(b_width_log2_lookup[bsize] == b_height_log2_lookup[bsize]);
3149 vpx_clear_system_state();
3154 nn_config = &vp9_partition_nnconfig_64x64;
3158 nn_config = &vp9_partition_nnconfig_32x32;
3162 nn_config = &vp9_partition_nnconfig_16x16;
3164 default: assert(0 && "Unexpected block size."); return 0;
3167 if (above_in_image) {
3168 context_size = xd->above_mi->sb_type;
3169 if (context_size < bsize)
3171 else if (context_size == bsize)
3175 if (left_in_image) {
3176 context_size = xd->left_mi->sb_type;
3177 if (context_size < bsize)
3179 else if (context_size == bsize)
3184 context_size = prev_mi[0]->sb_type;
3185 if (context_size < bsize)
3187 else if (context_size == bsize)
3191 mean = &vp9_partition_feature_mean[offset];
3192 sd = &vp9_partition_feature_std[offset];
3193 features[0] = ((float)ctx->rate - mean[0]) / sd[0];
3194 features[1] = ((float)ctx->dist - mean[1]) / sd[1];
3195 features[2] = ((float)mag_mv / 2 - mean[2]) * sd[2];
3196 features[3] = ((float)(left_par + above_par) / 2 - mean[3]) * sd[3];
3197 features[4] = ((float)ctx->sum_y_eobs - mean[4]) / sd[4];
3198 features[5] = ((float)cm->base_qindex - mean[5]) * sd[5];
3199 features[6] = ((float)last_par - mean[6]) * sd[6];
3201 // Predict using linear model.
3202 linear_weights = &vp9_partition_linear_weights[offset];
3203 linear_score = linear_weights[FEATURES];
3204 for (i = 0; i < FEATURES; ++i)
3205 linear_score += linear_weights[i] * features[i];
3206 if (linear_score > 0.1f) return 0;
3208 // Predict using neural net model.
3209 nn_predict(features, nn_config, &nn_score);
3211 if (linear_score < -0.0f && nn_score < 0.1f) return 1;
3212 if (nn_score < -0.0f && linear_score < 0.1f) return 1;
3218 // ML-based partition search breakout.
3219 static int ml_predict_breakout(VP9_COMP *const cpi, BLOCK_SIZE bsize,
3220 const MACROBLOCK *const x,
3221 const RD_COST *const rd_cost) {
3222 DECLARE_ALIGNED(16, static const uint8_t, vp9_64_zeros[64]) = { 0 };
3223 const VP9_COMMON *const cm = &cpi->common;
3224 float features[FEATURES];
3225 const float *linear_weights = NULL; // Linear model weights.
3226 float linear_score = 0.0f;
3227 const int qindex = cm->base_qindex;
3228 const int q_ctx = qindex >= 200 ? 0 : (qindex >= 150 ? 1 : 2);
3229 const int is_720p_or_larger = VPXMIN(cm->width, cm->height) >= 720;
3230 const int resolution_ctx = is_720p_or_larger ? 1 : 0;
3234 linear_weights = vp9_partition_breakout_weights_64[resolution_ctx][q_ctx];
3237 linear_weights = vp9_partition_breakout_weights_32[resolution_ctx][q_ctx];
3240 linear_weights = vp9_partition_breakout_weights_16[resolution_ctx][q_ctx];
3243 linear_weights = vp9_partition_breakout_weights_8[resolution_ctx][q_ctx];
3245 default: assert(0 && "Unexpected block size."); return 0;
3247 if (!linear_weights) return 0;
3249 { // Generate feature values.
3250 #if CONFIG_VP9_HIGHBITDEPTH
3252 vp9_ac_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3254 const int ac_q = vp9_ac_quant(qindex, 0, cm->bit_depth);
3255 #endif // CONFIG_VP9_HIGHBITDEPTH
3256 const int num_pels_log2 = num_pels_log2_lookup[bsize];
3257 int feature_index = 0;
3258 unsigned int var, sse;
3259 float rate_f, dist_f;
3261 #if CONFIG_VP9_HIGHBITDEPTH
3262 if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3264 vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, x->e_mbd.bd);
3266 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3267 vp9_64_zeros, 0, &sse);
3270 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3271 vp9_64_zeros, 0, &sse);
3273 var = var >> num_pels_log2;
3275 vpx_clear_system_state();
3277 rate_f = (float)VPXMIN(rd_cost->rate, INT_MAX);
3278 dist_f = (float)(VPXMIN(rd_cost->dist, INT_MAX) >> num_pels_log2);
3280 ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
3283 features[feature_index++] = rate_f;
3284 features[feature_index++] = dist_f;
3285 features[feature_index++] = (float)var;
3286 features[feature_index++] = (float)ac_q;
3287 assert(feature_index == FEATURES);
3290 { // Calculate the output score.
3292 linear_score = linear_weights[FEATURES];
3293 for (i = 0; i < FEATURES; ++i)
3294 linear_score += linear_weights[i] * features[i];
3297 return linear_score >= cpi->sf.rd_ml_partition.search_breakout_thresh[q_ctx];
3303 static void ml_prune_rect_partition(VP9_COMP *const cpi, MACROBLOCK *const x,
3305 const PC_TREE *const pc_tree,
3306 int *allow_horz, int *allow_vert,
3308 const NN_CONFIG *nn_config = NULL;
3309 float score[LABELS] = {
3316 if (ref_rd <= 0 || ref_rd > 1000000000) return;
3319 case BLOCK_8X8: break;
3321 nn_config = &vp9_rect_part_nnconfig_16;
3322 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[1];
3325 nn_config = &vp9_rect_part_nnconfig_32;
3326 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[2];
3329 nn_config = &vp9_rect_part_nnconfig_64;
3330 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[3];
3332 default: assert(0 && "Unexpected block size."); return;
3334 if (!nn_config || thresh < 0) return;
3336 // Feature extraction and model score calculation.
3338 const VP9_COMMON *const cm = &cpi->common;
3339 #if CONFIG_VP9_HIGHBITDEPTH
3341 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3343 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3344 #endif // CONFIG_VP9_HIGHBITDEPTH
3345 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3346 int feature_index = 0;
3347 float features[FEATURES];
3349 features[feature_index++] = logf((float)dc_q + 1.0f);
3350 features[feature_index++] =
3351 (float)(pc_tree->partitioning == PARTITION_NONE);
3352 features[feature_index++] = logf((float)ref_rd / bs / bs + 1.0f);
3355 const float norm_factor = 1.0f / ((float)ref_rd + 1.0f);
3356 const int64_t none_rdcost = pc_tree->none.rdcost;
3357 float rd_ratio = 2.0f;
3358 if (none_rdcost > 0 && none_rdcost < 1000000000)
3359 rd_ratio = (float)none_rdcost * norm_factor;
3360 features[feature_index++] = VPXMIN(rd_ratio, 2.0f);
3362 for (i = 0; i < 4; ++i) {
3363 const int64_t this_rd = pc_tree->split[i]->none.rdcost;
3364 const int rd_valid = this_rd > 0 && this_rd < 1000000000;
3365 // Ratio between sub-block RD and whole block RD.
3366 features[feature_index++] =
3367 rd_valid ? (float)this_rd * norm_factor : 1.0f;
3371 assert(feature_index == FEATURES);
3372 nn_predict(features, nn_config, score);
3375 // Make decisions based on the model score.
3377 int max_score = -1000;
3378 int horz = 0, vert = 0;
3379 int int_score[LABELS];
3380 for (i = 0; i < LABELS; ++i) {
3381 int_score[i] = (int)(100 * score[i]);
3382 max_score = VPXMAX(int_score[i], max_score);
3384 thresh = max_score - thresh;
3385 for (i = 0; i < LABELS; ++i) {
3386 if (int_score[i] >= thresh) {
3387 if ((i >> 0) & 1) horz = 1;
3388 if ((i >> 1) & 1) vert = 1;
3391 *allow_horz = *allow_horz && horz;
3392 *allow_vert = *allow_vert && vert;
3398 // Perform fast and coarse motion search for the given block. This is a
3399 // pre-processing step for the ML based partition search speedup.
3400 static void simple_motion_search(const VP9_COMP *const cpi, MACROBLOCK *const x,
3401 BLOCK_SIZE bsize, int mi_row, int mi_col,
3402 MV ref_mv, MV_REFERENCE_FRAME ref,
3403 uint8_t *const pred_buf) {
3404 const VP9_COMMON *const cm = &cpi->common;
3405 MACROBLOCKD *const xd = &x->e_mbd;
3406 MODE_INFO *const mi = xd->mi[0];
3407 const YV12_BUFFER_CONFIG *const yv12 = get_ref_frame_buffer(cpi, ref);
3408 const int step_param = 1;
3409 const MvLimits tmp_mv_limits = x->mv_limits;
3410 const SEARCH_METHODS search_method = NSTEP;
3411 const int sadpb = x->sadperbit16;
3412 MV ref_mv_full = { ref_mv.row >> 3, ref_mv.col >> 3 };
3413 MV best_mv = { 0, 0 };
3416 assert(yv12 != NULL);
3418 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
3419 &cm->frame_refs[ref - 1].sf);
3420 mi->ref_frame[0] = ref;
3421 mi->ref_frame[1] = NONE;
3422 mi->sb_type = bsize;
3423 vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
3424 vp9_full_pixel_search(cpi, x, bsize, &ref_mv_full, step_param, search_method,
3425 sadpb, cond_cost_list(cpi, cost_list), &ref_mv,
3429 x->mv_limits = tmp_mv_limits;
3430 mi->mv[0].as_mv = best_mv;
3432 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3433 xd->plane[0].dst.buf = pred_buf;
3434 xd->plane[0].dst.stride = 64;
3435 vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
3438 // Use a neural net model to prune partition-none and partition-split search.
3439 // Features used: QP; spatial block size contexts; variance of prediction
3440 // residue after simple_motion_search.
3442 static void ml_predict_var_rd_paritioning(const VP9_COMP *const cpi,
3443 MACROBLOCK *const x,
3444 PC_TREE *const pc_tree,
3445 BLOCK_SIZE bsize, int mi_row,
3446 int mi_col, int *none, int *split) {
3447 const VP9_COMMON *const cm = &cpi->common;
3448 const NN_CONFIG *nn_config = NULL;
3449 #if CONFIG_VP9_HIGHBITDEPTH
3450 MACROBLOCKD *xd = &x->e_mbd;
3451 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64 * 2]);
3452 uint8_t *const pred_buf = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
3453 ? (CONVERT_TO_BYTEPTR(pred_buffer))
3456 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64]);
3457 uint8_t *const pred_buf = pred_buffer;
3458 #endif // CONFIG_VP9_HIGHBITDEPTH
3459 const int speed = cpi->oxcf.speed;
3460 float thresh = 0.0f;
3464 nn_config = &vp9_part_split_nnconfig_64;
3465 thresh = speed > 0 ? 2.8f : 3.0f;
3468 nn_config = &vp9_part_split_nnconfig_32;
3469 thresh = speed > 0 ? 3.5f : 3.0f;
3472 nn_config = &vp9_part_split_nnconfig_16;
3473 thresh = speed > 0 ? 3.8f : 4.0f;
3476 nn_config = &vp9_part_split_nnconfig_8;
3477 if (cm->width >= 720 && cm->height >= 720)
3478 thresh = speed > 0 ? 2.5f : 2.0f;
3480 thresh = speed > 0 ? 3.8f : 2.0f;
3482 default: assert(0 && "Unexpected block size."); return;
3485 if (!nn_config) return;
3487 // Do a simple single motion search to find a prediction for current block.
3488 // The variance of the residue will be used as input features.
3491 const MV_REFERENCE_FRAME ref =
3492 cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
3493 // If bsize is 64x64, use zero MV as reference; otherwise, use MV result
3494 // of previous(larger) block as reference.
3495 if (bsize == BLOCK_64X64)
3496 ref_mv.row = ref_mv.col = 0;
3498 ref_mv = pc_tree->mv;
3499 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
3500 simple_motion_search(cpi, x, bsize, mi_row, mi_col, ref_mv, ref, pred_buf);
3501 pc_tree->mv = x->e_mbd.mi[0]->mv[0].as_mv;
3504 vpx_clear_system_state();
3507 float features[FEATURES] = { 0.0f };
3508 #if CONFIG_VP9_HIGHBITDEPTH
3510 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (xd->bd - 8);
3512 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3513 #endif // CONFIG_VP9_HIGHBITDEPTH
3514 int feature_idx = 0;
3517 // Generate model input features.
3518 features[feature_idx++] = logf((float)dc_q + 1.0f);
3520 // Get the variance of the residue as input features.
3522 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3523 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3524 const uint8_t *pred = pred_buf;
3525 const uint8_t *src = x->plane[0].src.buf;
3526 const int src_stride = x->plane[0].src.stride;
3527 const int pred_stride = 64;
3529 // Variance of whole block.
3530 const unsigned int var =
3531 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
3532 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
3533 const MACROBLOCKD *const xd = &x->e_mbd;
3534 const int has_above = !!xd->above_mi;
3535 const int has_left = !!xd->left_mi;
3536 const BLOCK_SIZE above_bsize = has_above ? xd->above_mi->sb_type : bsize;
3537 const BLOCK_SIZE left_bsize = has_left ? xd->left_mi->sb_type : bsize;
3540 features[feature_idx++] = (float)has_above;
3541 features[feature_idx++] = (float)b_width_log2_lookup[above_bsize];
3542 features[feature_idx++] = (float)b_height_log2_lookup[above_bsize];
3543 features[feature_idx++] = (float)has_left;
3544 features[feature_idx++] = (float)b_width_log2_lookup[left_bsize];
3545 features[feature_idx++] = (float)b_height_log2_lookup[left_bsize];
3546 features[feature_idx++] = logf((float)var + 1.0f);
3547 for (i = 0; i < 4; ++i) {
3548 const int x_idx = (i & 1) * bs / 2;
3549 const int y_idx = (i >> 1) * bs / 2;
3550 const int src_offset = y_idx * src_stride + x_idx;
3551 const int pred_offset = y_idx * pred_stride + x_idx;
3552 // Variance of quarter block.
3553 const unsigned int sub_var =
3554 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
3555 pred + pred_offset, pred_stride, &sse);
3556 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
3557 features[feature_idx++] = var_ratio;
3560 assert(feature_idx == FEATURES);
3562 // Feed the features into the model to get the confidence score.
3563 nn_predict(features, nn_config, &score);
3565 // Higher score means that the model has higher confidence that the split
3566 // partition is better than the non-split partition. So if the score is
3567 // high enough, we skip the none-split partition search; if the score is
3568 // low enough, we skip the split partition search.
3569 if (score > thresh) *none = 0;
3570 if (score < -thresh) *split = 0;
3575 static int wiener_var_rdmult(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3576 int mi_col, int orig_rdmult) {
3577 VP9_COMMON *cm = &cpi->common;
3578 int mb_row_start = mi_row >> 1;
3579 int mb_col_start = mi_col >> 1;
3581 VPXMIN((mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3583 VPXMIN((mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3586 int64_t wiener_variance = 0;
3587 KMEANS_DATA *kmeans_data;
3588 vpx_clear_system_state();
3590 assert(cpi->norm_wiener_variance > 0);
3592 for (row = mb_row_start; row < mb_row_end; ++row)
3593 for (col = mb_col_start; col < mb_col_end; ++col)
3594 wiener_variance += cpi->mb_wiener_variance[row * cm->mb_cols + col];
3596 kmeans_data = &cpi->kmeans_data_arr[cpi->kmeans_data_size++];
3597 kmeans_data->value = log(1 + wiener_variance);
3598 kmeans_data->pos = mi_row * cpi->kmeans_data_stride + mi_col;
3599 if (wiener_variance)
3601 (mb_row_end - mb_row_start) * (mb_col_end - mb_col_start);
3602 rdmult = (orig_rdmult * wiener_variance) / cpi->norm_wiener_variance;
3604 rdmult = VPXMIN(rdmult, orig_rdmult * 3);
3605 rdmult = VPXMAX(rdmult, orig_rdmult / 4);
3610 static int get_rdmult_delta(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3611 int mi_col, int orig_rdmult) {
3612 const int gf_group_index = cpi->twopass.gf_group.index;
3613 TplDepFrame *tpl_frame = &cpi->tpl_stats[gf_group_index];
3614 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
3615 int tpl_stride = tpl_frame->stride;
3616 int64_t intra_cost = 0;
3617 int64_t mc_dep_cost = 0;
3618 int mi_wide = num_8x8_blocks_wide_lookup[bsize];
3619 int mi_high = num_8x8_blocks_high_lookup[bsize];
3624 double r0, rk, beta;
3626 if (tpl_frame->is_valid == 0) return orig_rdmult;
3628 if (cpi->twopass.gf_group.layer_depth[gf_group_index] > 1) return orig_rdmult;
3630 if (gf_group_index >= MAX_ARF_GOP_SIZE) return orig_rdmult;
3632 for (row = mi_row; row < mi_row + mi_high; ++row) {
3633 for (col = mi_col; col < mi_col + mi_wide; ++col) {
3634 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
3636 if (row >= cpi->common.mi_rows || col >= cpi->common.mi_cols) continue;
3638 intra_cost += this_stats->intra_cost;
3639 mc_dep_cost += this_stats->mc_dep_cost;
3645 vpx_clear_system_state();
3648 rk = (double)intra_cost / mc_dep_cost;
3650 dr = vp9_get_adaptive_rdmult(cpi, beta);
3652 dr = VPXMIN(dr, orig_rdmult * 3 / 2);
3653 dr = VPXMAX(dr, orig_rdmult * 1 / 2);
3660 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
3661 // unlikely to be selected depending on previous rate-distortion optimization
3662 // results, for encoding speed-up.
3663 static void rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3664 TileDataEnc *tile_data, TOKENEXTRA **tp,
3665 int mi_row, int mi_col, BLOCK_SIZE bsize,
3666 RD_COST *rd_cost, int64_t best_rd,
3668 VP9_COMMON *const cm = &cpi->common;
3669 TileInfo *const tile_info = &tile_data->tile_info;
3670 MACROBLOCK *const x = &td->mb;
3671 MACROBLOCKD *const xd = &x->e_mbd;
3672 const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
3673 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
3674 PARTITION_CONTEXT sl[8], sa[8];
3675 TOKENEXTRA *tp_orig = *tp;
3676 PICK_MODE_CONTEXT *const ctx = &pc_tree->none;
3678 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3680 RD_COST this_rdc, sum_rdc, best_rdc;
3681 int do_split = bsize >= BLOCK_8X8;
3683 INTERP_FILTER pred_interp_filter;
3685 // Override skipping rectangular partition operations for edge blocks
3686 const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
3687 const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
3688 const int xss = x->e_mbd.plane[1].subsampling_x;
3689 const int yss = x->e_mbd.plane[1].subsampling_y;
3691 BLOCK_SIZE min_size = x->min_partition_size;
3692 BLOCK_SIZE max_size = x->max_partition_size;
3694 #if CONFIG_FP_MB_STATS
3695 unsigned int src_diff_var = UINT_MAX;
3696 int none_complexity = 0;
3699 int partition_none_allowed = !force_horz_split && !force_vert_split;
3700 int partition_horz_allowed =
3701 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
3702 int partition_vert_allowed =
3703 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
3705 int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_thr.dist;
3706 int rate_breakout_thr = cpi->sf.partition_search_breakout_thr.rate;
3709 (cpi->sf.enable_tpl_model || cpi->sf.enable_wiener_variance) &&
3710 cpi->oxcf.aq_mode == NO_AQ
3713 // Ref frames picked in the [i_th] quarter subblock during square partition
3714 // RD search. It may be used to prune ref frame selection of rect partitions.
3715 uint8_t ref_frames_used[4] = { 0, 0, 0, 0 };
3719 assert(num_8x8_blocks_wide_lookup[bsize] ==
3720 num_8x8_blocks_high_lookup[bsize]);
3722 dist_breakout_thr >>=
3723 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
3725 rate_breakout_thr *= num_pels_log2_lookup[bsize];
3727 vp9_rd_cost_init(&this_rdc);
3728 vp9_rd_cost_init(&sum_rdc);
3729 vp9_rd_cost_reset(&best_rdc);
3730 best_rdc.rdcost = best_rd;
3732 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3734 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ &&
3735 cpi->oxcf.aq_mode != LOOKAHEAD_AQ)
3736 x->mb_energy = vp9_block_energy(cpi, x, bsize);
3738 if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
3739 int cb_partition_search_ctrl =
3740 ((pc_tree->index == 0 || pc_tree->index == 3) +
3741 get_chessboard_index(cm->current_video_frame)) &
3744 if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
3745 set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
3748 // Get sub block energy range
3749 if (bsize >= BLOCK_16X16) {
3750 int min_energy, max_energy;
3751 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3753 must_split = (min_energy < -3) && (max_energy - min_energy > 2);
3756 // Determine partition types in search according to the speed features.
3757 // The threshold set here has to be of square block size.
3758 if (cpi->sf.auto_min_max_partition_size) {
3759 partition_none_allowed &= (bsize <= max_size);
3760 partition_horz_allowed &=
3761 ((bsize <= max_size && bsize > min_size) || force_horz_split);
3762 partition_vert_allowed &=
3763 ((bsize <= max_size && bsize > min_size) || force_vert_split);
3764 do_split &= bsize > min_size;
3767 if (cpi->sf.use_square_partition_only &&
3768 (bsize > cpi->sf.use_square_only_thresh_high ||
3769 bsize < cpi->sf.use_square_only_thresh_low)) {
3771 if (!vp9_active_h_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3772 partition_horz_allowed &= force_horz_split;
3773 if (!vp9_active_v_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3774 partition_vert_allowed &= force_vert_split;
3776 partition_horz_allowed &= force_horz_split;
3777 partition_vert_allowed &= force_vert_split;
3781 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3783 #if CONFIG_FP_MB_STATS
3784 if (cpi->use_fp_mb_stats) {
3785 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3786 src_diff_var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src, mi_row,
3791 #if CONFIG_FP_MB_STATS
3792 // Decide whether we shall split directly and skip searching NONE by using
3793 // the first pass block statistics
3794 if (cpi->use_fp_mb_stats && bsize >= BLOCK_32X32 && do_split &&
3795 partition_none_allowed && src_diff_var > 4 &&
3796 cm->base_qindex < qindex_split_threshold_lookup[bsize]) {
3797 int mb_row = mi_row >> 1;
3798 int mb_col = mi_col >> 1;
3800 VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
3802 VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
3805 // compute a complexity measure, basically measure inconsistency of motion
3806 // vectors obtained from the first pass in the current block
3807 for (r = mb_row; r < mb_row_end; r++) {
3808 for (c = mb_col; c < mb_col_end; c++) {
3809 const int mb_index = r * cm->mb_cols + c;
3811 MOTION_DIRECTION this_mv;
3812 MOTION_DIRECTION right_mv;
3813 MOTION_DIRECTION bottom_mv;
3816 get_motion_direction_fp(cpi->twopass.this_frame_mb_stats[mb_index]);
3819 if (c != mb_col_end - 1) {
3820 right_mv = get_motion_direction_fp(
3821 cpi->twopass.this_frame_mb_stats[mb_index + 1]);
3822 none_complexity += get_motion_inconsistency(this_mv, right_mv);
3826 if (r != mb_row_end - 1) {
3827 bottom_mv = get_motion_direction_fp(
3828 cpi->twopass.this_frame_mb_stats[mb_index + cm->mb_cols]);
3829 none_complexity += get_motion_inconsistency(this_mv, bottom_mv);
3832 // do not count its left and top neighbors to avoid double counting
3836 if (none_complexity > complexity_16x16_blocks_threshold[bsize]) {
3837 partition_none_allowed = 0;
3842 pc_tree->partitioning = PARTITION_NONE;
3844 if (cpi->sf.rd_ml_partition.var_pruning && !frame_is_intra_only(cm)) {
3845 const int do_rd_ml_partition_var_pruning =
3846 partition_none_allowed && do_split &&
3847 mi_row + num_8x8_blocks_high_lookup[bsize] <= cm->mi_rows &&
3848 mi_col + num_8x8_blocks_wide_lookup[bsize] <= cm->mi_cols;
3849 if (do_rd_ml_partition_var_pruning) {
3850 ml_predict_var_rd_paritioning(cpi, x, pc_tree, bsize, mi_row, mi_col,
3851 &partition_none_allowed, &do_split);
3853 vp9_zero(pc_tree->mv);
3855 if (bsize > BLOCK_8X8) { // Store MV result as reference for subblocks.
3856 for (i = 0; i < 4; ++i) pc_tree->split[i]->mv = pc_tree->mv;
3861 if (partition_none_allowed) {
3862 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize, ctx,
3864 ctx->rdcost = this_rdc.rdcost;
3865 if (this_rdc.rate != INT_MAX) {
3866 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
3867 const int ref1 = ctx->mic.ref_frame[0];
3868 const int ref2 = ctx->mic.ref_frame[1];
3869 for (i = 0; i < 4; ++i) {
3870 ref_frames_used[i] |= (1 << ref1);
3871 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3874 if (bsize >= BLOCK_8X8) {
3875 this_rdc.rdcost += RDCOST(partition_mul, x->rddiv,
3876 cpi->partition_cost[pl][PARTITION_NONE], 0);
3877 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3880 if (this_rdc.rdcost < best_rdc.rdcost) {
3881 MODE_INFO *mi = xd->mi[0];
3883 best_rdc = this_rdc;
3884 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
3886 if (cpi->sf.rd_ml_partition.search_early_termination) {
3887 // Currently, the machine-learning based partition search early
3888 // termination is only used while bsize is 16x16, 32x32 or 64x64,
3889 // VPXMIN(cm->width, cm->height) >= 480, and speed = 0.
3890 if (!x->e_mbd.lossless &&
3891 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP) &&
3892 ctx->mic.mode >= INTRA_MODES && bsize >= BLOCK_16X16) {
3893 if (ml_pruning_partition(cm, xd, ctx, mi_row, mi_col, bsize)) {
3900 if ((do_split || do_rect) && !x->e_mbd.lossless && ctx->skippable) {
3901 const int use_ml_based_breakout =
3902 cpi->sf.rd_ml_partition.search_breakout && cm->base_qindex >= 100;
3903 if (use_ml_based_breakout) {
3904 if (ml_predict_breakout(cpi, bsize, x, &this_rdc)) {
3909 if (!cpi->sf.rd_ml_partition.search_early_termination) {
3910 if ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
3911 (best_rdc.dist < dist_breakout_thr &&
3912 best_rdc.rate < rate_breakout_thr)) {
3920 #if CONFIG_FP_MB_STATS
3921 // Check if every 16x16 first pass block statistics has zero
3922 // motion and the corresponding first pass residue is small enough.
3923 // If that is the case, check the difference variance between the
3924 // current frame and the last frame. If the variance is small enough,
3925 // stop further splitting in RD optimization
3926 if (cpi->use_fp_mb_stats && do_split != 0 &&
3927 cm->base_qindex > qindex_skip_threshold_lookup[bsize]) {
3928 int mb_row = mi_row >> 1;
3929 int mb_col = mi_col >> 1;
3931 VPXMIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
3933 VPXMIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
3937 for (r = mb_row; r < mb_row_end; r++) {
3938 for (c = mb_col; c < mb_col_end; c++) {
3939 const int mb_index = r * cm->mb_cols + c;
3940 if (!(cpi->twopass.this_frame_mb_stats[mb_index] &
3941 FPMB_MOTION_ZERO_MASK) ||
3942 !(cpi->twopass.this_frame_mb_stats[mb_index] &
3943 FPMB_ERROR_SMALL_MASK)) {
3954 if (src_diff_var == UINT_MAX) {
3955 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3956 src_diff_var = get_sby_perpixel_diff_variance(
3957 cpi, &x->plane[0].src, mi_row, mi_col, bsize);
3959 if (src_diff_var < 8) {
3968 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3970 vp9_zero(ctx->pred_mv);
3971 ctx->mic.interp_filter = EIGHTTAP;
3974 // store estimated motion vector
3975 store_pred_mv(x, ctx);
3977 // If the interp_filter is marked as SWITCHABLE_FILTERS, it was for an
3978 // intra block and used for context purposes.
3979 if (ctx->mic.interp_filter == SWITCHABLE_FILTERS) {
3980 pred_interp_filter = EIGHTTAP;
3982 pred_interp_filter = ctx->mic.interp_filter;
3986 // TODO(jingning): use the motion vectors given by the above search as
3987 // the starting point of motion search in the following partition type check.
3988 pc_tree->split[0]->none.rdcost = 0;
3989 pc_tree->split[1]->none.rdcost = 0;
3990 pc_tree->split[2]->none.rdcost = 0;
3991 pc_tree->split[3]->none.rdcost = 0;
3992 if (do_split || must_split) {
3993 subsize = get_subsize(bsize, PARTITION_SPLIT);
3994 load_pred_mv(x, ctx);
3995 if (bsize == BLOCK_8X8) {
3997 if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
3998 pc_tree->leaf_split[0]->pred_interp_filter = pred_interp_filter;
3999 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4000 pc_tree->leaf_split[0], best_rdc.rdcost);
4001 if (sum_rdc.rate == INT_MAX) {
4002 sum_rdc.rdcost = INT64_MAX;
4004 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4005 const int ref1 = pc_tree->leaf_split[0]->mic.ref_frame[0];
4006 const int ref2 = pc_tree->leaf_split[0]->mic.ref_frame[1];
4007 for (i = 0; i < 4; ++i) {
4008 ref_frames_used[i] |= (1 << ref1);
4009 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4014 for (i = 0; (i < 4) && ((sum_rdc.rdcost < best_rdc.rdcost) || must_split);
4016 const int x_idx = (i & 1) * mi_step;
4017 const int y_idx = (i >> 1) * mi_step;
4019 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4022 pc_tree->split[i]->index = i;
4023 if (cpi->sf.prune_ref_frame_for_rect_partitions)
4024 pc_tree->split[i]->none.rate = INT_MAX;
4025 rd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4026 mi_col + x_idx, subsize, &this_rdc,
4027 // A must split test here increases the number of sub
4028 // partitions but hurts metrics results quite a bit,
4029 // so this extra test is commented out pending
4030 // further tests on whether it adds much in terms of
4032 // (must_split) ? best_rdc.rdcost
4033 // : best_rdc.rdcost - sum_rdc.rdcost,
4034 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4036 if (this_rdc.rate == INT_MAX) {
4037 sum_rdc.rdcost = INT64_MAX;
4040 if (cpi->sf.prune_ref_frame_for_rect_partitions &&
4041 pc_tree->split[i]->none.rate != INT_MAX) {
4042 const int ref1 = pc_tree->split[i]->none.mic.ref_frame[0];
4043 const int ref2 = pc_tree->split[i]->none.mic.ref_frame[1];
4044 ref_frames_used[i] |= (1 << ref1);
4045 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4047 sum_rdc.rate += this_rdc.rate;
4048 sum_rdc.dist += this_rdc.dist;
4049 sum_rdc.rdcost += this_rdc.rdcost;
4054 if (((sum_rdc.rdcost < best_rdc.rdcost) || must_split) && i == 4) {
4055 sum_rdc.rdcost += RDCOST(partition_mul, x->rddiv,
4056 cpi->partition_cost[pl][PARTITION_SPLIT], 0);
4057 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4059 if ((sum_rdc.rdcost < best_rdc.rdcost) ||
4060 (must_split && (sum_rdc.dist < best_rdc.dist))) {
4062 pc_tree->partitioning = PARTITION_SPLIT;
4064 // Rate and distortion based partition search termination clause.
4065 if (!cpi->sf.rd_ml_partition.search_early_termination &&
4066 !x->e_mbd.lossless &&
4067 ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4068 (best_rdc.dist < dist_breakout_thr &&
4069 best_rdc.rate < rate_breakout_thr))) {
4074 // skip rectangular partition test when larger block size
4075 // gives better rd cost
4076 if (cpi->sf.less_rectangular_check &&
4077 (bsize > cpi->sf.use_square_only_thresh_high ||
4078 best_rdc.dist < dist_breakout_thr))
4079 do_rect &= !partition_none_allowed;
4081 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4084 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
4085 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
4086 pc_tree->vertical[0].skip_ref_frame_mask = 0;
4087 pc_tree->vertical[1].skip_ref_frame_mask = 0;
4088 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4089 uint8_t used_frames;
4090 used_frames = ref_frames_used[0] | ref_frames_used[1];
4091 if (used_frames) pc_tree->horizontal[0].skip_ref_frame_mask = ~used_frames;
4092 used_frames = ref_frames_used[2] | ref_frames_used[3];
4093 if (used_frames) pc_tree->horizontal[1].skip_ref_frame_mask = ~used_frames;
4094 used_frames = ref_frames_used[0] | ref_frames_used[2];
4095 if (used_frames) pc_tree->vertical[0].skip_ref_frame_mask = ~used_frames;
4096 used_frames = ref_frames_used[1] | ref_frames_used[3];
4097 if (used_frames) pc_tree->vertical[1].skip_ref_frame_mask = ~used_frames;
4101 const int do_ml_rect_partition_pruning =
4102 !frame_is_intra_only(cm) && !force_horz_split && !force_vert_split &&
4103 (partition_horz_allowed || partition_vert_allowed) && bsize > BLOCK_8X8;
4104 if (do_ml_rect_partition_pruning) {
4105 ml_prune_rect_partition(cpi, x, bsize, pc_tree, &partition_horz_allowed,
4106 &partition_vert_allowed, best_rdc.rdcost);
4111 if (partition_horz_allowed &&
4112 (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
4113 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_HORZ];
4114 const int64_t part_mode_rdcost =
4115 RDCOST(partition_mul, x->rddiv, part_mode_rate, 0);
4116 subsize = get_subsize(bsize, PARTITION_HORZ);
4117 load_pred_mv(x, ctx);
4118 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4119 partition_none_allowed)
4120 pc_tree->horizontal[0].pred_interp_filter = pred_interp_filter;
4121 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4122 &pc_tree->horizontal[0],
4123 best_rdc.rdcost - part_mode_rdcost);
4124 if (sum_rdc.rdcost < INT64_MAX) {
4125 sum_rdc.rdcost += part_mode_rdcost;
4126 sum_rdc.rate += part_mode_rate;
4129 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
4130 bsize > BLOCK_8X8) {
4131 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
4132 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
4133 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
4134 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4135 partition_none_allowed)
4136 pc_tree->horizontal[1].pred_interp_filter = pred_interp_filter;
4137 rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col, &this_rdc,
4138 subsize, &pc_tree->horizontal[1],
4139 best_rdc.rdcost - sum_rdc.rdcost);
4140 if (this_rdc.rate == INT_MAX) {
4141 sum_rdc.rdcost = INT64_MAX;
4143 sum_rdc.rate += this_rdc.rate;
4144 sum_rdc.dist += this_rdc.dist;
4145 sum_rdc.rdcost += this_rdc.rdcost;
4149 if (sum_rdc.rdcost < best_rdc.rdcost) {
4151 pc_tree->partitioning = PARTITION_HORZ;
4153 if (cpi->sf.less_rectangular_check &&
4154 bsize > cpi->sf.use_square_only_thresh_high)
4157 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4161 if (partition_vert_allowed &&
4162 (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
4163 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_VERT];
4164 const int64_t part_mode_rdcost =
4165 RDCOST(partition_mul, x->rddiv, part_mode_rate, 0);
4166 subsize = get_subsize(bsize, PARTITION_VERT);
4167 load_pred_mv(x, ctx);
4168 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4169 partition_none_allowed)
4170 pc_tree->vertical[0].pred_interp_filter = pred_interp_filter;
4171 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4172 &pc_tree->vertical[0], best_rdc.rdcost - part_mode_rdcost);
4173 if (sum_rdc.rdcost < INT64_MAX) {
4174 sum_rdc.rdcost += part_mode_rdcost;
4175 sum_rdc.rate += part_mode_rate;
4178 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
4179 bsize > BLOCK_8X8) {
4180 update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
4181 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
4182 &pc_tree->vertical[0]);
4183 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4184 partition_none_allowed)
4185 pc_tree->vertical[1].pred_interp_filter = pred_interp_filter;
4186 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step, &this_rdc,
4187 subsize, &pc_tree->vertical[1],
4188 best_rdc.rdcost - sum_rdc.rdcost);
4189 if (this_rdc.rate == INT_MAX) {
4190 sum_rdc.rdcost = INT64_MAX;
4192 sum_rdc.rate += this_rdc.rate;
4193 sum_rdc.dist += this_rdc.dist;
4194 sum_rdc.rdcost += this_rdc.rdcost;
4198 if (sum_rdc.rdcost < best_rdc.rdcost) {
4200 pc_tree->partitioning = PARTITION_VERT;
4202 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4205 // TODO(jbb): This code added so that we avoid static analysis
4206 // warning related to the fact that best_rd isn't used after this
4207 // point. This code should be refactored so that the duplicate
4208 // checks occur in some sub function and thus are used...
4210 *rd_cost = best_rdc;
4212 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX &&
4213 pc_tree->index != 3) {
4214 int output_enabled = (bsize == BLOCK_64X64);
4215 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4219 if (bsize == BLOCK_64X64) {
4220 assert(tp_orig < *tp);
4221 assert(best_rdc.rate < INT_MAX);
4222 assert(best_rdc.dist < INT64_MAX);
4224 assert(tp_orig == *tp);
4228 static void encode_rd_sb_row(VP9_COMP *cpi, ThreadData *td,
4229 TileDataEnc *tile_data, int mi_row,
4231 VP9_COMMON *const cm = &cpi->common;
4232 TileInfo *const tile_info = &tile_data->tile_info;
4233 MACROBLOCK *const x = &td->mb;
4234 MACROBLOCKD *const xd = &x->e_mbd;
4235 SPEED_FEATURES *const sf = &cpi->sf;
4236 const int mi_col_start = tile_info->mi_col_start;
4237 const int mi_col_end = tile_info->mi_col_end;
4239 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
4240 const int num_sb_cols =
4241 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
4244 // Initialize the left context for the new SB row
4245 memset(&xd->left_context, 0, sizeof(xd->left_context));
4246 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
4248 // Code each SB in the row
4249 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
4250 mi_col += MI_BLOCK_SIZE, sb_col_in_tile++) {
4251 const struct segmentation *const seg = &cm->seg;
4257 int orig_rdmult = cpi->rd.RDMULT;
4259 const int idx_str = cm->mi_stride * mi_row + mi_col;
4260 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
4262 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
4265 if (sf->adaptive_pred_interp_filter) {
4266 for (i = 0; i < 64; ++i) td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
4268 for (i = 0; i < 64; ++i) {
4269 td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
4270 td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
4271 td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
4272 td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
4276 for (i = 0; i < MAX_REF_FRAMES; ++i) {
4277 x->pred_mv[i].row = INT16_MAX;
4278 x->pred_mv[i].col = INT16_MAX;
4280 td->pc_root->index = 0;
4283 const uint8_t *const map =
4284 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
4285 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
4286 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
4289 x->source_variance = UINT_MAX;
4291 x->cb_rdmult = orig_rdmult;
4293 if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
4294 const BLOCK_SIZE bsize =
4295 seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
4296 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4297 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4298 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4299 &dummy_rate, &dummy_dist, 1, td->pc_root);
4300 } else if (cpi->partition_search_skippable_frame) {
4302 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4303 bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col);
4304 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4305 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4306 &dummy_rate, &dummy_dist, 1, td->pc_root);
4307 } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
4308 cm->frame_type != KEY_FRAME) {
4309 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
4310 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4311 &dummy_rate, &dummy_dist, 1, td->pc_root);
4313 if (cpi->twopass.gf_group.index > 0 && cpi->sf.enable_tpl_model) {
4315 get_rdmult_delta(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4319 if (cpi->sf.enable_wiener_variance && cm->show_frame)
4321 wiener_var_rdmult(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4323 // If required set upper and lower partition size limits
4324 if (sf->auto_min_max_partition_size) {
4325 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4326 rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
4327 &x->min_partition_size, &x->max_partition_size);
4329 td->pc_root->none.rdcost = 0;
4330 rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
4331 &dummy_rdc, INT64_MAX, td->pc_root);
4333 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
4334 sb_col_in_tile, num_sb_cols);
4338 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
4339 MACROBLOCK *const x = &cpi->td.mb;
4340 VP9_COMMON *const cm = &cpi->common;
4341 MACROBLOCKD *const xd = &x->e_mbd;
4342 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
4344 // Copy data over into macro block data structures.
4345 vp9_setup_src_planes(x, cpi->Source, 0, 0);
4347 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
4349 // Note: this memset assumes above_context[0], [1] and [2]
4350 // are allocated as part of the same buffer.
4351 memset(xd->above_context[0], 0,
4352 sizeof(*xd->above_context[0]) * 2 * aligned_mi_cols * MAX_MB_PLANE);
4353 memset(xd->above_seg_context, 0,
4354 sizeof(*xd->above_seg_context) * aligned_mi_cols);
4357 static int check_dual_ref_flags(VP9_COMP *cpi) {
4358 const int ref_flags = cpi->ref_frame_flags;
4360 if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
4363 return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG) +
4364 !!(ref_flags & VP9_ALT_FLAG)) >= 2;
4368 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
4370 const int mis = cm->mi_stride;
4371 MODE_INFO **mi_ptr = cm->mi_grid_visible;
4373 for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
4374 for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
4375 if (mi_ptr[mi_col]->tx_size > max_tx_size)
4376 mi_ptr[mi_col]->tx_size = max_tx_size;
4381 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
4382 if (frame_is_intra_only(&cpi->common))
4384 else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
4385 return ALTREF_FRAME;
4386 else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
4387 return GOLDEN_FRAME;
4392 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
4393 if (xd->lossless) return ONLY_4X4;
4394 if (cpi->common.frame_type == KEY_FRAME && cpi->sf.use_nonrd_pick_mode)
4396 if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
4398 else if (cpi->sf.tx_size_search_method == USE_FULL_RD ||
4399 cpi->sf.tx_size_search_method == USE_TX_8X8)
4400 return TX_MODE_SELECT;
4402 return cpi->common.tx_mode;
4405 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
4406 RD_COST *rd_cost, BLOCK_SIZE bsize,
4407 PICK_MODE_CONTEXT *ctx) {
4408 if (!cpi->sf.nonrd_keyframe && bsize < BLOCK_16X16)
4409 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4411 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4414 static void hybrid_search_svc_baseiskey(VP9_COMP *cpi, MACROBLOCK *const x,
4415 RD_COST *rd_cost, BLOCK_SIZE bsize,
4416 PICK_MODE_CONTEXT *ctx,
4417 TileDataEnc *tile_data, int mi_row,
4419 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4420 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4422 if (cpi->svc.disable_inter_layer_pred == INTER_LAYER_PRED_OFF)
4423 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4424 else if (bsize >= BLOCK_8X8)
4425 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4428 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4432 static void hybrid_search_scene_change(VP9_COMP *cpi, MACROBLOCK *const x,
4433 RD_COST *rd_cost, BLOCK_SIZE bsize,
4434 PICK_MODE_CONTEXT *ctx,
4435 TileDataEnc *tile_data, int mi_row,
4437 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4438 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4440 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize, ctx);
4444 static void nonrd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
4445 MACROBLOCK *const x, int mi_row, int mi_col,
4446 RD_COST *rd_cost, BLOCK_SIZE bsize,
4447 PICK_MODE_CONTEXT *ctx) {
4448 VP9_COMMON *const cm = &cpi->common;
4449 TileInfo *const tile_info = &tile_data->tile_info;
4450 MACROBLOCKD *const xd = &x->e_mbd;
4452 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
4453 BLOCK_SIZE bs = VPXMAX(bsize, BLOCK_8X8); // processing unit block size
4454 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bs];
4455 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bs];
4458 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4460 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
4463 mi->sb_type = bsize;
4465 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4466 struct macroblockd_plane *pd = &xd->plane[plane];
4467 memcpy(a + num_4x4_blocks_wide * plane, pd->above_context,
4468 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4469 memcpy(l + num_4x4_blocks_high * plane, pd->left_context,
4470 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4473 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
4474 if (cyclic_refresh_segment_id_boosted(mi->segment_id))
4475 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
4477 if (frame_is_intra_only(cm))
4478 hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
4479 else if (cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
4480 hybrid_search_svc_baseiskey(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4482 else if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
4483 set_mode_info_seg_skip(x, cm->tx_mode, rd_cost, bsize);
4484 else if (bsize >= BLOCK_8X8) {
4485 if (cpi->rc.hybrid_intra_scene_change)
4486 hybrid_search_scene_change(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4489 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4492 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4495 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4497 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4498 struct macroblockd_plane *pd = &xd->plane[plane];
4499 memcpy(pd->above_context, a + num_4x4_blocks_wide * plane,
4500 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4501 memcpy(pd->left_context, l + num_4x4_blocks_high * plane,
4502 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4505 if (rd_cost->rate == INT_MAX) vp9_rd_cost_reset(rd_cost);
4507 ctx->rate = rd_cost->rate;
4508 ctx->dist = rd_cost->dist;
4511 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x, int mi_row,
4512 int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4513 MACROBLOCKD *xd = &x->e_mbd;
4514 int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4515 PARTITION_TYPE partition = pc_tree->partitioning;
4516 BLOCK_SIZE subsize = get_subsize(bsize, partition);
4518 assert(bsize >= BLOCK_8X8);
4520 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4522 switch (partition) {
4523 case PARTITION_NONE:
4524 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4525 *(xd->mi[0]) = pc_tree->none.mic;
4526 *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
4527 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4529 case PARTITION_VERT:
4530 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4531 *(xd->mi[0]) = pc_tree->vertical[0].mic;
4532 *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
4533 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4535 if (mi_col + hbs < cm->mi_cols) {
4536 set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
4537 *(xd->mi[0]) = pc_tree->vertical[1].mic;
4538 *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
4539 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
4542 case PARTITION_HORZ:
4543 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4544 *(xd->mi[0]) = pc_tree->horizontal[0].mic;
4545 *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
4546 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4547 if (mi_row + hbs < cm->mi_rows) {
4548 set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
4549 *(xd->mi[0]) = pc_tree->horizontal[1].mic;
4550 *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
4551 duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
4554 case PARTITION_SPLIT: {
4555 fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
4556 fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
4558 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
4560 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
4568 // Reset the prediction pixel ready flag recursively.
4569 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
4570 pc_tree->none.pred_pixel_ready = 0;
4571 pc_tree->horizontal[0].pred_pixel_ready = 0;
4572 pc_tree->horizontal[1].pred_pixel_ready = 0;
4573 pc_tree->vertical[0].pred_pixel_ready = 0;
4574 pc_tree->vertical[1].pred_pixel_ready = 0;
4576 if (bsize > BLOCK_8X8) {
4577 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4579 for (i = 0; i < 4; ++i) pred_pixel_ready_reset(pc_tree->split[i], subsize);
4585 static int ml_predict_var_paritioning(VP9_COMP *cpi, MACROBLOCK *x,
4586 BLOCK_SIZE bsize, int mi_row,
4588 VP9_COMMON *const cm = &cpi->common;
4589 const NN_CONFIG *nn_config = NULL;
4592 case BLOCK_64X64: nn_config = &vp9_var_part_nnconfig_64; break;
4593 case BLOCK_32X32: nn_config = &vp9_var_part_nnconfig_32; break;
4594 case BLOCK_16X16: nn_config = &vp9_var_part_nnconfig_16; break;
4595 case BLOCK_8X8: break;
4596 default: assert(0 && "Unexpected block size."); return -1;
4599 if (!nn_config) return -1;
4601 vpx_clear_system_state();
4604 const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
4605 float features[FEATURES] = { 0.0f };
4606 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
4607 int feature_idx = 0;
4608 float score[LABELS];
4610 features[feature_idx++] = logf((float)(dc_q * dc_q) / 256.0f + 1.0f);
4611 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
4613 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
4614 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4615 const int sb_offset_row = 8 * (mi_row & 7);
4616 const int sb_offset_col = 8 * (mi_col & 7);
4617 const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
4618 const uint8_t *src = x->plane[0].src.buf;
4619 const int src_stride = x->plane[0].src.stride;
4620 const int pred_stride = 64;
4623 // Variance of whole block.
4624 const unsigned int var =
4625 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
4626 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
4628 features[feature_idx++] = logf((float)var + 1.0f);
4629 for (i = 0; i < 4; ++i) {
4630 const int x_idx = (i & 1) * bs / 2;
4631 const int y_idx = (i >> 1) * bs / 2;
4632 const int src_offset = y_idx * src_stride + x_idx;
4633 const int pred_offset = y_idx * pred_stride + x_idx;
4634 // Variance of quarter block.
4635 const unsigned int sub_var =
4636 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
4637 pred + pred_offset, pred_stride, &sse);
4638 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
4639 features[feature_idx++] = var_ratio;
4643 assert(feature_idx == FEATURES);
4644 nn_predict(features, nn_config, score);
4645 if (score[0] > thresh) return PARTITION_SPLIT;
4646 if (score[0] < -thresh) return PARTITION_NONE;
4653 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
4654 TileDataEnc *tile_data, TOKENEXTRA **tp,
4655 int mi_row, int mi_col, BLOCK_SIZE bsize,
4656 RD_COST *rd_cost, int do_recon,
4657 int64_t best_rd, PC_TREE *pc_tree) {
4658 const SPEED_FEATURES *const sf = &cpi->sf;
4659 VP9_COMMON *const cm = &cpi->common;
4660 TileInfo *const tile_info = &tile_data->tile_info;
4661 MACROBLOCK *const x = &td->mb;
4662 MACROBLOCKD *const xd = &x->e_mbd;
4663 const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
4664 TOKENEXTRA *tp_orig = *tp;
4665 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
4667 BLOCK_SIZE subsize = bsize;
4668 RD_COST this_rdc, sum_rdc, best_rdc;
4669 int do_split = bsize >= BLOCK_8X8;
4671 // Override skipping rectangular partition operations for edge blocks
4672 const int force_horz_split = (mi_row + ms >= cm->mi_rows);
4673 const int force_vert_split = (mi_col + ms >= cm->mi_cols);
4674 const int xss = x->e_mbd.plane[1].subsampling_x;
4675 const int yss = x->e_mbd.plane[1].subsampling_y;
4677 int partition_none_allowed = !force_horz_split && !force_vert_split;
4678 int partition_horz_allowed =
4679 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
4680 int partition_vert_allowed =
4681 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
4682 const int use_ml_based_partitioning =
4683 sf->partition_search_type == ML_BASED_PARTITION;
4687 // Avoid checking for rectangular partitions for speed >= 6.
4688 if (cpi->oxcf.speed >= 6) do_rect = 0;
4690 assert(num_8x8_blocks_wide_lookup[bsize] ==
4691 num_8x8_blocks_high_lookup[bsize]);
4693 vp9_rd_cost_init(&sum_rdc);
4694 vp9_rd_cost_reset(&best_rdc);
4695 best_rdc.rdcost = best_rd;
4697 // Determine partition types in search according to the speed features.
4698 // The threshold set here has to be of square block size.
4699 if (sf->auto_min_max_partition_size) {
4700 partition_none_allowed &=
4701 (bsize <= x->max_partition_size && bsize >= x->min_partition_size);
4702 partition_horz_allowed &=
4703 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4705 partition_vert_allowed &=
4706 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4708 do_split &= bsize > x->min_partition_size;
4710 if (sf->use_square_partition_only) {
4711 partition_horz_allowed &= force_horz_split;
4712 partition_vert_allowed &= force_vert_split;
4715 if (use_ml_based_partitioning) {
4716 if (partition_none_allowed || do_split) do_rect = 0;
4717 if (partition_none_allowed && do_split) {
4718 const int ml_predicted_partition =
4719 ml_predict_var_paritioning(cpi, x, bsize, mi_row, mi_col);
4720 if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
4721 if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
4725 if (!partition_none_allowed && !do_split) do_rect = 1;
4727 ctx->pred_pixel_ready =
4728 !(partition_vert_allowed || partition_horz_allowed || do_split);
4731 if (partition_none_allowed) {
4732 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
4734 ctx->mic = *xd->mi[0];
4735 ctx->mbmi_ext = *x->mbmi_ext;
4736 ctx->skip_txfm[0] = x->skip_txfm[0];
4737 ctx->skip = x->skip;
4739 if (this_rdc.rate != INT_MAX) {
4740 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4741 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4743 RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
4744 if (this_rdc.rdcost < best_rdc.rdcost) {
4745 best_rdc = this_rdc;
4746 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4748 if (!use_ml_based_partitioning) {
4749 int64_t dist_breakout_thr = sf->partition_search_breakout_thr.dist;
4750 int64_t rate_breakout_thr = sf->partition_search_breakout_thr.rate;
4751 dist_breakout_thr >>=
4752 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4753 rate_breakout_thr *= num_pels_log2_lookup[bsize];
4754 if (!x->e_mbd.lossless && this_rdc.rate < rate_breakout_thr &&
4755 this_rdc.dist < dist_breakout_thr) {
4764 // store estimated motion vector
4765 store_pred_mv(x, ctx);
4769 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4770 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4771 sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4772 subsize = get_subsize(bsize, PARTITION_SPLIT);
4773 for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
4774 const int x_idx = (i & 1) * ms;
4775 const int y_idx = (i >> 1) * ms;
4777 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4779 load_pred_mv(x, ctx);
4780 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4781 mi_col + x_idx, subsize, &this_rdc, 0,
4782 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4784 if (this_rdc.rate == INT_MAX) {
4785 vp9_rd_cost_reset(&sum_rdc);
4787 sum_rdc.rate += this_rdc.rate;
4788 sum_rdc.dist += this_rdc.dist;
4789 sum_rdc.rdcost += this_rdc.rdcost;
4793 if (sum_rdc.rdcost < best_rdc.rdcost) {
4795 pc_tree->partitioning = PARTITION_SPLIT;
4797 // skip rectangular partition test when larger block size
4798 // gives better rd cost
4799 if (sf->less_rectangular_check) do_rect &= !partition_none_allowed;
4804 if (partition_horz_allowed && do_rect) {
4805 subsize = get_subsize(bsize, PARTITION_HORZ);
4806 load_pred_mv(x, ctx);
4807 pc_tree->horizontal[0].pred_pixel_ready = 1;
4808 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4809 &pc_tree->horizontal[0]);
4811 pc_tree->horizontal[0].mic = *xd->mi[0];
4812 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4813 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4814 pc_tree->horizontal[0].skip = x->skip;
4816 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
4817 load_pred_mv(x, ctx);
4818 pc_tree->horizontal[1].pred_pixel_ready = 1;
4819 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc,
4820 subsize, &pc_tree->horizontal[1]);
4822 pc_tree->horizontal[1].mic = *xd->mi[0];
4823 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
4824 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
4825 pc_tree->horizontal[1].skip = x->skip;
4827 if (this_rdc.rate == INT_MAX) {
4828 vp9_rd_cost_reset(&sum_rdc);
4830 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4831 this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
4832 sum_rdc.rate += this_rdc.rate;
4833 sum_rdc.dist += this_rdc.dist;
4835 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4839 if (sum_rdc.rdcost < best_rdc.rdcost) {
4841 pc_tree->partitioning = PARTITION_HORZ;
4843 pred_pixel_ready_reset(pc_tree, bsize);
4848 if (partition_vert_allowed && do_rect) {
4849 subsize = get_subsize(bsize, PARTITION_VERT);
4850 load_pred_mv(x, ctx);
4851 pc_tree->vertical[0].pred_pixel_ready = 1;
4852 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4853 &pc_tree->vertical[0]);
4854 pc_tree->vertical[0].mic = *xd->mi[0];
4855 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4856 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4857 pc_tree->vertical[0].skip = x->skip;
4859 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
4860 load_pred_mv(x, ctx);
4861 pc_tree->vertical[1].pred_pixel_ready = 1;
4862 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc,
4863 subsize, &pc_tree->vertical[1]);
4864 pc_tree->vertical[1].mic = *xd->mi[0];
4865 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4866 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4867 pc_tree->vertical[1].skip = x->skip;
4869 if (this_rdc.rate == INT_MAX) {
4870 vp9_rd_cost_reset(&sum_rdc);
4872 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4873 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
4874 sum_rdc.rate += this_rdc.rate;
4875 sum_rdc.dist += this_rdc.dist;
4877 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4881 if (sum_rdc.rdcost < best_rdc.rdcost) {
4883 pc_tree->partitioning = PARTITION_VERT;
4885 pred_pixel_ready_reset(pc_tree, bsize);
4889 *rd_cost = best_rdc;
4891 if (best_rdc.rate == INT_MAX) {
4892 vp9_rd_cost_reset(rd_cost);
4896 // update mode info array
4897 fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
4899 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
4900 int output_enabled = (bsize == BLOCK_64X64);
4901 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4905 if (bsize == BLOCK_64X64 && do_recon) {
4906 assert(tp_orig < *tp);
4907 assert(best_rdc.rate < INT_MAX);
4908 assert(best_rdc.dist < INT64_MAX);
4910 assert(tp_orig == *tp);
4914 static void nonrd_select_partition(VP9_COMP *cpi, ThreadData *td,
4915 TileDataEnc *tile_data, MODE_INFO **mi,
4916 TOKENEXTRA **tp, int mi_row, int mi_col,
4917 BLOCK_SIZE bsize, int output_enabled,
4918 RD_COST *rd_cost, PC_TREE *pc_tree) {
4919 VP9_COMMON *const cm = &cpi->common;
4920 TileInfo *const tile_info = &tile_data->tile_info;
4921 MACROBLOCK *const x = &td->mb;
4922 MACROBLOCKD *const xd = &x->e_mbd;
4923 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4924 const int mis = cm->mi_stride;
4925 PARTITION_TYPE partition;
4928 BLOCK_SIZE subsize_ref =
4929 (cpi->sf.adapt_partition_source_sad) ? BLOCK_8X8 : BLOCK_16X16;
4931 vp9_rd_cost_reset(&this_rdc);
4932 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4934 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
4935 partition = partition_lookup[bsl][subsize];
4937 if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
4938 x->max_partition_size = BLOCK_32X32;
4939 x->min_partition_size = BLOCK_16X16;
4940 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4941 0, INT64_MAX, pc_tree);
4942 } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
4943 subsize >= subsize_ref) {
4944 x->max_partition_size = BLOCK_32X32;
4945 x->min_partition_size = BLOCK_8X8;
4946 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4947 0, INT64_MAX, pc_tree);
4948 } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
4949 x->max_partition_size = BLOCK_16X16;
4950 x->min_partition_size = BLOCK_8X8;
4951 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4952 0, INT64_MAX, pc_tree);
4954 switch (partition) {
4955 case PARTITION_NONE:
4956 pc_tree->none.pred_pixel_ready = 1;
4957 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4959 pc_tree->none.mic = *xd->mi[0];
4960 pc_tree->none.mbmi_ext = *x->mbmi_ext;
4961 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
4962 pc_tree->none.skip = x->skip;
4964 case PARTITION_VERT:
4965 pc_tree->vertical[0].pred_pixel_ready = 1;
4966 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4967 &pc_tree->vertical[0]);
4968 pc_tree->vertical[0].mic = *xd->mi[0];
4969 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4970 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4971 pc_tree->vertical[0].skip = x->skip;
4972 if (mi_col + hbs < cm->mi_cols) {
4973 pc_tree->vertical[1].pred_pixel_ready = 1;
4974 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
4975 &this_rdc, subsize, &pc_tree->vertical[1]);
4976 pc_tree->vertical[1].mic = *xd->mi[0];
4977 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4978 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4979 pc_tree->vertical[1].skip = x->skip;
4980 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4981 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4982 rd_cost->rate += this_rdc.rate;
4983 rd_cost->dist += this_rdc.dist;
4987 case PARTITION_HORZ:
4988 pc_tree->horizontal[0].pred_pixel_ready = 1;
4989 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4990 &pc_tree->horizontal[0]);
4991 pc_tree->horizontal[0].mic = *xd->mi[0];
4992 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4993 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4994 pc_tree->horizontal[0].skip = x->skip;
4995 if (mi_row + hbs < cm->mi_rows) {
4996 pc_tree->horizontal[1].pred_pixel_ready = 1;
4997 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
4998 &this_rdc, subsize, &pc_tree->horizontal[1]);
4999 pc_tree->horizontal[1].mic = *xd->mi[0];
5000 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5001 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5002 pc_tree->horizontal[1].skip = x->skip;
5003 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5004 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5005 rd_cost->rate += this_rdc.rate;
5006 rd_cost->dist += this_rdc.dist;
5011 assert(partition == PARTITION_SPLIT);
5012 subsize = get_subsize(bsize, PARTITION_SPLIT);
5013 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5014 subsize, output_enabled, rd_cost,
5016 nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5017 mi_col + hbs, subsize, output_enabled, &this_rdc,
5019 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5020 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5021 rd_cost->rate += this_rdc.rate;
5022 rd_cost->dist += this_rdc.dist;
5024 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5025 mi_row + hbs, mi_col, subsize, output_enabled,
5026 &this_rdc, pc_tree->split[2]);
5027 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5028 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5029 rd_cost->rate += this_rdc.rate;
5030 rd_cost->dist += this_rdc.dist;
5032 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5033 mi_row + hbs, mi_col + hbs, subsize,
5034 output_enabled, &this_rdc, pc_tree->split[3]);
5035 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5036 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5037 rd_cost->rate += this_rdc.rate;
5038 rd_cost->dist += this_rdc.dist;
5044 if (bsize == BLOCK_64X64 && output_enabled)
5045 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
5048 static void nonrd_use_partition(VP9_COMP *cpi, ThreadData *td,
5049 TileDataEnc *tile_data, MODE_INFO **mi,
5050 TOKENEXTRA **tp, int mi_row, int mi_col,
5051 BLOCK_SIZE bsize, int output_enabled,
5052 RD_COST *dummy_cost, PC_TREE *pc_tree) {
5053 VP9_COMMON *const cm = &cpi->common;
5054 TileInfo *tile_info = &tile_data->tile_info;
5055 MACROBLOCK *const x = &td->mb;
5056 MACROBLOCKD *const xd = &x->e_mbd;
5057 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5058 const int mis = cm->mi_stride;
5059 PARTITION_TYPE partition;
5062 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5064 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5065 partition = partition_lookup[bsl][subsize];
5067 if (output_enabled && bsize != BLOCK_4X4) {
5068 int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
5069 td->counts->partition[ctx][partition]++;
5072 switch (partition) {
5073 case PARTITION_NONE:
5074 pc_tree->none.pred_pixel_ready = 1;
5075 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5076 subsize, &pc_tree->none);
5077 pc_tree->none.mic = *xd->mi[0];
5078 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5079 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5080 pc_tree->none.skip = x->skip;
5081 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5082 subsize, &pc_tree->none);
5084 case PARTITION_VERT:
5085 pc_tree->vertical[0].pred_pixel_ready = 1;
5086 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5087 subsize, &pc_tree->vertical[0]);
5088 pc_tree->vertical[0].mic = *xd->mi[0];
5089 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5090 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5091 pc_tree->vertical[0].skip = x->skip;
5092 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5093 subsize, &pc_tree->vertical[0]);
5094 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
5095 pc_tree->vertical[1].pred_pixel_ready = 1;
5096 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost,
5097 subsize, &pc_tree->vertical[1]);
5098 pc_tree->vertical[1].mic = *xd->mi[0];
5099 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5100 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5101 pc_tree->vertical[1].skip = x->skip;
5102 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
5103 output_enabled, subsize, &pc_tree->vertical[1]);
5106 case PARTITION_HORZ:
5107 pc_tree->horizontal[0].pred_pixel_ready = 1;
5108 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5109 subsize, &pc_tree->horizontal[0]);
5110 pc_tree->horizontal[0].mic = *xd->mi[0];
5111 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5112 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5113 pc_tree->horizontal[0].skip = x->skip;
5114 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5115 subsize, &pc_tree->horizontal[0]);
5117 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
5118 pc_tree->horizontal[1].pred_pixel_ready = 1;
5119 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost,
5120 subsize, &pc_tree->horizontal[1]);
5121 pc_tree->horizontal[1].mic = *xd->mi[0];
5122 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5123 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5124 pc_tree->horizontal[1].skip = x->skip;
5125 encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
5126 output_enabled, subsize, &pc_tree->horizontal[1]);
5130 assert(partition == PARTITION_SPLIT);
5131 subsize = get_subsize(bsize, PARTITION_SPLIT);
5132 if (bsize == BLOCK_8X8) {
5133 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5134 subsize, pc_tree->leaf_split[0]);
5135 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5136 subsize, pc_tree->leaf_split[0]);
5138 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, subsize,
5139 output_enabled, dummy_cost, pc_tree->split[0]);
5140 nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5141 mi_col + hbs, subsize, output_enabled, dummy_cost,
5143 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5144 mi_row + hbs, mi_col, subsize, output_enabled,
5145 dummy_cost, pc_tree->split[2]);
5146 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5147 mi_row + hbs, mi_col + hbs, subsize, output_enabled,
5148 dummy_cost, pc_tree->split[3]);
5153 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
5154 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
5157 // Get a prediction(stored in x->est_pred) for the whole 64x64 superblock.
5158 static void get_estimated_pred(VP9_COMP *cpi, const TileInfo *const tile,
5159 MACROBLOCK *x, int mi_row, int mi_col) {
5160 VP9_COMMON *const cm = &cpi->common;
5161 const int is_key_frame = frame_is_intra_only(cm);
5162 MACROBLOCKD *xd = &x->e_mbd;
5164 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
5166 if (!is_key_frame) {
5167 MODE_INFO *mi = xd->mi[0];
5168 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
5169 const YV12_BUFFER_CONFIG *yv12_g = NULL;
5170 const BLOCK_SIZE bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
5171 (mi_row + 4 < cm->mi_rows);
5172 unsigned int y_sad_g, y_sad_thr;
5173 unsigned int y_sad = UINT_MAX;
5175 assert(yv12 != NULL);
5177 if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id) ||
5178 cpi->svc.use_gf_temporal_ref_current_layer) {
5179 // For now, GOLDEN will not be used for non-zero spatial layers, since
5180 // it may not be a temporal reference.
5181 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
5184 // Only compute y_sad_g (sad for golden reference) for speed < 8.
5185 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
5186 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
5187 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5188 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5189 y_sad_g = cpi->fn_ptr[bsize].sdf(
5190 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
5191 xd->plane[0].pre[0].stride);
5196 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
5197 cpi->rc.is_src_frame_alt_ref) {
5198 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
5199 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5200 &cm->frame_refs[ALTREF_FRAME - 1].sf);
5201 mi->ref_frame[0] = ALTREF_FRAME;
5204 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5205 &cm->frame_refs[LAST_FRAME - 1].sf);
5206 mi->ref_frame[0] = LAST_FRAME;
5208 mi->ref_frame[1] = NONE;
5209 mi->sb_type = BLOCK_64X64;
5210 mi->mv[0].as_int = 0;
5211 mi->interp_filter = BILINEAR;
5214 const MV dummy_mv = { 0, 0 };
5215 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
5217 x->sb_use_mv_part = 1;
5218 x->sb_mvcol_part = mi->mv[0].as_mv.col;
5219 x->sb_mvrow_part = mi->mv[0].as_mv.row;
5222 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
5223 // are close if short_circuit_low_temp_var is on.
5224 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
5225 if (y_sad_g < y_sad_thr) {
5226 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5227 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5228 mi->ref_frame[0] = GOLDEN_FRAME;
5229 mi->mv[0].as_int = 0;
5231 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
5234 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
5235 xd->plane[0].dst.buf = x->est_pred;
5236 xd->plane[0].dst.stride = 64;
5237 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
5239 #if CONFIG_VP9_HIGHBITDEPTH
5241 case 8: memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); break;
5243 memset(x->est_pred, 128 * 4, 64 * 64 * sizeof(x->est_pred[0]));
5246 memset(x->est_pred, 128 * 16, 64 * 64 * sizeof(x->est_pred[0]));
5250 memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0]));
5251 #endif // CONFIG_VP9_HIGHBITDEPTH
5255 static void encode_nonrd_sb_row(VP9_COMP *cpi, ThreadData *td,
5256 TileDataEnc *tile_data, int mi_row,
5258 SPEED_FEATURES *const sf = &cpi->sf;
5259 VP9_COMMON *const cm = &cpi->common;
5260 TileInfo *const tile_info = &tile_data->tile_info;
5261 MACROBLOCK *const x = &td->mb;
5262 MACROBLOCKD *const xd = &x->e_mbd;
5263 const int mi_col_start = tile_info->mi_col_start;
5264 const int mi_col_end = tile_info->mi_col_end;
5266 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
5267 const int num_sb_cols =
5268 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
5271 // Initialize the left context for the new SB row
5272 memset(&xd->left_context, 0, sizeof(xd->left_context));
5273 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
5275 // Code each SB in the row
5276 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
5277 mi_col += MI_BLOCK_SIZE, ++sb_col_in_tile) {
5278 const struct segmentation *const seg = &cm->seg;
5280 const int idx_str = cm->mi_stride * mi_row + mi_col;
5281 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
5282 PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
5283 BLOCK_SIZE bsize = BLOCK_64X64;
5287 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
5290 if (cpi->use_skin_detection) {
5291 vp9_compute_skin_sb(cpi, BLOCK_16X16, mi_row, mi_col);
5294 x->source_variance = UINT_MAX;
5295 for (i = 0; i < MAX_REF_FRAMES; ++i) {
5296 x->pred_mv[i].row = INT16_MAX;
5297 x->pred_mv[i].col = INT16_MAX;
5299 vp9_rd_cost_init(&dummy_rdc);
5300 x->color_sensitivity[0] = 0;
5301 x->color_sensitivity[1] = 0;
5303 x->skip_low_source_sad = 0;
5304 x->lowvar_highsumdiff = 0;
5305 x->content_state_sb = 0;
5306 x->zero_temp_sad_source = 0;
5307 x->sb_use_mv_part = 0;
5308 x->sb_mvcol_part = 0;
5309 x->sb_mvrow_part = 0;
5310 x->sb_pickmode_part = 0;
5311 x->arf_frame_usage = 0;
5312 x->lastgolden_frame_usage = 0;
5315 const uint8_t *const map =
5316 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
5317 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
5318 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
5320 partition_search_type = FIXED_PARTITION;
5324 if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
5325 int shift = cpi->Source->y_stride * (mi_row << 3) + (mi_col << 3);
5326 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5327 int64_t source_sad = avg_source_sad(cpi, x, shift, sb_offset2);
5328 if (sf->adapt_partition_source_sad &&
5329 (cpi->oxcf.rc_mode == VPX_VBR && !cpi->rc.is_src_frame_alt_ref &&
5330 source_sad > sf->adapt_partition_thresh &&
5331 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)))
5332 partition_search_type = REFERENCE_PARTITION;
5335 // Set the partition type of the 64X64 block
5336 switch (partition_search_type) {
5337 case VAR_BASED_PARTITION:
5338 // TODO(jingning, marpan): The mode decision and encoding process
5339 // support both intra and inter sub8x8 block coding for RTC mode.
5340 // Tune the thresholds accordingly to use sub8x8 block coding for
5341 // coding performance improvement.
5342 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5343 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5344 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5346 case ML_BASED_PARTITION:
5347 get_estimated_pred(cpi, tile_info, x, mi_row, mi_col);
5348 x->max_partition_size = BLOCK_64X64;
5349 x->min_partition_size = BLOCK_8X8;
5350 x->sb_pickmode_part = 1;
5351 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5352 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5355 case SOURCE_VAR_BASED_PARTITION:
5356 set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
5357 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5358 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5360 case FIXED_PARTITION:
5361 if (!seg_skip) bsize = sf->always_this_block_size;
5362 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
5363 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5364 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5367 assert(partition_search_type == REFERENCE_PARTITION);
5368 x->sb_pickmode_part = 1;
5369 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
5370 // Use nonrd_pick_partition on scene-cut for VBR mode.
5371 // nonrd_pick_partition does not support 4x4 partition, so avoid it
5372 // on key frame for now.
5373 if ((cpi->oxcf.rc_mode == VPX_VBR && cpi->rc.high_source_sad &&
5374 cpi->oxcf.speed < 6 && !frame_is_intra_only(cm) &&
5375 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
5376 // Use lower max_partition_size for low resoultions.
5377 if (cm->width <= 352 && cm->height <= 288)
5378 x->max_partition_size = BLOCK_32X32;
5380 x->max_partition_size = BLOCK_64X64;
5381 x->min_partition_size = BLOCK_8X8;
5382 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5383 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5386 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5387 // TODO(marpan): Seems like nonrd_select_partition does not support
5388 // 4x4 partition. Since 4x4 is used on key frame, use this switch
5390 if (frame_is_intra_only(cm))
5391 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5392 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5394 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5395 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5401 // Update ref_frame usage for inter frame if this group is ARF group.
5402 if (!cpi->rc.is_src_frame_alt_ref && !cpi->refresh_golden_frame &&
5403 !cpi->refresh_alt_ref_frame && cpi->rc.alt_ref_gf_group &&
5404 cpi->sf.use_altref_onepass) {
5405 int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5406 if (cpi->count_arf_frame_usage != NULL)
5407 cpi->count_arf_frame_usage[sboffset] = x->arf_frame_usage;
5408 if (cpi->count_lastgolden_frame_usage != NULL)
5409 cpi->count_lastgolden_frame_usage[sboffset] = x->lastgolden_frame_usage;
5412 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
5413 sb_col_in_tile, num_sb_cols);
5416 // end RTC play code
5418 static INLINE uint32_t variance(const diff *const d) {
5419 return d->sse - (uint32_t)(((int64_t)d->sum * d->sum) >> 8);
5422 #if CONFIG_VP9_HIGHBITDEPTH
5423 static INLINE uint32_t variance_highbd(diff *const d) {
5424 const int64_t var = (int64_t)d->sse - (((int64_t)d->sum * d->sum) >> 8);
5425 return (var >= 0) ? (uint32_t)var : 0;
5427 #endif // CONFIG_VP9_HIGHBITDEPTH
5429 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
5430 const SPEED_FEATURES *const sf = &cpi->sf;
5431 const VP9_COMMON *const cm = &cpi->common;
5433 const uint8_t *src = cpi->Source->y_buffer;
5434 const uint8_t *last_src = cpi->Last_Source->y_buffer;
5435 const int src_stride = cpi->Source->y_stride;
5436 const int last_stride = cpi->Last_Source->y_stride;
5438 // Pick cutoff threshold
5439 const int cutoff = (VPXMIN(cm->width, cm->height) >= 720)
5440 ? (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100)
5441 : (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
5442 DECLARE_ALIGNED(16, int, hist[VAR_HIST_BINS]);
5443 diff *var16 = cpi->source_diff_var;
5448 memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
5450 for (i = 0; i < cm->mb_rows; i++) {
5451 for (j = 0; j < cm->mb_cols; j++) {
5452 #if CONFIG_VP9_HIGHBITDEPTH
5453 if (cm->use_highbitdepth) {
5454 switch (cm->bit_depth) {
5456 vpx_highbd_8_get16x16var(src, src_stride, last_src, last_stride,
5457 &var16->sse, &var16->sum);
5458 var16->var = variance(var16);
5461 vpx_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
5462 &var16->sse, &var16->sum);
5463 var16->var = variance_highbd(var16);
5466 assert(cm->bit_depth == VPX_BITS_12);
5467 vpx_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
5468 &var16->sse, &var16->sum);
5469 var16->var = variance_highbd(var16);
5473 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5475 var16->var = variance(var16);
5478 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5480 var16->var = variance(var16);
5481 #endif // CONFIG_VP9_HIGHBITDEPTH
5483 if (var16->var >= VAR_HIST_MAX_BG_VAR)
5484 hist[VAR_HIST_BINS - 1]++;
5486 hist[var16->var / VAR_HIST_FACTOR]++;
5493 src = src - cm->mb_cols * 16 + 16 * src_stride;
5494 last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
5497 cpi->source_var_thresh = 0;
5499 if (hist[VAR_HIST_BINS - 1] < cutoff) {
5500 for (i = 0; i < VAR_HIST_BINS - 1; i++) {
5504 cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
5510 return sf->search_type_check_frequency;
5513 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
5514 VP9_COMMON *const cm = &cpi->common;
5515 SPEED_FEATURES *const sf = &cpi->sf;
5517 if (cm->frame_type == KEY_FRAME) {
5518 // For key frame, use SEARCH_PARTITION.
5519 sf->partition_search_type = SEARCH_PARTITION;
5520 } else if (cm->intra_only) {
5521 sf->partition_search_type = FIXED_PARTITION;
5523 if (cm->last_width != cm->width || cm->last_height != cm->height) {
5524 if (cpi->source_diff_var) vpx_free(cpi->source_diff_var);
5526 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
5527 vpx_calloc(cm->MBs, sizeof(diff)));
5530 if (!cpi->frames_till_next_var_check)
5531 cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
5533 if (cpi->frames_till_next_var_check > 0) {
5534 sf->partition_search_type = FIXED_PARTITION;
5535 cpi->frames_till_next_var_check--;
5540 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
5541 unsigned int intra_count = 0, inter_count = 0;
5544 for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
5545 intra_count += td->counts->intra_inter[j][0];
5546 inter_count += td->counts->intra_inter[j][1];
5549 return (intra_count << 2) < inter_count && cm->frame_type != KEY_FRAME &&
5553 void vp9_init_tile_data(VP9_COMP *cpi) {
5554 VP9_COMMON *const cm = &cpi->common;
5555 const int tile_cols = 1 << cm->log2_tile_cols;
5556 const int tile_rows = 1 << cm->log2_tile_rows;
5557 int tile_col, tile_row;
5558 TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
5559 TOKENLIST *tplist = cpi->tplist[0][0];
5561 int tplist_count = 0;
5563 if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
5564 if (cpi->tile_data != NULL) vpx_free(cpi->tile_data);
5567 vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
5568 cpi->allocated_tiles = tile_cols * tile_rows;
5570 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5571 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5572 TileDataEnc *tile_data =
5573 &cpi->tile_data[tile_row * tile_cols + tile_col];
5575 for (i = 0; i < BLOCK_SIZES; ++i) {
5576 for (j = 0; j < MAX_MODES; ++j) {
5577 tile_data->thresh_freq_fact[i][j] = RD_THRESH_INIT_FACT;
5578 #if CONFIG_CONSISTENT_RECODE
5579 tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5581 tile_data->mode_map[i][j] = j;
5584 #if CONFIG_MULTITHREAD
5585 tile_data->row_base_thresh_freq_fact = NULL;
5590 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
5591 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5592 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5593 TileInfo *tile_info = &this_tile->tile_info;
5594 if (cpi->sf.adaptive_rd_thresh_row_mt &&
5595 this_tile->row_base_thresh_freq_fact == NULL)
5596 vp9_row_mt_alloc_rd_thresh(cpi, this_tile);
5597 vp9_tile_init(tile_info, cm, tile_row, tile_col);
5599 cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
5600 pre_tok = cpi->tile_tok[tile_row][tile_col];
5601 tile_tok = allocated_tokens(*tile_info);
5603 cpi->tplist[tile_row][tile_col] = tplist + tplist_count;
5604 tplist = cpi->tplist[tile_row][tile_col];
5605 tplist_count = get_num_vert_units(*tile_info, MI_BLOCK_SIZE_LOG2);
5610 void vp9_encode_sb_row(VP9_COMP *cpi, ThreadData *td, int tile_row,
5611 int tile_col, int mi_row) {
5612 VP9_COMMON *const cm = &cpi->common;
5613 const int tile_cols = 1 << cm->log2_tile_cols;
5614 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5615 const TileInfo *const tile_info = &this_tile->tile_info;
5616 TOKENEXTRA *tok = NULL;
5618 int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
5620 tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile_info->mi_row_start) >>
5622 get_start_tok(cpi, tile_row, tile_col, mi_row, &tok);
5623 cpi->tplist[tile_row][tile_col][tile_sb_row].start = tok;
5625 if (cpi->sf.use_nonrd_pick_mode)
5626 encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5628 encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
5630 cpi->tplist[tile_row][tile_col][tile_sb_row].stop = tok;
5631 cpi->tplist[tile_row][tile_col][tile_sb_row].count =
5632 (unsigned int)(cpi->tplist[tile_row][tile_col][tile_sb_row].stop -
5633 cpi->tplist[tile_row][tile_col][tile_sb_row].start);
5634 assert(tok - cpi->tplist[tile_row][tile_col][tile_sb_row].start <=
5635 get_token_alloc(MI_BLOCK_SIZE >> 1, tile_mb_cols));
5640 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td, int tile_row,
5642 VP9_COMMON *const cm = &cpi->common;
5643 const int tile_cols = 1 << cm->log2_tile_cols;
5644 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5645 const TileInfo *const tile_info = &this_tile->tile_info;
5646 const int mi_row_start = tile_info->mi_row_start;
5647 const int mi_row_end = tile_info->mi_row_end;
5650 for (mi_row = mi_row_start; mi_row < mi_row_end; mi_row += MI_BLOCK_SIZE)
5651 vp9_encode_sb_row(cpi, td, tile_row, tile_col, mi_row);
5654 static void encode_tiles(VP9_COMP *cpi) {
5655 VP9_COMMON *const cm = &cpi->common;
5656 const int tile_cols = 1 << cm->log2_tile_cols;
5657 const int tile_rows = 1 << cm->log2_tile_rows;
5658 int tile_col, tile_row;
5660 vp9_init_tile_data(cpi);
5662 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5663 for (tile_col = 0; tile_col < tile_cols; ++tile_col)
5664 vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
5667 #if CONFIG_FP_MB_STATS
5668 static int input_fpmb_stats(FIRSTPASS_MB_STATS *firstpass_mb_stats,
5669 VP9_COMMON *cm, uint8_t **this_frame_mb_stats) {
5670 uint8_t *mb_stats_in = firstpass_mb_stats->mb_stats_start +
5671 cm->current_video_frame * cm->MBs * sizeof(uint8_t);
5673 if (mb_stats_in > firstpass_mb_stats->mb_stats_end) return EOF;
5675 *this_frame_mb_stats = mb_stats_in;
5681 static int compare_kmeans_data(const void *a, const void *b) {
5682 if (((const KMEANS_DATA *)a)->value > ((const KMEANS_DATA *)b)->value) {
5684 } else if (((const KMEANS_DATA *)a)->value <
5685 ((const KMEANS_DATA *)b)->value) {
5692 static void compute_boundary_ls(const double *ctr_ls, int k,
5693 double *boundary_ls) {
5694 // boundary_ls[j] is the upper bound of data centered at ctr_ls[j]
5696 for (j = 0; j < k - 1; ++j) {
5697 boundary_ls[j] = (ctr_ls[j] + ctr_ls[j + 1]) / 2.;
5699 boundary_ls[k - 1] = DBL_MAX;
5702 int vp9_get_group_idx(double value, double *boundary_ls, int k) {
5704 while (value >= boundary_ls[group_idx]) {
5706 if (group_idx == k - 1) {
5713 void vp9_kmeans(double *ctr_ls, double *boundary_ls, int k, KMEANS_DATA *arr,
5723 vpx_clear_system_state();
5725 assert(k >= 2 && k <= MAX_KMEANS_GROUPS);
5727 qsort(arr, size, sizeof(*arr), compare_kmeans_data);
5730 max = arr[size - 1].value;
5732 // initialize the center points
5733 step = (max - min) * 1. / k;
5734 for (j = 0; j < k; ++j) {
5735 ctr_ls[j] = min + j * step + step / 2;
5738 for (itr = 0; itr < 10; ++itr) {
5739 compute_boundary_ls(ctr_ls, k, boundary_ls);
5743 for (i = 0; i < size; ++i) {
5744 while (arr[i].value >= boundary_ls[group_idx]) {
5746 if (group_idx == k - 1) {
5751 sum += arr[i].value;
5754 if (i + 1 == size || arr[i + 1].value >= boundary_ls[group_idx]) {
5756 ctr_ls[group_idx] = sum / count;
5764 // compute group_idx
5765 compute_boundary_ls(ctr_ls, k, boundary_ls);
5767 for (i = 0; i < size; ++i) {
5768 while (arr[i].value >= boundary_ls[group_idx]) {
5770 if (group_idx == k - 1) {
5774 arr[i].group_idx = group_idx;
5778 static void encode_frame_internal(VP9_COMP *cpi) {
5779 SPEED_FEATURES *const sf = &cpi->sf;
5780 ThreadData *const td = &cpi->td;
5781 MACROBLOCK *const x = &td->mb;
5782 VP9_COMMON *const cm = &cpi->common;
5783 MACROBLOCKD *const xd = &x->e_mbd;
5784 const int gf_group_index = cpi->twopass.gf_group.index;
5786 xd->mi = cm->mi_grid_visible;
5788 vp9_zero(*td->counts);
5789 vp9_zero(cpi->td.rd_counts);
5791 xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
5792 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
5794 #if CONFIG_VP9_HIGHBITDEPTH
5795 if (cm->use_highbitdepth)
5796 x->fwd_txfm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
5798 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5799 x->highbd_inv_txfm_add =
5800 xd->lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
5802 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5803 #endif // CONFIG_VP9_HIGHBITDEPTH
5804 x->inv_txfm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
5805 #if CONFIG_CONSISTENT_RECODE
5806 x->optimize = sf->optimize_coefficients == 1 && cpi->oxcf.pass != 1;
5808 if (xd->lossless) x->optimize = 0;
5809 x->sharpness = cpi->oxcf.sharpness;
5810 x->adjust_rdmult_by_segment = (cpi->oxcf.aq_mode == VARIANCE_AQ);
5812 cm->tx_mode = select_tx_mode(cpi, xd);
5814 vp9_frame_init_quantizer(cpi);
5816 vp9_initialize_rd_consts(cpi);
5817 vp9_initialize_me_consts(cpi, x, cm->base_qindex);
5818 init_encode_frame_mb_context(cpi);
5819 cm->use_prev_frame_mvs =
5820 !cm->error_resilient_mode && cm->width == cm->last_width &&
5821 cm->height == cm->last_height && !cm->intra_only && cm->last_show_frame;
5822 // Special case: set prev_mi to NULL when the previous mode info
5823 // context cannot be used.
5825 cm->use_prev_frame_mvs ? cm->prev_mip + cm->mi_stride + 1 : NULL;
5827 x->quant_fp = cpi->sf.use_quant_fp;
5828 vp9_zero(x->skip_txfm);
5829 if (sf->use_nonrd_pick_mode) {
5830 // Initialize internal buffer pointers for rtc coding, where non-RD
5831 // mode decision is used and hence no buffer pointer swap needed.
5833 struct macroblock_plane *const p = x->plane;
5834 struct macroblockd_plane *const pd = xd->plane;
5835 PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
5837 for (i = 0; i < MAX_MB_PLANE; ++i) {
5838 p[i].coeff = ctx->coeff_pbuf[i][0];
5839 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
5840 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
5841 p[i].eobs = ctx->eobs_pbuf[i][0];
5843 vp9_zero(x->zcoeff_blk);
5845 if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0 &&
5846 !(cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) &&
5848 cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
5850 if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
5851 source_var_based_partition_search_method(cpi);
5852 } else if (gf_group_index && gf_group_index < MAX_ARF_GOP_SIZE &&
5853 cpi->sf.enable_tpl_model) {
5854 TplDepFrame *tpl_frame = &cpi->tpl_stats[cpi->twopass.gf_group.index];
5855 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
5857 int tpl_stride = tpl_frame->stride;
5858 int64_t intra_cost_base = 0;
5859 int64_t mc_dep_cost_base = 0;
5862 for (row = 0; row < cm->mi_rows && tpl_frame->is_valid; ++row) {
5863 for (col = 0; col < cm->mi_cols; ++col) {
5864 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
5865 intra_cost_base += this_stats->intra_cost;
5866 mc_dep_cost_base += this_stats->mc_dep_cost;
5870 vpx_clear_system_state();
5872 if (tpl_frame->is_valid)
5873 cpi->rd.r0 = (double)intra_cost_base / mc_dep_cost_base;
5876 // Frame segmentation
5877 if (cpi->sf.enable_wiener_variance && cm->show_frame) {
5879 cpi->kmeans_data_size = 0;
5880 cpi->kmeans_ctr_num = 5;
5882 for (mi_row = 0; mi_row < cm->mi_rows; mi_row += MI_BLOCK_SIZE)
5883 for (mi_col = 0; mi_col < cm->mi_cols; mi_col += MI_BLOCK_SIZE)
5884 wiener_var_rdmult(cpi, BLOCK_64X64, mi_row, mi_col, cpi->rd.RDMULT);
5886 vp9_kmeans(cpi->kmeans_ctr_ls, cpi->kmeans_boundary_ls, cpi->kmeans_ctr_num,
5887 cpi->kmeans_data_arr, cpi->kmeans_data_size);
5891 struct vpx_usec_timer emr_timer;
5892 vpx_usec_timer_start(&emr_timer);
5894 #if CONFIG_FP_MB_STATS
5895 if (cpi->use_fp_mb_stats) {
5896 input_fpmb_stats(&cpi->twopass.firstpass_mb_stats, cm,
5897 &cpi->twopass.this_frame_mb_stats);
5902 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
5903 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
5904 // If allowed, encoding tiles in parallel with one thread handling one
5905 // tile when row based multi-threading is disabled.
5906 if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
5907 vp9_encode_tiles_mt(cpi);
5911 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
5912 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
5913 vp9_encode_tiles_row_mt(cpi);
5916 vpx_usec_timer_mark(&emr_timer);
5917 cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
5920 sf->skip_encode_frame =
5921 sf->skip_encode_sb ? get_skip_encode_frame(cm, td) : 0;
5924 // Keep record of the total distortion this time around for future use
5925 cpi->last_frame_distortion = cpi->frame_distortion;
5929 static INTERP_FILTER get_interp_filter(
5930 const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
5931 if (!is_alt_ref && threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
5932 threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
5933 threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
5934 return EIGHTTAP_SMOOTH;
5935 } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
5936 threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
5937 return EIGHTTAP_SHARP;
5938 } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
5945 static int compute_frame_aq_offset(struct VP9_COMP *cpi) {
5946 VP9_COMMON *const cm = &cpi->common;
5947 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
5948 struct segmentation *const seg = &cm->seg;
5956 for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
5957 MODE_INFO **mi_8x8 = mi_8x8_ptr;
5958 for (mi_col = 0; mi_col < cm->mi_cols; mi_col++, mi_8x8++) {
5959 segment_id = mi_8x8[0]->segment_id;
5960 qdelta_index = get_segdata(seg, segment_id, SEG_LVL_ALT_Q);
5961 sum_delta += qdelta_index;
5964 mi_8x8_ptr += cm->mi_stride;
5967 return sum_delta / (cm->mi_rows * cm->mi_cols);
5970 #if CONFIG_CONSISTENT_RECODE
5971 static void restore_encode_params(VP9_COMP *cpi) {
5972 VP9_COMMON *const cm = &cpi->common;
5973 const int tile_cols = 1 << cm->log2_tile_cols;
5974 const int tile_rows = 1 << cm->log2_tile_rows;
5975 int tile_col, tile_row;
5977 RD_OPT *rd_opt = &cpi->rd;
5978 for (i = 0; i < MAX_REF_FRAMES; i++) {
5979 for (j = 0; j < REFERENCE_MODES; j++)
5980 rd_opt->prediction_type_threshes[i][j] =
5981 rd_opt->prediction_type_threshes_prev[i][j];
5983 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
5984 rd_opt->filter_threshes[i][j] = rd_opt->filter_threshes_prev[i][j];
5987 if (cpi->tile_data != NULL) {
5988 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5989 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5990 TileDataEnc *tile_data =
5991 &cpi->tile_data[tile_row * tile_cols + tile_col];
5992 for (i = 0; i < BLOCK_SIZES; ++i) {
5993 for (j = 0; j < MAX_MODES; ++j) {
5994 tile_data->thresh_freq_fact[i][j] =
5995 tile_data->thresh_freq_fact_prev[i][j];
6001 cm->interp_filter = cpi->sf.default_interp_filter;
6005 void vp9_encode_frame(VP9_COMP *cpi) {
6006 VP9_COMMON *const cm = &cpi->common;
6008 #if CONFIG_CONSISTENT_RECODE
6009 restore_encode_params(cpi);
6012 // In the longer term the encoder should be generalized to match the
6013 // decoder such that we allow compound where one of the 3 buffers has a
6014 // different sign bias and that buffer is then the fixed ref. However, this
6015 // requires further work in the rd loop. For now the only supported encoder
6016 // side behavior is where the ALT ref buffer has opposite sign bias to
6018 if (!frame_is_intra_only(cm)) {
6019 if (vp9_compound_reference_allowed(cm)) {
6020 cpi->allow_comp_inter_inter = 1;
6021 vp9_setup_compound_reference_mode(cm);
6023 cpi->allow_comp_inter_inter = 0;
6027 if (cpi->sf.frame_parameter_update) {
6029 RD_OPT *const rd_opt = &cpi->rd;
6030 FRAME_COUNTS *counts = cpi->td.counts;
6031 RD_COUNTS *const rdc = &cpi->td.rd_counts;
6033 // This code does a single RD pass over the whole frame assuming
6034 // either compound, single or hybrid prediction as per whatever has
6035 // worked best for that type of frame in the past.
6036 // It also predicts whether another coding mode would have worked
6037 // better than this coding mode. If that is the case, it remembers
6038 // that for subsequent frames.
6039 // It also does the same analysis for transform size selection.
6040 const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
6041 int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
6042 int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
6043 const int is_alt_ref = frame_type == ALTREF_FRAME;
6045 /* prediction (compound, single or hybrid) mode selection */
6046 if (is_alt_ref || !cpi->allow_comp_inter_inter)
6047 cm->reference_mode = SINGLE_REFERENCE;
6048 else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
6049 mode_thrs[COMPOUND_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT] &&
6050 check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
6051 cm->reference_mode = COMPOUND_REFERENCE;
6052 else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
6053 cm->reference_mode = SINGLE_REFERENCE;
6055 cm->reference_mode = REFERENCE_MODE_SELECT;
6057 if (cm->interp_filter == SWITCHABLE)
6058 cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
6060 encode_frame_internal(cpi);
6062 for (i = 0; i < REFERENCE_MODES; ++i)
6063 mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
6065 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
6066 filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
6068 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6069 int single_count_zero = 0;
6070 int comp_count_zero = 0;
6072 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6073 single_count_zero += counts->comp_inter[i][0];
6074 comp_count_zero += counts->comp_inter[i][1];
6077 if (comp_count_zero == 0) {
6078 cm->reference_mode = SINGLE_REFERENCE;
6079 vp9_zero(counts->comp_inter);
6080 } else if (single_count_zero == 0) {
6081 cm->reference_mode = COMPOUND_REFERENCE;
6082 vp9_zero(counts->comp_inter);
6086 if (cm->tx_mode == TX_MODE_SELECT) {
6088 int count8x8_lp = 0, count8x8_8x8p = 0;
6089 int count16x16_16x16p = 0, count16x16_lp = 0;
6092 for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
6093 count4x4 += counts->tx.p32x32[i][TX_4X4];
6094 count4x4 += counts->tx.p16x16[i][TX_4X4];
6095 count4x4 += counts->tx.p8x8[i][TX_4X4];
6097 count8x8_lp += counts->tx.p32x32[i][TX_8X8];
6098 count8x8_lp += counts->tx.p16x16[i][TX_8X8];
6099 count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
6101 count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
6102 count16x16_lp += counts->tx.p32x32[i][TX_16X16];
6103 count32x32 += counts->tx.p32x32[i][TX_32X32];
6105 if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
6107 cm->tx_mode = ALLOW_8X8;
6108 reset_skip_tx_size(cm, TX_8X8);
6109 } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
6110 count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
6111 cm->tx_mode = ONLY_4X4;
6112 reset_skip_tx_size(cm, TX_4X4);
6113 } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
6114 cm->tx_mode = ALLOW_32X32;
6115 } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
6116 cm->tx_mode = ALLOW_16X16;
6117 reset_skip_tx_size(cm, TX_16X16);
6121 FRAME_COUNTS *counts = cpi->td.counts;
6122 cm->reference_mode = SINGLE_REFERENCE;
6123 if (cpi->allow_comp_inter_inter && cpi->sf.use_compound_nonrd_pickmode &&
6124 cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
6125 cm->frame_type != KEY_FRAME)
6126 cm->reference_mode = REFERENCE_MODE_SELECT;
6128 encode_frame_internal(cpi);
6130 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6131 int single_count_zero = 0;
6132 int comp_count_zero = 0;
6134 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6135 single_count_zero += counts->comp_inter[i][0];
6136 comp_count_zero += counts->comp_inter[i][1];
6138 if (comp_count_zero == 0) {
6139 cm->reference_mode = SINGLE_REFERENCE;
6140 vp9_zero(counts->comp_inter);
6141 } else if (single_count_zero == 0) {
6142 cm->reference_mode = COMPOUND_REFERENCE;
6143 vp9_zero(counts->comp_inter);
6148 // If segmented AQ is enabled compute the average AQ weighting.
6149 if (cm->seg.enabled && (cpi->oxcf.aq_mode != NO_AQ) &&
6150 (cm->seg.update_map || cm->seg.update_data)) {
6151 cm->seg.aq_av_offset = compute_frame_aq_offset(cpi);
6155 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
6156 const PREDICTION_MODE y_mode = mi->mode;
6157 const PREDICTION_MODE uv_mode = mi->uv_mode;
6158 const BLOCK_SIZE bsize = mi->sb_type;
6160 if (bsize < BLOCK_8X8) {
6162 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
6163 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
6164 for (idy = 0; idy < 2; idy += num_4x4_h)
6165 for (idx = 0; idx < 2; idx += num_4x4_w)
6166 ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
6168 ++counts->y_mode[size_group_lookup[bsize]][y_mode];
6171 ++counts->uv_mode[y_mode][uv_mode];
6174 static void update_zeromv_cnt(VP9_COMP *const cpi, const MODE_INFO *const mi,
6175 int mi_row, int mi_col, BLOCK_SIZE bsize) {
6176 const VP9_COMMON *const cm = &cpi->common;
6177 MV mv = mi->mv[0].as_mv;
6178 const int bw = num_8x8_blocks_wide_lookup[bsize];
6179 const int bh = num_8x8_blocks_high_lookup[bsize];
6180 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
6181 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
6182 const int block_index = mi_row * cm->mi_cols + mi_col;
6184 for (y = 0; y < ymis; y++)
6185 for (x = 0; x < xmis; x++) {
6186 int map_offset = block_index + y * cm->mi_cols + x;
6187 if (mi->ref_frame[0] == LAST_FRAME && is_inter_block(mi) &&
6188 mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
6189 if (abs(mv.row) < 8 && abs(mv.col) < 8) {
6190 if (cpi->consec_zero_mv[map_offset] < 255)
6191 cpi->consec_zero_mv[map_offset]++;
6193 cpi->consec_zero_mv[map_offset] = 0;
6199 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
6200 int output_enabled, int mi_row, int mi_col,
6201 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
6202 VP9_COMMON *const cm = &cpi->common;
6203 MACROBLOCK *const x = &td->mb;
6204 MACROBLOCKD *const xd = &x->e_mbd;
6205 MODE_INFO *mi = xd->mi[0];
6206 const int seg_skip =
6207 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP);
6208 x->skip_recode = !x->select_tx_size && mi->sb_type >= BLOCK_8X8 &&
6209 cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
6210 cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
6211 cpi->sf.allow_skip_recode;
6213 if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
6214 memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
6216 x->skip_optimize = ctx->is_coded;
6218 x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
6219 x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
6220 x->q_index < QIDX_SKIP_THRESH);
6222 if (x->skip_encode) return;
6224 if (!is_inter_block(mi)) {
6226 #if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6227 if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
6228 (xd->above_mi == NULL || xd->left_mi == NULL) &&
6229 need_top_left[mi->uv_mode])
6231 #endif // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6233 for (plane = 0; plane < MAX_MB_PLANE; ++plane)
6234 vp9_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane, 1);
6235 if (output_enabled) sum_intra_stats(td->counts, mi);
6236 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6237 VPXMAX(bsize, BLOCK_8X8));
6240 const int is_compound = has_second_ref(mi);
6241 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
6242 for (ref = 0; ref < 1 + is_compound; ++ref) {
6243 YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, mi->ref_frame[ref]);
6244 assert(cfg != NULL);
6245 vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
6246 &xd->block_refs[ref]->sf);
6248 if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
6249 vp9_build_inter_predictors_sby(xd, mi_row, mi_col,
6250 VPXMAX(bsize, BLOCK_8X8));
6252 vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col,
6253 VPXMAX(bsize, BLOCK_8X8));
6255 vp9_encode_sb(x, VPXMAX(bsize, BLOCK_8X8));
6256 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6257 VPXMAX(bsize, BLOCK_8X8));
6264 if (output_enabled) {
6265 if (cm->tx_mode == TX_MODE_SELECT && mi->sb_type >= BLOCK_8X8 &&
6266 !(is_inter_block(mi) && mi->skip)) {
6267 ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
6268 &td->counts->tx)[mi->tx_size];
6270 // The new intra coding scheme requires no change of transform size
6271 if (is_inter_block(mi)) {
6272 mi->tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
6273 max_txsize_lookup[bsize]);
6275 mi->tx_size = (bsize >= BLOCK_8X8) ? mi->tx_size : TX_4X4;
6279 ++td->counts->tx.tx_totals[mi->tx_size];
6280 ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])];
6281 if (cm->seg.enabled && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
6282 vp9_cyclic_refresh_update_sb_postencode(cpi, mi, mi_row, mi_col, bsize);
6283 if (cpi->oxcf.pass == 0 && cpi->svc.temporal_layer_id == 0 &&
6286 !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
6287 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)))
6288 update_zeromv_cnt(cpi, mi, mi_row, mi_col, bsize);