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