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