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