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