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