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