1 /*
2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3 *
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.
9 */
10
11 #include <float.h>
12 #include <limits.h>
13 #include <math.h>
14 #include <stdio.h>
15
16 #include "./vp9_rtcd.h"
17 #include "./vpx_dsp_rtcd.h"
18 #include "./vpx_config.h"
19
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"
24
25 #if CONFIG_MISMATCH_DEBUG
26 #include "vpx_util/vpx_debug_util.h"
27 #endif // CONFIG_MISMATCH_DEBUG
28
29 #include "vp9/common/vp9_common.h"
30 #include "vp9/common/vp9_entropy.h"
31 #include "vp9/common/vp9_entropymode.h"
32 #include "vp9/common/vp9_idct.h"
33 #include "vp9/common/vp9_mvref_common.h"
34 #include "vp9/common/vp9_pred_common.h"
35 #include "vp9/common/vp9_quant_common.h"
36 #include "vp9/common/vp9_reconintra.h"
37 #include "vp9/common/vp9_reconinter.h"
38 #include "vp9/common/vp9_seg_common.h"
39 #include "vp9/common/vp9_tile_common.h"
40 #if !CONFIG_REALTIME_ONLY
41 #include "vp9/encoder/vp9_aq_360.h"
42 #include "vp9/encoder/vp9_aq_complexity.h"
43 #endif
44 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
45 #if !CONFIG_REALTIME_ONLY
46 #include "vp9/encoder/vp9_aq_variance.h"
47 #endif
48 #include "vp9/encoder/vp9_encodeframe.h"
49 #include "vp9/encoder/vp9_encodemb.h"
50 #include "vp9/encoder/vp9_encodemv.h"
51 #include "vp9/encoder/vp9_ethread.h"
52 #include "vp9/encoder/vp9_extend.h"
53 #include "vp9/encoder/vp9_multi_thread.h"
54 #include "vp9/encoder/vp9_partition_models.h"
55 #include "vp9/encoder/vp9_pickmode.h"
56 #include "vp9/encoder/vp9_rd.h"
57 #include "vp9/encoder/vp9_rdopt.h"
58 #include "vp9/encoder/vp9_segmentation.h"
59 #include "vp9/encoder/vp9_tokenize.h"
60
61 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
62 int output_enabled, int mi_row, int mi_col,
63 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx);
64
65 // This is used as a reference when computing the source variance for the
66 // purpose of activity masking.
67 // Eventually this should be replaced by custom no-reference routines,
68 // which will be faster.
69 static const uint8_t VP9_VAR_OFFS[64] = {
70 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
71 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
72 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
73 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
74 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
75 };
76
77 #if CONFIG_VP9_HIGHBITDEPTH
78 static const uint16_t VP9_HIGH_VAR_OFFS_8[64] = {
79 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
80 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
81 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
82 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
83 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
84 };
85
86 static const uint16_t VP9_HIGH_VAR_OFFS_10[64] = {
87 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
88 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
89 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
90 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
91 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
92 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
93 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
94 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4
95 };
96
97 static const uint16_t VP9_HIGH_VAR_OFFS_12[64] = {
98 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
99 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
100 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
101 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
102 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
103 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
104 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
105 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
106 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
107 128 * 16
108 };
109 #endif // CONFIG_VP9_HIGHBITDEPTH
110
vp9_get_sby_variance(VP9_COMP * cpi,const struct buf_2d * ref,BLOCK_SIZE bs)111 unsigned int vp9_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
112 BLOCK_SIZE bs) {
113 unsigned int sse;
114 const unsigned int var =
115 cpi->fn_ptr[bs].vf(ref->buf, ref->stride, VP9_VAR_OFFS, 0, &sse);
116 return var;
117 }
118
119 #if CONFIG_VP9_HIGHBITDEPTH
vp9_high_get_sby_variance(VP9_COMP * cpi,const struct buf_2d * ref,BLOCK_SIZE bs,int bd)120 unsigned int vp9_high_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
121 BLOCK_SIZE bs, int bd) {
122 unsigned int var, sse;
123 switch (bd) {
124 case 10:
125 var =
126 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
127 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10), 0, &sse);
128 break;
129 case 12:
130 var =
131 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
132 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12), 0, &sse);
133 break;
134 case 8:
135 default:
136 var =
137 cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
138 CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8), 0, &sse);
139 break;
140 }
141 return var;
142 }
143 #endif // CONFIG_VP9_HIGHBITDEPTH
144
vp9_get_sby_perpixel_variance(VP9_COMP * cpi,const struct buf_2d * ref,BLOCK_SIZE bs)145 unsigned int vp9_get_sby_perpixel_variance(VP9_COMP *cpi,
146 const struct buf_2d *ref,
147 BLOCK_SIZE bs) {
148 return ROUND_POWER_OF_TWO(vp9_get_sby_variance(cpi, ref, bs),
149 num_pels_log2_lookup[bs]);
150 }
151
152 #if CONFIG_VP9_HIGHBITDEPTH
vp9_high_get_sby_perpixel_variance(VP9_COMP * cpi,const struct buf_2d * ref,BLOCK_SIZE bs,int bd)153 unsigned int vp9_high_get_sby_perpixel_variance(VP9_COMP *cpi,
154 const struct buf_2d *ref,
155 BLOCK_SIZE bs, int bd) {
156 return (unsigned int)ROUND64_POWER_OF_TWO(
157 (int64_t)vp9_high_get_sby_variance(cpi, ref, bs, bd),
158 num_pels_log2_lookup[bs]);
159 }
160 #endif // CONFIG_VP9_HIGHBITDEPTH
161
set_segment_index(VP9_COMP * cpi,MACROBLOCK * const x,int mi_row,int mi_col,BLOCK_SIZE bsize,int segment_index)162 static void set_segment_index(VP9_COMP *cpi, MACROBLOCK *const x, int mi_row,
163 int mi_col, BLOCK_SIZE bsize, int segment_index) {
164 VP9_COMMON *const cm = &cpi->common;
165 const struct segmentation *const seg = &cm->seg;
166 MACROBLOCKD *const xd = &x->e_mbd;
167 MODE_INFO *mi = xd->mi[0];
168
169 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
170 const uint8_t *const map =
171 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
172
173 // Initialize the segmentation index as 0.
174 mi->segment_id = 0;
175
176 // Skip the rest if AQ mode is disabled.
177 if (!seg->enabled) return;
178
179 switch (aq_mode) {
180 case CYCLIC_REFRESH_AQ:
181 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
182 break;
183 #if !CONFIG_REALTIME_ONLY
184 case VARIANCE_AQ:
185 if (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
186 cpi->force_update_segmentation ||
187 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
188 int min_energy;
189 int max_energy;
190 // Get sub block energy range
191 if (bsize >= BLOCK_32X32) {
192 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
193 &max_energy);
194 } else {
195 min_energy = bsize <= BLOCK_16X16 ? x->mb_energy
196 : vp9_block_energy(cpi, x, bsize);
197 }
198 mi->segment_id = vp9_vaq_segment_id(min_energy);
199 } else {
200 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
201 }
202 break;
203 case EQUATOR360_AQ:
204 if (cm->frame_type == KEY_FRAME || cpi->force_update_segmentation)
205 mi->segment_id = vp9_360aq_segment_id(mi_row, cm->mi_rows);
206 else
207 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
208 break;
209 #endif
210 case LOOKAHEAD_AQ:
211 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
212 break;
213 case PSNR_AQ: mi->segment_id = segment_index; break;
214 case PERCEPTUAL_AQ: mi->segment_id = x->segment_id; break;
215 default:
216 // NO_AQ or PSNR_AQ
217 break;
218 }
219
220 // Set segment index if ROI map or active_map is enabled.
221 if (cpi->roi.enabled || cpi->active_map.enabled)
222 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
223
224 vp9_init_plane_quantizers(cpi, x);
225 }
226
227 // Lighter version of set_offsets that only sets the mode info
228 // pointers.
set_mode_info_offsets(VP9_COMMON * const cm,MACROBLOCK * const x,MACROBLOCKD * const xd,int mi_row,int mi_col)229 static INLINE void set_mode_info_offsets(VP9_COMMON *const cm,
230 MACROBLOCK *const x,
231 MACROBLOCKD *const xd, int mi_row,
232 int mi_col) {
233 const int idx_str = xd->mi_stride * mi_row + mi_col;
234 xd->mi = cm->mi_grid_visible + idx_str;
235 xd->mi[0] = cm->mi + idx_str;
236 x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
237 }
238
set_ssim_rdmult(VP9_COMP * const cpi,MACROBLOCK * const x,const BLOCK_SIZE bsize,const int mi_row,const int mi_col,int * const rdmult)239 static void set_ssim_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
240 const BLOCK_SIZE bsize, const int mi_row,
241 const int mi_col, int *const rdmult) {
242 const VP9_COMMON *const cm = &cpi->common;
243
244 const int bsize_base = BLOCK_16X16;
245 const int num_8x8_w = num_8x8_blocks_wide_lookup[bsize_base];
246 const int num_8x8_h = num_8x8_blocks_high_lookup[bsize_base];
247 const int num_cols = (cm->mi_cols + num_8x8_w - 1) / num_8x8_w;
248 const int num_rows = (cm->mi_rows + num_8x8_h - 1) / num_8x8_h;
249 const int num_bcols =
250 (num_8x8_blocks_wide_lookup[bsize] + num_8x8_w - 1) / num_8x8_w;
251 const int num_brows =
252 (num_8x8_blocks_high_lookup[bsize] + num_8x8_h - 1) / num_8x8_h;
253 int row, col;
254 double num_of_mi = 0.0;
255 double geom_mean_of_scale = 0.0;
256
257 assert(cpi->oxcf.tuning == VP8_TUNE_SSIM);
258
259 for (row = mi_row / num_8x8_w;
260 row < num_rows && row < mi_row / num_8x8_w + num_brows; ++row) {
261 for (col = mi_col / num_8x8_h;
262 col < num_cols && col < mi_col / num_8x8_h + num_bcols; ++col) {
263 const int index = row * num_cols + col;
264 geom_mean_of_scale += log(cpi->mi_ssim_rdmult_scaling_factors[index]);
265 num_of_mi += 1.0;
266 }
267 }
268 geom_mean_of_scale = exp(geom_mean_of_scale / num_of_mi);
269
270 *rdmult = (int)((double)(*rdmult) * geom_mean_of_scale);
271 *rdmult = VPXMAX(*rdmult, 0);
272 set_error_per_bit(x, *rdmult);
273 vpx_clear_system_state();
274 }
275
set_offsets(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCK * const x,int mi_row,int mi_col,BLOCK_SIZE bsize)276 static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
277 MACROBLOCK *const x, int mi_row, int mi_col,
278 BLOCK_SIZE bsize) {
279 VP9_COMMON *const cm = &cpi->common;
280 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
281 MACROBLOCKD *const xd = &x->e_mbd;
282 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
283 const int mi_height = num_8x8_blocks_high_lookup[bsize];
284 MvLimits *const mv_limits = &x->mv_limits;
285
286 set_skip_context(xd, mi_row, mi_col);
287
288 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
289
290 // Set up destination pointers.
291 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
292
293 // Set up limit values for MV components.
294 // Mv beyond the range do not produce new/different prediction block.
295 mv_limits->row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
296 mv_limits->col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
297 mv_limits->row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
298 mv_limits->col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
299
300 // Set up distance of MB to edge of frame in 1/8th pel units.
301 assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
302 set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width, cm->mi_rows,
303 cm->mi_cols);
304
305 // Set up source buffers.
306 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
307
308 // R/D setup.
309 x->rddiv = cpi->rd.RDDIV;
310 x->rdmult = cpi->rd.RDMULT;
311 if (oxcf->tuning == VP8_TUNE_SSIM) {
312 set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
313 }
314
315 // required by vp9_append_sub8x8_mvs_for_idx() and vp9_find_best_ref_mvs()
316 xd->tile = *tile;
317 }
318
duplicate_mode_info_in_sb(VP9_COMMON * cm,MACROBLOCKD * xd,int mi_row,int mi_col,BLOCK_SIZE bsize)319 static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
320 int mi_row, int mi_col,
321 BLOCK_SIZE bsize) {
322 const int block_width =
323 VPXMIN(num_8x8_blocks_wide_lookup[bsize], cm->mi_cols - mi_col);
324 const int block_height =
325 VPXMIN(num_8x8_blocks_high_lookup[bsize], cm->mi_rows - mi_row);
326 const int mi_stride = xd->mi_stride;
327 MODE_INFO *const src_mi = xd->mi[0];
328 int i, j;
329
330 for (j = 0; j < block_height; ++j)
331 for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
332 }
333
set_block_size(VP9_COMP * const cpi,MACROBLOCK * const x,MACROBLOCKD * const xd,int mi_row,int mi_col,BLOCK_SIZE bsize)334 static void set_block_size(VP9_COMP *const cpi, MACROBLOCK *const x,
335 MACROBLOCKD *const xd, int mi_row, int mi_col,
336 BLOCK_SIZE bsize) {
337 if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
338 set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
339 xd->mi[0]->sb_type = bsize;
340 }
341 }
342
343 typedef struct {
344 // This struct is used for computing variance in choose_partitioning(), where
345 // the max number of samples within a superblock is 16x16 (with 4x4 avg). Even
346 // in high bitdepth, uint32_t is enough for sum_square_error (2^12 * 2^12 * 16
347 // * 16 = 2^32).
348 uint32_t sum_square_error;
349 int32_t sum_error;
350 int log2_count;
351 int variance;
352 } var;
353
354 typedef struct {
355 var none;
356 var horz[2];
357 var vert[2];
358 } partition_variance;
359
360 typedef struct {
361 partition_variance part_variances;
362 var split[4];
363 } v4x4;
364
365 typedef struct {
366 partition_variance part_variances;
367 v4x4 split[4];
368 } v8x8;
369
370 typedef struct {
371 partition_variance part_variances;
372 v8x8 split[4];
373 } v16x16;
374
375 typedef struct {
376 partition_variance part_variances;
377 v16x16 split[4];
378 } v32x32;
379
380 typedef struct {
381 partition_variance part_variances;
382 v32x32 split[4];
383 } v64x64;
384
385 typedef struct {
386 partition_variance *part_variances;
387 var *split[4];
388 } variance_node;
389
390 typedef enum {
391 V16X16,
392 V32X32,
393 V64X64,
394 } TREE_LEVEL;
395
tree_to_node(void * data,BLOCK_SIZE bsize,variance_node * node)396 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
397 int i;
398 node->part_variances = NULL;
399 switch (bsize) {
400 case BLOCK_64X64: {
401 v64x64 *vt = (v64x64 *)data;
402 node->part_variances = &vt->part_variances;
403 for (i = 0; i < 4; i++)
404 node->split[i] = &vt->split[i].part_variances.none;
405 break;
406 }
407 case BLOCK_32X32: {
408 v32x32 *vt = (v32x32 *)data;
409 node->part_variances = &vt->part_variances;
410 for (i = 0; i < 4; i++)
411 node->split[i] = &vt->split[i].part_variances.none;
412 break;
413 }
414 case BLOCK_16X16: {
415 v16x16 *vt = (v16x16 *)data;
416 node->part_variances = &vt->part_variances;
417 for (i = 0; i < 4; i++)
418 node->split[i] = &vt->split[i].part_variances.none;
419 break;
420 }
421 case BLOCK_8X8: {
422 v8x8 *vt = (v8x8 *)data;
423 node->part_variances = &vt->part_variances;
424 for (i = 0; i < 4; i++)
425 node->split[i] = &vt->split[i].part_variances.none;
426 break;
427 }
428 default: {
429 v4x4 *vt = (v4x4 *)data;
430 assert(bsize == BLOCK_4X4);
431 node->part_variances = &vt->part_variances;
432 for (i = 0; i < 4; i++) node->split[i] = &vt->split[i];
433 break;
434 }
435 }
436 }
437
438 // Set variance values given sum square error, sum error, count.
fill_variance(uint32_t s2,int32_t s,int c,var * v)439 static void fill_variance(uint32_t s2, int32_t s, int c, var *v) {
440 v->sum_square_error = s2;
441 v->sum_error = s;
442 v->log2_count = c;
443 }
444
get_variance(var * v)445 static void get_variance(var *v) {
446 v->variance =
447 (int)(256 * (v->sum_square_error -
448 (uint32_t)(((int64_t)v->sum_error * v->sum_error) >>
449 v->log2_count)) >>
450 v->log2_count);
451 }
452
sum_2_variances(const var * a,const var * b,var * r)453 static void sum_2_variances(const var *a, const var *b, var *r) {
454 assert(a->log2_count == b->log2_count);
455 fill_variance(a->sum_square_error + b->sum_square_error,
456 a->sum_error + b->sum_error, a->log2_count + 1, r);
457 }
458
fill_variance_tree(void * data,BLOCK_SIZE bsize)459 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
460 variance_node node;
461 memset(&node, 0, sizeof(node));
462 tree_to_node(data, bsize, &node);
463 sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
464 sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
465 sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
466 sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
467 sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
468 &node.part_variances->none);
469 }
470
set_vt_partitioning(VP9_COMP * cpi,MACROBLOCK * const x,MACROBLOCKD * const xd,void * data,BLOCK_SIZE bsize,int mi_row,int mi_col,int64_t threshold,BLOCK_SIZE bsize_min,int force_split)471 static int set_vt_partitioning(VP9_COMP *cpi, MACROBLOCK *const x,
472 MACROBLOCKD *const xd, void *data,
473 BLOCK_SIZE bsize, int mi_row, int mi_col,
474 int64_t threshold, BLOCK_SIZE bsize_min,
475 int force_split) {
476 VP9_COMMON *const cm = &cpi->common;
477 variance_node vt;
478 const int block_width = num_8x8_blocks_wide_lookup[bsize];
479 const int block_height = num_8x8_blocks_high_lookup[bsize];
480
481 assert(block_height == block_width);
482 tree_to_node(data, bsize, &vt);
483
484 if (force_split == 1) return 0;
485
486 // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
487 // variance is below threshold, otherwise split will be selected.
488 // No check for vert/horiz split as too few samples for variance.
489 if (bsize == bsize_min) {
490 // Variance already computed to set the force_split.
491 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
492 if (mi_col + block_width / 2 < cm->mi_cols &&
493 mi_row + block_height / 2 < cm->mi_rows &&
494 vt.part_variances->none.variance < threshold) {
495 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
496 return 1;
497 }
498 return 0;
499 } else if (bsize > bsize_min) {
500 // Variance already computed to set the force_split.
501 if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
502 // For key frame: take split for bsize above 32X32 or very high variance.
503 if (frame_is_intra_only(cm) &&
504 (bsize > BLOCK_32X32 ||
505 vt.part_variances->none.variance > (threshold << 4))) {
506 return 0;
507 }
508 // If variance is low, take the bsize (no split).
509 if (mi_col + block_width / 2 < cm->mi_cols &&
510 mi_row + block_height / 2 < cm->mi_rows &&
511 vt.part_variances->none.variance < threshold) {
512 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
513 return 1;
514 }
515
516 // Check vertical split.
517 if (mi_row + block_height / 2 < cm->mi_rows) {
518 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
519 get_variance(&vt.part_variances->vert[0]);
520 get_variance(&vt.part_variances->vert[1]);
521 if (vt.part_variances->vert[0].variance < threshold &&
522 vt.part_variances->vert[1].variance < threshold &&
523 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
524 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
525 set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
526 return 1;
527 }
528 }
529 // Check horizontal split.
530 if (mi_col + block_width / 2 < cm->mi_cols) {
531 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
532 get_variance(&vt.part_variances->horz[0]);
533 get_variance(&vt.part_variances->horz[1]);
534 if (vt.part_variances->horz[0].variance < threshold &&
535 vt.part_variances->horz[1].variance < threshold &&
536 get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
537 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
538 set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
539 return 1;
540 }
541 }
542
543 return 0;
544 }
545 return 0;
546 }
547
scale_part_thresh_sumdiff(int64_t threshold_base,int speed,int width,int height,int content_state)548 static int64_t scale_part_thresh_sumdiff(int64_t threshold_base, int speed,
549 int width, int height,
550 int content_state) {
551 if (speed >= 8) {
552 if (width <= 640 && height <= 480)
553 return (5 * threshold_base) >> 2;
554 else if ((content_state == kLowSadLowSumdiff) ||
555 (content_state == kHighSadLowSumdiff) ||
556 (content_state == kLowVarHighSumdiff))
557 return (5 * threshold_base) >> 2;
558 } else if (speed == 7) {
559 if ((content_state == kLowSadLowSumdiff) ||
560 (content_state == kHighSadLowSumdiff) ||
561 (content_state == kLowVarHighSumdiff)) {
562 return (5 * threshold_base) >> 2;
563 }
564 }
565 return threshold_base;
566 }
567
568 // Set the variance split thresholds for following the block sizes:
569 // 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
570 // 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
571 // currently only used on key frame.
set_vbp_thresholds(VP9_COMP * cpi,int64_t thresholds[],int q,int content_state)572 static void set_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q,
573 int content_state) {
574 VP9_COMMON *const cm = &cpi->common;
575 const int is_key_frame = frame_is_intra_only(cm);
576 const int threshold_multiplier =
577 is_key_frame ? 20 : cpi->sf.variance_part_thresh_mult;
578 int64_t threshold_base =
579 (int64_t)(threshold_multiplier * cpi->y_dequant[q][1]);
580
581 if (is_key_frame) {
582 thresholds[0] = threshold_base;
583 thresholds[1] = threshold_base >> 2;
584 thresholds[2] = threshold_base >> 2;
585 thresholds[3] = threshold_base << 2;
586 } else {
587 // Increase base variance threshold based on estimated noise level.
588 if (cpi->noise_estimate.enabled && cm->width >= 640 && cm->height >= 480) {
589 NOISE_LEVEL noise_level =
590 vp9_noise_estimate_extract_level(&cpi->noise_estimate);
591 if (noise_level == kHigh)
592 threshold_base = 3 * threshold_base;
593 else if (noise_level == kMedium)
594 threshold_base = threshold_base << 1;
595 else if (noise_level < kLow)
596 threshold_base = (7 * threshold_base) >> 3;
597 }
598 #if CONFIG_VP9_TEMPORAL_DENOISING
599 if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
600 cpi->oxcf.speed > 5 && cpi->denoiser.denoising_level >= kDenLow)
601 threshold_base =
602 vp9_scale_part_thresh(threshold_base, cpi->denoiser.denoising_level,
603 content_state, cpi->svc.temporal_layer_id);
604 else
605 threshold_base =
606 scale_part_thresh_sumdiff(threshold_base, cpi->oxcf.speed, cm->width,
607 cm->height, content_state);
608 #else
609 // Increase base variance threshold based on content_state/sum_diff level.
610 threshold_base = scale_part_thresh_sumdiff(
611 threshold_base, cpi->oxcf.speed, cm->width, cm->height, content_state);
612 #endif
613 thresholds[0] = threshold_base;
614 thresholds[2] = threshold_base << cpi->oxcf.speed;
615 if (cm->width >= 1280 && cm->height >= 720 && cpi->oxcf.speed < 7)
616 thresholds[2] = thresholds[2] << 1;
617 if (cm->width <= 352 && cm->height <= 288) {
618 thresholds[0] = threshold_base >> 3;
619 thresholds[1] = threshold_base >> 1;
620 thresholds[2] = threshold_base << 3;
621 if (cpi->rc.avg_frame_qindex[INTER_FRAME] > 220)
622 thresholds[2] = thresholds[2] << 2;
623 else if (cpi->rc.avg_frame_qindex[INTER_FRAME] > 200)
624 thresholds[2] = thresholds[2] << 1;
625 } else if (cm->width < 1280 && cm->height < 720) {
626 thresholds[1] = (5 * threshold_base) >> 2;
627 } else if (cm->width < 1920 && cm->height < 1080) {
628 thresholds[1] = threshold_base << 1;
629 } else {
630 thresholds[1] = (5 * threshold_base) >> 1;
631 }
632 if (cpi->sf.disable_16x16part_nonkey) thresholds[2] = INT64_MAX;
633 }
634 }
635
vp9_set_variance_partition_thresholds(VP9_COMP * cpi,int q,int content_state)636 void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q,
637 int content_state) {
638 VP9_COMMON *const cm = &cpi->common;
639 SPEED_FEATURES *const sf = &cpi->sf;
640 const int is_key_frame = frame_is_intra_only(cm);
641 if (sf->partition_search_type != VAR_BASED_PARTITION &&
642 sf->partition_search_type != REFERENCE_PARTITION) {
643 return;
644 } else {
645 set_vbp_thresholds(cpi, cpi->vbp_thresholds, q, content_state);
646 // The thresholds below are not changed locally.
647 if (is_key_frame) {
648 cpi->vbp_threshold_sad = 0;
649 cpi->vbp_threshold_copy = 0;
650 cpi->vbp_bsize_min = BLOCK_8X8;
651 } else {
652 if (cm->width <= 352 && cm->height <= 288)
653 cpi->vbp_threshold_sad = 10;
654 else
655 cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000
656 ? (cpi->y_dequant[q][1] << 1)
657 : 1000;
658 cpi->vbp_bsize_min = BLOCK_16X16;
659 if (cm->width <= 352 && cm->height <= 288)
660 cpi->vbp_threshold_copy = 4000;
661 else if (cm->width <= 640 && cm->height <= 360)
662 cpi->vbp_threshold_copy = 8000;
663 else
664 cpi->vbp_threshold_copy = (cpi->y_dequant[q][1] << 3) > 8000
665 ? (cpi->y_dequant[q][1] << 3)
666 : 8000;
667 if (cpi->rc.high_source_sad ||
668 (cpi->use_svc && cpi->svc.high_source_sad_superframe)) {
669 cpi->vbp_threshold_sad = 0;
670 cpi->vbp_threshold_copy = 0;
671 }
672 }
673 cpi->vbp_threshold_minmax = 15 + (q >> 3);
674 }
675 }
676
677 // Compute the minmax over the 8x8 subblocks.
compute_minmax_8x8(const uint8_t * s,int sp,const uint8_t * d,int dp,int x16_idx,int y16_idx,int highbd_flag,int pixels_wide,int pixels_high)678 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
679 int dp, int x16_idx, int y16_idx,
680 #if CONFIG_VP9_HIGHBITDEPTH
681 int highbd_flag,
682 #endif
683 int pixels_wide, int pixels_high) {
684 int k;
685 int minmax_max = 0;
686 int minmax_min = 255;
687 // Loop over the 4 8x8 subblocks.
688 for (k = 0; k < 4; k++) {
689 int x8_idx = x16_idx + ((k & 1) << 3);
690 int y8_idx = y16_idx + ((k >> 1) << 3);
691 int min = 0;
692 int max = 0;
693 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
694 #if CONFIG_VP9_HIGHBITDEPTH
695 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
696 vpx_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
697 d + y8_idx * dp + x8_idx, dp, &min, &max);
698 } else {
699 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx,
700 dp, &min, &max);
701 }
702 #else
703 vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx, dp,
704 &min, &max);
705 #endif
706 if ((max - min) > minmax_max) minmax_max = (max - min);
707 if ((max - min) < minmax_min) minmax_min = (max - min);
708 }
709 }
710 return (minmax_max - minmax_min);
711 }
712
fill_variance_4x4avg(const uint8_t * s,int sp,const uint8_t * d,int dp,int x8_idx,int y8_idx,v8x8 * vst,int highbd_flag,int pixels_wide,int pixels_high,int is_key_frame)713 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
714 int dp, int x8_idx, int y8_idx, v8x8 *vst,
715 #if CONFIG_VP9_HIGHBITDEPTH
716 int highbd_flag,
717 #endif
718 int pixels_wide, int pixels_high,
719 int is_key_frame) {
720 int k;
721 for (k = 0; k < 4; k++) {
722 int x4_idx = x8_idx + ((k & 1) << 2);
723 int y4_idx = y8_idx + ((k >> 1) << 2);
724 unsigned int sse = 0;
725 int sum = 0;
726 if (x4_idx < pixels_wide && y4_idx < pixels_high) {
727 int s_avg;
728 int d_avg = 128;
729 #if CONFIG_VP9_HIGHBITDEPTH
730 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
731 s_avg = vpx_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
732 if (!is_key_frame)
733 d_avg = vpx_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
734 } else {
735 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
736 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
737 }
738 #else
739 s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
740 if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
741 #endif
742 sum = s_avg - d_avg;
743 sse = sum * sum;
744 }
745 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
746 }
747 }
748
fill_variance_8x8avg(const uint8_t * s,int sp,const uint8_t * d,int dp,int x16_idx,int y16_idx,v16x16 * vst,int highbd_flag,int pixels_wide,int pixels_high,int is_key_frame)749 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
750 int dp, int x16_idx, int y16_idx, v16x16 *vst,
751 #if CONFIG_VP9_HIGHBITDEPTH
752 int highbd_flag,
753 #endif
754 int pixels_wide, int pixels_high,
755 int is_key_frame) {
756 int k;
757 for (k = 0; k < 4; k++) {
758 int x8_idx = x16_idx + ((k & 1) << 3);
759 int y8_idx = y16_idx + ((k >> 1) << 3);
760 unsigned int sse = 0;
761 int sum = 0;
762 if (x8_idx < pixels_wide && y8_idx < pixels_high) {
763 int s_avg;
764 int d_avg = 128;
765 #if CONFIG_VP9_HIGHBITDEPTH
766 if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
767 s_avg = vpx_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
768 if (!is_key_frame)
769 d_avg = vpx_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
770 } else {
771 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
772 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
773 }
774 #else
775 s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
776 if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
777 #endif
778 sum = s_avg - d_avg;
779 sse = sum * sum;
780 }
781 fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
782 }
783 }
784
785 // Check if most of the superblock is skin content, and if so, force split to
786 // 32x32, and set x->sb_is_skin for use in mode selection.
skin_sb_split(VP9_COMP * cpi,const int low_res,int mi_row,int mi_col,int * force_split)787 static int skin_sb_split(VP9_COMP *cpi, const int low_res, int mi_row,
788 int mi_col, int *force_split) {
789 VP9_COMMON *const cm = &cpi->common;
790 #if CONFIG_VP9_HIGHBITDEPTH
791 if (cm->use_highbitdepth) return 0;
792 #endif
793 // Avoid checking superblocks on/near boundary and avoid low resolutions.
794 // Note superblock may still pick 64X64 if y_sad is very small
795 // (i.e., y_sad < cpi->vbp_threshold_sad) below. For now leave this as is.
796 if (!low_res && (mi_col >= 8 && mi_col + 8 < cm->mi_cols && mi_row >= 8 &&
797 mi_row + 8 < cm->mi_rows)) {
798 int num_16x16_skin = 0;
799 int num_16x16_nonskin = 0;
800 const int block_index = mi_row * cm->mi_cols + mi_col;
801 const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
802 const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
803 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
804 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
805 // Loop through the 16x16 sub-blocks.
806 int i, j;
807 for (i = 0; i < ymis; i += 2) {
808 for (j = 0; j < xmis; j += 2) {
809 int bl_index = block_index + i * cm->mi_cols + j;
810 int is_skin = cpi->skin_map[bl_index];
811 num_16x16_skin += is_skin;
812 num_16x16_nonskin += (1 - is_skin);
813 if (num_16x16_nonskin > 3) {
814 // Exit loop if at least 4 of the 16x16 blocks are not skin.
815 i = ymis;
816 break;
817 }
818 }
819 }
820 if (num_16x16_skin > 12) {
821 *force_split = 1;
822 return 1;
823 }
824 }
825 return 0;
826 }
827
set_low_temp_var_flag(VP9_COMP * cpi,MACROBLOCK * x,MACROBLOCKD * xd,v64x64 * vt,int64_t thresholds[],MV_REFERENCE_FRAME ref_frame_partition,int mi_col,int mi_row)828 static void set_low_temp_var_flag(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
829 v64x64 *vt, int64_t thresholds[],
830 MV_REFERENCE_FRAME ref_frame_partition,
831 int mi_col, int mi_row) {
832 int i, j;
833 VP9_COMMON *const cm = &cpi->common;
834 const int mv_thr = cm->width > 640 ? 8 : 4;
835 // Check temporal variance for bsize >= 16x16, if LAST_FRAME was selected and
836 // int_pro mv is small. If the temporal variance is small set the flag
837 // variance_low for the block. The variance threshold can be adjusted, the
838 // higher the more aggressive.
839 if (ref_frame_partition == LAST_FRAME &&
840 (cpi->sf.short_circuit_low_temp_var == 1 ||
841 (xd->mi[0]->mv[0].as_mv.col < mv_thr &&
842 xd->mi[0]->mv[0].as_mv.col > -mv_thr &&
843 xd->mi[0]->mv[0].as_mv.row < mv_thr &&
844 xd->mi[0]->mv[0].as_mv.row > -mv_thr))) {
845 if (xd->mi[0]->sb_type == BLOCK_64X64) {
846 if ((vt->part_variances).none.variance < (thresholds[0] >> 1))
847 x->variance_low[0] = 1;
848 } else if (xd->mi[0]->sb_type == BLOCK_64X32) {
849 for (i = 0; i < 2; i++) {
850 if (vt->part_variances.horz[i].variance < (thresholds[0] >> 2))
851 x->variance_low[i + 1] = 1;
852 }
853 } else if (xd->mi[0]->sb_type == BLOCK_32X64) {
854 for (i = 0; i < 2; i++) {
855 if (vt->part_variances.vert[i].variance < (thresholds[0] >> 2))
856 x->variance_low[i + 3] = 1;
857 }
858 } else {
859 for (i = 0; i < 4; i++) {
860 const int idx[4][2] = { { 0, 0 }, { 0, 4 }, { 4, 0 }, { 4, 4 } };
861 const int idx_str =
862 cm->mi_stride * (mi_row + idx[i][0]) + mi_col + idx[i][1];
863 MODE_INFO **this_mi = cm->mi_grid_visible + idx_str;
864
865 if (cm->mi_cols <= mi_col + idx[i][1] ||
866 cm->mi_rows <= mi_row + idx[i][0])
867 continue;
868
869 if ((*this_mi)->sb_type == BLOCK_32X32) {
870 int64_t threshold_32x32 = (cpi->sf.short_circuit_low_temp_var == 1 ||
871 cpi->sf.short_circuit_low_temp_var == 3)
872 ? ((5 * thresholds[1]) >> 3)
873 : (thresholds[1] >> 1);
874 if (vt->split[i].part_variances.none.variance < threshold_32x32)
875 x->variance_low[i + 5] = 1;
876 } else if (cpi->sf.short_circuit_low_temp_var >= 2) {
877 // For 32x16 and 16x32 blocks, the flag is set on each 16x16 block
878 // inside.
879 if ((*this_mi)->sb_type == BLOCK_16X16 ||
880 (*this_mi)->sb_type == BLOCK_32X16 ||
881 (*this_mi)->sb_type == BLOCK_16X32) {
882 for (j = 0; j < 4; j++) {
883 if (vt->split[i].split[j].part_variances.none.variance <
884 (thresholds[2] >> 8))
885 x->variance_low[(i << 2) + j + 9] = 1;
886 }
887 }
888 }
889 }
890 }
891 }
892 }
893
copy_partitioning_helper(VP9_COMP * cpi,MACROBLOCK * x,MACROBLOCKD * xd,BLOCK_SIZE bsize,int mi_row,int mi_col)894 static void copy_partitioning_helper(VP9_COMP *cpi, MACROBLOCK *x,
895 MACROBLOCKD *xd, BLOCK_SIZE bsize,
896 int mi_row, int mi_col) {
897 VP9_COMMON *const cm = &cpi->common;
898 BLOCK_SIZE *prev_part = cpi->prev_partition;
899 int start_pos = mi_row * cm->mi_stride + mi_col;
900
901 const int bsl = b_width_log2_lookup[bsize];
902 const int bs = (1 << bsl) >> 2;
903 BLOCK_SIZE subsize;
904 PARTITION_TYPE partition;
905
906 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
907
908 partition = partition_lookup[bsl][prev_part[start_pos]];
909 subsize = get_subsize(bsize, partition);
910
911 if (subsize < BLOCK_8X8) {
912 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
913 } else {
914 switch (partition) {
915 case PARTITION_NONE:
916 set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
917 break;
918 case PARTITION_HORZ:
919 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
920 set_block_size(cpi, x, xd, mi_row + bs, mi_col, subsize);
921 break;
922 case PARTITION_VERT:
923 set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
924 set_block_size(cpi, x, xd, mi_row, mi_col + bs, subsize);
925 break;
926 default:
927 assert(partition == PARTITION_SPLIT);
928 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col);
929 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col);
930 copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col + bs);
931 copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col + bs);
932 break;
933 }
934 }
935 }
936
copy_partitioning(VP9_COMP * cpi,MACROBLOCK * x,MACROBLOCKD * xd,int mi_row,int mi_col,int segment_id,int sb_offset)937 static int copy_partitioning(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
938 int mi_row, int mi_col, int segment_id,
939 int sb_offset) {
940 int svc_copy_allowed = 1;
941 int frames_since_key_thresh = 1;
942 if (cpi->use_svc) {
943 // For SVC, don't allow copy if base spatial layer is key frame, or if
944 // frame is not a temporal enhancement layer frame.
945 int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
946 cpi->svc.number_temporal_layers);
947 const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
948 if (lc->is_key_frame || !cpi->svc.non_reference_frame) svc_copy_allowed = 0;
949 frames_since_key_thresh = cpi->svc.number_spatial_layers << 1;
950 }
951 if (cpi->rc.frames_since_key > frames_since_key_thresh && svc_copy_allowed &&
952 !cpi->resize_pending && segment_id == CR_SEGMENT_ID_BASE &&
953 cpi->prev_segment_id[sb_offset] == CR_SEGMENT_ID_BASE &&
954 cpi->copied_frame_cnt[sb_offset] < cpi->max_copied_frame) {
955 if (cpi->prev_partition != NULL) {
956 copy_partitioning_helper(cpi, x, xd, BLOCK_64X64, mi_row, mi_col);
957 cpi->copied_frame_cnt[sb_offset] += 1;
958 memcpy(x->variance_low, &(cpi->prev_variance_low[sb_offset * 25]),
959 sizeof(x->variance_low));
960 return 1;
961 }
962 }
963
964 return 0;
965 }
966
scale_partitioning_svc(VP9_COMP * cpi,MACROBLOCK * x,MACROBLOCKD * xd,BLOCK_SIZE bsize,int mi_row,int mi_col,int mi_row_high,int mi_col_high)967 static int scale_partitioning_svc(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
968 BLOCK_SIZE bsize, int mi_row, int mi_col,
969 int mi_row_high, int mi_col_high) {
970 VP9_COMMON *const cm = &cpi->common;
971 SVC *const svc = &cpi->svc;
972 BLOCK_SIZE *prev_part = svc->prev_partition_svc;
973 // Variables with _high are for higher resolution.
974 int bsize_high = 0;
975 int subsize_high = 0;
976 const int bsl_high = b_width_log2_lookup[bsize];
977 const int bs_high = (1 << bsl_high) >> 2;
978 const int has_rows = (mi_row_high + bs_high) < cm->mi_rows;
979 const int has_cols = (mi_col_high + bs_high) < cm->mi_cols;
980
981 const int row_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 1, 0,
982 1, 1, 0, 1, 1,
983 0, 1, 0 };
984 const int col_boundary_block_scale_factor[BLOCK_SIZES] = { 13, 13, 13, 2, 2,
985 0, 2, 2, 0, 2,
986 2, 0, 0 };
987 int start_pos;
988 BLOCK_SIZE bsize_low;
989 PARTITION_TYPE partition_high;
990
991 if (mi_row_high >= cm->mi_rows || mi_col_high >= cm->mi_cols) return 0;
992 if (mi_row >= svc->mi_rows[svc->spatial_layer_id - 1] ||
993 mi_col >= svc->mi_cols[svc->spatial_layer_id - 1])
994 return 0;
995
996 // Find corresponding (mi_col/mi_row) block down-scaled by 2x2.
997 start_pos = mi_row * (svc->mi_stride[svc->spatial_layer_id - 1]) + mi_col;
998 bsize_low = prev_part[start_pos];
999 // The block size is too big for boundaries. Do variance based partitioning.
1000 if ((!has_rows || !has_cols) && bsize_low > BLOCK_16X16) return 1;
1001
1002 // For reference frames: return 1 (do variance-based partitioning) if the
1003 // superblock is not low source sad and lower-resoln bsize is below 32x32.
1004 if (!cpi->svc.non_reference_frame && !x->skip_low_source_sad &&
1005 bsize_low < BLOCK_32X32)
1006 return 1;
1007
1008 // Scale up block size by 2x2. Force 64x64 for size larger than 32x32.
1009 if (bsize_low < BLOCK_32X32) {
1010 bsize_high = bsize_low + 3;
1011 } else if (bsize_low >= BLOCK_32X32) {
1012 bsize_high = BLOCK_64X64;
1013 }
1014 // Scale up blocks on boundary.
1015 if (!has_cols && has_rows) {
1016 bsize_high = bsize_low + row_boundary_block_scale_factor[bsize_low];
1017 } else if (has_cols && !has_rows) {
1018 bsize_high = bsize_low + col_boundary_block_scale_factor[bsize_low];
1019 } else if (!has_cols && !has_rows) {
1020 bsize_high = bsize_low;
1021 }
1022
1023 partition_high = partition_lookup[bsl_high][bsize_high];
1024 subsize_high = get_subsize(bsize, partition_high);
1025
1026 if (subsize_high < BLOCK_8X8) {
1027 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1028 } else {
1029 const int bsl = b_width_log2_lookup[bsize];
1030 const int bs = (1 << bsl) >> 2;
1031 switch (partition_high) {
1032 case PARTITION_NONE:
1033 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1034 break;
1035 case PARTITION_HORZ:
1036 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1037 if (subsize_high < BLOCK_64X64)
1038 set_block_size(cpi, x, xd, mi_row_high + bs_high, mi_col_high,
1039 subsize_high);
1040 break;
1041 case PARTITION_VERT:
1042 set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1043 if (subsize_high < BLOCK_64X64)
1044 set_block_size(cpi, x, xd, mi_row_high, mi_col_high + bs_high,
1045 subsize_high);
1046 break;
1047 default:
1048 assert(partition_high == PARTITION_SPLIT);
1049 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row, mi_col,
1050 mi_row_high, mi_col_high))
1051 return 1;
1052 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1053 mi_col, mi_row_high + bs_high, mi_col_high))
1054 return 1;
1055 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row,
1056 mi_col + (bs >> 1), mi_row_high,
1057 mi_col_high + bs_high))
1058 return 1;
1059 if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1060 mi_col + (bs >> 1), mi_row_high + bs_high,
1061 mi_col_high + bs_high))
1062 return 1;
1063 break;
1064 }
1065 }
1066
1067 return 0;
1068 }
1069
update_partition_svc(VP9_COMP * cpi,BLOCK_SIZE bsize,int mi_row,int mi_col)1070 static void update_partition_svc(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
1071 int mi_col) {
1072 VP9_COMMON *const cm = &cpi->common;
1073 BLOCK_SIZE *prev_part = cpi->svc.prev_partition_svc;
1074 int start_pos = mi_row * cm->mi_stride + mi_col;
1075 const int bsl = b_width_log2_lookup[bsize];
1076 const int bs = (1 << bsl) >> 2;
1077 BLOCK_SIZE subsize;
1078 PARTITION_TYPE partition;
1079 const MODE_INFO *mi = NULL;
1080 int xx, yy;
1081
1082 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1083
1084 mi = cm->mi_grid_visible[start_pos];
1085 partition = partition_lookup[bsl][mi->sb_type];
1086 subsize = get_subsize(bsize, partition);
1087 if (subsize < BLOCK_8X8) {
1088 prev_part[start_pos] = bsize;
1089 } else {
1090 switch (partition) {
1091 case PARTITION_NONE:
1092 prev_part[start_pos] = bsize;
1093 if (bsize == BLOCK_64X64) {
1094 for (xx = 0; xx < 8; xx += 4)
1095 for (yy = 0; yy < 8; yy += 4) {
1096 if ((mi_row + xx < cm->mi_rows) && (mi_col + yy < cm->mi_cols))
1097 prev_part[start_pos + xx * cm->mi_stride + yy] = bsize;
1098 }
1099 }
1100 break;
1101 case PARTITION_HORZ:
1102 prev_part[start_pos] = subsize;
1103 if (mi_row + bs < cm->mi_rows)
1104 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1105 break;
1106 case PARTITION_VERT:
1107 prev_part[start_pos] = subsize;
1108 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1109 break;
1110 default:
1111 assert(partition == PARTITION_SPLIT);
1112 update_partition_svc(cpi, subsize, mi_row, mi_col);
1113 update_partition_svc(cpi, subsize, mi_row + bs, mi_col);
1114 update_partition_svc(cpi, subsize, mi_row, mi_col + bs);
1115 update_partition_svc(cpi, subsize, mi_row + bs, mi_col + bs);
1116 break;
1117 }
1118 }
1119 }
1120
update_prev_partition_helper(VP9_COMP * cpi,BLOCK_SIZE bsize,int mi_row,int mi_col)1121 static void update_prev_partition_helper(VP9_COMP *cpi, BLOCK_SIZE bsize,
1122 int mi_row, int mi_col) {
1123 VP9_COMMON *const cm = &cpi->common;
1124 BLOCK_SIZE *prev_part = cpi->prev_partition;
1125 int start_pos = mi_row * cm->mi_stride + mi_col;
1126 const int bsl = b_width_log2_lookup[bsize];
1127 const int bs = (1 << bsl) >> 2;
1128 BLOCK_SIZE subsize;
1129 PARTITION_TYPE partition;
1130 const MODE_INFO *mi = NULL;
1131
1132 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1133
1134 mi = cm->mi_grid_visible[start_pos];
1135 partition = partition_lookup[bsl][mi->sb_type];
1136 subsize = get_subsize(bsize, partition);
1137 if (subsize < BLOCK_8X8) {
1138 prev_part[start_pos] = bsize;
1139 } else {
1140 switch (partition) {
1141 case PARTITION_NONE: prev_part[start_pos] = bsize; break;
1142 case PARTITION_HORZ:
1143 prev_part[start_pos] = subsize;
1144 if (mi_row + bs < cm->mi_rows)
1145 prev_part[start_pos + bs * cm->mi_stride] = subsize;
1146 break;
1147 case PARTITION_VERT:
1148 prev_part[start_pos] = subsize;
1149 if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1150 break;
1151 default:
1152 assert(partition == PARTITION_SPLIT);
1153 update_prev_partition_helper(cpi, subsize, mi_row, mi_col);
1154 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col);
1155 update_prev_partition_helper(cpi, subsize, mi_row, mi_col + bs);
1156 update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col + bs);
1157 break;
1158 }
1159 }
1160 }
1161
update_prev_partition(VP9_COMP * cpi,MACROBLOCK * x,int segment_id,int mi_row,int mi_col,int sb_offset)1162 static void update_prev_partition(VP9_COMP *cpi, MACROBLOCK *x, int segment_id,
1163 int mi_row, int mi_col, int sb_offset) {
1164 update_prev_partition_helper(cpi, BLOCK_64X64, mi_row, mi_col);
1165 cpi->prev_segment_id[sb_offset] = segment_id;
1166 memcpy(&(cpi->prev_variance_low[sb_offset * 25]), x->variance_low,
1167 sizeof(x->variance_low));
1168 // Reset the counter for copy partitioning
1169 cpi->copied_frame_cnt[sb_offset] = 0;
1170 }
1171
chroma_check(VP9_COMP * cpi,MACROBLOCK * x,int bsize,unsigned int y_sad,int is_key_frame,int scene_change_detected)1172 static void chroma_check(VP9_COMP *cpi, MACROBLOCK *x, int bsize,
1173 unsigned int y_sad, int is_key_frame,
1174 int scene_change_detected) {
1175 int i;
1176 MACROBLOCKD *xd = &x->e_mbd;
1177 int shift = 2;
1178
1179 if (is_key_frame) return;
1180
1181 // For speed > 8, avoid the chroma check if y_sad is above threshold.
1182 if (cpi->oxcf.speed > 8) {
1183 if (y_sad > cpi->vbp_thresholds[1] &&
1184 (!cpi->noise_estimate.enabled ||
1185 vp9_noise_estimate_extract_level(&cpi->noise_estimate) < kMedium))
1186 return;
1187 }
1188
1189 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN && scene_change_detected)
1190 shift = 5;
1191
1192 for (i = 1; i <= 2; ++i) {
1193 unsigned int uv_sad = UINT_MAX;
1194 struct macroblock_plane *p = &x->plane[i];
1195 struct macroblockd_plane *pd = &xd->plane[i];
1196 const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
1197
1198 if (bs != BLOCK_INVALID)
1199 uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride, pd->dst.buf,
1200 pd->dst.stride);
1201
1202 // TODO(marpan): Investigate if we should lower this threshold if
1203 // superblock is detected as skin.
1204 x->color_sensitivity[i - 1] = uv_sad > (y_sad >> shift);
1205 }
1206 }
1207
avg_source_sad(VP9_COMP * cpi,MACROBLOCK * x,int shift,int sb_offset)1208 static uint64_t avg_source_sad(VP9_COMP *cpi, MACROBLOCK *x, int shift,
1209 int sb_offset) {
1210 unsigned int tmp_sse;
1211 uint64_t tmp_sad;
1212 unsigned int tmp_variance;
1213 const BLOCK_SIZE bsize = BLOCK_64X64;
1214 uint8_t *src_y = cpi->Source->y_buffer;
1215 int src_ystride = cpi->Source->y_stride;
1216 uint8_t *last_src_y = cpi->Last_Source->y_buffer;
1217 int last_src_ystride = cpi->Last_Source->y_stride;
1218 uint64_t avg_source_sad_threshold = 10000;
1219 uint64_t avg_source_sad_threshold2 = 12000;
1220 #if CONFIG_VP9_HIGHBITDEPTH
1221 if (cpi->common.use_highbitdepth) return 0;
1222 #endif
1223 src_y += shift;
1224 last_src_y += shift;
1225 tmp_sad =
1226 cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y, last_src_ystride);
1227 tmp_variance = vpx_variance64x64(src_y, src_ystride, last_src_y,
1228 last_src_ystride, &tmp_sse);
1229 // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1230 if (tmp_sad < avg_source_sad_threshold)
1231 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kLowSadLowSumdiff
1232 : kLowSadHighSumdiff;
1233 else
1234 x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kHighSadLowSumdiff
1235 : kHighSadHighSumdiff;
1236
1237 // Detect large lighting change.
1238 if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
1239 cpi->oxcf.rc_mode == VPX_CBR && tmp_variance < (tmp_sse >> 3) &&
1240 (tmp_sse - tmp_variance) > 10000)
1241 x->content_state_sb = kLowVarHighSumdiff;
1242 else if (tmp_sad > (avg_source_sad_threshold << 1))
1243 x->content_state_sb = kVeryHighSad;
1244
1245 if (cpi->content_state_sb_fd != NULL) {
1246 if (tmp_sad < avg_source_sad_threshold2) {
1247 // Cap the increment to 255.
1248 if (cpi->content_state_sb_fd[sb_offset] < 255)
1249 cpi->content_state_sb_fd[sb_offset]++;
1250 } else {
1251 cpi->content_state_sb_fd[sb_offset] = 0;
1252 }
1253 }
1254 if (tmp_sad == 0) x->zero_temp_sad_source = 1;
1255 return tmp_sad;
1256 }
1257
1258 // This function chooses partitioning based on the variance between source and
1259 // reconstructed last, where variance is computed for down-sampled inputs.
choose_partitioning(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCK * x,int mi_row,int mi_col)1260 static int choose_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1261 MACROBLOCK *x, int mi_row, int mi_col) {
1262 VP9_COMMON *const cm = &cpi->common;
1263 MACROBLOCKD *xd = &x->e_mbd;
1264 int i, j, k, m;
1265 v64x64 vt;
1266 v16x16 *vt2 = NULL;
1267 int force_split[21];
1268 int avg_32x32;
1269 int max_var_32x32 = 0;
1270 int min_var_32x32 = INT_MAX;
1271 int var_32x32;
1272 int avg_16x16[4];
1273 int maxvar_16x16[4];
1274 int minvar_16x16[4];
1275 int64_t threshold_4x4avg;
1276 NOISE_LEVEL noise_level = kLow;
1277 int content_state = 0;
1278 uint8_t *s;
1279 const uint8_t *d;
1280 int sp;
1281 int dp;
1282 int compute_minmax_variance = 1;
1283 unsigned int y_sad = UINT_MAX;
1284 BLOCK_SIZE bsize = BLOCK_64X64;
1285 // Ref frame used in partitioning.
1286 MV_REFERENCE_FRAME ref_frame_partition = LAST_FRAME;
1287 int pixels_wide = 64, pixels_high = 64;
1288 int64_t thresholds[4] = { cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
1289 cpi->vbp_thresholds[2], cpi->vbp_thresholds[3] };
1290 int scene_change_detected =
1291 cpi->rc.high_source_sad ||
1292 (cpi->use_svc && cpi->svc.high_source_sad_superframe);
1293 int force_64_split = scene_change_detected ||
1294 (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1295 cpi->compute_source_sad_onepass &&
1296 cpi->sf.use_source_sad && !x->zero_temp_sad_source);
1297
1298 // For the variance computation under SVC mode, we treat the frame as key if
1299 // the reference (base layer frame) is key frame (i.e., is_key_frame == 1).
1300 int is_key_frame =
1301 (frame_is_intra_only(cm) ||
1302 (is_one_pass_svc(cpi) &&
1303 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame));
1304 // Always use 4x4 partition for key frame.
1305 const int use_4x4_partition = frame_is_intra_only(cm);
1306 const int low_res = (cm->width <= 352 && cm->height <= 288);
1307 int variance4x4downsample[16];
1308 int segment_id;
1309 int sb_offset = (cm->mi_stride >> 3) * (mi_row >> 3) + (mi_col >> 3);
1310
1311 // For SVC: check if LAST frame is NULL or if the resolution of LAST is
1312 // different than the current frame resolution, and if so, treat this frame
1313 // as a key frame, for the purpose of the superblock partitioning.
1314 // LAST == NULL can happen in some cases where enhancement spatial layers are
1315 // enabled dyanmically in the stream and the only reference is the spatial
1316 // reference (GOLDEN).
1317 if (cpi->use_svc) {
1318 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, LAST_FRAME);
1319 if (ref == NULL || ref->y_crop_height != cm->height ||
1320 ref->y_crop_width != cm->width)
1321 is_key_frame = 1;
1322 }
1323
1324 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
1325 set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
1326 segment_id = xd->mi[0]->segment_id;
1327
1328 if (cpi->oxcf.speed >= 8 || (cpi->use_svc && cpi->svc.non_reference_frame))
1329 compute_minmax_variance = 0;
1330
1331 memset(x->variance_low, 0, sizeof(x->variance_low));
1332
1333 if (cpi->sf.use_source_sad && !is_key_frame) {
1334 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1335 content_state = x->content_state_sb;
1336 x->skip_low_source_sad = (content_state == kLowSadLowSumdiff ||
1337 content_state == kLowSadHighSumdiff)
1338 ? 1
1339 : 0;
1340 x->lowvar_highsumdiff = (content_state == kLowVarHighSumdiff) ? 1 : 0;
1341 if (cpi->content_state_sb_fd != NULL)
1342 x->last_sb_high_content = cpi->content_state_sb_fd[sb_offset2];
1343
1344 // For SVC on top spatial layer: use/scale the partition from
1345 // the lower spatial resolution if svc_use_lowres_part is enabled.
1346 if (cpi->sf.svc_use_lowres_part &&
1347 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1348 cpi->svc.prev_partition_svc != NULL && content_state != kVeryHighSad) {
1349 if (!scale_partitioning_svc(cpi, x, xd, BLOCK_64X64, mi_row >> 1,
1350 mi_col >> 1, mi_row, mi_col)) {
1351 if (cpi->sf.copy_partition_flag) {
1352 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1353 }
1354 return 0;
1355 }
1356 }
1357 // If source_sad is low copy the partition without computing the y_sad.
1358 if (x->skip_low_source_sad && cpi->sf.copy_partition_flag &&
1359 !force_64_split &&
1360 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1361 x->sb_use_mv_part = 1;
1362 if (cpi->sf.svc_use_lowres_part &&
1363 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1364 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1365 return 0;
1366 }
1367 }
1368
1369 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
1370 cyclic_refresh_segment_id_boosted(segment_id)) {
1371 int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
1372 set_vbp_thresholds(cpi, thresholds, q, content_state);
1373 } else {
1374 set_vbp_thresholds(cpi, thresholds, cm->base_qindex, content_state);
1375 }
1376 // Decrease 32x32 split threshold for screen on base layer, for scene
1377 // change/high motion frames.
1378 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1379 cpi->svc.spatial_layer_id == 0 && force_64_split)
1380 thresholds[1] = 3 * thresholds[1] >> 2;
1381
1382 // For non keyframes, disable 4x4 average for low resolution when speed = 8
1383 threshold_4x4avg = (cpi->oxcf.speed < 8) ? thresholds[1] << 1 : INT64_MAX;
1384
1385 if (xd->mb_to_right_edge < 0) pixels_wide += (xd->mb_to_right_edge >> 3);
1386 if (xd->mb_to_bottom_edge < 0) pixels_high += (xd->mb_to_bottom_edge >> 3);
1387
1388 s = x->plane[0].src.buf;
1389 sp = x->plane[0].src.stride;
1390
1391 // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
1392 // 5-20 for the 16x16 blocks.
1393 force_split[0] = force_64_split;
1394
1395 if (!is_key_frame) {
1396 // In the case of spatial/temporal scalable coding, the assumption here is
1397 // that the temporal reference frame will always be of type LAST_FRAME.
1398 // TODO(marpan): If that assumption is broken, we need to revisit this code.
1399 MODE_INFO *mi = xd->mi[0];
1400 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1401
1402 const YV12_BUFFER_CONFIG *yv12_g = NULL;
1403 unsigned int y_sad_g, y_sad_thr, y_sad_last;
1404 bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
1405 (mi_row + 4 < cm->mi_rows);
1406
1407 assert(yv12 != NULL);
1408
1409 if (!(is_one_pass_svc(cpi) && cpi->svc.spatial_layer_id) ||
1410 cpi->svc.use_gf_temporal_ref_current_layer) {
1411 // For now, GOLDEN will not be used for non-zero spatial layers, since
1412 // it may not be a temporal reference.
1413 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1414 }
1415
1416 // Only compute y_sad_g (sad for golden reference) for speed < 8.
1417 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
1418 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
1419 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1420 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1421 y_sad_g = cpi->fn_ptr[bsize].sdf(
1422 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1423 xd->plane[0].pre[0].stride);
1424 } else {
1425 y_sad_g = UINT_MAX;
1426 }
1427
1428 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
1429 cpi->rc.is_src_frame_alt_ref) {
1430 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
1431 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1432 &cm->frame_refs[ALTREF_FRAME - 1].sf);
1433 mi->ref_frame[0] = ALTREF_FRAME;
1434 y_sad_g = UINT_MAX;
1435 } else {
1436 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1437 &cm->frame_refs[LAST_FRAME - 1].sf);
1438 mi->ref_frame[0] = LAST_FRAME;
1439 }
1440 mi->ref_frame[1] = NONE;
1441 mi->sb_type = BLOCK_64X64;
1442 mi->mv[0].as_int = 0;
1443 mi->interp_filter = BILINEAR;
1444
1445 if (cpi->oxcf.speed >= 8 && !low_res &&
1446 x->content_state_sb != kVeryHighSad) {
1447 y_sad = cpi->fn_ptr[bsize].sdf(
1448 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1449 xd->plane[0].pre[0].stride);
1450 } else {
1451 const MV dummy_mv = { 0, 0 };
1452 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
1453 &dummy_mv);
1454 x->sb_use_mv_part = 1;
1455 x->sb_mvcol_part = mi->mv[0].as_mv.col;
1456 x->sb_mvrow_part = mi->mv[0].as_mv.row;
1457 if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1458 cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
1459 cpi->svc.high_num_blocks_with_motion && !x->zero_temp_sad_source &&
1460 cm->width > 640 && cm->height > 480) {
1461 // Disable split below 16x16 block size when scroll motion (horz or
1462 // vert) is detected.
1463 // TODO(marpan/jianj): Improve this condition: issue is that search
1464 // range is hard-coded/limited in vp9_int_pro_motion_estimation() so
1465 // scroll motion may not be detected here.
1466 if (((abs(x->sb_mvrow_part) >= 48 && abs(x->sb_mvcol_part) <= 8) ||
1467 (abs(x->sb_mvcol_part) >= 48 && abs(x->sb_mvrow_part) <= 8)) &&
1468 y_sad < 100000) {
1469 compute_minmax_variance = 0;
1470 thresholds[2] = INT64_MAX;
1471 }
1472 }
1473 }
1474
1475 y_sad_last = y_sad;
1476 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
1477 // are close if short_circuit_low_temp_var is on.
1478 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
1479 if (y_sad_g < y_sad_thr) {
1480 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1481 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1482 mi->ref_frame[0] = GOLDEN_FRAME;
1483 mi->mv[0].as_int = 0;
1484 y_sad = y_sad_g;
1485 ref_frame_partition = GOLDEN_FRAME;
1486 } else {
1487 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
1488 ref_frame_partition = LAST_FRAME;
1489 }
1490
1491 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
1492 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
1493
1494 if (cpi->use_skin_detection)
1495 x->sb_is_skin = skin_sb_split(cpi, low_res, mi_row, mi_col, force_split);
1496
1497 d = xd->plane[0].dst.buf;
1498 dp = xd->plane[0].dst.stride;
1499
1500 // If the y_sad is very small, take 64x64 as partition and exit.
1501 // Don't check on boosted segment for now, as 64x64 is suppressed there.
1502 if (segment_id == CR_SEGMENT_ID_BASE && y_sad < cpi->vbp_threshold_sad) {
1503 const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
1504 const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
1505 if (mi_col + block_width / 2 < cm->mi_cols &&
1506 mi_row + block_height / 2 < cm->mi_rows) {
1507 set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
1508 x->variance_low[0] = 1;
1509 chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1510 if (cpi->sf.svc_use_lowres_part &&
1511 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1512 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1513 if (cpi->sf.copy_partition_flag) {
1514 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1515 }
1516 return 0;
1517 }
1518 }
1519
1520 // If the y_sad is small enough, copy the partition of the superblock in the
1521 // last frame to current frame only if the last frame is not a keyframe.
1522 // Stop the copy every cpi->max_copied_frame to refresh the partition.
1523 // TODO(jianj) : tune the threshold.
1524 if (cpi->sf.copy_partition_flag && y_sad_last < cpi->vbp_threshold_copy &&
1525 copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1526 chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1527 if (cpi->sf.svc_use_lowres_part &&
1528 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1529 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1530 return 0;
1531 }
1532 } else {
1533 d = VP9_VAR_OFFS;
1534 dp = 0;
1535 #if CONFIG_VP9_HIGHBITDEPTH
1536 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1537 switch (xd->bd) {
1538 case 10: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10); break;
1539 case 12: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12); break;
1540 case 8:
1541 default: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8); break;
1542 }
1543 }
1544 #endif // CONFIG_VP9_HIGHBITDEPTH
1545 }
1546
1547 if (low_res && threshold_4x4avg < INT64_MAX)
1548 CHECK_MEM_ERROR(cm, vt2, vpx_calloc(16, sizeof(*vt2)));
1549 // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
1550 // for splits.
1551 for (i = 0; i < 4; i++) {
1552 const int x32_idx = ((i & 1) << 5);
1553 const int y32_idx = ((i >> 1) << 5);
1554 const int i2 = i << 2;
1555 force_split[i + 1] = 0;
1556 avg_16x16[i] = 0;
1557 maxvar_16x16[i] = 0;
1558 minvar_16x16[i] = INT_MAX;
1559 for (j = 0; j < 4; j++) {
1560 const int x16_idx = x32_idx + ((j & 1) << 4);
1561 const int y16_idx = y32_idx + ((j >> 1) << 4);
1562 const int split_index = 5 + i2 + j;
1563 v16x16 *vst = &vt.split[i].split[j];
1564 force_split[split_index] = 0;
1565 variance4x4downsample[i2 + j] = 0;
1566 if (!is_key_frame) {
1567 fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
1568 #if CONFIG_VP9_HIGHBITDEPTH
1569 xd->cur_buf->flags,
1570 #endif
1571 pixels_wide, pixels_high, is_key_frame);
1572 fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1573 get_variance(&vt.split[i].split[j].part_variances.none);
1574 avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance;
1575 if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i])
1576 minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1577 if (vt.split[i].split[j].part_variances.none.variance > maxvar_16x16[i])
1578 maxvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1579 if (vt.split[i].split[j].part_variances.none.variance > thresholds[2]) {
1580 // 16X16 variance is above threshold for split, so force split to 8x8
1581 // for this 16x16 block (this also forces splits for upper levels).
1582 force_split[split_index] = 1;
1583 force_split[i + 1] = 1;
1584 force_split[0] = 1;
1585 } else if (compute_minmax_variance &&
1586 vt.split[i].split[j].part_variances.none.variance >
1587 thresholds[1] &&
1588 !cyclic_refresh_segment_id_boosted(segment_id)) {
1589 // We have some nominal amount of 16x16 variance (based on average),
1590 // compute the minmax over the 8x8 sub-blocks, and if above threshold,
1591 // force split to 8x8 block for this 16x16 block.
1592 int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
1593 #if CONFIG_VP9_HIGHBITDEPTH
1594 xd->cur_buf->flags,
1595 #endif
1596 pixels_wide, pixels_high);
1597 int thresh_minmax = (int)cpi->vbp_threshold_minmax;
1598 if (x->content_state_sb == kVeryHighSad)
1599 thresh_minmax = thresh_minmax << 1;
1600 if (minmax > thresh_minmax) {
1601 force_split[split_index] = 1;
1602 force_split[i + 1] = 1;
1603 force_split[0] = 1;
1604 }
1605 }
1606 }
1607 if (is_key_frame ||
1608 (low_res && vt.split[i].split[j].part_variances.none.variance >
1609 threshold_4x4avg)) {
1610 force_split[split_index] = 0;
1611 // Go down to 4x4 down-sampling for variance.
1612 variance4x4downsample[i2 + j] = 1;
1613 for (k = 0; k < 4; k++) {
1614 int x8_idx = x16_idx + ((k & 1) << 3);
1615 int y8_idx = y16_idx + ((k >> 1) << 3);
1616 v8x8 *vst2 = is_key_frame ? &vst->split[k] : &vt2[i2 + j].split[k];
1617 fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
1618 #if CONFIG_VP9_HIGHBITDEPTH
1619 xd->cur_buf->flags,
1620 #endif
1621 pixels_wide, pixels_high, is_key_frame);
1622 }
1623 }
1624 }
1625 }
1626 if (cpi->noise_estimate.enabled)
1627 noise_level = vp9_noise_estimate_extract_level(&cpi->noise_estimate);
1628 // Fill the rest of the variance tree by summing split partition values.
1629 avg_32x32 = 0;
1630 for (i = 0; i < 4; i++) {
1631 const int i2 = i << 2;
1632 for (j = 0; j < 4; j++) {
1633 if (variance4x4downsample[i2 + j] == 1) {
1634 v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] : &vt.split[i].split[j];
1635 for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
1636 fill_variance_tree(vtemp, BLOCK_16X16);
1637 // If variance of this 16x16 block is above the threshold, force block
1638 // to split. This also forces a split on the upper levels.
1639 get_variance(&vtemp->part_variances.none);
1640 if (vtemp->part_variances.none.variance > thresholds[2]) {
1641 force_split[5 + i2 + j] = 1;
1642 force_split[i + 1] = 1;
1643 force_split[0] = 1;
1644 }
1645 }
1646 }
1647 fill_variance_tree(&vt.split[i], BLOCK_32X32);
1648 // If variance of this 32x32 block is above the threshold, or if its above
1649 // (some threshold of) the average variance over the sub-16x16 blocks, then
1650 // force this block to split. This also forces a split on the upper
1651 // (64x64) level.
1652 if (!force_split[i + 1]) {
1653 get_variance(&vt.split[i].part_variances.none);
1654 var_32x32 = vt.split[i].part_variances.none.variance;
1655 max_var_32x32 = VPXMAX(var_32x32, max_var_32x32);
1656 min_var_32x32 = VPXMIN(var_32x32, min_var_32x32);
1657 if (vt.split[i].part_variances.none.variance > thresholds[1] ||
1658 (!is_key_frame &&
1659 vt.split[i].part_variances.none.variance > (thresholds[1] >> 1) &&
1660 vt.split[i].part_variances.none.variance > (avg_16x16[i] >> 1))) {
1661 force_split[i + 1] = 1;
1662 force_split[0] = 1;
1663 } else if (!is_key_frame && noise_level < kLow && cm->height <= 360 &&
1664 (maxvar_16x16[i] - minvar_16x16[i]) > (thresholds[1] >> 1) &&
1665 maxvar_16x16[i] > thresholds[1]) {
1666 force_split[i + 1] = 1;
1667 force_split[0] = 1;
1668 }
1669 avg_32x32 += var_32x32;
1670 }
1671 }
1672 if (!force_split[0]) {
1673 fill_variance_tree(&vt, BLOCK_64X64);
1674 get_variance(&vt.part_variances.none);
1675 // If variance of this 64x64 block is above (some threshold of) the average
1676 // variance over the sub-32x32 blocks, then force this block to split.
1677 // Only checking this for noise level >= medium for now.
1678 if (!is_key_frame && noise_level >= kMedium &&
1679 vt.part_variances.none.variance > (9 * avg_32x32) >> 5)
1680 force_split[0] = 1;
1681 // Else if the maximum 32x32 variance minus the miniumum 32x32 variance in
1682 // a 64x64 block is greater than threshold and the maximum 32x32 variance is
1683 // above a miniumum threshold, then force the split of a 64x64 block
1684 // Only check this for low noise.
1685 else if (!is_key_frame && noise_level < kMedium &&
1686 (max_var_32x32 - min_var_32x32) > 3 * (thresholds[0] >> 3) &&
1687 max_var_32x32 > thresholds[0] >> 1)
1688 force_split[0] = 1;
1689 }
1690
1691 // Now go through the entire structure, splitting every block size until
1692 // we get to one that's got a variance lower than our threshold.
1693 if (mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
1694 !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
1695 thresholds[0], BLOCK_16X16, force_split[0])) {
1696 for (i = 0; i < 4; ++i) {
1697 const int x32_idx = ((i & 1) << 2);
1698 const int y32_idx = ((i >> 1) << 2);
1699 const int i2 = i << 2;
1700 if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
1701 (mi_row + y32_idx), (mi_col + x32_idx),
1702 thresholds[1], BLOCK_16X16,
1703 force_split[i + 1])) {
1704 for (j = 0; j < 4; ++j) {
1705 const int x16_idx = ((j & 1) << 1);
1706 const int y16_idx = ((j >> 1) << 1);
1707 // For inter frames: if variance4x4downsample[] == 1 for this 16x16
1708 // block, then the variance is based on 4x4 down-sampling, so use vt2
1709 // in set_vt_partioning(), otherwise use vt.
1710 v16x16 *vtemp = (!is_key_frame && variance4x4downsample[i2 + j] == 1)
1711 ? &vt2[i2 + j]
1712 : &vt.split[i].split[j];
1713 if (!set_vt_partitioning(
1714 cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx,
1715 mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min,
1716 force_split[5 + i2 + j])) {
1717 for (k = 0; k < 4; ++k) {
1718 const int x8_idx = (k & 1);
1719 const int y8_idx = (k >> 1);
1720 if (use_4x4_partition) {
1721 if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
1722 BLOCK_8X8,
1723 mi_row + y32_idx + y16_idx + y8_idx,
1724 mi_col + x32_idx + x16_idx + x8_idx,
1725 thresholds[3], BLOCK_8X8, 0)) {
1726 set_block_size(
1727 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1728 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_4X4);
1729 }
1730 } else {
1731 set_block_size(
1732 cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1733 (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_8X8);
1734 }
1735 }
1736 }
1737 }
1738 }
1739 }
1740 }
1741
1742 if (!frame_is_intra_only(cm) && cpi->sf.copy_partition_flag) {
1743 update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1744 }
1745
1746 if (!frame_is_intra_only(cm) && cpi->sf.svc_use_lowres_part &&
1747 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1748 update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1749
1750 if (cpi->sf.short_circuit_low_temp_var) {
1751 set_low_temp_var_flag(cpi, x, xd, &vt, thresholds, ref_frame_partition,
1752 mi_col, mi_row);
1753 }
1754
1755 chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1756 if (vt2) vpx_free(vt2);
1757 return 0;
1758 }
1759
1760 #if !CONFIG_REALTIME_ONLY
update_state(VP9_COMP * cpi,ThreadData * td,PICK_MODE_CONTEXT * ctx,int mi_row,int mi_col,BLOCK_SIZE bsize,int output_enabled)1761 static void update_state(VP9_COMP *cpi, ThreadData *td, PICK_MODE_CONTEXT *ctx,
1762 int mi_row, int mi_col, BLOCK_SIZE bsize,
1763 int output_enabled) {
1764 int i, x_idx, y;
1765 VP9_COMMON *const cm = &cpi->common;
1766 RD_COUNTS *const rdc = &td->rd_counts;
1767 MACROBLOCK *const x = &td->mb;
1768 MACROBLOCKD *const xd = &x->e_mbd;
1769 struct macroblock_plane *const p = x->plane;
1770 struct macroblockd_plane *const pd = xd->plane;
1771 MODE_INFO *mi = &ctx->mic;
1772 MODE_INFO *const xdmi = xd->mi[0];
1773 MODE_INFO *mi_addr = xd->mi[0];
1774 const struct segmentation *const seg = &cm->seg;
1775 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
1776 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
1777 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1778 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1779 MV_REF *const frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1780 int w, h;
1781
1782 const int mis = cm->mi_stride;
1783 const int mi_width = num_8x8_blocks_wide_lookup[bsize];
1784 const int mi_height = num_8x8_blocks_high_lookup[bsize];
1785 int max_plane;
1786
1787 assert(mi->sb_type == bsize);
1788
1789 *mi_addr = *mi;
1790 *x->mbmi_ext = ctx->mbmi_ext;
1791
1792 // If segmentation in use
1793 if (seg->enabled) {
1794 // For in frame complexity AQ copy the segment id from the segment map.
1795 if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1796 const uint8_t *const map =
1797 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1798 mi_addr->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1799 }
1800 // Else for cyclic refresh mode update the segment map, set the segment id
1801 // and then update the quantizer.
1802 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
1803 cpi->cyclic_refresh->content_mode) {
1804 vp9_cyclic_refresh_update_segment(cpi, xd->mi[0], mi_row, mi_col, bsize,
1805 ctx->rate, ctx->dist, x->skip, p);
1806 }
1807 }
1808
1809 max_plane = is_inter_block(xdmi) ? MAX_MB_PLANE : 1;
1810 for (i = 0; i < max_plane; ++i) {
1811 p[i].coeff = ctx->coeff_pbuf[i][1];
1812 p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1813 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1814 p[i].eobs = ctx->eobs_pbuf[i][1];
1815 }
1816
1817 for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1818 p[i].coeff = ctx->coeff_pbuf[i][2];
1819 p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1820 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1821 p[i].eobs = ctx->eobs_pbuf[i][2];
1822 }
1823
1824 // Restore the coding context of the MB to that that was in place
1825 // when the mode was picked for it
1826 for (y = 0; y < mi_height; y++)
1827 for (x_idx = 0; x_idx < mi_width; x_idx++)
1828 if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx &&
1829 (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1830 xd->mi[x_idx + y * mis] = mi_addr;
1831 }
1832
1833 if (cpi->oxcf.aq_mode != NO_AQ) vp9_init_plane_quantizers(cpi, x);
1834
1835 if (is_inter_block(xdmi) && xdmi->sb_type < BLOCK_8X8) {
1836 xdmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1837 xdmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1838 }
1839
1840 x->skip = ctx->skip;
1841 memcpy(x->zcoeff_blk[xdmi->tx_size], ctx->zcoeff_blk,
1842 sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1843
1844 if (!output_enabled) return;
1845
1846 #if CONFIG_INTERNAL_STATS
1847 if (frame_is_intra_only(cm)) {
1848 static const int kf_mode_index[] = {
1849 THR_DC /*DC_PRED*/, THR_V_PRED /*V_PRED*/,
1850 THR_H_PRED /*H_PRED*/, THR_D45_PRED /*D45_PRED*/,
1851 THR_D135_PRED /*D135_PRED*/, THR_D117_PRED /*D117_PRED*/,
1852 THR_D153_PRED /*D153_PRED*/, THR_D207_PRED /*D207_PRED*/,
1853 THR_D63_PRED /*D63_PRED*/, THR_TM /*TM_PRED*/,
1854 };
1855 ++cpi->mode_chosen_counts[kf_mode_index[xdmi->mode]];
1856 } else {
1857 // Note how often each mode chosen as best
1858 ++cpi->mode_chosen_counts[ctx->best_mode_index];
1859 }
1860 #endif
1861 if (!frame_is_intra_only(cm)) {
1862 if (is_inter_block(xdmi)) {
1863 vp9_update_mv_count(td);
1864
1865 if (cm->interp_filter == SWITCHABLE) {
1866 const int ctx = get_pred_context_switchable_interp(xd);
1867 ++td->counts->switchable_interp[ctx][xdmi->interp_filter];
1868 }
1869 }
1870
1871 rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1872 rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1873 rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1874
1875 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1876 rdc->filter_diff[i] += ctx->best_filter_diff[i];
1877 }
1878
1879 for (h = 0; h < y_mis; ++h) {
1880 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1881 for (w = 0; w < x_mis; ++w) {
1882 MV_REF *const mv = frame_mv + w;
1883 mv->ref_frame[0] = mi->ref_frame[0];
1884 mv->ref_frame[1] = mi->ref_frame[1];
1885 mv->mv[0].as_int = mi->mv[0].as_int;
1886 mv->mv[1].as_int = mi->mv[1].as_int;
1887 }
1888 }
1889 }
1890 #endif // !CONFIG_REALTIME_ONLY
1891
vp9_setup_src_planes(MACROBLOCK * x,const YV12_BUFFER_CONFIG * src,int mi_row,int mi_col)1892 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1893 int mi_row, int mi_col) {
1894 uint8_t *const buffers[3] = { src->y_buffer, src->u_buffer, src->v_buffer };
1895 const int strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
1896 int i;
1897
1898 // Set current frame pointer.
1899 x->e_mbd.cur_buf = src;
1900
1901 for (i = 0; i < MAX_MB_PLANE; i++)
1902 setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1903 NULL, x->e_mbd.plane[i].subsampling_x,
1904 x->e_mbd.plane[i].subsampling_y);
1905 }
1906
set_mode_info_seg_skip(MACROBLOCK * x,TX_MODE tx_mode,INTERP_FILTER interp_filter,RD_COST * rd_cost,BLOCK_SIZE bsize)1907 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1908 INTERP_FILTER interp_filter,
1909 RD_COST *rd_cost, BLOCK_SIZE bsize) {
1910 MACROBLOCKD *const xd = &x->e_mbd;
1911 MODE_INFO *const mi = xd->mi[0];
1912 INTERP_FILTER filter_ref;
1913
1914 filter_ref = get_pred_context_switchable_interp(xd);
1915 if (interp_filter == BILINEAR)
1916 filter_ref = BILINEAR;
1917 else if (filter_ref == SWITCHABLE_FILTERS)
1918 filter_ref = EIGHTTAP;
1919
1920 mi->sb_type = bsize;
1921 mi->mode = ZEROMV;
1922 mi->tx_size =
1923 VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[tx_mode]);
1924 mi->skip = 1;
1925 mi->uv_mode = DC_PRED;
1926 mi->ref_frame[0] = LAST_FRAME;
1927 mi->ref_frame[1] = NONE;
1928 mi->mv[0].as_int = 0;
1929 mi->interp_filter = filter_ref;
1930
1931 xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1932 x->skip = 1;
1933
1934 vp9_rd_cost_init(rd_cost);
1935 }
1936
1937 #if !CONFIG_REALTIME_ONLY
set_segment_rdmult(VP9_COMP * const cpi,MACROBLOCK * const x,int mi_row,int mi_col,BLOCK_SIZE bsize,AQ_MODE aq_mode)1938 static void set_segment_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
1939 int mi_row, int mi_col, BLOCK_SIZE bsize,
1940 AQ_MODE aq_mode) {
1941 VP9_COMMON *const cm = &cpi->common;
1942 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1943 const uint8_t *const map =
1944 cm->seg.update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1945
1946 vp9_init_plane_quantizers(cpi, x);
1947 vpx_clear_system_state();
1948
1949 if (aq_mode == NO_AQ || aq_mode == PSNR_AQ) {
1950 if (cpi->sf.enable_tpl_model) x->rdmult = x->cb_rdmult;
1951 } else if (aq_mode == PERCEPTUAL_AQ) {
1952 x->rdmult = x->cb_rdmult;
1953 } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1954 // If segment is boosted, use rdmult for that segment.
1955 if (cyclic_refresh_segment_id_boosted(
1956 get_segment_id(cm, map, bsize, mi_row, mi_col)))
1957 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1958 } else {
1959 x->rdmult = vp9_compute_rd_mult(cpi, cm->base_qindex + cm->y_dc_delta_q);
1960 }
1961
1962 if (oxcf->tuning == VP8_TUNE_SSIM) {
1963 set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
1964 }
1965 }
1966
rd_pick_sb_modes(VP9_COMP * cpi,TileDataEnc * tile_data,MACROBLOCK * const x,int mi_row,int mi_col,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,int rate_in_best_rd,int64_t dist_in_best_rd)1967 static void rd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
1968 MACROBLOCK *const x, int mi_row, int mi_col,
1969 RD_COST *rd_cost, BLOCK_SIZE bsize,
1970 PICK_MODE_CONTEXT *ctx, int rate_in_best_rd,
1971 int64_t dist_in_best_rd) {
1972 VP9_COMMON *const cm = &cpi->common;
1973 TileInfo *const tile_info = &tile_data->tile_info;
1974 MACROBLOCKD *const xd = &x->e_mbd;
1975 MODE_INFO *mi;
1976 struct macroblock_plane *const p = x->plane;
1977 struct macroblockd_plane *const pd = xd->plane;
1978 const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1979 int i, orig_rdmult;
1980 int64_t best_rd = INT64_MAX;
1981
1982 vpx_clear_system_state();
1983
1984 // Use the lower precision, but faster, 32x32 fdct for mode selection.
1985 x->use_lp32x32fdct = 1;
1986
1987 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1988 mi = xd->mi[0];
1989 mi->sb_type = bsize;
1990
1991 for (i = 0; i < MAX_MB_PLANE; ++i) {
1992 p[i].coeff = ctx->coeff_pbuf[i][0];
1993 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1994 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1995 p[i].eobs = ctx->eobs_pbuf[i][0];
1996 }
1997 ctx->is_coded = 0;
1998 ctx->skippable = 0;
1999 ctx->pred_pixel_ready = 0;
2000 x->skip_recode = 0;
2001
2002 // Set to zero to make sure we do not use the previous encoded frame stats
2003 mi->skip = 0;
2004
2005 #if CONFIG_VP9_HIGHBITDEPTH
2006 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2007 x->source_variance = vp9_high_get_sby_perpixel_variance(
2008 cpi, &x->plane[0].src, bsize, xd->bd);
2009 } else {
2010 x->source_variance =
2011 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2012 }
2013 #else
2014 x->source_variance =
2015 vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2016 #endif // CONFIG_VP9_HIGHBITDEPTH
2017
2018 // Save rdmult before it might be changed, so it can be restored later.
2019 orig_rdmult = x->rdmult;
2020
2021 if ((cpi->sf.tx_domain_thresh > 0.0) || (cpi->sf.quant_opt_thresh > 0.0)) {
2022 double logvar = vp9_log_block_var(cpi, x, bsize);
2023 // Check block complexity as part of descision on using pixel or transform
2024 // domain distortion in rd tests.
2025 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion &&
2026 (logvar >= cpi->sf.tx_domain_thresh);
2027
2028 // Check block complexity as part of descision on using quantized
2029 // coefficient optimisation inside the rd loop.
2030 x->block_qcoeff_opt =
2031 cpi->sf.allow_quant_coeff_opt && (logvar <= cpi->sf.quant_opt_thresh);
2032 } else {
2033 x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion;
2034 x->block_qcoeff_opt = cpi->sf.allow_quant_coeff_opt;
2035 }
2036
2037 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
2038 set_segment_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode);
2039 if (rate_in_best_rd < INT_MAX && dist_in_best_rd < INT64_MAX) {
2040 best_rd = vp9_calculate_rd_cost(x->rdmult, x->rddiv, rate_in_best_rd,
2041 dist_in_best_rd);
2042 }
2043
2044 // Find best coding mode & reconstruct the MB so it is available
2045 // as a predictor for MBs that follow in the SB
2046 if (frame_is_intra_only(cm)) {
2047 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
2048 } else {
2049 if (bsize >= BLOCK_8X8) {
2050 if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
2051 vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
2052 ctx, best_rd);
2053 else
2054 vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2055 bsize, ctx, best_rd);
2056 } else {
2057 vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2058 bsize, ctx, best_rd);
2059 }
2060 }
2061
2062 // Examine the resulting rate and for AQ mode 2 make a segment choice.
2063 if ((rd_cost->rate != INT_MAX) && (aq_mode == COMPLEXITY_AQ) &&
2064 (bsize >= BLOCK_16X16) &&
2065 (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
2066 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
2067 vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
2068 }
2069
2070 // TODO(jingning) The rate-distortion optimization flow needs to be
2071 // refactored to provide proper exit/return handle.
2072 if (rd_cost->rate == INT_MAX || rd_cost->dist == INT64_MAX)
2073 rd_cost->rdcost = INT64_MAX;
2074 else
2075 rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2076
2077 x->rdmult = orig_rdmult;
2078
2079 ctx->rate = rd_cost->rate;
2080 ctx->dist = rd_cost->dist;
2081 }
2082 #endif // !CONFIG_REALTIME_ONLY
2083
update_stats(VP9_COMMON * cm,ThreadData * td)2084 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
2085 const MACROBLOCK *x = &td->mb;
2086 const MACROBLOCKD *const xd = &x->e_mbd;
2087 const MODE_INFO *const mi = xd->mi[0];
2088 const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2089 const BLOCK_SIZE bsize = mi->sb_type;
2090
2091 if (!frame_is_intra_only(cm)) {
2092 FRAME_COUNTS *const counts = td->counts;
2093 const int inter_block = is_inter_block(mi);
2094 const int seg_ref_active =
2095 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_REF_FRAME);
2096 if (!seg_ref_active) {
2097 counts->intra_inter[get_intra_inter_context(xd)][inter_block]++;
2098 // If the segment reference feature is enabled we have only a single
2099 // reference frame allowed for the segment so exclude it from
2100 // the reference frame counts used to work out probabilities.
2101 if (inter_block) {
2102 const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
2103 if (cm->reference_mode == REFERENCE_MODE_SELECT)
2104 counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
2105 [has_second_ref(mi)]++;
2106
2107 if (has_second_ref(mi)) {
2108 const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
2109 const int ctx = vp9_get_pred_context_comp_ref_p(cm, xd);
2110 const int bit = mi->ref_frame[!idx] == cm->comp_var_ref[1];
2111 counts->comp_ref[ctx][bit]++;
2112 } else {
2113 counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
2114 [ref0 != LAST_FRAME]++;
2115 if (ref0 != LAST_FRAME)
2116 counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
2117 [ref0 != GOLDEN_FRAME]++;
2118 }
2119 }
2120 }
2121 if (inter_block &&
2122 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP)) {
2123 const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
2124 if (bsize >= BLOCK_8X8) {
2125 const PREDICTION_MODE mode = mi->mode;
2126 ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
2127 } else {
2128 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2129 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2130 int idx, idy;
2131 for (idy = 0; idy < 2; idy += num_4x4_h) {
2132 for (idx = 0; idx < 2; idx += num_4x4_w) {
2133 const int j = idy * 2 + idx;
2134 const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
2135 ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
2136 }
2137 }
2138 }
2139 }
2140 }
2141 }
2142
2143 #if !CONFIG_REALTIME_ONLY
restore_context(MACROBLOCK * const x,int mi_row,int mi_col,ENTROPY_CONTEXT a[16* MAX_MB_PLANE],ENTROPY_CONTEXT l[16* MAX_MB_PLANE],PARTITION_CONTEXT sa[8],PARTITION_CONTEXT sl[8],BLOCK_SIZE bsize)2144 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
2145 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2146 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2147 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2148 BLOCK_SIZE bsize) {
2149 MACROBLOCKD *const xd = &x->e_mbd;
2150 int p;
2151 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2152 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2153 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2154 int mi_height = num_8x8_blocks_high_lookup[bsize];
2155 for (p = 0; p < MAX_MB_PLANE; p++) {
2156 memcpy(xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
2157 a + num_4x4_blocks_wide * p,
2158 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2159 xd->plane[p].subsampling_x);
2160 memcpy(xd->left_context[p] +
2161 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2162 l + num_4x4_blocks_high * p,
2163 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2164 xd->plane[p].subsampling_y);
2165 }
2166 memcpy(xd->above_seg_context + mi_col, sa,
2167 sizeof(*xd->above_seg_context) * mi_width);
2168 memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
2169 sizeof(xd->left_seg_context[0]) * mi_height);
2170 }
2171
save_context(MACROBLOCK * const x,int mi_row,int mi_col,ENTROPY_CONTEXT a[16* MAX_MB_PLANE],ENTROPY_CONTEXT l[16* MAX_MB_PLANE],PARTITION_CONTEXT sa[8],PARTITION_CONTEXT sl[8],BLOCK_SIZE bsize)2172 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
2173 ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2174 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2175 PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2176 BLOCK_SIZE bsize) {
2177 const MACROBLOCKD *const xd = &x->e_mbd;
2178 int p;
2179 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2180 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2181 int mi_width = num_8x8_blocks_wide_lookup[bsize];
2182 int mi_height = num_8x8_blocks_high_lookup[bsize];
2183
2184 // buffer the above/left context information of the block in search.
2185 for (p = 0; p < MAX_MB_PLANE; ++p) {
2186 memcpy(a + num_4x4_blocks_wide * p,
2187 xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
2188 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2189 xd->plane[p].subsampling_x);
2190 memcpy(l + num_4x4_blocks_high * p,
2191 xd->left_context[p] +
2192 ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2193 (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2194 xd->plane[p].subsampling_y);
2195 }
2196 memcpy(sa, xd->above_seg_context + mi_col,
2197 sizeof(*xd->above_seg_context) * mi_width);
2198 memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
2199 sizeof(xd->left_seg_context[0]) * mi_height);
2200 }
2201
encode_b(VP9_COMP * cpi,const TileInfo * const tile,ThreadData * td,TOKENEXTRA ** tp,int mi_row,int mi_col,int output_enabled,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)2202 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile, ThreadData *td,
2203 TOKENEXTRA **tp, int mi_row, int mi_col,
2204 int output_enabled, BLOCK_SIZE bsize,
2205 PICK_MODE_CONTEXT *ctx) {
2206 MACROBLOCK *const x = &td->mb;
2207 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2208
2209 if (cpi->sf.enable_tpl_model &&
2210 (cpi->oxcf.aq_mode == NO_AQ || cpi->oxcf.aq_mode == PERCEPTUAL_AQ)) {
2211 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2212 x->rdmult = x->cb_rdmult;
2213 if (oxcf->tuning == VP8_TUNE_SSIM) {
2214 set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
2215 }
2216 }
2217
2218 update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
2219 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2220
2221 if (output_enabled) {
2222 update_stats(&cpi->common, td);
2223
2224 (*tp)->token = EOSB_TOKEN;
2225 (*tp)++;
2226 }
2227 }
2228
encode_sb(VP9_COMP * cpi,ThreadData * td,const TileInfo * const tile,TOKENEXTRA ** tp,int mi_row,int mi_col,int output_enabled,BLOCK_SIZE bsize,PC_TREE * pc_tree)2229 static void encode_sb(VP9_COMP *cpi, ThreadData *td, const TileInfo *const tile,
2230 TOKENEXTRA **tp, int mi_row, int mi_col,
2231 int output_enabled, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2232 VP9_COMMON *const cm = &cpi->common;
2233 MACROBLOCK *const x = &td->mb;
2234 MACROBLOCKD *const xd = &x->e_mbd;
2235
2236 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2237 int ctx;
2238 PARTITION_TYPE partition;
2239 BLOCK_SIZE subsize = bsize;
2240
2241 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2242
2243 if (bsize >= BLOCK_8X8) {
2244 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2245 subsize = get_subsize(bsize, pc_tree->partitioning);
2246 } else {
2247 ctx = 0;
2248 subsize = BLOCK_4X4;
2249 }
2250
2251 partition = partition_lookup[bsl][subsize];
2252 if (output_enabled && bsize != BLOCK_4X4)
2253 td->counts->partition[ctx][partition]++;
2254
2255 switch (partition) {
2256 case PARTITION_NONE:
2257 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2258 &pc_tree->none);
2259 break;
2260 case PARTITION_VERT:
2261 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2262 &pc_tree->vertical[0]);
2263 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2264 encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
2265 subsize, &pc_tree->vertical[1]);
2266 }
2267 break;
2268 case PARTITION_HORZ:
2269 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2270 &pc_tree->horizontal[0]);
2271 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2272 encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
2273 subsize, &pc_tree->horizontal[1]);
2274 }
2275 break;
2276 default:
2277 assert(partition == PARTITION_SPLIT);
2278 if (bsize == BLOCK_8X8) {
2279 encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2280 pc_tree->leaf_split[0]);
2281 } else {
2282 encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2283 pc_tree->split[0]);
2284 encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2285 subsize, pc_tree->split[1]);
2286 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2287 subsize, pc_tree->split[2]);
2288 encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
2289 subsize, pc_tree->split[3]);
2290 }
2291 break;
2292 }
2293
2294 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2295 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2296 }
2297 #endif // !CONFIG_REALTIME_ONLY
2298
2299 // Check to see if the given partition size is allowed for a specified number
2300 // of 8x8 block rows and columns remaining in the image.
2301 // If not then return the largest allowed partition size
find_partition_size(BLOCK_SIZE bsize,int rows_left,int cols_left,int * bh,int * bw)2302 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
2303 int cols_left, int *bh, int *bw) {
2304 if (rows_left <= 0 || cols_left <= 0) {
2305 return VPXMIN(bsize, BLOCK_8X8);
2306 } else {
2307 for (; bsize > 0; bsize -= 3) {
2308 *bh = num_8x8_blocks_high_lookup[bsize];
2309 *bw = num_8x8_blocks_wide_lookup[bsize];
2310 if ((*bh <= rows_left) && (*bw <= cols_left)) {
2311 break;
2312 }
2313 }
2314 }
2315 return bsize;
2316 }
2317
set_partial_b64x64_partition(MODE_INFO * mi,int mis,int bh_in,int bw_in,int row8x8_remaining,int col8x8_remaining,BLOCK_SIZE bsize,MODE_INFO ** mi_8x8)2318 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis, int bh_in,
2319 int bw_in, int row8x8_remaining,
2320 int col8x8_remaining, BLOCK_SIZE bsize,
2321 MODE_INFO **mi_8x8) {
2322 int bh = bh_in;
2323 int r, c;
2324 for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
2325 int bw = bw_in;
2326 for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
2327 const int index = r * mis + c;
2328 mi_8x8[index] = mi + index;
2329 mi_8x8[index]->sb_type = find_partition_size(
2330 bsize, row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
2331 }
2332 }
2333 }
2334
2335 // This function attempts to set all mode info entries in a given SB64
2336 // to the same block partition size.
2337 // However, at the bottom and right borders of the image the requested size
2338 // may not be allowed in which case this code attempts to choose the largest
2339 // allowable partition.
set_fixed_partitioning(VP9_COMP * cpi,const TileInfo * const tile,MODE_INFO ** mi_8x8,int mi_row,int mi_col,BLOCK_SIZE bsize)2340 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
2341 MODE_INFO **mi_8x8, int mi_row, int mi_col,
2342 BLOCK_SIZE bsize) {
2343 VP9_COMMON *const cm = &cpi->common;
2344 const int mis = cm->mi_stride;
2345 const int row8x8_remaining = tile->mi_row_end - mi_row;
2346 const int col8x8_remaining = tile->mi_col_end - mi_col;
2347 int block_row, block_col;
2348 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2349 int bh = num_8x8_blocks_high_lookup[bsize];
2350 int bw = num_8x8_blocks_wide_lookup[bsize];
2351
2352 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2353
2354 // Apply the requested partition size to the SB64 if it is all "in image"
2355 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2356 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2357 for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
2358 for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
2359 int index = block_row * mis + block_col;
2360 mi_8x8[index] = mi_upper_left + index;
2361 mi_8x8[index]->sb_type = bsize;
2362 }
2363 }
2364 } else {
2365 // Else this is a partial SB64.
2366 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2367 col8x8_remaining, bsize, mi_8x8);
2368 }
2369 }
2370
2371 static const struct {
2372 int row;
2373 int col;
2374 } coord_lookup[16] = {
2375 // 32x32 index = 0
2376 { 0, 0 },
2377 { 0, 2 },
2378 { 2, 0 },
2379 { 2, 2 },
2380 // 32x32 index = 1
2381 { 0, 4 },
2382 { 0, 6 },
2383 { 2, 4 },
2384 { 2, 6 },
2385 // 32x32 index = 2
2386 { 4, 0 },
2387 { 4, 2 },
2388 { 6, 0 },
2389 { 6, 2 },
2390 // 32x32 index = 3
2391 { 4, 4 },
2392 { 4, 6 },
2393 { 6, 4 },
2394 { 6, 6 },
2395 };
2396
set_source_var_based_partition(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCK * const x,MODE_INFO ** mi_8x8,int mi_row,int mi_col)2397 static void set_source_var_based_partition(VP9_COMP *cpi,
2398 const TileInfo *const tile,
2399 MACROBLOCK *const x,
2400 MODE_INFO **mi_8x8, int mi_row,
2401 int mi_col) {
2402 VP9_COMMON *const cm = &cpi->common;
2403 const int mis = cm->mi_stride;
2404 const int row8x8_remaining = tile->mi_row_end - mi_row;
2405 const int col8x8_remaining = tile->mi_col_end - mi_col;
2406 MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2407
2408 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
2409
2410 assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2411
2412 // In-image SB64
2413 if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2414 (row8x8_remaining >= MI_BLOCK_SIZE)) {
2415 int i, j;
2416 int index;
2417 diff d32[4];
2418 const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
2419 int is_larger_better = 0;
2420 int use32x32 = 0;
2421 unsigned int thr = cpi->source_var_thresh;
2422
2423 memset(d32, 0, 4 * sizeof(diff));
2424
2425 for (i = 0; i < 4; i++) {
2426 diff *d16[4];
2427
2428 for (j = 0; j < 4; j++) {
2429 int b_mi_row = coord_lookup[i * 4 + j].row;
2430 int b_mi_col = coord_lookup[i * 4 + j].col;
2431 int boffset = b_mi_row / 2 * cm->mb_cols + b_mi_col / 2;
2432
2433 d16[j] = cpi->source_diff_var + offset + boffset;
2434
2435 index = b_mi_row * mis + b_mi_col;
2436 mi_8x8[index] = mi_upper_left + index;
2437 mi_8x8[index]->sb_type = BLOCK_16X16;
2438
2439 // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
2440 // size to further improve quality.
2441 }
2442
2443 is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
2444 (d16[2]->var < thr) && (d16[3]->var < thr);
2445
2446 // Use 32x32 partition
2447 if (is_larger_better) {
2448 use32x32 += 1;
2449
2450 for (j = 0; j < 4; j++) {
2451 d32[i].sse += d16[j]->sse;
2452 d32[i].sum += d16[j]->sum;
2453 }
2454
2455 d32[i].var =
2456 (unsigned int)(d32[i].sse -
2457 (unsigned int)(((int64_t)d32[i].sum * d32[i].sum) >>
2458 10));
2459
2460 index = coord_lookup[i * 4].row * mis + coord_lookup[i * 4].col;
2461 mi_8x8[index] = mi_upper_left + index;
2462 mi_8x8[index]->sb_type = BLOCK_32X32;
2463 }
2464 }
2465
2466 if (use32x32 == 4) {
2467 thr <<= 1;
2468 is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
2469 (d32[2].var < thr) && (d32[3].var < thr);
2470
2471 // Use 64x64 partition
2472 if (is_larger_better) {
2473 mi_8x8[0] = mi_upper_left;
2474 mi_8x8[0]->sb_type = BLOCK_64X64;
2475 }
2476 }
2477 } else { // partial in-image SB64
2478 int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
2479 int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
2480 set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2481 col8x8_remaining, BLOCK_16X16, mi_8x8);
2482 }
2483 }
2484
update_state_rt(VP9_COMP * cpi,ThreadData * td,PICK_MODE_CONTEXT * ctx,int mi_row,int mi_col,int bsize)2485 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
2486 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
2487 int bsize) {
2488 VP9_COMMON *const cm = &cpi->common;
2489 MACROBLOCK *const x = &td->mb;
2490 MACROBLOCKD *const xd = &x->e_mbd;
2491 MODE_INFO *const mi = xd->mi[0];
2492 struct macroblock_plane *const p = x->plane;
2493 const struct segmentation *const seg = &cm->seg;
2494 const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
2495 const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
2496 const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
2497 const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
2498
2499 *(xd->mi[0]) = ctx->mic;
2500 *(x->mbmi_ext) = ctx->mbmi_ext;
2501
2502 if (seg->enabled && (cpi->oxcf.aq_mode != NO_AQ || cpi->roi.enabled ||
2503 cpi->active_map.enabled)) {
2504 // Setting segmentation map for cyclic_refresh.
2505 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
2506 cpi->cyclic_refresh->content_mode) {
2507 vp9_cyclic_refresh_update_segment(cpi, mi, mi_row, mi_col, bsize,
2508 ctx->rate, ctx->dist, x->skip, p);
2509 } else {
2510 const uint8_t *const map =
2511 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
2512 mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
2513 }
2514 vp9_init_plane_quantizers(cpi, x);
2515 }
2516
2517 if (is_inter_block(mi)) {
2518 vp9_update_mv_count(td);
2519 if (cm->interp_filter == SWITCHABLE) {
2520 const int pred_ctx = get_pred_context_switchable_interp(xd);
2521 ++td->counts->switchable_interp[pred_ctx][mi->interp_filter];
2522 }
2523
2524 if (mi->sb_type < BLOCK_8X8) {
2525 mi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
2526 mi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
2527 }
2528 }
2529
2530 if (cm->use_prev_frame_mvs || !cm->error_resilient_mode ||
2531 (cpi->svc.use_base_mv && cpi->svc.number_spatial_layers > 1 &&
2532 cpi->svc.spatial_layer_id != cpi->svc.number_spatial_layers - 1)) {
2533 MV_REF *const frame_mvs =
2534 cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
2535 int w, h;
2536
2537 for (h = 0; h < y_mis; ++h) {
2538 MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
2539 for (w = 0; w < x_mis; ++w) {
2540 MV_REF *const mv = frame_mv + w;
2541 mv->ref_frame[0] = mi->ref_frame[0];
2542 mv->ref_frame[1] = mi->ref_frame[1];
2543 mv->mv[0].as_int = mi->mv[0].as_int;
2544 mv->mv[1].as_int = mi->mv[1].as_int;
2545 }
2546 }
2547 }
2548
2549 x->skip = ctx->skip;
2550 x->skip_txfm[0] = (mi->segment_id || xd->lossless) ? 0 : ctx->skip_txfm[0];
2551 }
2552
encode_b_rt(VP9_COMP * cpi,ThreadData * td,const TileInfo * const tile,TOKENEXTRA ** tp,int mi_row,int mi_col,int output_enabled,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)2553 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
2554 const TileInfo *const tile, TOKENEXTRA **tp, int mi_row,
2555 int mi_col, int output_enabled, BLOCK_SIZE bsize,
2556 PICK_MODE_CONTEXT *ctx) {
2557 MACROBLOCK *const x = &td->mb;
2558 set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2559 update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
2560
2561 encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2562 update_stats(&cpi->common, td);
2563
2564 (*tp)->token = EOSB_TOKEN;
2565 (*tp)++;
2566 }
2567
encode_sb_rt(VP9_COMP * cpi,ThreadData * td,const TileInfo * const tile,TOKENEXTRA ** tp,int mi_row,int mi_col,int output_enabled,BLOCK_SIZE bsize,PC_TREE * pc_tree)2568 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
2569 const TileInfo *const tile, TOKENEXTRA **tp,
2570 int mi_row, int mi_col, int output_enabled,
2571 BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2572 VP9_COMMON *const cm = &cpi->common;
2573 MACROBLOCK *const x = &td->mb;
2574 MACROBLOCKD *const xd = &x->e_mbd;
2575
2576 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2577 int ctx;
2578 PARTITION_TYPE partition;
2579 BLOCK_SIZE subsize;
2580
2581 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2582
2583 if (bsize >= BLOCK_8X8) {
2584 const int idx_str = xd->mi_stride * mi_row + mi_col;
2585 MODE_INFO **mi_8x8 = cm->mi_grid_visible + idx_str;
2586 ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2587 subsize = mi_8x8[0]->sb_type;
2588 } else {
2589 ctx = 0;
2590 subsize = BLOCK_4X4;
2591 }
2592
2593 partition = partition_lookup[bsl][subsize];
2594 if (output_enabled && bsize != BLOCK_4X4)
2595 td->counts->partition[ctx][partition]++;
2596
2597 switch (partition) {
2598 case PARTITION_NONE:
2599 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2600 &pc_tree->none);
2601 break;
2602 case PARTITION_VERT:
2603 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2604 &pc_tree->vertical[0]);
2605 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2606 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2607 subsize, &pc_tree->vertical[1]);
2608 }
2609 break;
2610 case PARTITION_HORZ:
2611 encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2612 &pc_tree->horizontal[0]);
2613 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2614 encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2615 subsize, &pc_tree->horizontal[1]);
2616 }
2617 break;
2618 default:
2619 assert(partition == PARTITION_SPLIT);
2620 subsize = get_subsize(bsize, PARTITION_SPLIT);
2621 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2622 pc_tree->split[0]);
2623 encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2624 subsize, pc_tree->split[1]);
2625 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2626 subsize, pc_tree->split[2]);
2627 encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
2628 output_enabled, subsize, pc_tree->split[3]);
2629 break;
2630 }
2631
2632 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2633 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2634 }
2635
2636 #if !CONFIG_REALTIME_ONLY
rd_use_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,MODE_INFO ** mi_8x8,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,int * rate,int64_t * dist,int do_recon,PC_TREE * pc_tree)2637 static void rd_use_partition(VP9_COMP *cpi, ThreadData *td,
2638 TileDataEnc *tile_data, MODE_INFO **mi_8x8,
2639 TOKENEXTRA **tp, int mi_row, int mi_col,
2640 BLOCK_SIZE bsize, int *rate, int64_t *dist,
2641 int do_recon, PC_TREE *pc_tree) {
2642 VP9_COMMON *const cm = &cpi->common;
2643 TileInfo *const tile_info = &tile_data->tile_info;
2644 MACROBLOCK *const x = &td->mb;
2645 MACROBLOCKD *const xd = &x->e_mbd;
2646 const int mis = cm->mi_stride;
2647 const int bsl = b_width_log2_lookup[bsize];
2648 const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
2649 const int bss = (1 << bsl) / 4;
2650 int i, pl;
2651 PARTITION_TYPE partition = PARTITION_NONE;
2652 BLOCK_SIZE subsize;
2653 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2654 PARTITION_CONTEXT sl[8], sa[8];
2655 RD_COST last_part_rdc, none_rdc, chosen_rdc;
2656 BLOCK_SIZE sub_subsize = BLOCK_4X4;
2657 int splits_below = 0;
2658 BLOCK_SIZE bs_type = mi_8x8[0]->sb_type;
2659 int do_partition_search = 1;
2660 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2661
2662 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2663
2664 assert(num_4x4_blocks_wide_lookup[bsize] ==
2665 num_4x4_blocks_high_lookup[bsize]);
2666
2667 vp9_rd_cost_reset(&last_part_rdc);
2668 vp9_rd_cost_reset(&none_rdc);
2669 vp9_rd_cost_reset(&chosen_rdc);
2670
2671 partition = partition_lookup[bsl][bs_type];
2672 subsize = get_subsize(bsize, partition);
2673
2674 pc_tree->partitioning = partition;
2675 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2676
2677 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ) {
2678 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2679 x->mb_energy = vp9_block_energy(cpi, x, bsize);
2680 }
2681
2682 if (do_partition_search &&
2683 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2684 cpi->sf.adjust_partitioning_from_last_frame) {
2685 // Check if any of the sub blocks are further split.
2686 if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
2687 sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
2688 splits_below = 1;
2689 for (i = 0; i < 4; i++) {
2690 int jj = i >> 1, ii = i & 0x01;
2691 MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
2692 if (this_mi && this_mi->sb_type >= sub_subsize) {
2693 splits_below = 0;
2694 }
2695 }
2696 }
2697
2698 // If partition is not none try none unless each of the 4 splits are split
2699 // even further..
2700 if (partition != PARTITION_NONE && !splits_below &&
2701 mi_row + (mi_step >> 1) < cm->mi_rows &&
2702 mi_col + (mi_step >> 1) < cm->mi_cols) {
2703 pc_tree->partitioning = PARTITION_NONE;
2704 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize, ctx,
2705 INT_MAX, INT64_MAX);
2706
2707 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2708
2709 if (none_rdc.rate < INT_MAX) {
2710 none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2711 none_rdc.rdcost =
2712 RDCOST(x->rdmult, x->rddiv, none_rdc.rate, none_rdc.dist);
2713 }
2714
2715 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2716 mi_8x8[0]->sb_type = bs_type;
2717 pc_tree->partitioning = partition;
2718 }
2719 }
2720
2721 switch (partition) {
2722 case PARTITION_NONE:
2723 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc, bsize,
2724 ctx, INT_MAX, INT64_MAX);
2725 break;
2726 case PARTITION_HORZ:
2727 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
2728 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2729 subsize, &pc_tree->horizontal[0], INT_MAX, INT64_MAX);
2730 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2731 mi_row + (mi_step >> 1) < cm->mi_rows) {
2732 RD_COST tmp_rdc;
2733 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2734 vp9_rd_cost_init(&tmp_rdc);
2735 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2736 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2737 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
2738 rd_pick_sb_modes(cpi, tile_data, x, mi_row + (mi_step >> 1), mi_col,
2739 &tmp_rdc, subsize, &pc_tree->horizontal[1], INT_MAX,
2740 INT64_MAX);
2741 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2742 vp9_rd_cost_reset(&last_part_rdc);
2743 break;
2744 }
2745 last_part_rdc.rate += tmp_rdc.rate;
2746 last_part_rdc.dist += tmp_rdc.dist;
2747 last_part_rdc.rdcost += tmp_rdc.rdcost;
2748 }
2749 break;
2750 case PARTITION_VERT:
2751 pc_tree->vertical[0].skip_ref_frame_mask = 0;
2752 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2753 subsize, &pc_tree->vertical[0], INT_MAX, INT64_MAX);
2754 if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2755 mi_col + (mi_step >> 1) < cm->mi_cols) {
2756 RD_COST tmp_rdc;
2757 PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
2758 vp9_rd_cost_init(&tmp_rdc);
2759 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2760 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2761 pc_tree->vertical[bsize > BLOCK_8X8].skip_ref_frame_mask = 0;
2762 rd_pick_sb_modes(
2763 cpi, tile_data, x, mi_row, mi_col + (mi_step >> 1), &tmp_rdc,
2764 subsize, &pc_tree->vertical[bsize > BLOCK_8X8], INT_MAX, INT64_MAX);
2765 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2766 vp9_rd_cost_reset(&last_part_rdc);
2767 break;
2768 }
2769 last_part_rdc.rate += tmp_rdc.rate;
2770 last_part_rdc.dist += tmp_rdc.dist;
2771 last_part_rdc.rdcost += tmp_rdc.rdcost;
2772 }
2773 break;
2774 default:
2775 assert(partition == PARTITION_SPLIT);
2776 if (bsize == BLOCK_8X8) {
2777 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2778 subsize, pc_tree->leaf_split[0], INT_MAX, INT64_MAX);
2779 break;
2780 }
2781 last_part_rdc.rate = 0;
2782 last_part_rdc.dist = 0;
2783 last_part_rdc.rdcost = 0;
2784 for (i = 0; i < 4; i++) {
2785 int x_idx = (i & 1) * (mi_step >> 1);
2786 int y_idx = (i >> 1) * (mi_step >> 1);
2787 int jj = i >> 1, ii = i & 0x01;
2788 RD_COST tmp_rdc;
2789 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2790 continue;
2791
2792 vp9_rd_cost_init(&tmp_rdc);
2793 rd_use_partition(cpi, td, tile_data, mi_8x8 + jj * bss * mis + ii * bss,
2794 tp, mi_row + y_idx, mi_col + x_idx, subsize,
2795 &tmp_rdc.rate, &tmp_rdc.dist, i != 3,
2796 pc_tree->split[i]);
2797 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2798 vp9_rd_cost_reset(&last_part_rdc);
2799 break;
2800 }
2801 last_part_rdc.rate += tmp_rdc.rate;
2802 last_part_rdc.dist += tmp_rdc.dist;
2803 }
2804 break;
2805 }
2806
2807 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2808 if (last_part_rdc.rate < INT_MAX) {
2809 last_part_rdc.rate += cpi->partition_cost[pl][partition];
2810 last_part_rdc.rdcost =
2811 RDCOST(x->rdmult, x->rddiv, last_part_rdc.rate, last_part_rdc.dist);
2812 }
2813
2814 if (do_partition_search && cpi->sf.adjust_partitioning_from_last_frame &&
2815 cpi->sf.partition_search_type == SEARCH_PARTITION &&
2816 partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
2817 (mi_row + mi_step < cm->mi_rows ||
2818 mi_row + (mi_step >> 1) == cm->mi_rows) &&
2819 (mi_col + mi_step < cm->mi_cols ||
2820 mi_col + (mi_step >> 1) == cm->mi_cols)) {
2821 BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2822 chosen_rdc.rate = 0;
2823 chosen_rdc.dist = 0;
2824 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2825 pc_tree->partitioning = PARTITION_SPLIT;
2826
2827 // Split partition.
2828 for (i = 0; i < 4; i++) {
2829 int x_idx = (i & 1) * (mi_step >> 1);
2830 int y_idx = (i >> 1) * (mi_step >> 1);
2831 RD_COST tmp_rdc;
2832 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2833 PARTITION_CONTEXT sl[8], sa[8];
2834
2835 if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2836 continue;
2837
2838 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2839 pc_tree->split[i]->partitioning = PARTITION_NONE;
2840 rd_pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2841 &tmp_rdc, split_subsize, &pc_tree->split[i]->none,
2842 INT_MAX, INT64_MAX);
2843
2844 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2845
2846 if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2847 vp9_rd_cost_reset(&chosen_rdc);
2848 break;
2849 }
2850
2851 chosen_rdc.rate += tmp_rdc.rate;
2852 chosen_rdc.dist += tmp_rdc.dist;
2853
2854 if (i != 3)
2855 encode_sb(cpi, td, tile_info, tp, mi_row + y_idx, mi_col + x_idx, 0,
2856 split_subsize, pc_tree->split[i]);
2857
2858 pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2859 split_subsize);
2860 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2861 }
2862 pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2863 if (chosen_rdc.rate < INT_MAX) {
2864 chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2865 chosen_rdc.rdcost =
2866 RDCOST(x->rdmult, x->rddiv, chosen_rdc.rate, chosen_rdc.dist);
2867 }
2868 }
2869
2870 // If last_part is better set the partitioning to that.
2871 if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2872 mi_8x8[0]->sb_type = bsize;
2873 if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2874 chosen_rdc = last_part_rdc;
2875 }
2876 // If none was better set the partitioning to that.
2877 if (none_rdc.rdcost < chosen_rdc.rdcost) {
2878 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2879 chosen_rdc = none_rdc;
2880 }
2881
2882 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2883
2884 // We must have chosen a partitioning and encoding or we'll fail later on.
2885 // No other opportunities for success.
2886 if (bsize == BLOCK_64X64)
2887 assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2888
2889 if (do_recon) {
2890 int output_enabled = (bsize == BLOCK_64X64);
2891 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2892 pc_tree);
2893 }
2894
2895 *rate = chosen_rdc.rate;
2896 *dist = chosen_rdc.dist;
2897 }
2898
2899 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2900 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2901 BLOCK_4X4, BLOCK_8X8, BLOCK_8X8, BLOCK_8X8, BLOCK_16X16,
2902 BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
2903 };
2904
2905 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2906 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2907 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2908 BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
2909 };
2910
2911 // Look at all the mode_info entries for blocks that are part of this
2912 // partition and find the min and max values for sb_type.
2913 // At the moment this is designed to work on a 64x64 SB but could be
2914 // adjusted to use a size parameter.
2915 //
2916 // The min and max are assumed to have been initialized prior to calling this
2917 // function so repeat calls can accumulate a min and max of more than one sb64.
get_sb_partition_size_range(MACROBLOCKD * xd,MODE_INFO ** mi_8x8,BLOCK_SIZE * min_block_size,BLOCK_SIZE * max_block_size,int bs_hist[BLOCK_SIZES])2918 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2919 BLOCK_SIZE *min_block_size,
2920 BLOCK_SIZE *max_block_size,
2921 int bs_hist[BLOCK_SIZES]) {
2922 int sb_width_in_blocks = MI_BLOCK_SIZE;
2923 int sb_height_in_blocks = MI_BLOCK_SIZE;
2924 int i, j;
2925 int index = 0;
2926
2927 // Check the sb_type for each block that belongs to this region.
2928 for (i = 0; i < sb_height_in_blocks; ++i) {
2929 for (j = 0; j < sb_width_in_blocks; ++j) {
2930 MODE_INFO *mi = mi_8x8[index + j];
2931 BLOCK_SIZE sb_type = mi ? mi->sb_type : 0;
2932 bs_hist[sb_type]++;
2933 *min_block_size = VPXMIN(*min_block_size, sb_type);
2934 *max_block_size = VPXMAX(*max_block_size, sb_type);
2935 }
2936 index += xd->mi_stride;
2937 }
2938 }
2939
2940 // Next square block size less or equal than current block size.
2941 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2942 BLOCK_4X4, BLOCK_4X4, BLOCK_4X4, BLOCK_8X8, BLOCK_8X8,
2943 BLOCK_8X8, BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2944 BLOCK_32X32, BLOCK_32X32, BLOCK_64X64
2945 };
2946
2947 // Look at neighboring blocks and set a min and max partition size based on
2948 // what they chose.
rd_auto_partition_range(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCKD * const xd,int mi_row,int mi_col,BLOCK_SIZE * min_block_size,BLOCK_SIZE * max_block_size)2949 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2950 MACROBLOCKD *const xd, int mi_row,
2951 int mi_col, BLOCK_SIZE *min_block_size,
2952 BLOCK_SIZE *max_block_size) {
2953 VP9_COMMON *const cm = &cpi->common;
2954 MODE_INFO **mi = xd->mi;
2955 const int left_in_image = !!xd->left_mi;
2956 const int above_in_image = !!xd->above_mi;
2957 const int row8x8_remaining = tile->mi_row_end - mi_row;
2958 const int col8x8_remaining = tile->mi_col_end - mi_col;
2959 int bh, bw;
2960 BLOCK_SIZE min_size = BLOCK_4X4;
2961 BLOCK_SIZE max_size = BLOCK_64X64;
2962 int bs_hist[BLOCK_SIZES] = { 0 };
2963
2964 // Trap case where we do not have a prediction.
2965 if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2966 // Default "min to max" and "max to min"
2967 min_size = BLOCK_64X64;
2968 max_size = BLOCK_4X4;
2969
2970 // NOTE: each call to get_sb_partition_size_range() uses the previous
2971 // passed in values for min and max as a starting point.
2972 // Find the min and max partition used in previous frame at this location
2973 if (cm->frame_type != KEY_FRAME) {
2974 MODE_INFO **prev_mi =
2975 &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2976 get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2977 }
2978 // Find the min and max partition sizes used in the left SB64
2979 if (left_in_image) {
2980 MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2981 get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2982 bs_hist);
2983 }
2984 // Find the min and max partition sizes used in the above SB64.
2985 if (above_in_image) {
2986 MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2987 get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2988 bs_hist);
2989 }
2990
2991 // Adjust observed min and max for "relaxed" auto partition case.
2992 if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2993 min_size = min_partition_size[min_size];
2994 max_size = max_partition_size[max_size];
2995 }
2996 }
2997
2998 // Check border cases where max and min from neighbors may not be legal.
2999 max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
3000 &bh, &bw);
3001 // Test for blocks at the edge of the active image.
3002 // This may be the actual edge of the image or where there are formatting
3003 // bars.
3004 if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
3005 min_size = BLOCK_4X4;
3006 } else {
3007 min_size =
3008 VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
3009 }
3010
3011 // When use_square_partition_only is true, make sure at least one square
3012 // partition is allowed by selecting the next smaller square size as
3013 // *min_block_size.
3014 if (cpi->sf.use_square_partition_only &&
3015 next_square_size[max_size] < min_size) {
3016 min_size = next_square_size[max_size];
3017 }
3018
3019 *min_block_size = min_size;
3020 *max_block_size = max_size;
3021 }
3022
3023 // TODO(jingning) refactor functions setting partition search range
set_partition_range(VP9_COMMON * cm,MACROBLOCKD * xd,int mi_row,int mi_col,BLOCK_SIZE bsize,BLOCK_SIZE * min_bs,BLOCK_SIZE * max_bs)3024 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd, int mi_row,
3025 int mi_col, BLOCK_SIZE bsize,
3026 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
3027 int mi_width = num_8x8_blocks_wide_lookup[bsize];
3028 int mi_height = num_8x8_blocks_high_lookup[bsize];
3029 int idx, idy;
3030
3031 MODE_INFO *mi;
3032 const int idx_str = cm->mi_stride * mi_row + mi_col;
3033 MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
3034 BLOCK_SIZE bs, min_size, max_size;
3035
3036 min_size = BLOCK_64X64;
3037 max_size = BLOCK_4X4;
3038
3039 if (prev_mi) {
3040 for (idy = 0; idy < mi_height; ++idy) {
3041 for (idx = 0; idx < mi_width; ++idx) {
3042 mi = prev_mi[idy * cm->mi_stride + idx];
3043 bs = mi ? mi->sb_type : bsize;
3044 min_size = VPXMIN(min_size, bs);
3045 max_size = VPXMAX(max_size, bs);
3046 }
3047 }
3048 }
3049
3050 if (xd->left_mi) {
3051 for (idy = 0; idy < mi_height; ++idy) {
3052 mi = xd->mi[idy * cm->mi_stride - 1];
3053 bs = mi ? mi->sb_type : bsize;
3054 min_size = VPXMIN(min_size, bs);
3055 max_size = VPXMAX(max_size, bs);
3056 }
3057 }
3058
3059 if (xd->above_mi) {
3060 for (idx = 0; idx < mi_width; ++idx) {
3061 mi = xd->mi[idx - cm->mi_stride];
3062 bs = mi ? mi->sb_type : bsize;
3063 min_size = VPXMIN(min_size, bs);
3064 max_size = VPXMAX(max_size, bs);
3065 }
3066 }
3067
3068 if (min_size == max_size) {
3069 min_size = min_partition_size[min_size];
3070 max_size = max_partition_size[max_size];
3071 }
3072
3073 *min_bs = min_size;
3074 *max_bs = max_size;
3075 }
3076 #endif // !CONFIG_REALTIME_ONLY
3077
store_pred_mv(MACROBLOCK * x,PICK_MODE_CONTEXT * ctx)3078 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3079 memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
3080 }
3081
load_pred_mv(MACROBLOCK * x,PICK_MODE_CONTEXT * ctx)3082 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
3083 memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
3084 }
3085
3086 // Calculate prediction based on the given input features and neural net config.
3087 // Assume there are no more than NN_MAX_NODES_PER_LAYER nodes in each hidden
3088 // layer.
nn_predict(const float * features,const NN_CONFIG * nn_config,float * output)3089 static void nn_predict(const float *features, const NN_CONFIG *nn_config,
3090 float *output) {
3091 int num_input_nodes = nn_config->num_inputs;
3092 int buf_index = 0;
3093 float buf[2][NN_MAX_NODES_PER_LAYER];
3094 const float *input_nodes = features;
3095
3096 // Propagate hidden layers.
3097 const int num_layers = nn_config->num_hidden_layers;
3098 int layer, node, i;
3099 assert(num_layers <= NN_MAX_HIDDEN_LAYERS);
3100 for (layer = 0; layer < num_layers; ++layer) {
3101 const float *weights = nn_config->weights[layer];
3102 const float *bias = nn_config->bias[layer];
3103 float *output_nodes = buf[buf_index];
3104 const int num_output_nodes = nn_config->num_hidden_nodes[layer];
3105 assert(num_output_nodes < NN_MAX_NODES_PER_LAYER);
3106 for (node = 0; node < num_output_nodes; ++node) {
3107 float val = 0.0f;
3108 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3109 val += bias[node];
3110 // ReLU as activation function.
3111 val = VPXMAX(val, 0.0f);
3112 output_nodes[node] = val;
3113 weights += num_input_nodes;
3114 }
3115 num_input_nodes = num_output_nodes;
3116 input_nodes = output_nodes;
3117 buf_index = 1 - buf_index;
3118 }
3119
3120 // Final output layer.
3121 {
3122 const float *weights = nn_config->weights[num_layers];
3123 for (node = 0; node < nn_config->num_outputs; ++node) {
3124 const float *bias = nn_config->bias[num_layers];
3125 float val = 0.0f;
3126 for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3127 output[node] = val + bias[node];
3128 weights += num_input_nodes;
3129 }
3130 }
3131 }
3132
3133 #if !CONFIG_REALTIME_ONLY
3134 #define FEATURES 7
3135 // Machine-learning based partition search early termination.
3136 // Return 1 to skip split and rect partitions.
ml_pruning_partition(VP9_COMMON * const cm,MACROBLOCKD * const xd,PICK_MODE_CONTEXT * ctx,int mi_row,int mi_col,BLOCK_SIZE bsize)3137 static int ml_pruning_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
3138 PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
3139 BLOCK_SIZE bsize) {
3140 const int mag_mv =
3141 abs(ctx->mic.mv[0].as_mv.col) + abs(ctx->mic.mv[0].as_mv.row);
3142 const int left_in_image = !!xd->left_mi;
3143 const int above_in_image = !!xd->above_mi;
3144 MODE_INFO **prev_mi =
3145 &cm->prev_mi_grid_visible[mi_col + cm->mi_stride * mi_row];
3146 int above_par = 0; // above_partitioning
3147 int left_par = 0; // left_partitioning
3148 int last_par = 0; // last_partitioning
3149 int offset = 0;
3150 int i;
3151 BLOCK_SIZE context_size;
3152 const NN_CONFIG *nn_config = NULL;
3153 const float *mean, *sd, *linear_weights;
3154 float nn_score, linear_score;
3155 float features[FEATURES];
3156
3157 assert(b_width_log2_lookup[bsize] == b_height_log2_lookup[bsize]);
3158 vpx_clear_system_state();
3159
3160 switch (bsize) {
3161 case BLOCK_64X64:
3162 offset = 0;
3163 nn_config = &vp9_partition_nnconfig_64x64;
3164 break;
3165 case BLOCK_32X32:
3166 offset = 8;
3167 nn_config = &vp9_partition_nnconfig_32x32;
3168 break;
3169 case BLOCK_16X16:
3170 offset = 16;
3171 nn_config = &vp9_partition_nnconfig_16x16;
3172 break;
3173 default: assert(0 && "Unexpected block size."); return 0;
3174 }
3175
3176 if (above_in_image) {
3177 context_size = xd->above_mi->sb_type;
3178 if (context_size < bsize)
3179 above_par = 2;
3180 else if (context_size == bsize)
3181 above_par = 1;
3182 }
3183
3184 if (left_in_image) {
3185 context_size = xd->left_mi->sb_type;
3186 if (context_size < bsize)
3187 left_par = 2;
3188 else if (context_size == bsize)
3189 left_par = 1;
3190 }
3191
3192 if (prev_mi) {
3193 context_size = prev_mi[0]->sb_type;
3194 if (context_size < bsize)
3195 last_par = 2;
3196 else if (context_size == bsize)
3197 last_par = 1;
3198 }
3199
3200 mean = &vp9_partition_feature_mean[offset];
3201 sd = &vp9_partition_feature_std[offset];
3202 features[0] = ((float)ctx->rate - mean[0]) / sd[0];
3203 features[1] = ((float)ctx->dist - mean[1]) / sd[1];
3204 features[2] = ((float)mag_mv / 2 - mean[2]) * sd[2];
3205 features[3] = ((float)(left_par + above_par) / 2 - mean[3]) * sd[3];
3206 features[4] = ((float)ctx->sum_y_eobs - mean[4]) / sd[4];
3207 features[5] = ((float)cm->base_qindex - mean[5]) * sd[5];
3208 features[6] = ((float)last_par - mean[6]) * sd[6];
3209
3210 // Predict using linear model.
3211 linear_weights = &vp9_partition_linear_weights[offset];
3212 linear_score = linear_weights[FEATURES];
3213 for (i = 0; i < FEATURES; ++i)
3214 linear_score += linear_weights[i] * features[i];
3215 if (linear_score > 0.1f) return 0;
3216
3217 // Predict using neural net model.
3218 nn_predict(features, nn_config, &nn_score);
3219
3220 if (linear_score < -0.0f && nn_score < 0.1f) return 1;
3221 if (nn_score < -0.0f && linear_score < 0.1f) return 1;
3222 return 0;
3223 }
3224 #undef FEATURES
3225
3226 #define FEATURES 4
3227 // ML-based partition search breakout.
ml_predict_breakout(VP9_COMP * const cpi,BLOCK_SIZE bsize,const MACROBLOCK * const x,const RD_COST * const rd_cost)3228 static int ml_predict_breakout(VP9_COMP *const cpi, BLOCK_SIZE bsize,
3229 const MACROBLOCK *const x,
3230 const RD_COST *const rd_cost) {
3231 DECLARE_ALIGNED(16, static const uint8_t, vp9_64_zeros[64]) = { 0 };
3232 const VP9_COMMON *const cm = &cpi->common;
3233 float features[FEATURES];
3234 const float *linear_weights = NULL; // Linear model weights.
3235 float linear_score = 0.0f;
3236 const int qindex = cm->base_qindex;
3237 const int q_ctx = qindex >= 200 ? 0 : (qindex >= 150 ? 1 : 2);
3238 const int is_720p_or_larger = VPXMIN(cm->width, cm->height) >= 720;
3239 const int resolution_ctx = is_720p_or_larger ? 1 : 0;
3240
3241 switch (bsize) {
3242 case BLOCK_64X64:
3243 linear_weights = vp9_partition_breakout_weights_64[resolution_ctx][q_ctx];
3244 break;
3245 case BLOCK_32X32:
3246 linear_weights = vp9_partition_breakout_weights_32[resolution_ctx][q_ctx];
3247 break;
3248 case BLOCK_16X16:
3249 linear_weights = vp9_partition_breakout_weights_16[resolution_ctx][q_ctx];
3250 break;
3251 case BLOCK_8X8:
3252 linear_weights = vp9_partition_breakout_weights_8[resolution_ctx][q_ctx];
3253 break;
3254 default: assert(0 && "Unexpected block size."); return 0;
3255 }
3256 if (!linear_weights) return 0;
3257
3258 { // Generate feature values.
3259 #if CONFIG_VP9_HIGHBITDEPTH
3260 const int ac_q =
3261 vp9_ac_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3262 #else
3263 const int ac_q = vp9_ac_quant(qindex, 0, cm->bit_depth);
3264 #endif // CONFIG_VP9_HIGHBITDEPTH
3265 const int num_pels_log2 = num_pels_log2_lookup[bsize];
3266 int feature_index = 0;
3267 unsigned int var, sse;
3268 float rate_f, dist_f;
3269
3270 #if CONFIG_VP9_HIGHBITDEPTH
3271 if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3272 var =
3273 vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, x->e_mbd.bd);
3274 } else {
3275 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3276 vp9_64_zeros, 0, &sse);
3277 }
3278 #else
3279 var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3280 vp9_64_zeros, 0, &sse);
3281 #endif
3282 var = var >> num_pels_log2;
3283
3284 vpx_clear_system_state();
3285
3286 rate_f = (float)VPXMIN(rd_cost->rate, INT_MAX);
3287 dist_f = (float)(VPXMIN(rd_cost->dist, INT_MAX) >> num_pels_log2);
3288 rate_f =
3289 ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
3290 rate_f;
3291
3292 features[feature_index++] = rate_f;
3293 features[feature_index++] = dist_f;
3294 features[feature_index++] = (float)var;
3295 features[feature_index++] = (float)ac_q;
3296 assert(feature_index == FEATURES);
3297 }
3298
3299 { // Calculate the output score.
3300 int i;
3301 linear_score = linear_weights[FEATURES];
3302 for (i = 0; i < FEATURES; ++i)
3303 linear_score += linear_weights[i] * features[i];
3304 }
3305
3306 return linear_score >= cpi->sf.rd_ml_partition.search_breakout_thresh[q_ctx];
3307 }
3308 #undef FEATURES
3309
3310 #define FEATURES 8
3311 #define LABELS 4
ml_prune_rect_partition(VP9_COMP * const cpi,MACROBLOCK * const x,BLOCK_SIZE bsize,const PC_TREE * const pc_tree,int * allow_horz,int * allow_vert,int64_t ref_rd)3312 static void ml_prune_rect_partition(VP9_COMP *const cpi, MACROBLOCK *const x,
3313 BLOCK_SIZE bsize,
3314 const PC_TREE *const pc_tree,
3315 int *allow_horz, int *allow_vert,
3316 int64_t ref_rd) {
3317 const NN_CONFIG *nn_config = NULL;
3318 float score[LABELS] = {
3319 0.0f,
3320 };
3321 int thresh = -1;
3322 int i;
3323 (void)x;
3324
3325 if (ref_rd <= 0 || ref_rd > 1000000000) return;
3326
3327 switch (bsize) {
3328 case BLOCK_8X8: break;
3329 case BLOCK_16X16:
3330 nn_config = &vp9_rect_part_nnconfig_16;
3331 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[1];
3332 break;
3333 case BLOCK_32X32:
3334 nn_config = &vp9_rect_part_nnconfig_32;
3335 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[2];
3336 break;
3337 case BLOCK_64X64:
3338 nn_config = &vp9_rect_part_nnconfig_64;
3339 thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[3];
3340 break;
3341 default: assert(0 && "Unexpected block size."); return;
3342 }
3343 if (!nn_config || thresh < 0) return;
3344
3345 // Feature extraction and model score calculation.
3346 {
3347 const VP9_COMMON *const cm = &cpi->common;
3348 #if CONFIG_VP9_HIGHBITDEPTH
3349 const int dc_q =
3350 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3351 #else
3352 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3353 #endif // CONFIG_VP9_HIGHBITDEPTH
3354 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3355 int feature_index = 0;
3356 float features[FEATURES];
3357
3358 features[feature_index++] = logf((float)dc_q + 1.0f);
3359 features[feature_index++] =
3360 (float)(pc_tree->partitioning == PARTITION_NONE);
3361 features[feature_index++] = logf((float)ref_rd / bs / bs + 1.0f);
3362
3363 {
3364 const float norm_factor = 1.0f / ((float)ref_rd + 1.0f);
3365 const int64_t none_rdcost = pc_tree->none.rdcost;
3366 float rd_ratio = 2.0f;
3367 if (none_rdcost > 0 && none_rdcost < 1000000000)
3368 rd_ratio = (float)none_rdcost * norm_factor;
3369 features[feature_index++] = VPXMIN(rd_ratio, 2.0f);
3370
3371 for (i = 0; i < 4; ++i) {
3372 const int64_t this_rd = pc_tree->split[i]->none.rdcost;
3373 const int rd_valid = this_rd > 0 && this_rd < 1000000000;
3374 // Ratio between sub-block RD and whole block RD.
3375 features[feature_index++] =
3376 rd_valid ? (float)this_rd * norm_factor : 1.0f;
3377 }
3378 }
3379
3380 assert(feature_index == FEATURES);
3381 nn_predict(features, nn_config, score);
3382 }
3383
3384 // Make decisions based on the model score.
3385 {
3386 int max_score = -1000;
3387 int horz = 0, vert = 0;
3388 int int_score[LABELS];
3389 for (i = 0; i < LABELS; ++i) {
3390 int_score[i] = (int)(100 * score[i]);
3391 max_score = VPXMAX(int_score[i], max_score);
3392 }
3393 thresh = max_score - thresh;
3394 for (i = 0; i < LABELS; ++i) {
3395 if (int_score[i] >= thresh) {
3396 if ((i >> 0) & 1) horz = 1;
3397 if ((i >> 1) & 1) vert = 1;
3398 }
3399 }
3400 *allow_horz = *allow_horz && horz;
3401 *allow_vert = *allow_vert && vert;
3402 }
3403 }
3404 #undef FEATURES
3405 #undef LABELS
3406
3407 // Perform fast and coarse motion search for the given block. This is a
3408 // pre-processing step for the ML based partition search speedup.
simple_motion_search(const VP9_COMP * const cpi,MACROBLOCK * const x,BLOCK_SIZE bsize,int mi_row,int mi_col,MV ref_mv,MV_REFERENCE_FRAME ref,uint8_t * const pred_buf)3409 static void simple_motion_search(const VP9_COMP *const cpi, MACROBLOCK *const x,
3410 BLOCK_SIZE bsize, int mi_row, int mi_col,
3411 MV ref_mv, MV_REFERENCE_FRAME ref,
3412 uint8_t *const pred_buf) {
3413 const VP9_COMMON *const cm = &cpi->common;
3414 MACROBLOCKD *const xd = &x->e_mbd;
3415 MODE_INFO *const mi = xd->mi[0];
3416 YV12_BUFFER_CONFIG *yv12;
3417 YV12_BUFFER_CONFIG *scaled_ref_frame = vp9_get_scaled_ref_frame(cpi, ref);
3418 const int step_param = 1;
3419 const MvLimits tmp_mv_limits = x->mv_limits;
3420 const SEARCH_METHODS search_method = NSTEP;
3421 const int sadpb = x->sadperbit16;
3422 MV ref_mv_full = { ref_mv.row >> 3, ref_mv.col >> 3 };
3423 MV best_mv = { 0, 0 };
3424 int cost_list[5];
3425
3426 if (scaled_ref_frame)
3427 yv12 = scaled_ref_frame;
3428 else
3429 yv12 = get_ref_frame_buffer(cpi, ref);
3430
3431 assert(yv12 != NULL);
3432 if (!yv12) return;
3433 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
3434 &cm->frame_refs[ref - 1].sf);
3435 mi->ref_frame[0] = ref;
3436 mi->ref_frame[1] = NONE;
3437 mi->sb_type = bsize;
3438 vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
3439 vp9_full_pixel_search(cpi, x, bsize, &ref_mv_full, step_param, search_method,
3440 sadpb, cond_cost_list(cpi, cost_list), &ref_mv,
3441 &best_mv, 0, 0);
3442 best_mv.row *= 8;
3443 best_mv.col *= 8;
3444 x->mv_limits = tmp_mv_limits;
3445 mi->mv[0].as_mv = best_mv;
3446
3447 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3448 xd->plane[0].dst.buf = pred_buf;
3449 xd->plane[0].dst.stride = 64;
3450 vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
3451 }
3452
3453 // Use a neural net model to prune partition-none and partition-split search.
3454 // Features used: QP; spatial block size contexts; variance of prediction
3455 // residue after simple_motion_search.
3456 #define FEATURES 12
ml_predict_var_rd_paritioning(const VP9_COMP * const cpi,MACROBLOCK * const x,PC_TREE * const pc_tree,BLOCK_SIZE bsize,int mi_row,int mi_col,int * none,int * split)3457 static void ml_predict_var_rd_paritioning(const VP9_COMP *const cpi,
3458 MACROBLOCK *const x,
3459 PC_TREE *const pc_tree,
3460 BLOCK_SIZE bsize, int mi_row,
3461 int mi_col, int *none, int *split) {
3462 const VP9_COMMON *const cm = &cpi->common;
3463 const NN_CONFIG *nn_config = NULL;
3464 #if CONFIG_VP9_HIGHBITDEPTH
3465 MACROBLOCKD *xd = &x->e_mbd;
3466 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64 * 2]);
3467 uint8_t *const pred_buf = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
3468 ? (CONVERT_TO_BYTEPTR(pred_buffer))
3469 : pred_buffer;
3470 #else
3471 DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64]);
3472 uint8_t *const pred_buf = pred_buffer;
3473 #endif // CONFIG_VP9_HIGHBITDEPTH
3474 const int speed = cpi->oxcf.speed;
3475 float thresh = 0.0f;
3476
3477 switch (bsize) {
3478 case BLOCK_64X64:
3479 nn_config = &vp9_part_split_nnconfig_64;
3480 thresh = speed > 0 ? 2.8f : 3.0f;
3481 break;
3482 case BLOCK_32X32:
3483 nn_config = &vp9_part_split_nnconfig_32;
3484 thresh = speed > 0 ? 3.5f : 3.0f;
3485 break;
3486 case BLOCK_16X16:
3487 nn_config = &vp9_part_split_nnconfig_16;
3488 thresh = speed > 0 ? 3.8f : 4.0f;
3489 break;
3490 case BLOCK_8X8:
3491 nn_config = &vp9_part_split_nnconfig_8;
3492 if (cm->width >= 720 && cm->height >= 720)
3493 thresh = speed > 0 ? 2.5f : 2.0f;
3494 else
3495 thresh = speed > 0 ? 3.8f : 2.0f;
3496 break;
3497 default: assert(0 && "Unexpected block size."); return;
3498 }
3499
3500 if (!nn_config) return;
3501
3502 // Do a simple single motion search to find a prediction for current block.
3503 // The variance of the residue will be used as input features.
3504 {
3505 MV ref_mv;
3506 const MV_REFERENCE_FRAME ref =
3507 cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
3508 // If bsize is 64x64, use zero MV as reference; otherwise, use MV result
3509 // of previous(larger) block as reference.
3510 if (bsize == BLOCK_64X64)
3511 ref_mv.row = ref_mv.col = 0;
3512 else
3513 ref_mv = pc_tree->mv;
3514 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
3515 simple_motion_search(cpi, x, bsize, mi_row, mi_col, ref_mv, ref, pred_buf);
3516 pc_tree->mv = x->e_mbd.mi[0]->mv[0].as_mv;
3517 }
3518
3519 vpx_clear_system_state();
3520
3521 {
3522 float features[FEATURES] = { 0.0f };
3523 #if CONFIG_VP9_HIGHBITDEPTH
3524 const int dc_q =
3525 vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (xd->bd - 8);
3526 #else
3527 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3528 #endif // CONFIG_VP9_HIGHBITDEPTH
3529 int feature_idx = 0;
3530 float score;
3531
3532 // Generate model input features.
3533 features[feature_idx++] = logf((float)dc_q + 1.0f);
3534
3535 // Get the variance of the residue as input features.
3536 {
3537 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3538 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3539 const uint8_t *pred = pred_buf;
3540 const uint8_t *src = x->plane[0].src.buf;
3541 const int src_stride = x->plane[0].src.stride;
3542 const int pred_stride = 64;
3543 unsigned int sse;
3544 // Variance of whole block.
3545 const unsigned int var =
3546 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
3547 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
3548 const MACROBLOCKD *const xd = &x->e_mbd;
3549 const int has_above = !!xd->above_mi;
3550 const int has_left = !!xd->left_mi;
3551 const BLOCK_SIZE above_bsize = has_above ? xd->above_mi->sb_type : bsize;
3552 const BLOCK_SIZE left_bsize = has_left ? xd->left_mi->sb_type : bsize;
3553 int i;
3554
3555 features[feature_idx++] = (float)has_above;
3556 features[feature_idx++] = (float)b_width_log2_lookup[above_bsize];
3557 features[feature_idx++] = (float)b_height_log2_lookup[above_bsize];
3558 features[feature_idx++] = (float)has_left;
3559 features[feature_idx++] = (float)b_width_log2_lookup[left_bsize];
3560 features[feature_idx++] = (float)b_height_log2_lookup[left_bsize];
3561 features[feature_idx++] = logf((float)var + 1.0f);
3562 for (i = 0; i < 4; ++i) {
3563 const int x_idx = (i & 1) * bs / 2;
3564 const int y_idx = (i >> 1) * bs / 2;
3565 const int src_offset = y_idx * src_stride + x_idx;
3566 const int pred_offset = y_idx * pred_stride + x_idx;
3567 // Variance of quarter block.
3568 const unsigned int sub_var =
3569 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
3570 pred + pred_offset, pred_stride, &sse);
3571 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
3572 features[feature_idx++] = var_ratio;
3573 }
3574 }
3575 assert(feature_idx == FEATURES);
3576
3577 // Feed the features into the model to get the confidence score.
3578 nn_predict(features, nn_config, &score);
3579
3580 // Higher score means that the model has higher confidence that the split
3581 // partition is better than the non-split partition. So if the score is
3582 // high enough, we skip the none-split partition search; if the score is
3583 // low enough, we skip the split partition search.
3584 if (score > thresh) *none = 0;
3585 if (score < -thresh) *split = 0;
3586 }
3587 }
3588 #undef FEATURES
3589 #endif // !CONFIG_REALTIME_ONLY
3590
log_wiener_var(int64_t wiener_variance)3591 static double log_wiener_var(int64_t wiener_variance) {
3592 return log(1.0 + wiener_variance) / log(2.0);
3593 }
3594
build_kmeans_segmentation(VP9_COMP * cpi)3595 static void build_kmeans_segmentation(VP9_COMP *cpi) {
3596 VP9_COMMON *cm = &cpi->common;
3597 BLOCK_SIZE bsize = BLOCK_64X64;
3598 KMEANS_DATA *kmeans_data;
3599
3600 vp9_disable_segmentation(&cm->seg);
3601 if (cm->show_frame) {
3602 int mi_row, mi_col;
3603 cpi->kmeans_data_size = 0;
3604 cpi->kmeans_ctr_num = 8;
3605
3606 for (mi_row = 0; mi_row < cm->mi_rows; mi_row += MI_BLOCK_SIZE) {
3607 for (mi_col = 0; mi_col < cm->mi_cols; mi_col += MI_BLOCK_SIZE) {
3608 int mb_row_start = mi_row >> 1;
3609 int mb_col_start = mi_col >> 1;
3610 int mb_row_end = VPXMIN(
3611 (mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3612 int mb_col_end = VPXMIN(
3613 (mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3614 int row, col;
3615 int64_t wiener_variance = 0;
3616
3617 for (row = mb_row_start; row < mb_row_end; ++row)
3618 for (col = mb_col_start; col < mb_col_end; ++col)
3619 wiener_variance += cpi->mb_wiener_variance[row * cm->mb_cols + col];
3620
3621 wiener_variance /=
3622 (mb_row_end - mb_row_start) * (mb_col_end - mb_col_start);
3623
3624 #if CONFIG_MULTITHREAD
3625 pthread_mutex_lock(&cpi->kmeans_mutex);
3626 #endif // CONFIG_MULTITHREAD
3627
3628 kmeans_data = &cpi->kmeans_data_arr[cpi->kmeans_data_size++];
3629 kmeans_data->value = log_wiener_var(wiener_variance);
3630 kmeans_data->pos = mi_row * cpi->kmeans_data_stride + mi_col;
3631 #if CONFIG_MULTITHREAD
3632 pthread_mutex_unlock(&cpi->kmeans_mutex);
3633 #endif // CONFIG_MULTITHREAD
3634 }
3635 }
3636
3637 vp9_kmeans(cpi->kmeans_ctr_ls, cpi->kmeans_boundary_ls,
3638 cpi->kmeans_count_ls, cpi->kmeans_ctr_num, cpi->kmeans_data_arr,
3639 cpi->kmeans_data_size);
3640
3641 vp9_perceptual_aq_mode_setup(cpi, &cm->seg);
3642 }
3643 }
3644
3645 #if !CONFIG_REALTIME_ONLY
wiener_var_segment(VP9_COMP * cpi,BLOCK_SIZE bsize,int mi_row,int mi_col)3646 static int wiener_var_segment(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3647 int mi_col) {
3648 VP9_COMMON *cm = &cpi->common;
3649 int mb_row_start = mi_row >> 1;
3650 int mb_col_start = mi_col >> 1;
3651 int mb_row_end =
3652 VPXMIN((mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3653 int mb_col_end =
3654 VPXMIN((mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3655 int row, col, idx;
3656 int64_t wiener_variance = 0;
3657 int segment_id;
3658 int8_t seg_hist[MAX_SEGMENTS] = { 0 };
3659 int8_t max_count = 0, max_index = -1;
3660
3661 vpx_clear_system_state();
3662
3663 assert(cpi->norm_wiener_variance > 0);
3664
3665 for (row = mb_row_start; row < mb_row_end; ++row) {
3666 for (col = mb_col_start; col < mb_col_end; ++col) {
3667 wiener_variance = cpi->mb_wiener_variance[row * cm->mb_cols + col];
3668 segment_id =
3669 vp9_get_group_idx(log_wiener_var(wiener_variance),
3670 cpi->kmeans_boundary_ls, cpi->kmeans_ctr_num);
3671 ++seg_hist[segment_id];
3672 }
3673 }
3674
3675 for (idx = 0; idx < cpi->kmeans_ctr_num; ++idx) {
3676 if (seg_hist[idx] > max_count) {
3677 max_count = seg_hist[idx];
3678 max_index = idx;
3679 }
3680 }
3681
3682 assert(max_index >= 0);
3683 segment_id = max_index;
3684
3685 return segment_id;
3686 }
3687
get_rdmult_delta(VP9_COMP * cpi,BLOCK_SIZE bsize,int mi_row,int mi_col,int orig_rdmult)3688 static int get_rdmult_delta(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3689 int mi_col, int orig_rdmult) {
3690 const int gf_group_index = cpi->twopass.gf_group.index;
3691 int64_t intra_cost = 0;
3692 int64_t mc_dep_cost = 0;
3693 int mi_wide = num_8x8_blocks_wide_lookup[bsize];
3694 int mi_high = num_8x8_blocks_high_lookup[bsize];
3695 int row, col;
3696
3697 int dr = 0;
3698 int count = 0;
3699 double r0, rk, beta;
3700
3701 TplDepFrame *tpl_frame;
3702 TplDepStats *tpl_stats;
3703 int tpl_stride;
3704
3705 if (gf_group_index >= MAX_ARF_GOP_SIZE) return orig_rdmult;
3706 tpl_frame = &cpi->tpl_stats[gf_group_index];
3707
3708 if (tpl_frame->is_valid == 0) return orig_rdmult;
3709 tpl_stats = tpl_frame->tpl_stats_ptr;
3710 tpl_stride = tpl_frame->stride;
3711
3712 if (cpi->twopass.gf_group.layer_depth[gf_group_index] > 1) return orig_rdmult;
3713
3714 for (row = mi_row; row < mi_row + mi_high; ++row) {
3715 for (col = mi_col; col < mi_col + mi_wide; ++col) {
3716 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
3717
3718 if (row >= cpi->common.mi_rows || col >= cpi->common.mi_cols) continue;
3719
3720 intra_cost += this_stats->intra_cost;
3721 mc_dep_cost += this_stats->mc_dep_cost;
3722
3723 ++count;
3724 }
3725 }
3726
3727 vpx_clear_system_state();
3728
3729 r0 = cpi->rd.r0;
3730 rk = (double)intra_cost / mc_dep_cost;
3731 beta = r0 / rk;
3732 dr = vp9_get_adaptive_rdmult(cpi, beta);
3733
3734 dr = VPXMIN(dr, orig_rdmult * 3 / 2);
3735 dr = VPXMAX(dr, orig_rdmult * 1 / 2);
3736
3737 dr = VPXMAX(1, dr);
3738
3739 return dr;
3740 }
3741 #endif // !CONFIG_REALTIME_ONLY
3742
3743 #if CONFIG_RATE_CTRL
assign_partition_info(const int row_start_4x4,const int col_start_4x4,const int block_width_4x4,const int block_height_4x4,const int num_unit_rows,const int num_unit_cols,PARTITION_INFO * partition_info)3744 static void assign_partition_info(
3745 const int row_start_4x4, const int col_start_4x4, const int block_width_4x4,
3746 const int block_height_4x4, const int num_unit_rows,
3747 const int num_unit_cols, PARTITION_INFO *partition_info) {
3748 int i, j;
3749 for (i = 0; i < block_height_4x4; ++i) {
3750 for (j = 0; j < block_width_4x4; ++j) {
3751 const int row_4x4 = row_start_4x4 + i;
3752 const int col_4x4 = col_start_4x4 + j;
3753 const int unit_index = row_4x4 * num_unit_cols + col_4x4;
3754 if (row_4x4 >= num_unit_rows || col_4x4 >= num_unit_cols) continue;
3755 partition_info[unit_index].row = row_4x4 << 2;
3756 partition_info[unit_index].column = col_4x4 << 2;
3757 partition_info[unit_index].row_start = row_start_4x4 << 2;
3758 partition_info[unit_index].column_start = col_start_4x4 << 2;
3759 partition_info[unit_index].width = block_width_4x4 << 2;
3760 partition_info[unit_index].height = block_height_4x4 << 2;
3761 }
3762 }
3763 }
3764
assign_motion_vector_info(const int block_width_4x4,const int block_height_4x4,const int row_start_4x4,const int col_start_4x4,const int num_unit_rows,const int num_unit_cols,MV * source_mv[2],MV_REFERENCE_FRAME source_ref_frame[2],MOTION_VECTOR_INFO * motion_vector_info)3765 static void assign_motion_vector_info(const int block_width_4x4,
3766 const int block_height_4x4,
3767 const int row_start_4x4,
3768 const int col_start_4x4,
3769 const int num_unit_rows,
3770 const int num_unit_cols, MV *source_mv[2],
3771 MV_REFERENCE_FRAME source_ref_frame[2],
3772 MOTION_VECTOR_INFO *motion_vector_info) {
3773 int i, j;
3774 for (i = 0; i < block_height_4x4; ++i) {
3775 for (j = 0; j < block_width_4x4; ++j) {
3776 const int row_4x4 = row_start_4x4 + i;
3777 const int col_4x4 = col_start_4x4 + j;
3778 const int unit_index = row_4x4 * num_unit_cols + col_4x4;
3779 if (row_4x4 >= num_unit_rows || col_4x4 >= num_unit_cols) continue;
3780 if (source_ref_frame[1] == NONE) {
3781 assert(source_mv[1]->row == 0 && source_mv[1]->col == 0);
3782 }
3783 motion_vector_info[unit_index].ref_frame[0] = source_ref_frame[0];
3784 motion_vector_info[unit_index].ref_frame[1] = source_ref_frame[1];
3785 motion_vector_info[unit_index].mv[0].as_mv.row = source_mv[0]->row;
3786 motion_vector_info[unit_index].mv[0].as_mv.col = source_mv[0]->col;
3787 motion_vector_info[unit_index].mv[1].as_mv.row = source_mv[1]->row;
3788 motion_vector_info[unit_index].mv[1].as_mv.col = source_mv[1]->col;
3789 }
3790 }
3791 }
3792
store_superblock_info(const PC_TREE * const pc_tree,MODE_INFO ** mi_grid_visible,const int mi_stride,const int square_size_4x4,const int num_unit_rows,const int num_unit_cols,const int row_start_4x4,const int col_start_4x4,PARTITION_INFO * partition_info,MOTION_VECTOR_INFO * motion_vector_info)3793 static void store_superblock_info(
3794 const PC_TREE *const pc_tree, MODE_INFO **mi_grid_visible,
3795 const int mi_stride, const int square_size_4x4, const int num_unit_rows,
3796 const int num_unit_cols, const int row_start_4x4, const int col_start_4x4,
3797 PARTITION_INFO *partition_info, MOTION_VECTOR_INFO *motion_vector_info) {
3798 const int subblock_square_size_4x4 = square_size_4x4 >> 1;
3799 if (row_start_4x4 >= num_unit_rows || col_start_4x4 >= num_unit_cols) return;
3800 assert(pc_tree->partitioning != PARTITION_INVALID);
3801 // End node, no split.
3802 if (pc_tree->partitioning == PARTITION_NONE ||
3803 pc_tree->partitioning == PARTITION_HORZ ||
3804 pc_tree->partitioning == PARTITION_VERT || square_size_4x4 == 1) {
3805 const int mi_row = row_start_4x4 >> 1;
3806 const int mi_col = col_start_4x4 >> 1;
3807 const int mi_idx = mi_stride * mi_row + mi_col;
3808 MODE_INFO **mi = mi_grid_visible + mi_idx;
3809 MV *source_mv[2];
3810 MV_REFERENCE_FRAME source_ref_frame[2];
3811
3812 // partition info
3813 const int block_width_4x4 = (pc_tree->partitioning == PARTITION_VERT)
3814 ? square_size_4x4 >> 1
3815 : square_size_4x4;
3816 const int block_height_4x4 = (pc_tree->partitioning == PARTITION_HORZ)
3817 ? square_size_4x4 >> 1
3818 : square_size_4x4;
3819 assign_partition_info(row_start_4x4, col_start_4x4, block_width_4x4,
3820 block_height_4x4, num_unit_rows, num_unit_cols,
3821 partition_info);
3822 if (pc_tree->partitioning == PARTITION_VERT) {
3823 assign_partition_info(row_start_4x4, col_start_4x4 + block_width_4x4,
3824 block_width_4x4, block_height_4x4, num_unit_rows,
3825 num_unit_cols, partition_info);
3826 } else if (pc_tree->partitioning == PARTITION_HORZ) {
3827 assign_partition_info(row_start_4x4 + block_height_4x4, col_start_4x4,
3828 block_width_4x4, block_height_4x4, num_unit_rows,
3829 num_unit_cols, partition_info);
3830 }
3831
3832 // motion vector info
3833 if (pc_tree->partitioning == PARTITION_HORZ) {
3834 int is_valid_second_rectangle = 0;
3835 assert(square_size_4x4 > 1);
3836 // First rectangle.
3837 source_ref_frame[0] = mi[0]->ref_frame[0];
3838 source_ref_frame[1] = mi[0]->ref_frame[1];
3839 source_mv[0] = &mi[0]->mv[0].as_mv;
3840 source_mv[1] = &mi[0]->mv[1].as_mv;
3841 assign_motion_vector_info(block_width_4x4, block_height_4x4,
3842 row_start_4x4, col_start_4x4, num_unit_rows,
3843 num_unit_cols, source_mv, source_ref_frame,
3844 motion_vector_info);
3845 // Second rectangle.
3846 if (square_size_4x4 == 2) {
3847 is_valid_second_rectangle = 1;
3848 source_ref_frame[0] = mi[0]->ref_frame[0];
3849 source_ref_frame[1] = mi[0]->ref_frame[1];
3850 source_mv[0] = &mi[0]->bmi[2].as_mv[0].as_mv;
3851 source_mv[1] = &mi[0]->bmi[2].as_mv[1].as_mv;
3852 } else {
3853 const int mi_row_2 = mi_row + (block_height_4x4 >> 1);
3854 const int mi_col_2 = mi_col;
3855 if (mi_row_2 * 2 < num_unit_rows && mi_col_2 * 2 < num_unit_cols) {
3856 const int mi_idx_2 = mi_stride * mi_row_2 + mi_col_2;
3857 is_valid_second_rectangle = 1;
3858 mi = mi_grid_visible + mi_idx_2;
3859 source_ref_frame[0] = mi[0]->ref_frame[0];
3860 source_ref_frame[1] = mi[0]->ref_frame[1];
3861 source_mv[0] = &mi[0]->mv[0].as_mv;
3862 source_mv[1] = &mi[0]->mv[1].as_mv;
3863 }
3864 }
3865 if (is_valid_second_rectangle) {
3866 assign_motion_vector_info(
3867 block_width_4x4, block_height_4x4, row_start_4x4 + block_height_4x4,
3868 col_start_4x4, num_unit_rows, num_unit_cols, source_mv,
3869 source_ref_frame, motion_vector_info);
3870 }
3871 } else if (pc_tree->partitioning == PARTITION_VERT) {
3872 int is_valid_second_rectangle = 0;
3873 assert(square_size_4x4 > 1);
3874 // First rectangle.
3875 source_ref_frame[0] = mi[0]->ref_frame[0];
3876 source_ref_frame[1] = mi[0]->ref_frame[1];
3877 source_mv[0] = &mi[0]->mv[0].as_mv;
3878 source_mv[1] = &mi[0]->mv[1].as_mv;
3879 assign_motion_vector_info(block_width_4x4, block_height_4x4,
3880 row_start_4x4, col_start_4x4, num_unit_rows,
3881 num_unit_cols, source_mv, source_ref_frame,
3882 motion_vector_info);
3883 // Second rectangle.
3884 if (square_size_4x4 == 2) {
3885 is_valid_second_rectangle = 1;
3886 source_ref_frame[0] = mi[0]->ref_frame[0];
3887 source_ref_frame[1] = mi[0]->ref_frame[1];
3888 source_mv[0] = &mi[0]->bmi[1].as_mv[0].as_mv;
3889 source_mv[1] = &mi[0]->bmi[1].as_mv[1].as_mv;
3890 } else {
3891 const int mi_row_2 = mi_row;
3892 const int mi_col_2 = mi_col + (block_width_4x4 >> 1);
3893 if (mi_row_2 * 2 < num_unit_rows && mi_col_2 * 2 < num_unit_cols) {
3894 const int mi_idx_2 = mi_stride * mi_row_2 + mi_col_2;
3895 is_valid_second_rectangle = 1;
3896 mi = mi_grid_visible + mi_idx_2;
3897 source_ref_frame[0] = mi[0]->ref_frame[0];
3898 source_ref_frame[1] = mi[0]->ref_frame[1];
3899 source_mv[0] = &mi[0]->mv[0].as_mv;
3900 source_mv[1] = &mi[0]->mv[1].as_mv;
3901 }
3902 }
3903 if (is_valid_second_rectangle) {
3904 assign_motion_vector_info(
3905 block_width_4x4, block_height_4x4, row_start_4x4,
3906 col_start_4x4 + block_width_4x4, num_unit_rows, num_unit_cols,
3907 source_mv, source_ref_frame, motion_vector_info);
3908 }
3909 } else {
3910 assert(pc_tree->partitioning == PARTITION_NONE || square_size_4x4 == 1);
3911 source_ref_frame[0] = mi[0]->ref_frame[0];
3912 source_ref_frame[1] = mi[0]->ref_frame[1];
3913 if (square_size_4x4 == 1) {
3914 const int sub8x8_row = row_start_4x4 % 2;
3915 const int sub8x8_col = col_start_4x4 % 2;
3916 const int sub8x8_idx = sub8x8_row * 2 + sub8x8_col;
3917 source_mv[0] = &mi[0]->bmi[sub8x8_idx].as_mv[0].as_mv;
3918 source_mv[1] = &mi[0]->bmi[sub8x8_idx].as_mv[1].as_mv;
3919 } else {
3920 source_mv[0] = &mi[0]->mv[0].as_mv;
3921 source_mv[1] = &mi[0]->mv[1].as_mv;
3922 }
3923 assign_motion_vector_info(block_width_4x4, block_height_4x4,
3924 row_start_4x4, col_start_4x4, num_unit_rows,
3925 num_unit_cols, source_mv, source_ref_frame,
3926 motion_vector_info);
3927 }
3928
3929 return;
3930 }
3931 // recursively traverse partition tree when partition is split.
3932 assert(pc_tree->partitioning == PARTITION_SPLIT);
3933 store_superblock_info(pc_tree->split[0], mi_grid_visible, mi_stride,
3934 subblock_square_size_4x4, num_unit_rows, num_unit_cols,
3935 row_start_4x4, col_start_4x4, partition_info,
3936 motion_vector_info);
3937 store_superblock_info(pc_tree->split[1], mi_grid_visible, mi_stride,
3938 subblock_square_size_4x4, num_unit_rows, num_unit_cols,
3939 row_start_4x4, col_start_4x4 + subblock_square_size_4x4,
3940 partition_info, motion_vector_info);
3941 store_superblock_info(pc_tree->split[2], mi_grid_visible, mi_stride,
3942 subblock_square_size_4x4, num_unit_rows, num_unit_cols,
3943 row_start_4x4 + subblock_square_size_4x4, col_start_4x4,
3944 partition_info, motion_vector_info);
3945 store_superblock_info(pc_tree->split[3], mi_grid_visible, mi_stride,
3946 subblock_square_size_4x4, num_unit_rows, num_unit_cols,
3947 row_start_4x4 + subblock_square_size_4x4,
3948 col_start_4x4 + subblock_square_size_4x4,
3949 partition_info, motion_vector_info);
3950 }
3951 #endif // CONFIG_RATE_CTRL
3952
3953 #if !CONFIG_REALTIME_ONLY
3954 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
3955 // unlikely to be selected depending on previous rate-distortion optimization
3956 // results, for encoding speed-up.
rd_pick_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,RD_COST * rd_cost,RD_COST best_rdc,PC_TREE * pc_tree)3957 static int rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3958 TileDataEnc *tile_data, TOKENEXTRA **tp,
3959 int mi_row, int mi_col, BLOCK_SIZE bsize,
3960 RD_COST *rd_cost, RD_COST best_rdc,
3961 PC_TREE *pc_tree) {
3962 VP9_COMMON *const cm = &cpi->common;
3963 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3964 TileInfo *const tile_info = &tile_data->tile_info;
3965 MACROBLOCK *const x = &td->mb;
3966 MACROBLOCKD *const xd = &x->e_mbd;
3967 const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
3968 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
3969 PARTITION_CONTEXT sl[8], sa[8];
3970 TOKENEXTRA *tp_orig = *tp;
3971 PICK_MODE_CONTEXT *const ctx = &pc_tree->none;
3972 int i;
3973 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3974 BLOCK_SIZE subsize;
3975 RD_COST this_rdc, sum_rdc;
3976 int do_split = bsize >= BLOCK_8X8;
3977 int do_rect = 1;
3978 INTERP_FILTER pred_interp_filter;
3979
3980 // Override skipping rectangular partition operations for edge blocks
3981 const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
3982 const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
3983 const int xss = x->e_mbd.plane[1].subsampling_x;
3984 const int yss = x->e_mbd.plane[1].subsampling_y;
3985
3986 BLOCK_SIZE min_size = x->min_partition_size;
3987 BLOCK_SIZE max_size = x->max_partition_size;
3988
3989 int partition_none_allowed = !force_horz_split && !force_vert_split;
3990 int partition_horz_allowed =
3991 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
3992 int partition_vert_allowed =
3993 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
3994
3995 int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_thr.dist;
3996 int rate_breakout_thr = cpi->sf.partition_search_breakout_thr.rate;
3997 int must_split = 0;
3998 int should_encode_sb = 0;
3999
4000 // Ref frames picked in the [i_th] quarter subblock during square partition
4001 // RD search. It may be used to prune ref frame selection of rect partitions.
4002 uint8_t ref_frames_used[4] = { 0, 0, 0, 0 };
4003
4004 int partition_mul = x->cb_rdmult;
4005
4006 (void)*tp_orig;
4007
4008 assert(num_8x8_blocks_wide_lookup[bsize] ==
4009 num_8x8_blocks_high_lookup[bsize]);
4010
4011 dist_breakout_thr >>=
4012 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4013
4014 rate_breakout_thr *= num_pels_log2_lookup[bsize];
4015
4016 vp9_rd_cost_init(&this_rdc);
4017 vp9_rd_cost_init(&sum_rdc);
4018
4019 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4020
4021 if (oxcf->tuning == VP8_TUNE_SSIM) {
4022 set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &partition_mul);
4023 }
4024 vp9_rd_cost_update(partition_mul, x->rddiv, &best_rdc);
4025
4026 if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ &&
4027 cpi->oxcf.aq_mode != LOOKAHEAD_AQ)
4028 x->mb_energy = vp9_block_energy(cpi, x, bsize);
4029
4030 if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
4031 int cb_partition_search_ctrl =
4032 ((pc_tree->index == 0 || pc_tree->index == 3) +
4033 get_chessboard_index(cm->current_video_frame)) &
4034 0x1;
4035
4036 if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
4037 set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
4038 }
4039
4040 // Get sub block energy range
4041 if (bsize >= BLOCK_16X16) {
4042 int min_energy, max_energy;
4043 vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
4044 &max_energy);
4045 must_split = (min_energy < -3) && (max_energy - min_energy > 2);
4046 }
4047
4048 // Determine partition types in search according to the speed features.
4049 // The threshold set here has to be of square block size.
4050 if (cpi->sf.auto_min_max_partition_size) {
4051 partition_none_allowed &= (bsize <= max_size);
4052 partition_horz_allowed &=
4053 ((bsize <= max_size && bsize > min_size) || force_horz_split);
4054 partition_vert_allowed &=
4055 ((bsize <= max_size && bsize > min_size) || force_vert_split);
4056 do_split &= bsize > min_size;
4057 }
4058
4059 if (cpi->sf.use_square_partition_only &&
4060 (bsize > cpi->sf.use_square_only_thresh_high ||
4061 bsize < cpi->sf.use_square_only_thresh_low)) {
4062 if (cpi->use_svc) {
4063 if (!vp9_active_h_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
4064 partition_horz_allowed &= force_horz_split;
4065 if (!vp9_active_v_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
4066 partition_vert_allowed &= force_vert_split;
4067 } else {
4068 partition_horz_allowed &= force_horz_split;
4069 partition_vert_allowed &= force_vert_split;
4070 }
4071 }
4072
4073 save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4074
4075 pc_tree->partitioning = PARTITION_NONE;
4076
4077 if (cpi->sf.rd_ml_partition.var_pruning && !frame_is_intra_only(cm)) {
4078 const int do_rd_ml_partition_var_pruning =
4079 partition_none_allowed && do_split &&
4080 mi_row + num_8x8_blocks_high_lookup[bsize] <= cm->mi_rows &&
4081 mi_col + num_8x8_blocks_wide_lookup[bsize] <= cm->mi_cols;
4082 if (do_rd_ml_partition_var_pruning) {
4083 ml_predict_var_rd_paritioning(cpi, x, pc_tree, bsize, mi_row, mi_col,
4084 &partition_none_allowed, &do_split);
4085 } else {
4086 vp9_zero(pc_tree->mv);
4087 }
4088 if (bsize > BLOCK_8X8) { // Store MV result as reference for subblocks.
4089 for (i = 0; i < 4; ++i) pc_tree->split[i]->mv = pc_tree->mv;
4090 }
4091 }
4092
4093 // PARTITION_NONE
4094 if (partition_none_allowed) {
4095 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize, ctx,
4096 best_rdc.rate, best_rdc.dist);
4097 ctx->rdcost = this_rdc.rdcost;
4098 if (this_rdc.rate != INT_MAX) {
4099 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4100 const int ref1 = ctx->mic.ref_frame[0];
4101 const int ref2 = ctx->mic.ref_frame[1];
4102 for (i = 0; i < 4; ++i) {
4103 ref_frames_used[i] |= (1 << ref1);
4104 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4105 }
4106 }
4107 if (bsize >= BLOCK_8X8) {
4108 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4109 vp9_rd_cost_update(partition_mul, x->rddiv, &this_rdc);
4110 }
4111
4112 if (this_rdc.rdcost < best_rdc.rdcost) {
4113 MODE_INFO *mi = xd->mi[0];
4114
4115 best_rdc = this_rdc;
4116 should_encode_sb = 1;
4117 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4118
4119 if (cpi->sf.rd_ml_partition.search_early_termination) {
4120 // Currently, the machine-learning based partition search early
4121 // termination is only used while bsize is 16x16, 32x32 or 64x64,
4122 // VPXMIN(cm->width, cm->height) >= 480, and speed = 0.
4123 if (!x->e_mbd.lossless &&
4124 !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP) &&
4125 ctx->mic.mode >= INTRA_MODES && bsize >= BLOCK_16X16) {
4126 if (ml_pruning_partition(cm, xd, ctx, mi_row, mi_col, bsize)) {
4127 do_split = 0;
4128 do_rect = 0;
4129 }
4130 }
4131 }
4132
4133 if ((do_split || do_rect) && !x->e_mbd.lossless && ctx->skippable) {
4134 const int use_ml_based_breakout =
4135 cpi->sf.rd_ml_partition.search_breakout && cm->base_qindex >= 100;
4136 if (use_ml_based_breakout) {
4137 if (ml_predict_breakout(cpi, bsize, x, &this_rdc)) {
4138 do_split = 0;
4139 do_rect = 0;
4140 }
4141 } else {
4142 if (!cpi->sf.rd_ml_partition.search_early_termination) {
4143 if ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4144 (best_rdc.dist < dist_breakout_thr &&
4145 best_rdc.rate < rate_breakout_thr)) {
4146 do_split = 0;
4147 do_rect = 0;
4148 }
4149 }
4150 }
4151 }
4152 }
4153 }
4154 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4155 } else {
4156 vp9_zero(ctx->pred_mv);
4157 ctx->mic.interp_filter = EIGHTTAP;
4158 }
4159
4160 // store estimated motion vector
4161 store_pred_mv(x, ctx);
4162
4163 // If the interp_filter is marked as SWITCHABLE_FILTERS, it was for an
4164 // intra block and used for context purposes.
4165 if (ctx->mic.interp_filter == SWITCHABLE_FILTERS) {
4166 pred_interp_filter = EIGHTTAP;
4167 } else {
4168 pred_interp_filter = ctx->mic.interp_filter;
4169 }
4170
4171 // PARTITION_SPLIT
4172 // TODO(jingning): use the motion vectors given by the above search as
4173 // the starting point of motion search in the following partition type check.
4174 pc_tree->split[0]->none.rdcost = 0;
4175 pc_tree->split[1]->none.rdcost = 0;
4176 pc_tree->split[2]->none.rdcost = 0;
4177 pc_tree->split[3]->none.rdcost = 0;
4178 if (do_split || must_split) {
4179 subsize = get_subsize(bsize, PARTITION_SPLIT);
4180 load_pred_mv(x, ctx);
4181 if (bsize == BLOCK_8X8) {
4182 i = 4;
4183 if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
4184 pc_tree->leaf_split[0]->pred_interp_filter = pred_interp_filter;
4185 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4186 pc_tree->leaf_split[0], best_rdc.rate, best_rdc.dist);
4187 if (sum_rdc.rate == INT_MAX) {
4188 sum_rdc.rdcost = INT64_MAX;
4189 } else {
4190 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4191 const int ref1 = pc_tree->leaf_split[0]->mic.ref_frame[0];
4192 const int ref2 = pc_tree->leaf_split[0]->mic.ref_frame[1];
4193 for (i = 0; i < 4; ++i) {
4194 ref_frames_used[i] |= (1 << ref1);
4195 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4196 }
4197 }
4198 }
4199 } else {
4200 for (i = 0; (i < 4) && ((sum_rdc.rdcost < best_rdc.rdcost) || must_split);
4201 ++i) {
4202 const int x_idx = (i & 1) * mi_step;
4203 const int y_idx = (i >> 1) * mi_step;
4204 int found_best_rd = 0;
4205 RD_COST best_rdc_split;
4206 vp9_rd_cost_reset(&best_rdc_split);
4207
4208 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX) {
4209 // A must split test here increases the number of sub
4210 // partitions but hurts metrics results quite a bit,
4211 // so this extra test is commented out pending
4212 // further tests on whether it adds much in terms of
4213 // visual quality.
4214 // (must_split) ? best_rdc.rate
4215 // : best_rdc.rate - sum_rdc.rate,
4216 // (must_split) ? best_rdc.dist
4217 // : best_rdc.dist - sum_rdc.dist,
4218 best_rdc_split.rate = best_rdc.rate - sum_rdc.rate;
4219 best_rdc_split.dist = best_rdc.dist - sum_rdc.dist;
4220 }
4221
4222 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4223 continue;
4224
4225 pc_tree->split[i]->index = i;
4226 if (cpi->sf.prune_ref_frame_for_rect_partitions)
4227 pc_tree->split[i]->none.rate = INT_MAX;
4228 found_best_rd = rd_pick_partition(
4229 cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx, subsize,
4230 &this_rdc, best_rdc_split, pc_tree->split[i]);
4231
4232 if (found_best_rd == 0) {
4233 sum_rdc.rdcost = INT64_MAX;
4234 break;
4235 } else {
4236 if (cpi->sf.prune_ref_frame_for_rect_partitions &&
4237 pc_tree->split[i]->none.rate != INT_MAX) {
4238 const int ref1 = pc_tree->split[i]->none.mic.ref_frame[0];
4239 const int ref2 = pc_tree->split[i]->none.mic.ref_frame[1];
4240 ref_frames_used[i] |= (1 << ref1);
4241 if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
4242 }
4243 sum_rdc.rate += this_rdc.rate;
4244 sum_rdc.dist += this_rdc.dist;
4245 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4246 }
4247 }
4248 }
4249
4250 if (((sum_rdc.rdcost < best_rdc.rdcost) || must_split) && i == 4) {
4251 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4252 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4253
4254 if ((sum_rdc.rdcost < best_rdc.rdcost) ||
4255 (must_split && (sum_rdc.dist < best_rdc.dist))) {
4256 best_rdc = sum_rdc;
4257 should_encode_sb = 1;
4258 pc_tree->partitioning = PARTITION_SPLIT;
4259
4260 // Rate and distortion based partition search termination clause.
4261 if (!cpi->sf.rd_ml_partition.search_early_termination &&
4262 !x->e_mbd.lossless &&
4263 ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
4264 (best_rdc.dist < dist_breakout_thr &&
4265 best_rdc.rate < rate_breakout_thr))) {
4266 do_rect = 0;
4267 }
4268 }
4269 } else {
4270 // skip rectangular partition test when larger block size
4271 // gives better rd cost
4272 if (cpi->sf.less_rectangular_check &&
4273 (bsize > cpi->sf.use_square_only_thresh_high ||
4274 best_rdc.dist < dist_breakout_thr))
4275 do_rect &= !partition_none_allowed;
4276 }
4277 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4278 }
4279
4280 pc_tree->horizontal[0].skip_ref_frame_mask = 0;
4281 pc_tree->horizontal[1].skip_ref_frame_mask = 0;
4282 pc_tree->vertical[0].skip_ref_frame_mask = 0;
4283 pc_tree->vertical[1].skip_ref_frame_mask = 0;
4284 if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4285 uint8_t used_frames;
4286 used_frames = ref_frames_used[0] | ref_frames_used[1];
4287 if (used_frames) {
4288 pc_tree->horizontal[0].skip_ref_frame_mask = ~used_frames & 0xff;
4289 }
4290 used_frames = ref_frames_used[2] | ref_frames_used[3];
4291 if (used_frames) {
4292 pc_tree->horizontal[1].skip_ref_frame_mask = ~used_frames & 0xff;
4293 }
4294 used_frames = ref_frames_used[0] | ref_frames_used[2];
4295 if (used_frames) {
4296 pc_tree->vertical[0].skip_ref_frame_mask = ~used_frames & 0xff;
4297 }
4298 used_frames = ref_frames_used[1] | ref_frames_used[3];
4299 if (used_frames) {
4300 pc_tree->vertical[1].skip_ref_frame_mask = ~used_frames & 0xff;
4301 }
4302 }
4303
4304 {
4305 const int do_ml_rect_partition_pruning =
4306 !frame_is_intra_only(cm) && !force_horz_split && !force_vert_split &&
4307 (partition_horz_allowed || partition_vert_allowed) && bsize > BLOCK_8X8;
4308 if (do_ml_rect_partition_pruning) {
4309 ml_prune_rect_partition(cpi, x, bsize, pc_tree, &partition_horz_allowed,
4310 &partition_vert_allowed, best_rdc.rdcost);
4311 }
4312 }
4313
4314 // PARTITION_HORZ
4315 if (partition_horz_allowed &&
4316 (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
4317 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_HORZ];
4318 subsize = get_subsize(bsize, PARTITION_HORZ);
4319 load_pred_mv(x, ctx);
4320 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4321 partition_none_allowed)
4322 pc_tree->horizontal[0].pred_interp_filter = pred_interp_filter;
4323 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4324 &pc_tree->horizontal[0], best_rdc.rate - part_mode_rate,
4325 best_rdc.dist);
4326 if (sum_rdc.rdcost < INT64_MAX) {
4327 sum_rdc.rate += part_mode_rate;
4328 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4329 }
4330
4331 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
4332 bsize > BLOCK_8X8) {
4333 PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
4334 update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
4335 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
4336 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4337 partition_none_allowed)
4338 pc_tree->horizontal[1].pred_interp_filter = pred_interp_filter;
4339 rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col, &this_rdc,
4340 subsize, &pc_tree->horizontal[1],
4341 best_rdc.rate - sum_rdc.rate,
4342 best_rdc.dist - sum_rdc.dist);
4343 if (this_rdc.rate == INT_MAX) {
4344 sum_rdc.rdcost = INT64_MAX;
4345 } else {
4346 sum_rdc.rate += this_rdc.rate;
4347 sum_rdc.dist += this_rdc.dist;
4348 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4349 }
4350 }
4351
4352 if (sum_rdc.rdcost < best_rdc.rdcost) {
4353 best_rdc = sum_rdc;
4354 should_encode_sb = 1;
4355 pc_tree->partitioning = PARTITION_HORZ;
4356
4357 if (cpi->sf.less_rectangular_check &&
4358 bsize > cpi->sf.use_square_only_thresh_high)
4359 do_rect = 0;
4360 }
4361 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4362 }
4363
4364 // PARTITION_VERT
4365 if (partition_vert_allowed &&
4366 (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
4367 const int part_mode_rate = cpi->partition_cost[pl][PARTITION_VERT];
4368 subsize = get_subsize(bsize, PARTITION_VERT);
4369 load_pred_mv(x, ctx);
4370 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4371 partition_none_allowed)
4372 pc_tree->vertical[0].pred_interp_filter = pred_interp_filter;
4373 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4374 &pc_tree->vertical[0], best_rdc.rate - part_mode_rate,
4375 best_rdc.dist);
4376 if (sum_rdc.rdcost < INT64_MAX) {
4377 sum_rdc.rate += part_mode_rate;
4378 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4379 }
4380
4381 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
4382 bsize > BLOCK_8X8) {
4383 update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
4384 encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
4385 &pc_tree->vertical[0]);
4386 if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4387 partition_none_allowed)
4388 pc_tree->vertical[1].pred_interp_filter = pred_interp_filter;
4389 rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step, &this_rdc,
4390 subsize, &pc_tree->vertical[1],
4391 best_rdc.rate - sum_rdc.rate,
4392 best_rdc.dist - sum_rdc.dist);
4393 if (this_rdc.rate == INT_MAX) {
4394 sum_rdc.rdcost = INT64_MAX;
4395 } else {
4396 sum_rdc.rate += this_rdc.rate;
4397 sum_rdc.dist += this_rdc.dist;
4398 vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4399 }
4400 }
4401
4402 if (sum_rdc.rdcost < best_rdc.rdcost) {
4403 best_rdc = sum_rdc;
4404 should_encode_sb = 1;
4405 pc_tree->partitioning = PARTITION_VERT;
4406 }
4407 restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4408 }
4409
4410 *rd_cost = best_rdc;
4411
4412 if (should_encode_sb && pc_tree->index != 3) {
4413 int output_enabled = (bsize == BLOCK_64X64);
4414 encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4415 pc_tree);
4416 #if CONFIG_RATE_CTRL
4417 if (oxcf->use_simple_encode_api) {
4418 // Store partition, motion vector of the superblock.
4419 if (output_enabled) {
4420 const int num_unit_rows =
4421 get_num_unit_4x4(cpi->frame_info.frame_height);
4422 const int num_unit_cols = get_num_unit_4x4(cpi->frame_info.frame_width);
4423 store_superblock_info(pc_tree, cm->mi_grid_visible, cm->mi_stride,
4424 num_4x4_blocks_wide_lookup[BLOCK_64X64],
4425 num_unit_rows, num_unit_cols, mi_row << 1,
4426 mi_col << 1, cpi->partition_info,
4427 cpi->motion_vector_info);
4428 }
4429 }
4430 #endif // CONFIG_RATE_CTRL
4431 }
4432
4433 if (bsize == BLOCK_64X64) {
4434 assert(tp_orig < *tp);
4435 assert(best_rdc.rate < INT_MAX);
4436 assert(best_rdc.dist < INT64_MAX);
4437 } else {
4438 assert(tp_orig == *tp);
4439 }
4440
4441 return should_encode_sb;
4442 }
4443
encode_rd_sb_row(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,int mi_row,TOKENEXTRA ** tp)4444 static void encode_rd_sb_row(VP9_COMP *cpi, ThreadData *td,
4445 TileDataEnc *tile_data, int mi_row,
4446 TOKENEXTRA **tp) {
4447 VP9_COMMON *const cm = &cpi->common;
4448 TileInfo *const tile_info = &tile_data->tile_info;
4449 MACROBLOCK *const x = &td->mb;
4450 MACROBLOCKD *const xd = &x->e_mbd;
4451 SPEED_FEATURES *const sf = &cpi->sf;
4452 const int mi_col_start = tile_info->mi_col_start;
4453 const int mi_col_end = tile_info->mi_col_end;
4454 int mi_col;
4455 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
4456 const int num_sb_cols =
4457 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
4458 int sb_col_in_tile;
4459
4460 // Initialize the left context for the new SB row
4461 memset(&xd->left_context, 0, sizeof(xd->left_context));
4462 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
4463
4464 // Code each SB in the row
4465 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
4466 mi_col += MI_BLOCK_SIZE, sb_col_in_tile++) {
4467 const struct segmentation *const seg = &cm->seg;
4468 int dummy_rate;
4469 int64_t dummy_dist;
4470 RD_COST dummy_rdc;
4471 int i;
4472 int seg_skip = 0;
4473 int orig_rdmult = cpi->rd.RDMULT;
4474
4475 const int idx_str = cm->mi_stride * mi_row + mi_col;
4476 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
4477
4478 vp9_rd_cost_reset(&dummy_rdc);
4479 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
4480 sb_col_in_tile);
4481
4482 if (sf->adaptive_pred_interp_filter) {
4483 for (i = 0; i < 64; ++i) td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
4484
4485 for (i = 0; i < 64; ++i) {
4486 td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
4487 td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
4488 td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
4489 td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
4490 }
4491 }
4492
4493 for (i = 0; i < MAX_REF_FRAMES; ++i) {
4494 x->pred_mv[i].row = INT16_MAX;
4495 x->pred_mv[i].col = INT16_MAX;
4496 }
4497 td->pc_root->index = 0;
4498
4499 if (seg->enabled) {
4500 const uint8_t *const map =
4501 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
4502 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
4503 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
4504 }
4505
4506 x->source_variance = UINT_MAX;
4507
4508 x->cb_rdmult = orig_rdmult;
4509
4510 if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
4511 const BLOCK_SIZE bsize =
4512 seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
4513 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4514 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4515 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4516 &dummy_rate, &dummy_dist, 1, td->pc_root);
4517 } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
4518 cm->frame_type != KEY_FRAME) {
4519 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
4520 rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4521 &dummy_rate, &dummy_dist, 1, td->pc_root);
4522 } else {
4523 if (cpi->twopass.gf_group.index > 0 && cpi->sf.enable_tpl_model) {
4524 int dr =
4525 get_rdmult_delta(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4526 x->cb_rdmult = dr;
4527 }
4528
4529 if (cpi->oxcf.aq_mode == PERCEPTUAL_AQ && cm->show_frame) {
4530 x->segment_id = wiener_var_segment(cpi, BLOCK_64X64, mi_row, mi_col);
4531 x->cb_rdmult = vp9_compute_rd_mult(
4532 cpi, vp9_get_qindex(&cm->seg, x->segment_id, cm->base_qindex));
4533 }
4534
4535 // If required set upper and lower partition size limits
4536 if (sf->auto_min_max_partition_size) {
4537 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4538 rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
4539 &x->min_partition_size, &x->max_partition_size);
4540 }
4541 td->pc_root->none.rdcost = 0;
4542 rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
4543 &dummy_rdc, dummy_rdc, td->pc_root);
4544 }
4545 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
4546 sb_col_in_tile, num_sb_cols);
4547 }
4548 }
4549 #endif // !CONFIG_REALTIME_ONLY
4550
init_encode_frame_mb_context(VP9_COMP * cpi)4551 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
4552 MACROBLOCK *const x = &cpi->td.mb;
4553 VP9_COMMON *const cm = &cpi->common;
4554 MACROBLOCKD *const xd = &x->e_mbd;
4555 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
4556
4557 // Copy data over into macro block data structures.
4558 vp9_setup_src_planes(x, cpi->Source, 0, 0);
4559
4560 vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
4561
4562 // Note: this memset assumes above_context[0], [1] and [2]
4563 // are allocated as part of the same buffer.
4564 memset(xd->above_context[0], 0,
4565 sizeof(*xd->above_context[0]) * 2 * aligned_mi_cols * MAX_MB_PLANE);
4566 memset(xd->above_seg_context, 0,
4567 sizeof(*xd->above_seg_context) * aligned_mi_cols);
4568 }
4569
check_dual_ref_flags(VP9_COMP * cpi)4570 static int check_dual_ref_flags(VP9_COMP *cpi) {
4571 const int ref_flags = cpi->ref_frame_flags;
4572
4573 if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
4574 return 0;
4575 } else {
4576 return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG) +
4577 !!(ref_flags & VP9_ALT_FLAG)) >= 2;
4578 }
4579 }
4580
reset_skip_tx_size(VP9_COMMON * cm,TX_SIZE max_tx_size)4581 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
4582 int mi_row, mi_col;
4583 const int mis = cm->mi_stride;
4584 MODE_INFO **mi_ptr = cm->mi_grid_visible;
4585
4586 for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
4587 for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
4588 if (mi_ptr[mi_col]->tx_size > max_tx_size)
4589 mi_ptr[mi_col]->tx_size = max_tx_size;
4590 }
4591 }
4592 }
4593
get_frame_type(const VP9_COMP * cpi)4594 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
4595 if (frame_is_intra_only(&cpi->common))
4596 return INTRA_FRAME;
4597 else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
4598 return ALTREF_FRAME;
4599 else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
4600 return GOLDEN_FRAME;
4601 else
4602 return LAST_FRAME;
4603 }
4604
select_tx_mode(const VP9_COMP * cpi,MACROBLOCKD * const xd)4605 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
4606 if (xd->lossless) return ONLY_4X4;
4607 if (cpi->common.frame_type == KEY_FRAME && cpi->sf.use_nonrd_pick_mode)
4608 return ALLOW_16X16;
4609 if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
4610 return ALLOW_32X32;
4611 else if (cpi->sf.tx_size_search_method == USE_FULL_RD ||
4612 cpi->sf.tx_size_search_method == USE_TX_8X8)
4613 return TX_MODE_SELECT;
4614 else
4615 return cpi->common.tx_mode;
4616 }
4617
hybrid_intra_mode_search(VP9_COMP * cpi,MACROBLOCK * const x,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)4618 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
4619 RD_COST *rd_cost, BLOCK_SIZE bsize,
4620 PICK_MODE_CONTEXT *ctx) {
4621 if (!cpi->sf.nonrd_keyframe && bsize < BLOCK_16X16)
4622 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4623 else
4624 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4625 }
4626
hybrid_search_svc_baseiskey(VP9_COMP * cpi,MACROBLOCK * const x,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,TileDataEnc * tile_data,int mi_row,int mi_col)4627 static void hybrid_search_svc_baseiskey(VP9_COMP *cpi, MACROBLOCK *const x,
4628 RD_COST *rd_cost, BLOCK_SIZE bsize,
4629 PICK_MODE_CONTEXT *ctx,
4630 TileDataEnc *tile_data, int mi_row,
4631 int mi_col) {
4632 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4633 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4634 } else {
4635 if (cpi->svc.disable_inter_layer_pred == INTER_LAYER_PRED_OFF)
4636 vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4637 else if (bsize >= BLOCK_8X8)
4638 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4639 ctx);
4640 else
4641 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4642 }
4643 }
4644
hybrid_search_scene_change(VP9_COMP * cpi,MACROBLOCK * const x,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,TileDataEnc * tile_data,int mi_row,int mi_col)4645 static void hybrid_search_scene_change(VP9_COMP *cpi, MACROBLOCK *const x,
4646 RD_COST *rd_cost, BLOCK_SIZE bsize,
4647 PICK_MODE_CONTEXT *ctx,
4648 TileDataEnc *tile_data, int mi_row,
4649 int mi_col) {
4650 if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4651 vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4652 } else {
4653 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize, ctx);
4654 }
4655 }
4656
nonrd_pick_sb_modes(VP9_COMP * cpi,TileDataEnc * tile_data,MACROBLOCK * const x,int mi_row,int mi_col,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)4657 static void nonrd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
4658 MACROBLOCK *const x, int mi_row, int mi_col,
4659 RD_COST *rd_cost, BLOCK_SIZE bsize,
4660 PICK_MODE_CONTEXT *ctx) {
4661 VP9_COMMON *const cm = &cpi->common;
4662 TileInfo *const tile_info = &tile_data->tile_info;
4663 MACROBLOCKD *const xd = &x->e_mbd;
4664 MODE_INFO *mi;
4665 ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
4666 BLOCK_SIZE bs = VPXMAX(bsize, BLOCK_8X8); // processing unit block size
4667 const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bs];
4668 const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bs];
4669 int plane;
4670
4671 set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4672
4673 set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
4674
4675 mi = xd->mi[0];
4676 mi->sb_type = bsize;
4677
4678 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4679 struct macroblockd_plane *pd = &xd->plane[plane];
4680 memcpy(a + num_4x4_blocks_wide * plane, pd->above_context,
4681 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4682 memcpy(l + num_4x4_blocks_high * plane, pd->left_context,
4683 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4684 }
4685
4686 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
4687 if (cyclic_refresh_segment_id_boosted(mi->segment_id))
4688 x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
4689
4690 if (frame_is_intra_only(cm))
4691 hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
4692 else if (cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
4693 hybrid_search_svc_baseiskey(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4694 mi_col);
4695 else if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
4696 set_mode_info_seg_skip(x, cm->tx_mode, cm->interp_filter, rd_cost, bsize);
4697 else if (bsize >= BLOCK_8X8) {
4698 if (cpi->rc.hybrid_intra_scene_change)
4699 hybrid_search_scene_change(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4700 mi_col);
4701 else
4702 vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4703 ctx);
4704 } else {
4705 vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4706 }
4707
4708 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4709
4710 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4711 struct macroblockd_plane *pd = &xd->plane[plane];
4712 memcpy(pd->above_context, a + num_4x4_blocks_wide * plane,
4713 (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4714 memcpy(pd->left_context, l + num_4x4_blocks_high * plane,
4715 (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4716 }
4717
4718 if (rd_cost->rate == INT_MAX) vp9_rd_cost_reset(rd_cost);
4719
4720 ctx->rate = rd_cost->rate;
4721 ctx->dist = rd_cost->dist;
4722 }
4723
fill_mode_info_sb(VP9_COMMON * cm,MACROBLOCK * x,int mi_row,int mi_col,BLOCK_SIZE bsize,PC_TREE * pc_tree)4724 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x, int mi_row,
4725 int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4726 MACROBLOCKD *xd = &x->e_mbd;
4727 int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4728 PARTITION_TYPE partition = pc_tree->partitioning;
4729 BLOCK_SIZE subsize = get_subsize(bsize, partition);
4730
4731 assert(bsize >= BLOCK_8X8);
4732
4733 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4734
4735 switch (partition) {
4736 case PARTITION_NONE:
4737 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4738 *(xd->mi[0]) = pc_tree->none.mic;
4739 *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
4740 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4741 break;
4742 case PARTITION_VERT:
4743 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4744 *(xd->mi[0]) = pc_tree->vertical[0].mic;
4745 *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
4746 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4747
4748 if (mi_col + hbs < cm->mi_cols) {
4749 set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
4750 *(xd->mi[0]) = pc_tree->vertical[1].mic;
4751 *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
4752 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
4753 }
4754 break;
4755 case PARTITION_HORZ:
4756 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4757 *(xd->mi[0]) = pc_tree->horizontal[0].mic;
4758 *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
4759 duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4760 if (mi_row + hbs < cm->mi_rows) {
4761 set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
4762 *(xd->mi[0]) = pc_tree->horizontal[1].mic;
4763 *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
4764 duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
4765 }
4766 break;
4767 case PARTITION_SPLIT: {
4768 fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
4769 fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
4770 pc_tree->split[1]);
4771 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
4772 pc_tree->split[2]);
4773 fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
4774 pc_tree->split[3]);
4775 break;
4776 }
4777 default: break;
4778 }
4779 }
4780
4781 // Reset the prediction pixel ready flag recursively.
pred_pixel_ready_reset(PC_TREE * pc_tree,BLOCK_SIZE bsize)4782 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
4783 pc_tree->none.pred_pixel_ready = 0;
4784 pc_tree->horizontal[0].pred_pixel_ready = 0;
4785 pc_tree->horizontal[1].pred_pixel_ready = 0;
4786 pc_tree->vertical[0].pred_pixel_ready = 0;
4787 pc_tree->vertical[1].pred_pixel_ready = 0;
4788
4789 if (bsize > BLOCK_8X8) {
4790 BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4791 int i;
4792 for (i = 0; i < 4; ++i) pred_pixel_ready_reset(pc_tree->split[i], subsize);
4793 }
4794 }
4795
4796 #define FEATURES 6
4797 #define LABELS 2
ml_predict_var_paritioning(VP9_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int mi_row,int mi_col)4798 static int ml_predict_var_paritioning(VP9_COMP *cpi, MACROBLOCK *x,
4799 BLOCK_SIZE bsize, int mi_row,
4800 int mi_col) {
4801 VP9_COMMON *const cm = &cpi->common;
4802 const NN_CONFIG *nn_config = NULL;
4803
4804 switch (bsize) {
4805 case BLOCK_64X64: nn_config = &vp9_var_part_nnconfig_64; break;
4806 case BLOCK_32X32: nn_config = &vp9_var_part_nnconfig_32; break;
4807 case BLOCK_16X16: nn_config = &vp9_var_part_nnconfig_16; break;
4808 case BLOCK_8X8: break;
4809 default: assert(0 && "Unexpected block size."); return -1;
4810 }
4811
4812 if (!nn_config) return -1;
4813
4814 vpx_clear_system_state();
4815
4816 {
4817 const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
4818 float features[FEATURES] = { 0.0f };
4819 const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
4820 int feature_idx = 0;
4821 float score[LABELS];
4822
4823 features[feature_idx++] = logf((float)(dc_q * dc_q) / 256.0f + 1.0f);
4824 vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
4825 {
4826 const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
4827 const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4828 const int sb_offset_row = 8 * (mi_row & 7);
4829 const int sb_offset_col = 8 * (mi_col & 7);
4830 const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
4831 const uint8_t *src = x->plane[0].src.buf;
4832 const int src_stride = x->plane[0].src.stride;
4833 const int pred_stride = 64;
4834 unsigned int sse;
4835 int i;
4836 // Variance of whole block.
4837 const unsigned int var =
4838 cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
4839 const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
4840
4841 features[feature_idx++] = logf((float)var + 1.0f);
4842 for (i = 0; i < 4; ++i) {
4843 const int x_idx = (i & 1) * bs / 2;
4844 const int y_idx = (i >> 1) * bs / 2;
4845 const int src_offset = y_idx * src_stride + x_idx;
4846 const int pred_offset = y_idx * pred_stride + x_idx;
4847 // Variance of quarter block.
4848 const unsigned int sub_var =
4849 cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
4850 pred + pred_offset, pred_stride, &sse);
4851 const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
4852 features[feature_idx++] = var_ratio;
4853 }
4854 }
4855
4856 assert(feature_idx == FEATURES);
4857 nn_predict(features, nn_config, score);
4858 if (score[0] > thresh) return PARTITION_SPLIT;
4859 if (score[0] < -thresh) return PARTITION_NONE;
4860 return -1;
4861 }
4862 }
4863 #undef FEATURES
4864 #undef LABELS
4865
nonrd_pick_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,RD_COST * rd_cost,int do_recon,int64_t best_rd,PC_TREE * pc_tree)4866 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
4867 TileDataEnc *tile_data, TOKENEXTRA **tp,
4868 int mi_row, int mi_col, BLOCK_SIZE bsize,
4869 RD_COST *rd_cost, int do_recon,
4870 int64_t best_rd, PC_TREE *pc_tree) {
4871 const SPEED_FEATURES *const sf = &cpi->sf;
4872 VP9_COMMON *const cm = &cpi->common;
4873 TileInfo *const tile_info = &tile_data->tile_info;
4874 MACROBLOCK *const x = &td->mb;
4875 MACROBLOCKD *const xd = &x->e_mbd;
4876 const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
4877 TOKENEXTRA *tp_orig = *tp;
4878 PICK_MODE_CONTEXT *ctx = &pc_tree->none;
4879 int i;
4880 BLOCK_SIZE subsize = bsize;
4881 RD_COST this_rdc, sum_rdc, best_rdc;
4882 int do_split = bsize >= BLOCK_8X8;
4883 int do_rect = 1;
4884 // Override skipping rectangular partition operations for edge blocks
4885 const int force_horz_split = (mi_row + ms >= cm->mi_rows);
4886 const int force_vert_split = (mi_col + ms >= cm->mi_cols);
4887 const int xss = x->e_mbd.plane[1].subsampling_x;
4888 const int yss = x->e_mbd.plane[1].subsampling_y;
4889
4890 int partition_none_allowed = !force_horz_split && !force_vert_split;
4891 int partition_horz_allowed =
4892 !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
4893 int partition_vert_allowed =
4894 !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
4895 const int use_ml_based_partitioning =
4896 sf->partition_search_type == ML_BASED_PARTITION;
4897
4898 (void)*tp_orig;
4899
4900 // Avoid checking for rectangular partitions for speed >= 5.
4901 if (cpi->oxcf.speed >= 5) do_rect = 0;
4902
4903 assert(num_8x8_blocks_wide_lookup[bsize] ==
4904 num_8x8_blocks_high_lookup[bsize]);
4905
4906 vp9_rd_cost_init(&sum_rdc);
4907 vp9_rd_cost_reset(&best_rdc);
4908 best_rdc.rdcost = best_rd;
4909
4910 // Determine partition types in search according to the speed features.
4911 // The threshold set here has to be of square block size.
4912 if (sf->auto_min_max_partition_size) {
4913 partition_none_allowed &=
4914 (bsize <= x->max_partition_size && bsize >= x->min_partition_size);
4915 partition_horz_allowed &=
4916 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4917 force_horz_split);
4918 partition_vert_allowed &=
4919 ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4920 force_vert_split);
4921 do_split &= bsize > x->min_partition_size;
4922 }
4923 if (sf->use_square_partition_only) {
4924 partition_horz_allowed &= force_horz_split;
4925 partition_vert_allowed &= force_vert_split;
4926 }
4927
4928 if (use_ml_based_partitioning) {
4929 if (partition_none_allowed || do_split) do_rect = 0;
4930 if (partition_none_allowed && do_split) {
4931 const int ml_predicted_partition =
4932 ml_predict_var_paritioning(cpi, x, bsize, mi_row, mi_col);
4933 if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
4934 if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
4935 }
4936 }
4937
4938 if (!partition_none_allowed && !do_split) do_rect = 1;
4939
4940 ctx->pred_pixel_ready =
4941 !(partition_vert_allowed || partition_horz_allowed || do_split);
4942
4943 // PARTITION_NONE
4944 if (partition_none_allowed) {
4945 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
4946 ctx);
4947 ctx->mic = *xd->mi[0];
4948 ctx->mbmi_ext = *x->mbmi_ext;
4949 ctx->skip_txfm[0] = x->skip_txfm[0];
4950 ctx->skip = x->skip;
4951
4952 if (this_rdc.rate != INT_MAX) {
4953 const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4954 this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4955 this_rdc.rdcost =
4956 RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
4957 if (this_rdc.rdcost < best_rdc.rdcost) {
4958 best_rdc = this_rdc;
4959 if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4960
4961 if (!use_ml_based_partitioning) {
4962 int64_t dist_breakout_thr = sf->partition_search_breakout_thr.dist;
4963 int64_t rate_breakout_thr = sf->partition_search_breakout_thr.rate;
4964 dist_breakout_thr >>=
4965 8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4966 rate_breakout_thr *= num_pels_log2_lookup[bsize];
4967 if (!x->e_mbd.lossless && this_rdc.rate < rate_breakout_thr &&
4968 this_rdc.dist < dist_breakout_thr) {
4969 do_split = 0;
4970 do_rect = 0;
4971 }
4972 }
4973 }
4974 }
4975 }
4976
4977 // store estimated motion vector
4978 store_pred_mv(x, ctx);
4979
4980 // PARTITION_SPLIT
4981 if (do_split) {
4982 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4983 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4984 sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4985 subsize = get_subsize(bsize, PARTITION_SPLIT);
4986 for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
4987 const int x_idx = (i & 1) * ms;
4988 const int y_idx = (i >> 1) * ms;
4989
4990 if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4991 continue;
4992 load_pred_mv(x, ctx);
4993 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row + y_idx,
4994 mi_col + x_idx, subsize, &this_rdc, 0,
4995 best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
4996
4997 if (this_rdc.rate == INT_MAX) {
4998 vp9_rd_cost_reset(&sum_rdc);
4999 } else {
5000 sum_rdc.rate += this_rdc.rate;
5001 sum_rdc.dist += this_rdc.dist;
5002 sum_rdc.rdcost += this_rdc.rdcost;
5003 }
5004 }
5005
5006 if (sum_rdc.rdcost < best_rdc.rdcost) {
5007 best_rdc = sum_rdc;
5008 pc_tree->partitioning = PARTITION_SPLIT;
5009 } else {
5010 // skip rectangular partition test when larger block size
5011 // gives better rd cost
5012 if (sf->less_rectangular_check) do_rect &= !partition_none_allowed;
5013 }
5014 }
5015
5016 // PARTITION_HORZ
5017 if (partition_horz_allowed && do_rect) {
5018 subsize = get_subsize(bsize, PARTITION_HORZ);
5019 load_pred_mv(x, ctx);
5020 pc_tree->horizontal[0].pred_pixel_ready = 1;
5021 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
5022 &pc_tree->horizontal[0]);
5023
5024 pc_tree->horizontal[0].mic = *xd->mi[0];
5025 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5026 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5027 pc_tree->horizontal[0].skip = x->skip;
5028
5029 if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
5030 load_pred_mv(x, ctx);
5031 pc_tree->horizontal[1].pred_pixel_ready = 1;
5032 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc,
5033 subsize, &pc_tree->horizontal[1]);
5034
5035 pc_tree->horizontal[1].mic = *xd->mi[0];
5036 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5037 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5038 pc_tree->horizontal[1].skip = x->skip;
5039
5040 if (this_rdc.rate == INT_MAX) {
5041 vp9_rd_cost_reset(&sum_rdc);
5042 } else {
5043 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
5044 this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
5045 sum_rdc.rate += this_rdc.rate;
5046 sum_rdc.dist += this_rdc.dist;
5047 sum_rdc.rdcost =
5048 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
5049 }
5050 }
5051
5052 if (sum_rdc.rdcost < best_rdc.rdcost) {
5053 best_rdc = sum_rdc;
5054 pc_tree->partitioning = PARTITION_HORZ;
5055 } else {
5056 pred_pixel_ready_reset(pc_tree, bsize);
5057 }
5058 }
5059
5060 // PARTITION_VERT
5061 if (partition_vert_allowed && do_rect) {
5062 subsize = get_subsize(bsize, PARTITION_VERT);
5063 load_pred_mv(x, ctx);
5064 pc_tree->vertical[0].pred_pixel_ready = 1;
5065 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
5066 &pc_tree->vertical[0]);
5067 pc_tree->vertical[0].mic = *xd->mi[0];
5068 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5069 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5070 pc_tree->vertical[0].skip = x->skip;
5071
5072 if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
5073 load_pred_mv(x, ctx);
5074 pc_tree->vertical[1].pred_pixel_ready = 1;
5075 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc,
5076 subsize, &pc_tree->vertical[1]);
5077 pc_tree->vertical[1].mic = *xd->mi[0];
5078 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5079 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5080 pc_tree->vertical[1].skip = x->skip;
5081
5082 if (this_rdc.rate == INT_MAX) {
5083 vp9_rd_cost_reset(&sum_rdc);
5084 } else {
5085 int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
5086 sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
5087 sum_rdc.rate += this_rdc.rate;
5088 sum_rdc.dist += this_rdc.dist;
5089 sum_rdc.rdcost =
5090 RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
5091 }
5092 }
5093
5094 if (sum_rdc.rdcost < best_rdc.rdcost) {
5095 best_rdc = sum_rdc;
5096 pc_tree->partitioning = PARTITION_VERT;
5097 } else {
5098 pred_pixel_ready_reset(pc_tree, bsize);
5099 }
5100 }
5101
5102 *rd_cost = best_rdc;
5103
5104 if (best_rdc.rate == INT_MAX) {
5105 vp9_rd_cost_reset(rd_cost);
5106 return;
5107 }
5108
5109 // update mode info array
5110 fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
5111
5112 if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
5113 int output_enabled = (bsize == BLOCK_64X64);
5114 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
5115 pc_tree);
5116 }
5117
5118 if (bsize == BLOCK_64X64 && do_recon) {
5119 assert(tp_orig < *tp);
5120 assert(best_rdc.rate < INT_MAX);
5121 assert(best_rdc.dist < INT64_MAX);
5122 } else {
5123 assert(tp_orig == *tp);
5124 }
5125 }
5126
nonrd_select_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,MODE_INFO ** mi,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,int output_enabled,RD_COST * rd_cost,PC_TREE * pc_tree)5127 static void nonrd_select_partition(VP9_COMP *cpi, ThreadData *td,
5128 TileDataEnc *tile_data, MODE_INFO **mi,
5129 TOKENEXTRA **tp, int mi_row, int mi_col,
5130 BLOCK_SIZE bsize, int output_enabled,
5131 RD_COST *rd_cost, PC_TREE *pc_tree) {
5132 VP9_COMMON *const cm = &cpi->common;
5133 TileInfo *const tile_info = &tile_data->tile_info;
5134 MACROBLOCK *const x = &td->mb;
5135 MACROBLOCKD *const xd = &x->e_mbd;
5136 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5137 const int mis = cm->mi_stride;
5138 PARTITION_TYPE partition;
5139 BLOCK_SIZE subsize;
5140 RD_COST this_rdc;
5141 BLOCK_SIZE subsize_ref =
5142 (cpi->sf.adapt_partition_source_sad) ? BLOCK_8X8 : BLOCK_16X16;
5143
5144 vp9_rd_cost_reset(&this_rdc);
5145 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5146
5147 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5148 partition = partition_lookup[bsl][subsize];
5149
5150 if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
5151 x->max_partition_size = BLOCK_32X32;
5152 x->min_partition_size = BLOCK_16X16;
5153 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5154 0, INT64_MAX, pc_tree);
5155 } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
5156 subsize >= subsize_ref) {
5157 x->max_partition_size = BLOCK_32X32;
5158 x->min_partition_size = BLOCK_8X8;
5159 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5160 0, INT64_MAX, pc_tree);
5161 } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
5162 x->max_partition_size = BLOCK_16X16;
5163 x->min_partition_size = BLOCK_8X8;
5164 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
5165 0, INT64_MAX, pc_tree);
5166 } else {
5167 switch (partition) {
5168 case PARTITION_NONE:
5169 pc_tree->none.pred_pixel_ready = 1;
5170 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5171 &pc_tree->none);
5172 pc_tree->none.mic = *xd->mi[0];
5173 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5174 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5175 pc_tree->none.skip = x->skip;
5176 break;
5177 case PARTITION_VERT:
5178 pc_tree->vertical[0].pred_pixel_ready = 1;
5179 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5180 &pc_tree->vertical[0]);
5181 pc_tree->vertical[0].mic = *xd->mi[0];
5182 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5183 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5184 pc_tree->vertical[0].skip = x->skip;
5185 if (mi_col + hbs < cm->mi_cols) {
5186 pc_tree->vertical[1].pred_pixel_ready = 1;
5187 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
5188 &this_rdc, subsize, &pc_tree->vertical[1]);
5189 pc_tree->vertical[1].mic = *xd->mi[0];
5190 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5191 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5192 pc_tree->vertical[1].skip = x->skip;
5193 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5194 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5195 rd_cost->rate += this_rdc.rate;
5196 rd_cost->dist += this_rdc.dist;
5197 }
5198 }
5199 break;
5200 case PARTITION_HORZ:
5201 pc_tree->horizontal[0].pred_pixel_ready = 1;
5202 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
5203 &pc_tree->horizontal[0]);
5204 pc_tree->horizontal[0].mic = *xd->mi[0];
5205 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5206 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5207 pc_tree->horizontal[0].skip = x->skip;
5208 if (mi_row + hbs < cm->mi_rows) {
5209 pc_tree->horizontal[1].pred_pixel_ready = 1;
5210 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
5211 &this_rdc, subsize, &pc_tree->horizontal[1]);
5212 pc_tree->horizontal[1].mic = *xd->mi[0];
5213 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5214 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5215 pc_tree->horizontal[1].skip = x->skip;
5216 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5217 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5218 rd_cost->rate += this_rdc.rate;
5219 rd_cost->dist += this_rdc.dist;
5220 }
5221 }
5222 break;
5223 default:
5224 assert(partition == PARTITION_SPLIT);
5225 subsize = get_subsize(bsize, PARTITION_SPLIT);
5226 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5227 subsize, output_enabled, rd_cost,
5228 pc_tree->split[0]);
5229 nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5230 mi_col + hbs, subsize, output_enabled, &this_rdc,
5231 pc_tree->split[1]);
5232 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5233 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5234 rd_cost->rate += this_rdc.rate;
5235 rd_cost->dist += this_rdc.dist;
5236 }
5237 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5238 mi_row + hbs, mi_col, subsize, output_enabled,
5239 &this_rdc, pc_tree->split[2]);
5240 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5241 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5242 rd_cost->rate += this_rdc.rate;
5243 rd_cost->dist += this_rdc.dist;
5244 }
5245 nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5246 mi_row + hbs, mi_col + hbs, subsize,
5247 output_enabled, &this_rdc, pc_tree->split[3]);
5248 if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
5249 rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
5250 rd_cost->rate += this_rdc.rate;
5251 rd_cost->dist += this_rdc.dist;
5252 }
5253 break;
5254 }
5255 }
5256
5257 if (bsize == BLOCK_64X64 && output_enabled)
5258 encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
5259 }
5260
nonrd_use_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,MODE_INFO ** mi,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,int output_enabled,RD_COST * dummy_cost,PC_TREE * pc_tree)5261 static void nonrd_use_partition(VP9_COMP *cpi, ThreadData *td,
5262 TileDataEnc *tile_data, MODE_INFO **mi,
5263 TOKENEXTRA **tp, int mi_row, int mi_col,
5264 BLOCK_SIZE bsize, int output_enabled,
5265 RD_COST *dummy_cost, PC_TREE *pc_tree) {
5266 VP9_COMMON *const cm = &cpi->common;
5267 TileInfo *tile_info = &tile_data->tile_info;
5268 MACROBLOCK *const x = &td->mb;
5269 MACROBLOCKD *const xd = &x->e_mbd;
5270 const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5271 const int mis = cm->mi_stride;
5272 PARTITION_TYPE partition;
5273 BLOCK_SIZE subsize;
5274
5275 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5276
5277 subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5278 partition = partition_lookup[bsl][subsize];
5279
5280 if (output_enabled && bsize != BLOCK_4X4) {
5281 int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
5282 td->counts->partition[ctx][partition]++;
5283 }
5284
5285 switch (partition) {
5286 case PARTITION_NONE:
5287 pc_tree->none.pred_pixel_ready = 1;
5288 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5289 subsize, &pc_tree->none);
5290 pc_tree->none.mic = *xd->mi[0];
5291 pc_tree->none.mbmi_ext = *x->mbmi_ext;
5292 pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5293 pc_tree->none.skip = x->skip;
5294 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5295 subsize, &pc_tree->none);
5296 break;
5297 case PARTITION_VERT:
5298 pc_tree->vertical[0].pred_pixel_ready = 1;
5299 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5300 subsize, &pc_tree->vertical[0]);
5301 pc_tree->vertical[0].mic = *xd->mi[0];
5302 pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5303 pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5304 pc_tree->vertical[0].skip = x->skip;
5305 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5306 subsize, &pc_tree->vertical[0]);
5307 if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
5308 pc_tree->vertical[1].pred_pixel_ready = 1;
5309 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost,
5310 subsize, &pc_tree->vertical[1]);
5311 pc_tree->vertical[1].mic = *xd->mi[0];
5312 pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5313 pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5314 pc_tree->vertical[1].skip = x->skip;
5315 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
5316 output_enabled, subsize, &pc_tree->vertical[1]);
5317 }
5318 break;
5319 case PARTITION_HORZ:
5320 pc_tree->horizontal[0].pred_pixel_ready = 1;
5321 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5322 subsize, &pc_tree->horizontal[0]);
5323 pc_tree->horizontal[0].mic = *xd->mi[0];
5324 pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5325 pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5326 pc_tree->horizontal[0].skip = x->skip;
5327 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5328 subsize, &pc_tree->horizontal[0]);
5329
5330 if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
5331 pc_tree->horizontal[1].pred_pixel_ready = 1;
5332 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost,
5333 subsize, &pc_tree->horizontal[1]);
5334 pc_tree->horizontal[1].mic = *xd->mi[0];
5335 pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5336 pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5337 pc_tree->horizontal[1].skip = x->skip;
5338 encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
5339 output_enabled, subsize, &pc_tree->horizontal[1]);
5340 }
5341 break;
5342 default:
5343 assert(partition == PARTITION_SPLIT);
5344 subsize = get_subsize(bsize, PARTITION_SPLIT);
5345 if (bsize == BLOCK_8X8) {
5346 nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5347 subsize, pc_tree->leaf_split[0]);
5348 encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5349 subsize, pc_tree->leaf_split[0]);
5350 } else {
5351 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, subsize,
5352 output_enabled, dummy_cost, pc_tree->split[0]);
5353 nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5354 mi_col + hbs, subsize, output_enabled, dummy_cost,
5355 pc_tree->split[1]);
5356 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5357 mi_row + hbs, mi_col, subsize, output_enabled,
5358 dummy_cost, pc_tree->split[2]);
5359 nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5360 mi_row + hbs, mi_col + hbs, subsize, output_enabled,
5361 dummy_cost, pc_tree->split[3]);
5362 }
5363 break;
5364 }
5365
5366 if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
5367 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
5368 }
5369
5370 // Get a prediction(stored in x->est_pred) for the whole 64x64 superblock.
get_estimated_pred(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCK * x,int mi_row,int mi_col)5371 static void get_estimated_pred(VP9_COMP *cpi, const TileInfo *const tile,
5372 MACROBLOCK *x, int mi_row, int mi_col) {
5373 VP9_COMMON *const cm = &cpi->common;
5374 const int is_key_frame = frame_is_intra_only(cm);
5375 MACROBLOCKD *xd = &x->e_mbd;
5376
5377 set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
5378
5379 if (!is_key_frame) {
5380 MODE_INFO *mi = xd->mi[0];
5381 YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
5382 const YV12_BUFFER_CONFIG *yv12_g = NULL;
5383 const BLOCK_SIZE bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
5384 (mi_row + 4 < cm->mi_rows);
5385 unsigned int y_sad_g, y_sad_thr;
5386 unsigned int y_sad = UINT_MAX;
5387
5388 assert(yv12 != NULL);
5389
5390 if (!(is_one_pass_svc(cpi) && cpi->svc.spatial_layer_id) ||
5391 cpi->svc.use_gf_temporal_ref_current_layer) {
5392 // For now, GOLDEN will not be used for non-zero spatial layers, since
5393 // it may not be a temporal reference.
5394 yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
5395 }
5396
5397 // Only compute y_sad_g (sad for golden reference) for speed < 8.
5398 if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
5399 (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
5400 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5401 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5402 y_sad_g = cpi->fn_ptr[bsize].sdf(
5403 x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
5404 xd->plane[0].pre[0].stride);
5405 } else {
5406 y_sad_g = UINT_MAX;
5407 }
5408
5409 if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
5410 cpi->rc.is_src_frame_alt_ref) {
5411 yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
5412 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5413 &cm->frame_refs[ALTREF_FRAME - 1].sf);
5414 mi->ref_frame[0] = ALTREF_FRAME;
5415 y_sad_g = UINT_MAX;
5416 } else {
5417 vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5418 &cm->frame_refs[LAST_FRAME - 1].sf);
5419 mi->ref_frame[0] = LAST_FRAME;
5420 }
5421 mi->ref_frame[1] = NONE;
5422 mi->sb_type = BLOCK_64X64;
5423 mi->mv[0].as_int = 0;
5424 mi->interp_filter = BILINEAR;
5425
5426 {
5427 const MV dummy_mv = { 0, 0 };
5428 y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
5429 &dummy_mv);
5430 x->sb_use_mv_part = 1;
5431 x->sb_mvcol_part = mi->mv[0].as_mv.col;
5432 x->sb_mvrow_part = mi->mv[0].as_mv.row;
5433 }
5434
5435 // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
5436 // are close if short_circuit_low_temp_var is on.
5437 y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
5438 if (y_sad_g < y_sad_thr) {
5439 vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5440 &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5441 mi->ref_frame[0] = GOLDEN_FRAME;
5442 mi->mv[0].as_int = 0;
5443 } else {
5444 x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
5445 }
5446
5447 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
5448 xd->plane[0].dst.buf = x->est_pred;
5449 xd->plane[0].dst.stride = 64;
5450 vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
5451 } else {
5452 #if CONFIG_VP9_HIGHBITDEPTH
5453 switch (xd->bd) {
5454 case 8: memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); break;
5455 case 10:
5456 memset(x->est_pred, 128 * 4, 64 * 64 * sizeof(x->est_pred[0]));
5457 break;
5458 case 12:
5459 memset(x->est_pred, 128 * 16, 64 * 64 * sizeof(x->est_pred[0]));
5460 break;
5461 }
5462 #else
5463 memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0]));
5464 #endif // CONFIG_VP9_HIGHBITDEPTH
5465 }
5466 }
5467
encode_nonrd_sb_row(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,int mi_row,TOKENEXTRA ** tp)5468 static void encode_nonrd_sb_row(VP9_COMP *cpi, ThreadData *td,
5469 TileDataEnc *tile_data, int mi_row,
5470 TOKENEXTRA **tp) {
5471 SPEED_FEATURES *const sf = &cpi->sf;
5472 VP9_COMMON *const cm = &cpi->common;
5473 TileInfo *const tile_info = &tile_data->tile_info;
5474 MACROBLOCK *const x = &td->mb;
5475 MACROBLOCKD *const xd = &x->e_mbd;
5476 const int mi_col_start = tile_info->mi_col_start;
5477 const int mi_col_end = tile_info->mi_col_end;
5478 int mi_col;
5479 const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
5480 const int num_sb_cols =
5481 get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
5482 int sb_col_in_tile;
5483
5484 // Initialize the left context for the new SB row
5485 memset(&xd->left_context, 0, sizeof(xd->left_context));
5486 memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
5487
5488 // Code each SB in the row
5489 for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
5490 mi_col += MI_BLOCK_SIZE, ++sb_col_in_tile) {
5491 const struct segmentation *const seg = &cm->seg;
5492 RD_COST dummy_rdc;
5493 const int idx_str = cm->mi_stride * mi_row + mi_col;
5494 MODE_INFO **mi = cm->mi_grid_visible + idx_str;
5495 PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
5496 BLOCK_SIZE bsize = BLOCK_64X64;
5497 int seg_skip = 0;
5498 int i;
5499
5500 (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
5501 sb_col_in_tile);
5502
5503 if (cpi->use_skin_detection) {
5504 vp9_compute_skin_sb(cpi, BLOCK_16X16, mi_row, mi_col);
5505 }
5506
5507 x->source_variance = UINT_MAX;
5508 for (i = 0; i < MAX_REF_FRAMES; ++i) {
5509 x->pred_mv[i].row = INT16_MAX;
5510 x->pred_mv[i].col = INT16_MAX;
5511 }
5512 vp9_rd_cost_init(&dummy_rdc);
5513 x->color_sensitivity[0] = 0;
5514 x->color_sensitivity[1] = 0;
5515 x->sb_is_skin = 0;
5516 x->skip_low_source_sad = 0;
5517 x->lowvar_highsumdiff = 0;
5518 x->content_state_sb = 0;
5519 x->zero_temp_sad_source = 0;
5520 x->sb_use_mv_part = 0;
5521 x->sb_mvcol_part = 0;
5522 x->sb_mvrow_part = 0;
5523 x->sb_pickmode_part = 0;
5524 x->arf_frame_usage = 0;
5525 x->lastgolden_frame_usage = 0;
5526
5527 if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
5528 int shift = cpi->Source->y_stride * (mi_row << 3) + (mi_col << 3);
5529 int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5530 int64_t source_sad = avg_source_sad(cpi, x, shift, sb_offset2);
5531 if (sf->adapt_partition_source_sad &&
5532 (cpi->oxcf.rc_mode == VPX_VBR && !cpi->rc.is_src_frame_alt_ref &&
5533 source_sad > sf->adapt_partition_thresh &&
5534 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)))
5535 partition_search_type = REFERENCE_PARTITION;
5536 }
5537
5538 if (seg->enabled) {
5539 const uint8_t *const map =
5540 seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
5541 int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
5542 seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
5543
5544 if (cpi->roi.enabled && cpi->roi.skip[BACKGROUND_SEG_SKIP_ID] &&
5545 cpi->rc.frames_since_key > FRAMES_NO_SKIPPING_AFTER_KEY &&
5546 x->content_state_sb > kLowSadLowSumdiff) {
5547 // For ROI with skip, force segment = 0 (no skip) over whole
5548 // superblock to avoid artifacts if temporal change in source_sad is
5549 // not 0.
5550 int xi, yi;
5551 const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
5552 const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
5553 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
5554 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
5555 const int block_index = mi_row * cm->mi_cols + mi_col;
5556 set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
5557 for (yi = 0; yi < ymis; yi++)
5558 for (xi = 0; xi < xmis; xi++) {
5559 int map_offset = block_index + yi * cm->mi_cols + xi;
5560 cpi->segmentation_map[map_offset] = 0;
5561 }
5562 set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
5563 seg_skip = 0;
5564 }
5565 if (seg_skip) {
5566 partition_search_type = FIXED_PARTITION;
5567 }
5568 }
5569
5570 // Set the partition type of the 64X64 block
5571 switch (partition_search_type) {
5572 case VAR_BASED_PARTITION:
5573 // TODO(jingning, marpan): The mode decision and encoding process
5574 // support both intra and inter sub8x8 block coding for RTC mode.
5575 // Tune the thresholds accordingly to use sub8x8 block coding for
5576 // coding performance improvement.
5577 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5578 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5579 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5580 break;
5581 case ML_BASED_PARTITION:
5582 get_estimated_pred(cpi, tile_info, x, mi_row, mi_col);
5583 x->max_partition_size = BLOCK_64X64;
5584 x->min_partition_size = BLOCK_8X8;
5585 x->sb_pickmode_part = 1;
5586 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5587 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5588 td->pc_root);
5589 break;
5590 case SOURCE_VAR_BASED_PARTITION:
5591 set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
5592 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5593 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5594 break;
5595 case FIXED_PARTITION:
5596 if (!seg_skip) bsize = sf->always_this_block_size;
5597 set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
5598 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5599 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5600 break;
5601 default:
5602 assert(partition_search_type == REFERENCE_PARTITION);
5603 x->sb_pickmode_part = 1;
5604 set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
5605 // Use nonrd_pick_partition on scene-cut for VBR mode.
5606 // nonrd_pick_partition does not support 4x4 partition, so avoid it
5607 // on key frame for now.
5608 if ((cpi->oxcf.rc_mode == VPX_VBR && cpi->rc.high_source_sad &&
5609 cpi->oxcf.speed < 6 && !frame_is_intra_only(cm) &&
5610 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
5611 // Use lower max_partition_size for low resoultions.
5612 if (cm->width <= 352 && cm->height <= 288)
5613 x->max_partition_size = BLOCK_32X32;
5614 else
5615 x->max_partition_size = BLOCK_64X64;
5616 x->min_partition_size = BLOCK_8X8;
5617 nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5618 BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5619 td->pc_root);
5620 } else {
5621 choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5622 // TODO(marpan): Seems like nonrd_select_partition does not support
5623 // 4x4 partition. Since 4x4 is used on key frame, use this switch
5624 // for now.
5625 if (frame_is_intra_only(cm))
5626 nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5627 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5628 else
5629 nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5630 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5631 }
5632
5633 break;
5634 }
5635
5636 // Update ref_frame usage for inter frame if this group is ARF group.
5637 if (!cpi->rc.is_src_frame_alt_ref && !cpi->refresh_golden_frame &&
5638 !cpi->refresh_alt_ref_frame && cpi->rc.alt_ref_gf_group &&
5639 cpi->sf.use_altref_onepass) {
5640 int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5641 if (cpi->count_arf_frame_usage != NULL)
5642 cpi->count_arf_frame_usage[sboffset] = x->arf_frame_usage;
5643 if (cpi->count_lastgolden_frame_usage != NULL)
5644 cpi->count_lastgolden_frame_usage[sboffset] = x->lastgolden_frame_usage;
5645 }
5646
5647 (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
5648 sb_col_in_tile, num_sb_cols);
5649 }
5650 }
5651 // end RTC play code
5652
variance(const diff * const d)5653 static INLINE uint32_t variance(const diff *const d) {
5654 return d->sse - (uint32_t)(((int64_t)d->sum * d->sum) >> 8);
5655 }
5656
5657 #if CONFIG_VP9_HIGHBITDEPTH
variance_highbd(diff * const d)5658 static INLINE uint32_t variance_highbd(diff *const d) {
5659 const int64_t var = (int64_t)d->sse - (((int64_t)d->sum * d->sum) >> 8);
5660 return (var >= 0) ? (uint32_t)var : 0;
5661 }
5662 #endif // CONFIG_VP9_HIGHBITDEPTH
5663
set_var_thresh_from_histogram(VP9_COMP * cpi)5664 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
5665 const SPEED_FEATURES *const sf = &cpi->sf;
5666 const VP9_COMMON *const cm = &cpi->common;
5667
5668 const uint8_t *src = cpi->Source->y_buffer;
5669 const uint8_t *last_src = cpi->Last_Source->y_buffer;
5670 const int src_stride = cpi->Source->y_stride;
5671 const int last_stride = cpi->Last_Source->y_stride;
5672
5673 // Pick cutoff threshold
5674 const int cutoff = (VPXMIN(cm->width, cm->height) >= 720)
5675 ? (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100)
5676 : (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
5677 DECLARE_ALIGNED(16, int, hist[VAR_HIST_BINS]);
5678 diff *var16 = cpi->source_diff_var;
5679
5680 int sum = 0;
5681 int i, j;
5682
5683 memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
5684
5685 for (i = 0; i < cm->mb_rows; i++) {
5686 for (j = 0; j < cm->mb_cols; j++) {
5687 #if CONFIG_VP9_HIGHBITDEPTH
5688 if (cm->use_highbitdepth) {
5689 switch (cm->bit_depth) {
5690 case VPX_BITS_8:
5691 vpx_highbd_8_get16x16var(src, src_stride, last_src, last_stride,
5692 &var16->sse, &var16->sum);
5693 var16->var = variance(var16);
5694 break;
5695 case VPX_BITS_10:
5696 vpx_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
5697 &var16->sse, &var16->sum);
5698 var16->var = variance_highbd(var16);
5699 break;
5700 default:
5701 assert(cm->bit_depth == VPX_BITS_12);
5702 vpx_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
5703 &var16->sse, &var16->sum);
5704 var16->var = variance_highbd(var16);
5705 break;
5706 }
5707 } else {
5708 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5709 &var16->sum);
5710 var16->var = variance(var16);
5711 }
5712 #else
5713 vpx_get16x16var(src, src_stride, last_src, last_stride, &var16->sse,
5714 &var16->sum);
5715 var16->var = variance(var16);
5716 #endif // CONFIG_VP9_HIGHBITDEPTH
5717
5718 if (var16->var >= VAR_HIST_MAX_BG_VAR)
5719 hist[VAR_HIST_BINS - 1]++;
5720 else
5721 hist[var16->var / VAR_HIST_FACTOR]++;
5722
5723 src += 16;
5724 last_src += 16;
5725 var16++;
5726 }
5727
5728 src = src - cm->mb_cols * 16 + 16 * src_stride;
5729 last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
5730 }
5731
5732 cpi->source_var_thresh = 0;
5733
5734 if (hist[VAR_HIST_BINS - 1] < cutoff) {
5735 for (i = 0; i < VAR_HIST_BINS - 1; i++) {
5736 sum += hist[i];
5737
5738 if (sum > cutoff) {
5739 cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
5740 return 0;
5741 }
5742 }
5743 }
5744
5745 return sf->search_type_check_frequency;
5746 }
5747
source_var_based_partition_search_method(VP9_COMP * cpi)5748 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
5749 VP9_COMMON *const cm = &cpi->common;
5750 SPEED_FEATURES *const sf = &cpi->sf;
5751
5752 if (cm->frame_type == KEY_FRAME) {
5753 // For key frame, use SEARCH_PARTITION.
5754 sf->partition_search_type = SEARCH_PARTITION;
5755 } else if (cm->intra_only) {
5756 sf->partition_search_type = FIXED_PARTITION;
5757 } else {
5758 if (cm->last_width != cm->width || cm->last_height != cm->height) {
5759 if (cpi->source_diff_var) vpx_free(cpi->source_diff_var);
5760
5761 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
5762 vpx_calloc(cm->MBs, sizeof(diff)));
5763 }
5764
5765 if (!cpi->frames_till_next_var_check)
5766 cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
5767
5768 if (cpi->frames_till_next_var_check > 0) {
5769 sf->partition_search_type = FIXED_PARTITION;
5770 cpi->frames_till_next_var_check--;
5771 }
5772 }
5773 }
5774
get_skip_encode_frame(const VP9_COMMON * cm,ThreadData * const td)5775 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
5776 unsigned int intra_count = 0, inter_count = 0;
5777 int j;
5778
5779 for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
5780 intra_count += td->counts->intra_inter[j][0];
5781 inter_count += td->counts->intra_inter[j][1];
5782 }
5783
5784 return (intra_count << 2) < inter_count && cm->frame_type != KEY_FRAME &&
5785 cm->show_frame;
5786 }
5787
vp9_init_tile_data(VP9_COMP * cpi)5788 void vp9_init_tile_data(VP9_COMP *cpi) {
5789 VP9_COMMON *const cm = &cpi->common;
5790 const int tile_cols = 1 << cm->log2_tile_cols;
5791 const int tile_rows = 1 << cm->log2_tile_rows;
5792 int tile_col, tile_row;
5793 TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
5794 TOKENLIST *tplist = cpi->tplist[0][0];
5795 int tile_tok = 0;
5796 int tplist_count = 0;
5797
5798 if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
5799 if (cpi->tile_data != NULL) vpx_free(cpi->tile_data);
5800 CHECK_MEM_ERROR(
5801 cm, cpi->tile_data,
5802 vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
5803 cpi->allocated_tiles = tile_cols * tile_rows;
5804
5805 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5806 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5807 TileDataEnc *tile_data =
5808 &cpi->tile_data[tile_row * tile_cols + tile_col];
5809 int i, j;
5810 for (i = 0; i < BLOCK_SIZES; ++i) {
5811 for (j = 0; j < MAX_MODES; ++j) {
5812 tile_data->thresh_freq_fact[i][j] = RD_THRESH_INIT_FACT;
5813 #if CONFIG_RATE_CTRL
5814 if (cpi->oxcf.use_simple_encode_api) {
5815 tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5816 }
5817 #endif // CONFIG_RATE_CTRL
5818 #if CONFIG_CONSISTENT_RECODE
5819 tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5820 #endif // CONFIG_CONSISTENT_RECODE
5821 tile_data->mode_map[i][j] = j;
5822 }
5823 }
5824 #if CONFIG_MULTITHREAD
5825 tile_data->row_base_thresh_freq_fact = NULL;
5826 #endif
5827 }
5828 }
5829
5830 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
5831 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5832 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5833 TileInfo *tile_info = &this_tile->tile_info;
5834 if (cpi->sf.adaptive_rd_thresh_row_mt &&
5835 this_tile->row_base_thresh_freq_fact == NULL)
5836 vp9_row_mt_alloc_rd_thresh(cpi, this_tile);
5837 vp9_tile_init(tile_info, cm, tile_row, tile_col);
5838
5839 cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
5840 pre_tok = cpi->tile_tok[tile_row][tile_col];
5841 tile_tok = allocated_tokens(*tile_info);
5842
5843 cpi->tplist[tile_row][tile_col] = tplist + tplist_count;
5844 tplist = cpi->tplist[tile_row][tile_col];
5845 tplist_count = get_num_vert_units(*tile_info, MI_BLOCK_SIZE_LOG2);
5846 }
5847 }
5848 }
5849
vp9_encode_sb_row(VP9_COMP * cpi,ThreadData * td,int tile_row,int tile_col,int mi_row)5850 void vp9_encode_sb_row(VP9_COMP *cpi, ThreadData *td, int tile_row,
5851 int tile_col, int mi_row) {
5852 VP9_COMMON *const cm = &cpi->common;
5853 const int tile_cols = 1 << cm->log2_tile_cols;
5854 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5855 const TileInfo *const tile_info = &this_tile->tile_info;
5856 TOKENEXTRA *tok = NULL;
5857 int tile_sb_row;
5858 int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
5859
5860 tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile_info->mi_row_start) >>
5861 MI_BLOCK_SIZE_LOG2;
5862 get_start_tok(cpi, tile_row, tile_col, mi_row, &tok);
5863 cpi->tplist[tile_row][tile_col][tile_sb_row].start = tok;
5864
5865 #if CONFIG_REALTIME_ONLY
5866 assert(cpi->sf.use_nonrd_pick_mode);
5867 encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5868 #else
5869 if (cpi->sf.use_nonrd_pick_mode)
5870 encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5871 else
5872 encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
5873 #endif
5874
5875 cpi->tplist[tile_row][tile_col][tile_sb_row].stop = tok;
5876 cpi->tplist[tile_row][tile_col][tile_sb_row].count =
5877 (unsigned int)(cpi->tplist[tile_row][tile_col][tile_sb_row].stop -
5878 cpi->tplist[tile_row][tile_col][tile_sb_row].start);
5879 assert(tok - cpi->tplist[tile_row][tile_col][tile_sb_row].start <=
5880 get_token_alloc(MI_BLOCK_SIZE >> 1, tile_mb_cols));
5881
5882 (void)tile_mb_cols;
5883 }
5884
vp9_encode_tile(VP9_COMP * cpi,ThreadData * td,int tile_row,int tile_col)5885 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td, int tile_row,
5886 int tile_col) {
5887 VP9_COMMON *const cm = &cpi->common;
5888 const int tile_cols = 1 << cm->log2_tile_cols;
5889 TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5890 const TileInfo *const tile_info = &this_tile->tile_info;
5891 const int mi_row_start = tile_info->mi_row_start;
5892 const int mi_row_end = tile_info->mi_row_end;
5893 int mi_row;
5894
5895 for (mi_row = mi_row_start; mi_row < mi_row_end; mi_row += MI_BLOCK_SIZE)
5896 vp9_encode_sb_row(cpi, td, tile_row, tile_col, mi_row);
5897 }
5898
encode_tiles(VP9_COMP * cpi)5899 static void encode_tiles(VP9_COMP *cpi) {
5900 VP9_COMMON *const cm = &cpi->common;
5901 const int tile_cols = 1 << cm->log2_tile_cols;
5902 const int tile_rows = 1 << cm->log2_tile_rows;
5903 int tile_col, tile_row;
5904
5905 vp9_init_tile_data(cpi);
5906
5907 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5908 for (tile_col = 0; tile_col < tile_cols; ++tile_col)
5909 vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
5910 }
5911
compare_kmeans_data(const void * a,const void * b)5912 static int compare_kmeans_data(const void *a, const void *b) {
5913 if (((const KMEANS_DATA *)a)->value > ((const KMEANS_DATA *)b)->value) {
5914 return 1;
5915 } else if (((const KMEANS_DATA *)a)->value <
5916 ((const KMEANS_DATA *)b)->value) {
5917 return -1;
5918 } else {
5919 return 0;
5920 }
5921 }
5922
compute_boundary_ls(const double * ctr_ls,int k,double * boundary_ls)5923 static void compute_boundary_ls(const double *ctr_ls, int k,
5924 double *boundary_ls) {
5925 // boundary_ls[j] is the upper bound of data centered at ctr_ls[j]
5926 int j;
5927 for (j = 0; j < k - 1; ++j) {
5928 boundary_ls[j] = (ctr_ls[j] + ctr_ls[j + 1]) / 2.;
5929 }
5930 boundary_ls[k - 1] = DBL_MAX;
5931 }
5932
vp9_get_group_idx(double value,double * boundary_ls,int k)5933 int vp9_get_group_idx(double value, double *boundary_ls, int k) {
5934 int group_idx = 0;
5935 while (value >= boundary_ls[group_idx]) {
5936 ++group_idx;
5937 if (group_idx == k - 1) {
5938 break;
5939 }
5940 }
5941 return group_idx;
5942 }
5943
vp9_kmeans(double * ctr_ls,double * boundary_ls,int * count_ls,int k,KMEANS_DATA * arr,int size)5944 void vp9_kmeans(double *ctr_ls, double *boundary_ls, int *count_ls, int k,
5945 KMEANS_DATA *arr, int size) {
5946 int i, j;
5947 int itr;
5948 int group_idx;
5949 double sum[MAX_KMEANS_GROUPS];
5950 int count[MAX_KMEANS_GROUPS];
5951
5952 vpx_clear_system_state();
5953
5954 assert(k >= 2 && k <= MAX_KMEANS_GROUPS);
5955
5956 qsort(arr, size, sizeof(*arr), compare_kmeans_data);
5957
5958 // initialize the center points
5959 for (j = 0; j < k; ++j) {
5960 ctr_ls[j] = arr[(size * (2 * j + 1)) / (2 * k)].value;
5961 }
5962
5963 for (itr = 0; itr < 10; ++itr) {
5964 compute_boundary_ls(ctr_ls, k, boundary_ls);
5965 for (i = 0; i < MAX_KMEANS_GROUPS; ++i) {
5966 sum[i] = 0;
5967 count[i] = 0;
5968 }
5969
5970 // Both the data and centers are sorted in ascending order.
5971 // As each data point is processed in order, its corresponding group index
5972 // can only increase. So we only need to reset the group index to zero here.
5973 group_idx = 0;
5974 for (i = 0; i < size; ++i) {
5975 while (arr[i].value >= boundary_ls[group_idx]) {
5976 // place samples into clusters
5977 ++group_idx;
5978 if (group_idx == k - 1) {
5979 break;
5980 }
5981 }
5982 sum[group_idx] += arr[i].value;
5983 ++count[group_idx];
5984 }
5985
5986 for (group_idx = 0; group_idx < k; ++group_idx) {
5987 if (count[group_idx] > 0)
5988 ctr_ls[group_idx] = sum[group_idx] / count[group_idx];
5989
5990 sum[group_idx] = 0;
5991 count[group_idx] = 0;
5992 }
5993 }
5994
5995 // compute group_idx, boundary_ls and count_ls
5996 for (j = 0; j < k; ++j) {
5997 count_ls[j] = 0;
5998 }
5999 compute_boundary_ls(ctr_ls, k, boundary_ls);
6000 group_idx = 0;
6001 for (i = 0; i < size; ++i) {
6002 while (arr[i].value >= boundary_ls[group_idx]) {
6003 ++group_idx;
6004 if (group_idx == k - 1) {
6005 break;
6006 }
6007 }
6008 arr[i].group_idx = group_idx;
6009 ++count_ls[group_idx];
6010 }
6011 }
6012
encode_frame_internal(VP9_COMP * cpi)6013 static void encode_frame_internal(VP9_COMP *cpi) {
6014 SPEED_FEATURES *const sf = &cpi->sf;
6015 ThreadData *const td = &cpi->td;
6016 MACROBLOCK *const x = &td->mb;
6017 VP9_COMMON *const cm = &cpi->common;
6018 MACROBLOCKD *const xd = &x->e_mbd;
6019 const int gf_group_index = cpi->twopass.gf_group.index;
6020
6021 xd->mi = cm->mi_grid_visible;
6022 xd->mi[0] = cm->mi;
6023 vp9_zero(*td->counts);
6024 vp9_zero(cpi->td.rd_counts);
6025
6026 xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
6027 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
6028
6029 #if CONFIG_VP9_HIGHBITDEPTH
6030 if (cm->use_highbitdepth)
6031 x->fwd_txfm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
6032 else
6033 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
6034 x->highbd_inv_txfm_add =
6035 xd->lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
6036 #else
6037 x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
6038 #endif // CONFIG_VP9_HIGHBITDEPTH
6039 x->inv_txfm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
6040 #if CONFIG_CONSISTENT_RECODE
6041 x->optimize = sf->optimize_coefficients == 1 && cpi->oxcf.pass != 1;
6042 #endif
6043 if (xd->lossless) x->optimize = 0;
6044 x->sharpness = cpi->oxcf.sharpness;
6045 x->adjust_rdmult_by_segment = (cpi->oxcf.aq_mode == VARIANCE_AQ);
6046
6047 cm->tx_mode = select_tx_mode(cpi, xd);
6048
6049 vp9_frame_init_quantizer(cpi);
6050
6051 vp9_initialize_rd_consts(cpi);
6052 vp9_initialize_me_consts(cpi, x, cm->base_qindex);
6053 init_encode_frame_mb_context(cpi);
6054 cm->use_prev_frame_mvs =
6055 !cm->error_resilient_mode && cm->width == cm->last_width &&
6056 cm->height == cm->last_height && !cm->intra_only && cm->last_show_frame;
6057 // Special case: set prev_mi to NULL when the previous mode info
6058 // context cannot be used.
6059 cm->prev_mi =
6060 cm->use_prev_frame_mvs ? cm->prev_mip + cm->mi_stride + 1 : NULL;
6061
6062 x->quant_fp = cpi->sf.use_quant_fp;
6063 vp9_zero(x->skip_txfm);
6064 if (sf->use_nonrd_pick_mode) {
6065 // Initialize internal buffer pointers for rtc coding, where non-RD
6066 // mode decision is used and hence no buffer pointer swap needed.
6067 int i;
6068 struct macroblock_plane *const p = x->plane;
6069 struct macroblockd_plane *const pd = xd->plane;
6070 PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
6071
6072 for (i = 0; i < MAX_MB_PLANE; ++i) {
6073 p[i].coeff = ctx->coeff_pbuf[i][0];
6074 p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
6075 pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
6076 p[i].eobs = ctx->eobs_pbuf[i][0];
6077 }
6078 vp9_zero(x->zcoeff_blk);
6079
6080 if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0 &&
6081 !(cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) &&
6082 !cpi->use_svc)
6083 cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
6084
6085 if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
6086 source_var_based_partition_search_method(cpi);
6087 } else if (gf_group_index && gf_group_index < MAX_ARF_GOP_SIZE &&
6088 cpi->sf.enable_tpl_model) {
6089 TplDepFrame *tpl_frame = &cpi->tpl_stats[cpi->twopass.gf_group.index];
6090 TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
6091
6092 int tpl_stride = tpl_frame->stride;
6093 int64_t intra_cost_base = 0;
6094 int64_t mc_dep_cost_base = 0;
6095 int row, col;
6096
6097 for (row = 0; row < cm->mi_rows && tpl_frame->is_valid; ++row) {
6098 for (col = 0; col < cm->mi_cols; ++col) {
6099 TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
6100 intra_cost_base += this_stats->intra_cost;
6101 mc_dep_cost_base += this_stats->mc_dep_cost;
6102 }
6103 }
6104
6105 vpx_clear_system_state();
6106
6107 if (tpl_frame->is_valid)
6108 cpi->rd.r0 = (double)intra_cost_base / mc_dep_cost_base;
6109 }
6110
6111 // Frame segmentation
6112 if (cpi->oxcf.aq_mode == PERCEPTUAL_AQ) build_kmeans_segmentation(cpi);
6113
6114 {
6115 struct vpx_usec_timer emr_timer;
6116 vpx_usec_timer_start(&emr_timer);
6117
6118 if (!cpi->row_mt) {
6119 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
6120 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
6121 // If allowed, encoding tiles in parallel with one thread handling one
6122 // tile when row based multi-threading is disabled.
6123 if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
6124 vp9_encode_tiles_mt(cpi);
6125 else
6126 encode_tiles(cpi);
6127 } else {
6128 cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
6129 cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
6130 vp9_encode_tiles_row_mt(cpi);
6131 }
6132
6133 vpx_usec_timer_mark(&emr_timer);
6134 cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
6135 }
6136
6137 sf->skip_encode_frame =
6138 sf->skip_encode_sb ? get_skip_encode_frame(cm, td) : 0;
6139
6140 #if 0
6141 // Keep record of the total distortion this time around for future use
6142 cpi->last_frame_distortion = cpi->frame_distortion;
6143 #endif
6144 }
6145
get_interp_filter(const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS],int is_alt_ref)6146 static INTERP_FILTER get_interp_filter(
6147 const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
6148 if (!is_alt_ref && threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
6149 threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
6150 threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
6151 return EIGHTTAP_SMOOTH;
6152 } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
6153 threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
6154 return EIGHTTAP_SHARP;
6155 } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
6156 return EIGHTTAP;
6157 } else {
6158 return SWITCHABLE;
6159 }
6160 }
6161
compute_frame_aq_offset(struct VP9_COMP * cpi)6162 static int compute_frame_aq_offset(struct VP9_COMP *cpi) {
6163 VP9_COMMON *const cm = &cpi->common;
6164 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
6165 struct segmentation *const seg = &cm->seg;
6166
6167 int mi_row, mi_col;
6168 int sum_delta = 0;
6169 int map_index = 0;
6170 int qdelta_index;
6171 int segment_id;
6172
6173 for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
6174 MODE_INFO **mi_8x8 = mi_8x8_ptr;
6175 for (mi_col = 0; mi_col < cm->mi_cols; mi_col++, mi_8x8++) {
6176 segment_id = mi_8x8[0]->segment_id;
6177 qdelta_index = get_segdata(seg, segment_id, SEG_LVL_ALT_Q);
6178 sum_delta += qdelta_index;
6179 map_index++;
6180 }
6181 mi_8x8_ptr += cm->mi_stride;
6182 }
6183
6184 return sum_delta / (cm->mi_rows * cm->mi_cols);
6185 }
6186
6187 #if CONFIG_CONSISTENT_RECODE || CONFIG_RATE_CTRL
restore_encode_params(VP9_COMP * cpi)6188 static void restore_encode_params(VP9_COMP *cpi) {
6189 VP9_COMMON *const cm = &cpi->common;
6190 const int tile_cols = 1 << cm->log2_tile_cols;
6191 const int tile_rows = 1 << cm->log2_tile_rows;
6192 int tile_col, tile_row;
6193 int i, j;
6194 RD_OPT *rd_opt = &cpi->rd;
6195 for (i = 0; i < MAX_REF_FRAMES; i++) {
6196 for (j = 0; j < REFERENCE_MODES; j++)
6197 rd_opt->prediction_type_threshes[i][j] =
6198 rd_opt->prediction_type_threshes_prev[i][j];
6199
6200 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
6201 rd_opt->filter_threshes[i][j] = rd_opt->filter_threshes_prev[i][j];
6202 }
6203
6204 if (cpi->tile_data != NULL) {
6205 for (tile_row = 0; tile_row < tile_rows; ++tile_row)
6206 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
6207 TileDataEnc *tile_data =
6208 &cpi->tile_data[tile_row * tile_cols + tile_col];
6209 for (i = 0; i < BLOCK_SIZES; ++i) {
6210 for (j = 0; j < MAX_MODES; ++j) {
6211 tile_data->thresh_freq_fact[i][j] =
6212 tile_data->thresh_freq_fact_prev[i][j];
6213 }
6214 }
6215 }
6216 }
6217
6218 cm->interp_filter = cpi->sf.default_interp_filter;
6219 }
6220 #endif // CONFIG_CONSISTENT_RECODE || CONFIG_RATE_CTRL
6221
vp9_encode_frame(VP9_COMP * cpi)6222 void vp9_encode_frame(VP9_COMP *cpi) {
6223 VP9_COMMON *const cm = &cpi->common;
6224
6225 #if CONFIG_RATE_CTRL
6226 if (cpi->oxcf.use_simple_encode_api) {
6227 restore_encode_params(cpi);
6228 }
6229 #endif // CONFIG_RATE_CTRL
6230 #if CONFIG_CONSISTENT_RECODE
6231 restore_encode_params(cpi);
6232 #endif
6233
6234 #if CONFIG_MISMATCH_DEBUG
6235 mismatch_reset_frame(MAX_MB_PLANE);
6236 #endif
6237
6238 // In the longer term the encoder should be generalized to match the
6239 // decoder such that we allow compound where one of the 3 buffers has a
6240 // different sign bias and that buffer is then the fixed ref. However, this
6241 // requires further work in the rd loop. For now the only supported encoder
6242 // side behavior is where the ALT ref buffer has opposite sign bias to
6243 // the other two.
6244 if (!frame_is_intra_only(cm)) {
6245 if (vp9_compound_reference_allowed(cm)) {
6246 cpi->allow_comp_inter_inter = 1;
6247 vp9_setup_compound_reference_mode(cm);
6248 } else {
6249 cpi->allow_comp_inter_inter = 0;
6250 }
6251 }
6252
6253 if (cpi->sf.frame_parameter_update) {
6254 int i;
6255 RD_OPT *const rd_opt = &cpi->rd;
6256 FRAME_COUNTS *counts = cpi->td.counts;
6257 RD_COUNTS *const rdc = &cpi->td.rd_counts;
6258
6259 // This code does a single RD pass over the whole frame assuming
6260 // either compound, single or hybrid prediction as per whatever has
6261 // worked best for that type of frame in the past.
6262 // It also predicts whether another coding mode would have worked
6263 // better than this coding mode. If that is the case, it remembers
6264 // that for subsequent frames.
6265 // It also does the same analysis for transform size selection.
6266 const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
6267 int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
6268 int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
6269 const int is_alt_ref = frame_type == ALTREF_FRAME;
6270
6271 /* prediction (compound, single or hybrid) mode selection */
6272 if (is_alt_ref || !cpi->allow_comp_inter_inter)
6273 cm->reference_mode = SINGLE_REFERENCE;
6274 else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
6275 mode_thrs[COMPOUND_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT] &&
6276 check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
6277 cm->reference_mode = COMPOUND_REFERENCE;
6278 else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
6279 cm->reference_mode = SINGLE_REFERENCE;
6280 else
6281 cm->reference_mode = REFERENCE_MODE_SELECT;
6282
6283 if (cm->interp_filter == SWITCHABLE)
6284 cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
6285
6286 encode_frame_internal(cpi);
6287
6288 for (i = 0; i < REFERENCE_MODES; ++i)
6289 mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
6290
6291 for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
6292 filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
6293
6294 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6295 int single_count_zero = 0;
6296 int comp_count_zero = 0;
6297
6298 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6299 single_count_zero += counts->comp_inter[i][0];
6300 comp_count_zero += counts->comp_inter[i][1];
6301 }
6302
6303 if (comp_count_zero == 0) {
6304 cm->reference_mode = SINGLE_REFERENCE;
6305 vp9_zero(counts->comp_inter);
6306 } else if (single_count_zero == 0) {
6307 cm->reference_mode = COMPOUND_REFERENCE;
6308 vp9_zero(counts->comp_inter);
6309 }
6310 }
6311
6312 if (cm->tx_mode == TX_MODE_SELECT) {
6313 int count4x4 = 0;
6314 int count8x8_lp = 0, count8x8_8x8p = 0;
6315 int count16x16_16x16p = 0, count16x16_lp = 0;
6316 int count32x32 = 0;
6317
6318 for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
6319 count4x4 += counts->tx.p32x32[i][TX_4X4];
6320 count4x4 += counts->tx.p16x16[i][TX_4X4];
6321 count4x4 += counts->tx.p8x8[i][TX_4X4];
6322
6323 count8x8_lp += counts->tx.p32x32[i][TX_8X8];
6324 count8x8_lp += counts->tx.p16x16[i][TX_8X8];
6325 count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
6326
6327 count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
6328 count16x16_lp += counts->tx.p32x32[i][TX_16X16];
6329 count32x32 += counts->tx.p32x32[i][TX_32X32];
6330 }
6331 if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
6332 count32x32 == 0) {
6333 cm->tx_mode = ALLOW_8X8;
6334 reset_skip_tx_size(cm, TX_8X8);
6335 } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
6336 count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
6337 cm->tx_mode = ONLY_4X4;
6338 reset_skip_tx_size(cm, TX_4X4);
6339 } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
6340 cm->tx_mode = ALLOW_32X32;
6341 } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
6342 cm->tx_mode = ALLOW_16X16;
6343 reset_skip_tx_size(cm, TX_16X16);
6344 }
6345 }
6346 } else {
6347 FRAME_COUNTS *counts = cpi->td.counts;
6348 cm->reference_mode = SINGLE_REFERENCE;
6349 if (cpi->allow_comp_inter_inter && cpi->sf.use_compound_nonrd_pickmode &&
6350 cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
6351 cm->frame_type != KEY_FRAME)
6352 cm->reference_mode = REFERENCE_MODE_SELECT;
6353
6354 encode_frame_internal(cpi);
6355
6356 if (cm->reference_mode == REFERENCE_MODE_SELECT) {
6357 int single_count_zero = 0;
6358 int comp_count_zero = 0;
6359 int i;
6360 for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
6361 single_count_zero += counts->comp_inter[i][0];
6362 comp_count_zero += counts->comp_inter[i][1];
6363 }
6364 if (comp_count_zero == 0) {
6365 cm->reference_mode = SINGLE_REFERENCE;
6366 vp9_zero(counts->comp_inter);
6367 } else if (single_count_zero == 0) {
6368 cm->reference_mode = COMPOUND_REFERENCE;
6369 vp9_zero(counts->comp_inter);
6370 }
6371 }
6372 }
6373
6374 // If segmented AQ is enabled compute the average AQ weighting.
6375 if (cm->seg.enabled && (cpi->oxcf.aq_mode != NO_AQ) &&
6376 (cm->seg.update_map || cm->seg.update_data)) {
6377 cm->seg.aq_av_offset = compute_frame_aq_offset(cpi);
6378 }
6379 }
6380
sum_intra_stats(FRAME_COUNTS * counts,const MODE_INFO * mi)6381 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
6382 const PREDICTION_MODE y_mode = mi->mode;
6383 const PREDICTION_MODE uv_mode = mi->uv_mode;
6384 const BLOCK_SIZE bsize = mi->sb_type;
6385
6386 if (bsize < BLOCK_8X8) {
6387 int idx, idy;
6388 const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
6389 const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
6390 for (idy = 0; idy < 2; idy += num_4x4_h)
6391 for (idx = 0; idx < 2; idx += num_4x4_w)
6392 ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
6393 } else {
6394 ++counts->y_mode[size_group_lookup[bsize]][y_mode];
6395 }
6396
6397 ++counts->uv_mode[y_mode][uv_mode];
6398 }
6399
update_zeromv_cnt(VP9_COMP * const cpi,const MODE_INFO * const mi,int mi_row,int mi_col,BLOCK_SIZE bsize)6400 static void update_zeromv_cnt(VP9_COMP *const cpi, const MODE_INFO *const mi,
6401 int mi_row, int mi_col, BLOCK_SIZE bsize) {
6402 const VP9_COMMON *const cm = &cpi->common;
6403 MV mv = mi->mv[0].as_mv;
6404 const int bw = num_8x8_blocks_wide_lookup[bsize];
6405 const int bh = num_8x8_blocks_high_lookup[bsize];
6406 const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
6407 const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
6408 const int block_index = mi_row * cm->mi_cols + mi_col;
6409 int x, y;
6410 for (y = 0; y < ymis; y++)
6411 for (x = 0; x < xmis; x++) {
6412 int map_offset = block_index + y * cm->mi_cols + x;
6413 if (mi->ref_frame[0] == LAST_FRAME && is_inter_block(mi) &&
6414 mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
6415 if (abs(mv.row) < 8 && abs(mv.col) < 8) {
6416 if (cpi->consec_zero_mv[map_offset] < 255)
6417 cpi->consec_zero_mv[map_offset]++;
6418 } else {
6419 cpi->consec_zero_mv[map_offset] = 0;
6420 }
6421 }
6422 }
6423 }
6424
encode_superblock(VP9_COMP * cpi,ThreadData * td,TOKENEXTRA ** t,int output_enabled,int mi_row,int mi_col,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)6425 static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
6426 int output_enabled, int mi_row, int mi_col,
6427 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
6428 VP9_COMMON *const cm = &cpi->common;
6429 MACROBLOCK *const x = &td->mb;
6430 MACROBLOCKD *const xd = &x->e_mbd;
6431 MODE_INFO *mi = xd->mi[0];
6432 const int seg_skip =
6433 segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP);
6434 x->skip_recode = !x->select_tx_size && mi->sb_type >= BLOCK_8X8 &&
6435 cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
6436 cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
6437 cpi->sf.allow_skip_recode;
6438
6439 if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
6440 memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
6441
6442 x->skip_optimize = ctx->is_coded;
6443 ctx->is_coded = 1;
6444 x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
6445 x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
6446 x->q_index < QIDX_SKIP_THRESH);
6447
6448 if (x->skip_encode) return;
6449
6450 if (!is_inter_block(mi)) {
6451 int plane;
6452 #if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6453 if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
6454 (xd->above_mi == NULL || xd->left_mi == NULL) &&
6455 need_top_left[mi->uv_mode])
6456 assert(0);
6457 #endif // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6458 mi->skip = 1;
6459 for (plane = 0; plane < MAX_MB_PLANE; ++plane)
6460 vp9_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane, 1);
6461 if (output_enabled) sum_intra_stats(td->counts, mi);
6462 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6463 VPXMAX(bsize, BLOCK_8X8));
6464 } else {
6465 int ref;
6466 const int is_compound = has_second_ref(mi);
6467 set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
6468 for (ref = 0; ref < 1 + is_compound; ++ref) {
6469 YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, mi->ref_frame[ref]);
6470 assert(cfg != NULL);
6471 vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
6472 &xd->block_refs[ref]->sf);
6473 }
6474 if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
6475 vp9_build_inter_predictors_sby(xd, mi_row, mi_col,
6476 VPXMAX(bsize, BLOCK_8X8));
6477
6478 vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col,
6479 VPXMAX(bsize, BLOCK_8X8));
6480
6481 #if CONFIG_MISMATCH_DEBUG
6482 if (output_enabled) {
6483 int plane;
6484 for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
6485 const struct macroblockd_plane *pd = &xd->plane[plane];
6486 int pixel_c, pixel_r;
6487 const BLOCK_SIZE plane_bsize =
6488 get_plane_block_size(VPXMAX(bsize, BLOCK_8X8), &xd->plane[plane]);
6489 const int bw = get_block_width(plane_bsize);
6490 const int bh = get_block_height(plane_bsize);
6491 mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, 0, 0,
6492 pd->subsampling_x, pd->subsampling_y);
6493
6494 mismatch_record_block_pre(pd->dst.buf, pd->dst.stride, plane, pixel_c,
6495 pixel_r, bw, bh,
6496 xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
6497 }
6498 }
6499 #endif
6500
6501 vp9_encode_sb(x, VPXMAX(bsize, BLOCK_8X8), mi_row, mi_col, output_enabled);
6502 vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6503 VPXMAX(bsize, BLOCK_8X8));
6504 }
6505
6506 if (seg_skip) {
6507 assert(mi->skip);
6508 }
6509
6510 if (output_enabled) {
6511 if (cm->tx_mode == TX_MODE_SELECT && mi->sb_type >= BLOCK_8X8 &&
6512 !(is_inter_block(mi) && mi->skip)) {
6513 ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
6514 &td->counts->tx)[mi->tx_size];
6515 } else {
6516 // The new intra coding scheme requires no change of transform size
6517 if (is_inter_block(mi)) {
6518 mi->tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
6519 max_txsize_lookup[bsize]);
6520 } else {
6521 mi->tx_size = (bsize >= BLOCK_8X8) ? mi->tx_size : TX_4X4;
6522 }
6523 }
6524
6525 ++td->counts->tx.tx_totals[mi->tx_size];
6526 ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])];
6527 if (cm->seg.enabled && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
6528 cpi->cyclic_refresh->content_mode)
6529 vp9_cyclic_refresh_update_sb_postencode(cpi, mi, mi_row, mi_col, bsize);
6530 if (cpi->oxcf.pass == 0 && cpi->svc.temporal_layer_id == 0 &&
6531 (!cpi->use_svc ||
6532 (cpi->use_svc &&
6533 !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
6534 cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)))
6535 update_zeromv_cnt(cpi, mi, mi_row, mi_col, bsize);
6536 }
6537 }
6538